fix(discord): constrain embeds and role mentions

Respect combined embed and component limits as well as field caps.
Restrict allowed mentions to validated route roles so payload text
cannot notify everyone.
This commit is contained in:
翅膀 committed 2026-10-23 23:22:31 +08:00
1 parent 7cf507f654
commit bfbdf3b159
3 files changed
+93 -8

No files matched your search

+68 -8
View File
@@ -9,6 +9,54 @@ import {
splitMessageTitle,
} from "../../formatters/helpers";
/** Discord's cap on the combined characters of all embeds in a message. */
const MAX_EMBED_TOTAL = 6000;
/** Discord's caps on a button's custom_id and label. */
const MAX_CUSTOM_ID = 100;
const MAX_BUTTON_LABEL = 80;
type Embed = NonNullable<FormattedMessage["embeds"]>[number];
function embedLength(embed: Embed): number {
return (
(embed.title?.length ?? 0) +
(embed.description?.length ?? 0) +
(embed.author?.name.length ?? 0) +
(embed.footer?.text.length ?? 0) +
(embed.fields ?? []).reduce((n, f) => n + f.name.length + f.value.length, 0)
);
}
/** Description length kept before any field is given up. */
const MIN_DESCRIPTION = 1024;
/** Shorten the description by `over` characters (never below `floor`); returns what is left over. */
function shrinkDescription(embed: Embed, over: number, floor: number): number {
const text = embed.description;
if (!text || over <= 0 || text.length <= floor) return over;
const keep = Math.max(floor, text.length - over - 1);
embed.description = keep > 0 ? `${text.slice(0, keep)}…` : undefined;
return over - (text.length - (embed.description?.length ?? 0));
}
/**
* Fit an embed into the 6000-character total so the request is never
* rejected whole: a long description shrinks first (down to 1024 characters),
* then trailing fields are dropped, then the description shrinks further.
*/
function fitEmbed(embed: Embed): Embed {
let over = embedLength(embed) - MAX_EMBED_TOTAL;
if (over <= 0) return embed;
const out: Embed = { ...embed, fields: embed.fields ? [...embed.fields] : undefined };
over = shrinkDescription(out, over, MIN_DESCRIPTION);
while (over > 0 && out.fields && out.fields.length > 0) {
const f = out.fields.pop()!;
over -= f.name.length + f.value.length;
}
shrinkDescription(out, over, 0);
return out;
}
function toStyle(style: NeutralActionStyle): number {
switch (style) {
case "primary":
@@ -20,10 +68,16 @@ function toStyle(style: NeutralActionStyle): number {
}
}
/**
* Most roles one message mentions: well within Discord's 100 allowed-mention
* roles and 2000 content characters (a mention takes at most 24 with its
* space). Routes are validated against it; this is the safety net.
*/
export const MAX_ROLE_MENTIONS = 50;
export function renderNeutralMessage(message: NeutralMessage): FormattedMessage {
const content = message.mentionRoleIds?.length
? message.mentionRoleIds.map((id) => `<@&${id}>`).join(" ")
: undefined;
const roleIds = [...new Set(message.mentionRoleIds ?? [])].slice(0, MAX_ROLE_MENTIONS);
const content = roleIds.length ? roleIds.map((id) => `<@&${id}>`).join(" ") : undefined;
// Discord embed titles can only be linked as a whole, so only the repo head
// goes into the title (linked to the event's object URL); the `: subject`
@@ -41,10 +95,16 @@ export function renderNeutralMessage(message: NeutralMessage): FormattedMessage
[message.forge?.name, message.footer].filter(Boolean).join(" · "),
MAX_FOOTER,
);
// Buttons whose id would exceed Discord's limit (very long repo names) are
// left out rather than failing the whole message.
const actions = (message.actions ?? []).filter((a) => a.id.length <= MAX_CUSTOM_ID);
return {
content,
// Only the route's own roles may ping — never @everyone, @here or users,
// whatever text ends up in the message.
allowed_mentions: { parse: [], roles: roleIds },
embeds: [
{
fitEmbed({
title: cap(head, MAX_TITLE),
url: message.url,
color: message.color,
@@ -63,16 +123,16 @@ export function renderNeutralMessage(message: NeutralMessage): FormattedMessage
})),
footer: footerText ? { text: footerText, icon_url: message.forge?.iconUrl } : undefined,
timestamp: message.timestamp,
},
}),
],
components: message.actions?.length
components: actions.length
? [
{
type: 1,
components: message.actions.map((action) => ({
components: actions.map((action) => ({
type: 2,
style: toStyle(action.style),
label: action.label,
label: cap(action.label, MAX_BUTTON_LABEL),
custom_id: action.id,
})),
},
+2
View File
@@ -365,4 +365,6 @@ export interface FormattedMessage {
custom_id?: string;
}>;
}>;
/** Which mentions in `content` may notify; set so only the route's roles ping. */
allowed_mentions?: { parse: string[]; roles?: string[] };
}
+23
View File
@@ -34,6 +34,29 @@ describe("platform contract", () => {
}
expect(embed!.footer).toBeDefined();
expect(embed!.footer!.text.length).toBeLessThanOrEqual(MAX_FOOTER);
// Discord also caps the embed's combined text at 6000 characters.
const total =
embed!.title!.length +
embed!.description!.length +
embed!.footer!.text.length +
embed!.fields!.reduce((n, f) => n + f.name.length + f.value.length, 0);
expect(total).toBeLessThanOrEqual(6000);
});
test("discord render never lets content mention anyone but the route's roles", () => {
const out = renderDiscord({ title: "t", mentionRoleIds: ["123456789012345678"] });
expect(out.allowed_mentions).toEqual({ parse: [], roles: ["123456789012345678"] });
});
test("discord render drops buttons whose id exceeds Discord's limit", () => {
const out = renderDiscord({
title: "t",
actions: [
{ id: `ghpr|merge|o|${"r".repeat(120)}|1`, label: "Merge", style: "primary" },
{ id: "ghpr|close|o|r|1", label: "Close", style: "danger" },
],
});
expect(out.components![0]!.components.map((c) => c.custom_id)).toEqual(["ghpr|close|o|r|1"]);
});
test("telegram render stays within the 4096-char cap", () => {