Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
164 changes: 164 additions & 0 deletions src/plugins/baseConverter/BaseConverterAccessory.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2024 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { Message } from "@vencord/discord-types";
import { ChannelStore, Parser, useEffect, useRef, useState, UserStore } from "@webpack/common";

import { BaseConverterIcon } from "./BaseConverterIcon";
import { settings } from "./settings";
import { cl, ConversionResult, decode, EncodingType } from "./utils";

const ConversionSetters = new Map<string, (v: ConversionResult) => void>();
const DecodedMessages = new Map<string, ConversionResult>();
const ReplyListeners = new Map<string, Set<(v: ConversionResult) => void>>();

function notifyDecode(messageId: string, data: ConversionResult) {
DecodedMessages.set(messageId, data);
ReplyListeners.get(messageId)?.forEach(fn => fn(data));
}

export function handleDecode(messageId: string, data: ConversionResult) {
notifyDecode(messageId, data);
ConversionSetters.get(messageId)?.(data);
}

function findMessageContentEl(messageId: string): HTMLElement | null {
return document.getElementById(`message-content-${messageId}`);
}

export function BaseConverterAccessory({ message }: { message: Message; }) {
const { autoDecodeReceived, receiveEncoding, aesSecret, userKeys } = settings.use(["autoDecodeReceived", "receiveEncoding", "aesSecret", "userKeys"]);
const authorId: string | undefined = (message as any).author?.id;
const currentUserId = UserStore.getCurrentUser()?.id;

// For your own messages in a DM the author is YOU, so userKeys[authorId] is
// meaningless. Use the DM partner's key instead, since that's who you encoded for.
let effectiveKey: string;
if (authorId && authorId === currentUserId) {
const channel = ChannelStore.getChannel(message.channel_id);
const partnerRaw = (channel as any)?.recipients?.[0];
const partnerId: string | undefined = typeof partnerRaw === "string" ? partnerRaw : partnerRaw?.id;
effectiveKey = (partnerId && userKeys?.[partnerId]) ? userKeys[partnerId] : aesSecret;
Comment on lines +52 to +56
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The logic for resolving the effectiveKey when the current user is the author assumes that recipients[0] is the intended partner. This is true for 1-on-1 DMs, but in Group DMs, recipients contains multiple users. This could lead to using the wrong per-user key (or falling back to the global secret incorrectly) when viewing your own sent messages in a group context.

It is safer to check if the channel is a 1-on-1 DM before attempting to resolve a partner key.

Suggested change
if (authorId && authorId === currentUserId) {
const channel = ChannelStore.getChannel(message.channel_id);
const partnerRaw = (channel as any)?.recipients?.[0];
const partnerId: string | undefined = typeof partnerRaw === "string" ? partnerRaw : partnerRaw?.id;
effectiveKey = (partnerId && userKeys?.[partnerId]) ? userKeys[partnerId] : aesSecret;
if (authorId && authorId === currentUserId) {
const channel = ChannelStore.getChannel(message.channel_id);
const recipients = (channel as any)?.recipients;
const partnerId = recipients?.length === 1 ? recipients[0] : null;
const partnerIdStr = typeof partnerId === "string" ? partnerId : partnerId?.id;
effectiveKey = (partnerIdStr && userKeys?.[partnerIdStr]) ? userKeys[partnerIdStr] : aesSecret;
} else {

} else {
effectiveKey = (authorId && userKeys?.[authorId]) ? userKeys[authorId] : aesSecret;
}
const [result, setResult] = useState<ConversionResult | undefined>();
const [showOriginal, setShowOriginal] = useState(false);
const containerRef = useRef<HTMLSpanElement>(null);

const referencedMessageId = (message as any).messageReference?.messageId
?? (message as any).messageReference?.message_id;

const [referenceResult, setReferenceResult] = useState<ConversionResult | undefined>(
() => referencedMessageId ? DecodedMessages.get(referencedMessageId) : undefined
);

useEffect(() => {
if (!referencedMessageId) return;
const set = ReplyListeners.get(referencedMessageId) ?? new Set();
set.add(setReferenceResult);
ReplyListeners.set(referencedMessageId, set);
return () => {
set.delete(setReferenceResult);
if (!set.size) ReplyListeners.delete(referencedMessageId);
};
}, [referencedMessageId]);

useEffect(() => {
if ((message as any).vencordEmbeddedBy) return;

ConversionSetters.set(message.id, setResult);

if (autoDecodeReceived && message.content) {
decode(message.content, receiveEncoding as EncodingType, effectiveKey)
.then(decoded => {
if (decoded) {
setResult(decoded);
notifyDecode(message.id, decoded);
}
})
.catch(() => { /* silent — auto-decode is best-effort */ });
}

return () => void ConversionSetters.delete(message.id);
}, [message.id, autoDecodeReceived, receiveEncoding, effectiveKey]);

// Hide the original encrypted message content when decoded; show when toggled
useEffect(() => {
const mc = findMessageContentEl(message.id);
if (!mc) return;
mc.style.display = result && !showOriginal ? "none" : "";
return () => { mc.style.display = ""; };
}, [result, showOriginal]);

// Hide the reply bar's encoded reference text and show the decoded version
useEffect(() => {
if (!referenceResult) return;

const listItem = document.querySelector<HTMLElement>(
`li[id*="${message.id}"], [data-list-item-id*="${message.id}"]`
);
if (!listItem) return;

const replyContent = listItem.querySelector<HTMLElement>(
"[class*='repliedMessage'] [class*='messageContent']"
);
if (!replyContent || !replyContent.parentElement) return;

replyContent.style.display = "none";
const decoded = document.createElement("span");
decoded.textContent = referenceResult.text;
replyContent.parentElement.insertBefore(decoded, replyContent);

return () => {
replyContent.style.display = "";
decoded.remove();
};
}, [referenceResult]);
Comment on lines +110 to +132
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Manually manipulating the DOM to insert decoded text into the reply bar is fragile. Discord's DOM structure and class names are subject to frequent changes, which could break the querySelector logic. Additionally, using textContent (line 125) means that any markdown in the decoded referenced message will not be rendered, unlike the main message accessory which uses Parser.parse.

While patching the reply bar is difficult, consider if there is a more idiomatic way to hook into the message rendering or at least use the Parser for the reply preview text.


// Match decoded text color to the actual message content color
useEffect(() => {
if (!result || !containerRef.current) return;
const mc = findMessageContentEl(message.id);
if (!mc) return;
const color = window.getComputedStyle(mc).color;
containerRef.current.style.color = color;
return () => { if (containerRef.current) containerRef.current.style.color = ""; };
}, [result]);

if (!result) return null;

return (
<span ref={containerRef} className={cl("accessory")}>
<BaseConverterIcon width={16} height={16} className={cl("accessory-icon")} />
<span className={cl("decoded-text")}>{Parser.parse(result.text)}</span>
<br />
<span className={cl("meta")}>
<span className={cl("encoding-label")}>{result.encoding}</span>
{" — "}
<button className={cl("toggle-original")} onClick={() => setShowOriginal(v => !v)}>
{showOriginal ? "Hide original" : "Show original"}
</button>
{" — "}
<button className={cl("dismiss")} onClick={() => { setResult(undefined); setShowOriginal(false); }}>
Dismiss
</button>
</span>
</span>
);
}
97 changes: 97 additions & 0 deletions src/plugins/baseConverter/BaseConverterIcon.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
* Vencord, a modification for Discord's desktop app
* Copyright (c) 2024 Vendicated and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

import { ChatBarButton, ChatBarButtonFactory } from "@api/ChatButtons";
import { TooltipContainer } from "@components/TooltipContainer";
import { classes } from "@utils/misc";
import { IconComponent } from "@utils/types";
import { useEffect, useState } from "@webpack/common";

import { settings } from "./settings";
import { openBaseConverterModal } from "./BaseConverterModal";
import { cl } from "./utils";

/**
* Binary bars → arrow → text lines icon.
* Three vertical bars on the left represent binary digits (tall=1, short=0),
* a filled arrow points right, and three horizontal lines suggest decoded text.
*/
export const BaseConverterIcon: IconComponent = ({ height = 20, width = 20, className }) => (
<svg
viewBox="0 0 24 24"
height={height}
width={width}
fill="currentColor"
className={classes(cl("icon"), className)}
>
{/* Binary bars: 1 0 1 */}
<rect x="1" y="3" width="2.5" height="18" rx="1" />
<rect x="5" y="8" width="2.5" height="8" rx="1" />
<rect x="9" y="3" width="2.5" height="18" rx="1" />

{/* Arrow shaft */}
<rect x="13.5" y="10.5" width="5" height="1.5" />
{/* Arrow head (filled triangle) */}
<polygon points="18.5,8 22,11.25 18.5,14.5" />

{/* Text lines (decoded content representation) */}
<rect x="13.5" y="5" width="9" height="1.5" rx="0.75" />
<rect x="13.5" y="17" width="7" height="1.5" rx="0.75" />
</svg>
);

export let setShouldShowAutoEncodeTooltip: undefined | ((show: boolean) => void);

export const BaseConverterChatBarIcon: ChatBarButtonFactory = ({ isMainChat }) => {
const { autoEncodeOutgoing } = settings.use(["autoEncodeOutgoing"]);

const [shouldShowTooltip, setter] = useState(false);
useEffect(() => {
setShouldShowAutoEncodeTooltip = setter;
return () => { setShouldShowAutoEncodeTooltip = undefined; };
}, []);

if (!isMainChat) return null;

const toggle = () => {
settings.store.autoEncodeOutgoing = !autoEncodeOutgoing;
};

const button = (
<ChatBarButton
tooltip={autoEncodeOutgoing ? "Auto-Encode Enabled — click to open settings" : "Open Base Converter"}
onClick={e => {
if (e.shiftKey) return toggle();
openBaseConverterModal();
}}
onContextMenu={toggle}
buttonProps={{ "aria-haspopup": "dialog" }}
>
<BaseConverterIcon className={cl({ "auto-encode": autoEncodeOutgoing, "chat-button": true })} />
</ChatBarButton>
);

if (shouldShowTooltip && autoEncodeOutgoing)
return (
<TooltipContainer text="Auto-Encode Enabled" forceOpen>
{button}
</TooltipContainer>
);

return button;
};
Loading