Files
Kelx/tests/webhook-dispatch-hardening.test.js
T
2026-11-30 16:32:37 +00:00

661 lines
31 KiB
JavaScript

"use strict";
// Tests for the webhook dispatch hardening (audit findings P4.3, P4.4, P4.5).
//
// P4.3: in `multiple` mode a category without its own webhook silently fell
// back to the single webhook. Remediation: the routing decision is now an
// explicit admin control (`fallbackToSingle`, default true for backward
// compatibility) exposed via the API and the settings UI; when it is false,
// categories without their own webhook send nothing (strict per-category
// isolation).
//
// P4.4: legacy discordapp.com webhook URLs were rejected outright. They are
// the same Discord-operated resource (same id/token), so validation now
// accepts both hosts under identical rules and every persisted URL is
// normalized to the canonical discord.com host — outbound dispatches only
// ever target discord.com.
//
// P4.5: capacity eviction sorted all ~500 rate-limit entries (O(n log n)).
// It now deletes expired entries first (their 1s window has passed, they no
// longer rate-limit anything), then oldest-inserted keys (Map insertion
// order) until a quarter of capacity is freed — O(n), same eviction volume.
//
// index.js boots servers on require, so the webhook pipeline is sliced out
// of the source and evaluated in a vm sandbox (same technique as
// template-store-install-review.test.js and
// template-store-local-override.test.js).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const INDEX_JS = path.join(__dirname, "..", "index.js");
const SETTINGS_JS = path.join(__dirname, "..", "public", "js", "settings.js");
const SETTINGS_EJS = path.join(__dirname, "..", "views", "settings.ejs");
function endIndexOfFunction(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
const bodyStart = source.indexOf("{", start);
let depth = 0;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) return i + 1;
}
}
assert.fail(`unbalanced braces after marker ${startMarker}`);
}
// The shared activity-email masker (maskActivityEntryEmails and its
// maskPlannerEmailToLocalPart base) lives before the webhook slice in
// index.js; dispatchDiscordWebhook calls it at field-build time, so the real
// sources are prepended to the evaluated script (adpanel:activity-user-masking).
function maskerHelperSources(source) {
const start = source.indexOf("function maskPlannerEmailToLocalPart(value) {");
const end = source.indexOf("async function fetchPlannerItemsForServer(");
assert.ok(start !== -1 && end !== -1 && end > start, "masker helper region not found in index.js");
return source.slice(start, end);
}
function buildWebhookModule() {
const source = fs.readFileSync(INDEX_JS, "utf8");
// Slice starts at WEBHOOKS_CONFIG_PATH (not DANGEROUS_KEYS) because the
// P3.1 write-lock code below it evaluates module-level constants derived
// from the config path.
const slice = source.slice(
source.indexOf("const WEBHOOKS_CONFIG_PATH"),
endIndexOfFunction(source, "function dispatchWebhookForActivity")
);
assert.ok(slice.includes("normalizeDiscordWebhookUrl"), "slice must contain the normalizer");
assert.ok(slice.includes("dispatchWebhookForActivity"), "slice must contain the dispatcher");
const exposed = {};
const fetchCalls = [];
const sandbox = {
// Used by loadWebhooksConfig/saveWebhooksConfig; tests override
// loadWebhooksConfig per case, so the file layer is never exercised.
fs: { existsSync: () => false },
path,
__dirname: "/tmp",
console: { log() { }, warn() { }, error() { }, debug() { } },
setInterval: () => ({ unref() { } }),
setTimeout,
clearTimeout,
AbortController,
Buffer,
Date,
Set,
Map,
fetch: async (url, opts) => {
fetchCalls.push({ url, opts });
return { ok: true, status: 200, headers: { get: () => null } };
},
__exports: (obj) => Object.assign(exposed, obj),
};
const context = vm.createContext(sandbox);
// adpanel:activity-user-masking — dispatchDiscordWebhook routes the
// acting-user field and email-shaped details values through the ONE shared
// activity masker (maskActivityEntryEmails -> maskPlannerEmailToLocalPart),
// which lives BEFORE the webhook slice in index.js; the real sources are
// prepended and evaluated too so the sandbox runs shipped code, not a copy.
vm.runInContext(maskerHelperSources(source), context);
vm.runInContext(
`${slice}\n;__exports({ DANGEROUS_KEYS, DISCORD_WEBHOOK_REGEX, validateDiscordWebhookUrl,`
+ ` normalizeDiscordWebhookUrl, sanitizeWebhooksConfig, maskConfigForResponse,`
+ ` maskWebhookUrlServer, normalizeWebhookAction, VALID_CATEGORY_IDS, webhookRateLimit,`
+ ` WEBHOOK_RATE_LIMIT_MS, WEBHOOK_RATE_LIMIT_MAX_ENTRIES, sanitizeFieldValue,`
+ ` dispatchWebhookForActivity });`,
context,
{ filename: "webhook-slice.js" }
);
return { exposed, fetchCalls, sandbox, context };
}
const CANONICAL_URL = "https://discord.com/api/webhooks/123456789012345678/AbCdEf-gh_Ijklmnop";
const LEGACY_URL = "https://discordapp.com/api/webhooks/123456789012345678/AbCdEf-gh_Ijklmnop";
function freshModule() {
const mod = buildWebhookModule();
// Dispatch tests drive routing with an in-memory config. `loadWebhooksConfig`
// is a top-level function declaration inside the vm context, so it must be
// rebound there — assigning on the host-side `exposed` object would not be
// visible to the dispatcher's scope chain.
mod.overrideConfig = (config) => {
mod.sandbox.__testConfig = config;
vm.runInContext("loadWebhooksConfig = () => __testConfig;", mod.context);
};
return mod;
}
test("P4.4: webhook validation accepts the current discord.com host", () => {
const { exposed } = freshModule();
assert.equal(exposed.validateDiscordWebhookUrl(CANONICAL_URL), true);
});
test("P4.4: webhook validation accepts the legacy discordapp.com host", () => {
const { exposed } = freshModule();
assert.equal(exposed.validateDiscordWebhookUrl(LEGACY_URL), true);
assert.equal(exposed.validateDiscordWebhookUrl(` ${LEGACY_URL} `), true);
});
test("P4.4: webhook validation still rejects non-Discord and malformed URLs", () => {
const { exposed } = freshModule();
const bad = [
null,
undefined,
"",
"not a url",
"http://discord.com/api/webhooks/123/token", // not https
"https://discord.com.evil.example/api/webhooks/123/token",
"https://discordapp.com.evil.example/api/webhooks/123/token",
"https://evil.example/api/webhooks/123/token",
"https://discord.com/api/webhooks/abc/token", // non-numeric id
"https://discord.com/api/webhooks/123/to ken", // space in token
"https://discord.com/api/webhooks/123/", // missing token
`https://discord.com/api/webhooks/123/${"a".repeat(200)}`, // > 200 chars
];
for (const url of bad) {
assert.equal(exposed.validateDiscordWebhookUrl(url), false, `should reject: ${url}`);
}
});
test("P4.4: normalizer rewrites the legacy host to the canonical host, preserving id/token", () => {
const { exposed } = freshModule();
assert.equal(exposed.normalizeDiscordWebhookUrl(LEGACY_URL), CANONICAL_URL);
assert.equal(exposed.normalizeDiscordWebhookUrl(` ${LEGACY_URL} `), CANONICAL_URL);
assert.equal(exposed.normalizeDiscordWebhookUrl(CANONICAL_URL), CANONICAL_URL);
assert.equal(exposed.normalizeDiscordWebhookUrl(null), null);
});
test("P4.4: sanitized config normalizes legacy URLs on load", () => {
const { exposed } = freshModule();
const safe = exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: LEGACY_URL,
multiple: { server_create: LEGACY_URL, server_delete: CANONICAL_URL },
});
assert.equal(safe.single, CANONICAL_URL);
assert.equal(safe.multiple.server_create, CANONICAL_URL);
assert.equal(safe.multiple.server_delete, CANONICAL_URL);
});
test("sanitize: defaults are preserved for empty/legacy config files", () => {
const { exposed } = freshModule();
for (const raw of [null, undefined, {}, "nonsense"]) {
const safe = exposed.sanitizeWebhooksConfig(raw);
assert.equal(safe.mode, "single");
assert.equal(safe.fallbackToSingle, true, "historical fallback default");
assert.equal(safe.single, null);
assert.deepEqual(Object.keys(safe.multiple), []);
}
});
test("sanitize: fallbackToSingle only accepts an explicit boolean false", () => {
const { exposed } = freshModule();
assert.equal(exposed.sanitizeWebhooksConfig({ fallbackToSingle: false }).fallbackToSingle, false);
assert.equal(exposed.sanitizeWebhooksConfig({ fallbackToSingle: true }).fallbackToSingle, true);
assert.equal(exposed.sanitizeWebhooksConfig({ fallbackToSingle: "false" }).fallbackToSingle, true);
assert.equal(exposed.sanitizeWebhooksConfig({ fallbackToSingle: 0 }).fallbackToSingle, true);
assert.equal(exposed.sanitizeWebhooksConfig({}).fallbackToSingle, true);
});
test("sanitize: still rejects invalid URLs, unknown categories, and dangerous keys", () => {
const { exposed } = freshModule();
const safe = exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: "https://evil.example/api/webhooks/123/token",
multiple: {
server_create: "https://evil.example/api/webhooks/123/token", // invalid URL
not_a_category: CANONICAL_URL, // unknown category
__proto__: CANONICAL_URL, // dangerous key
server_delete: CANONICAL_URL, // valid
},
});
assert.equal(safe.single, null);
assert.deepEqual(Object.keys(safe.multiple), ["server_delete"]);
const protoSafe = exposed.sanitizeWebhooksConfig({ multiple: JSON.parse('{"__proto__": "' + CANONICAL_URL + '"}') });
assert.equal(Object.keys(protoSafe.multiple).includes("__proto__"), false);
});
test("maskConfigForResponse exposes fallbackToSingle and never exposes secrets", () => {
const { exposed } = freshModule();
const config = exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: CANONICAL_URL,
fallbackToSingle: false,
multiple: { server_create: CANONICAL_URL },
});
const masked = exposed.maskConfigForResponse(config);
assert.equal(masked.mode, "multiple");
assert.equal(masked.fallbackToSingle, false);
assert.equal(masked.singleConfigured, true);
assert.equal(masked.multipleConfigured.server_create, true);
assert.match(masked.single, /^https:\/\/discord\.com\/api\/webhooks\//);
assert.ok(masked.single.endsWith("••••••"));
assert.ok(!JSON.stringify(masked).includes("AbCdEf-gh_Ijklmnop"), "token must be masked");
});
test("P4.3: single mode routes everything to the single webhook", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "single",
single: CANONICAL_URL,
multiple: { server_create: LEGACY_URL },
fallbackToSingle: false,
}));
exposed.dispatchWebhookForActivity("server_create", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1);
assert.equal(fetchCalls[0].url, CANONICAL_URL);
});
test("P4.3: multiple mode uses the category webhook when configured", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: CANONICAL_URL,
multiple: { server_create: LEGACY_URL },
}));
exposed.dispatchWebhookForActivity("server_create", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1);
// Stored URLs are normalized; dispatch must hit the canonical host.
assert.equal(fetchCalls[0].url, CANONICAL_URL);
});
test("P4.3: multiple mode falls back to the single webhook by default (documented behavior)", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: CANONICAL_URL,
multiple: { server_create: LEGACY_URL },
}));
exposed.dispatchWebhookForActivity("server_delete", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1);
assert.equal(fetchCalls[0].url, CANONICAL_URL);
});
test("P4.3: strict isolation disables the fallback — unset categories send nothing", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: CANONICAL_URL,
multiple: { server_create: LEGACY_URL },
fallbackToSingle: false,
}));
exposed.dispatchWebhookForActivity("server_delete", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 0, "category without its own webhook must not fall back");
// And with no single webhook at all, still nothing.
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
multiple: { server_create: LEGACY_URL },
fallbackToSingle: false,
}));
exposed.dispatchWebhookForActivity("server_delete", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 0);
});
test("P4.3: strict isolation still routes configured categories", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
single: CANONICAL_URL,
multiple: { server_create: LEGACY_URL },
fallbackToSingle: false,
}));
exposed.dispatchWebhookForActivity("server_create", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1);
assert.equal(fetchCalls[0].url, CANONICAL_URL);
});
test("dispatch: legacy action aliases resolve to their category webhook", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "multiple",
multiple: { server_create: LEGACY_URL },
}));
exposed.dispatchWebhookForActivity("create-server", { msg: "hi" }, "admin", "srv1");
assert.equal(exposed.normalizeWebhookAction("create-server"), "server_create");
assert.equal(fetchCalls.length, 1);
});
test("P4.5: eviction drops expired entries first and keeps the map bounded", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
const map = exposed.webhookRateLimit;
const now = Date.now();
// 500 fully expired entries: all dead weight, dropped in one O(n) pass.
for (let i = 0; i < exposed.WEBHOOK_RATE_LIMIT_MAX_ENTRIES; i++) {
map.set(`expired:${i}`, now - 60_000);
}
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "single",
single: CANONICAL_URL,
}));
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
assert.ok(fetchCalls.length === 1, "dispatch must still go through");
assert.equal(map.size, 1, "all expired entries evicted, only the fresh key remains");
});
test("P4.5: eviction with fresh entries frees a quarter of capacity (insertion order)", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
const map = exposed.webhookRateLimit;
const now = Date.now();
const max = exposed.WEBHOOK_RATE_LIMIT_MAX_ENTRIES;
for (let i = 0; i < max; i++) map.set(`k${i}`, now);
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "single",
single: CANONICAL_URL,
}));
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
const toEvict = Math.max(1, Math.floor(max / 4));
assert.equal(map.size, max - toEvict + 1);
// Oldest-inserted keys are evicted first; recent ones and the new key stay.
assert.equal(map.has("k0"), false);
assert.equal(map.has(`k${toEvict - 1}`), false);
assert.equal(map.has(`k${toEvict}`), true);
assert.equal(map.has(`k${max - 1}`), true);
assert.ok(fetchCalls.length === 1, "dispatch must still go through");
});
test("P4.5: rate limiting still suppresses duplicate sends inside the window", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
const map = exposed.webhookRateLimit;
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "single",
single: CANONICAL_URL,
}));
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1, "same action/server/url within 1s must be deduped");
assert.ok(map.size >= 1);
});
test("P4.5: different keys never collide in the rate limiter", () => {
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({
mode: "single",
single: CANONICAL_URL,
}));
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
exposed.dispatchWebhookForActivity("server_stop", { msg: "hi" }, "admin", "srv1");
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv2");
assert.equal(fetchCalls.length, 3);
});
test("frontend contract: settings UI wires the explicit fallback control", () => {
const settingsJs = fs.readFileSync(SETTINGS_JS, "utf8");
assert.ok(settingsJs.includes("webhookFallbackToggle"), "toggle button must be wired");
assert.ok(settingsJs.includes("webhookFallbackNote"), "fallback notice must be rendered");
assert.ok(settingsJs.includes("fallbackToSingle"), "fallback flag must be sent to the API");
assert.ok(
settingsJs.includes("(?:discord|discordapp)"),
"client-side URL validation must accept the legacy discordapp.com host"
);
const settingsEjs = fs.readFileSync(SETTINGS_EJS, "utf8");
for (const id of ["webhookFallbackNote", "webhookFallbackText", "webhookFallbackToggle", "webhookModeMultipleDesc"]) {
assert.ok(settingsEjs.includes(`id="${id}"`), `settings.ejs must contain #${id}`);
}
});
test("server contract: POST endpoint validates the flag and normalizes stored URLs", () => {
const source = fs.readFileSync(INDEX_JS, "utf8");
const postStart = source.indexOf('app.post("/api/settings/webhooks"');
assert.ok(postStart >= 0, "webhooks POST route must exist");
const postEnd = endIndexOfFunction(source.slice(postStart), "async (req, res) => {") + postStart;
const handler = source.slice(postStart, postEnd);
assert.ok(handler.includes("hasFallback"), "endpoint must gate on the fallback flag");
assert.ok(handler.includes("normalizeDiscordWebhookUrl(url)"), "persisted URLs must be normalized");
});
test("dispatch: the fetch must reject redirects instead of following them (SSRF hardening)", () => {
// validateDiscordWebhookUrl pins the initial URL to discord.com, but that
// gate cannot cover redirect hops; undici follows up to 20 by default and a
// 307/308 would re-POST the payload to the Location target unvalidated.
const { exposed, fetchCalls, overrideConfig } = freshModule();
overrideConfig(exposed.sanitizeWebhooksConfig({ mode: "single", single: CANONICAL_URL }));
exposed.dispatchWebhookForActivity("server_start", { msg: "hi" }, "admin", "srv1");
assert.equal(fetchCalls.length, 1, "the dispatch must reach the fetch call");
assert.equal(
fetchCalls[0].opts.redirect,
"error",
"the dispatch fetch must be created with redirect: 'error'"
);
});
test("sanitizeFieldValue: objects and arrays render as JSON, hostile values degrade to a placeholder", () => {
const { exposed } = freshModule();
// Primitives keep the legacy String() rendering.
assert.equal(exposed.sanitizeFieldValue("plain"), "plain");
assert.equal(exposed.sanitizeFieldValue(42), "42");
assert.equal(exposed.sanitizeFieldValue(true), "true");
// Objects/arrays used to render as "[object Object]"/comma fragments.
assert.equal(exposed.sanitizeFieldValue({ a: 1, b: "x" }), '{"a":1,"b":"x"}');
assert.equal(exposed.sanitizeFieldValue(["x", "y"]), '["x","y"]');
// The 256-char cap and mention stripping apply to serialized objects too.
assert.equal(exposed.sanitizeFieldValue({ a: "x".repeat(300) }).length, 256);
const mentions = exposed.sanitizeFieldValue({ msg: "@everyone hi" });
assert.equal(mentions.includes('"@everyone"'), false, "mentions must be stripped inside serialized objects");
// Values that JSON.stringify cannot serialize (cyclic, BigInt) degrade to a
// fixed placeholder instead of killing the dispatch.
const cyclic = {};
cyclic.self = cyclic;
assert.equal(exposed.sanitizeFieldValue(cyclic), "[unserializable value]");
assert.equal(exposed.sanitizeFieldValue({ v: 1n }), "[unserializable value]");
assert.equal(exposed.sanitizeFieldValue(null), null);
assert.equal(exposed.sanitizeFieldValue(undefined), null);
});
// adpanel:webhook-markdown-link-injection — Discord renders markdown links in
// embed field values, and planner item titles (which keep brackets/parens
// through sanitizePlannerTitle) ride the activity details into those values.
// A planner-title-shaped "[click](https://evil.example)" must reach the embed
// as non-clickable plain text; bracket-bearing LINK TEXT is treated the same
// way (balanced nested brackets are part of a CommonMark/Discord link's
// text), and every non-link markdown form and non-link bracket usage passes
// through byte-identical.
test("sanitizeFieldValue: markdown hyperlinks are neutralized to plain text (planner-title injection)", () => {
const { exposed } = freshModule();
// The exact finding shape: a planner title masquerading as an urgent
// operator call-to-action must not stay clickable.
assert.equal(
exposed.sanitizeFieldValue("[Server compromised — verify now](https://evil.example)"),
"Server compromised — verify now (link: https://evil.example)",
"a well-formed [text](url) pair must render as the link text followed by the url as plain text"
);
assert.ok(
!exposed.sanitizeFieldValue("[click](https://evil.example)").includes("]("),
"no ]( adjacency may survive — Discord could not parse a link from the output"
);
// Multiple occurrences, and the url scheme is unrestricted (case cannot evade).
assert.equal(
exposed.sanitizeFieldValue("[a](https://x.example) then [b](HTTPS://y.example)"),
"a (link: https://x.example) then b (link: HTTPS://y.example)"
);
// Empty link text stays transparent without minting visible link text.
assert.equal(exposed.sanitizeFieldValue("[](https://quiet.example)"), "(link: https://quiet.example)");
// Balanced nested brackets in the text are part of a CommonMark/Discord
// link (spec 0.31.2 Example 512): one nesting level gets the same
// transparent rewrite, deeper nesting and the other declined shapes are
// not left as links either — the final substring defuse breaks their ](
// adjacency (content preserved, one space added). Non-link markdown
// (bold/italic) is untouched.
assert.equal(exposed.sanitizeFieldValue("[a [b] c](https://x.example)"), "a [b] c (link: https://x.example)");
assert.equal(
exposed.sanitizeFieldValue("[[Server compromised — verify now]](https://evil.example)"),
"[Server compromised — verify now] (link: https://evil.example)",
"a doubly-bracketed label renders as a live CommonMark/Discord link and must be neutralized, not passed through"
);
assert.equal(
exposed.sanitizeFieldValue("[a [b [c]]](https://evil.example)"),
"[a [b [c]]] (https://evil.example)",
"two+ bracket levels decline the pattern; the final substring defuse must break the ]( adjacency — CommonMark renders the original clickable"
);
assert.equal(exposed.sanitizeFieldValue("[text](https://x.example"), "[text] (https://x.example");
assert.equal(exposed.sanitizeFieldValue("[text]()"), "[text] ()");
assert.equal(exposed.sanitizeFieldValue("[text](has space)"), "[text] (has space)");
assert.equal(exposed.sanitizeFieldValue("**bold** and _italic_"), "**bold** and _italic_");
// Non-link bracket usage passes through byte-identical.
assert.equal(exposed.sanitizeFieldValue("Array[0] (ok) and [1] ref"), "Array[0] (ok) and [1] ref");
assert.equal(exposed.sanitizeFieldValue("plain value"), "plain value");
// Order pin: neutralization runs BEFORE the 256-char cap — a value longer
// than the cap whose link pair completes past the cap must still come out
// non-clickable (cap-first would truncate the destination mid-url and leave
// "](" alive), and the truncated rewrite is ordinary plain-text truncation.
// A link that fits entirely keeps its url visible.
const long = `[${"t".repeat(300)}](https://evil.example)`;
const capped = exposed.sanitizeFieldValue(long);
assert.ok(capped.length <= 256, "the 256-char cap must still apply");
assert.ok(!capped.includes("]("), "a long link value must not survive truncation as raw link syntax");
const fitting = `${"p".repeat(200)} [see this](https://docs.example/guide)`;
assert.equal(
exposed.sanitizeFieldValue(fitting),
`${"p".repeat(200)} see this (link: https://docs.example/guide)`,
"a link that fits within the cap keeps its full neutralized form"
);
});
// adpanel:webhook-markdown-link-injection — review round on the neutralizer:
// (1) balanced-paren destinations are valid CommonMark links, so the url
// charset must accept one nesting level (unbalanced parens still decline the
// pattern — CommonMark renders those inert); (2) composition order: mention
// stripping rewrites "<@1>" into "[mention removed]" and control-char removal
// joins raw bytes, so both must run BEFORE the neutralizer or they mint/join
// a clickable pair after it; (3) an UNCONDITIONAL final substring defuse
// breaks every surviving "](" adjacency — the completeness backstop for
// every shape the pattern could not model, at any bracket-nesting depth (a
// bracket-bearing url rewrite strands "[b)](evil.example)" from the
// surrounding text, which CommonMark parses as a live link).
test("sanitizeFieldValue: balanced-paren urls, mention/control-char compositions, and the final ]( -free invariant", () => {
const { exposed } = freshModule();
// (1) A balanced-paren destination is a real clickable CommonMark link and
// must be neutralized, not left byte-identical.
assert.equal(
exposed.sanitizeFieldValue("[Free money](https://evil.example/claim(x))"),
"Free money (link: https://evil.example/claim(x))",
"a balanced-paren destination must be neutralized — CommonMark renders it clickable"
);
assert.equal(
exposed.sanitizeFieldValue("[t](a(b)c(d)e)"),
"t (link: a(b)c(d)e)",
"sibling balanced groups are one nesting level each and must be neutralized"
);
// Unbalanced parens still decline the pattern (CommonMark renders those
// inert), but nothing ships byte-identical with a live "](" adjacency: the
// final substring defuse breaks it, content-preserving.
assert.equal(
exposed.sanitizeFieldValue("[t](url(x)"),
"[t] (url(x)",
"an unbalanced destination cannot form a CommonMark link, but the final defuse still breaks the ]( adjacency"
);
// (2) Mention-strip composition: "<@1>(url)" used to mint
// "[mention removed](url)" AFTER the neutralizer ran — stripping now runs
// first, so the minted pair is itself neutralized.
assert.equal(
exposed.sanitizeFieldValue("<@1>(https://evil.example)"),
"mention removed (link: https://evil.example)",
"a mention rewritten into [text](url) shape must be neutralized, not minted clickable"
);
// (3) Control-char composition: a raw \x01 byte in a non-planner detail
// value used to be removed AFTER the neutralizer, joining "](" across the
// byte into a live pair.
assert.equal(
exposed.sanitizeFieldValue("[x]\x01(https://evil.example)"),
"x (link: https://evil.example)",
"a control char splitting a link pair must be joined BEFORE neutralization"
);
// (4) Final invariant: after ALL steps no "](" adjacency survives. The
// first pass rewrites "[t](a[b)" (bracket-bearing url) and strands the
// surrounding "](evil.example)" against the url's own "[" — CommonMark
// parses "[b)](evil.example)" as a live link; the unconditional final
// substring defuse breaks the ]( adjacency, content-preserving.
assert.equal(
exposed.sanitizeFieldValue("[t](a[b)](evil.example)"),
"t (link: a[b)] (evil.example)",
"an exotic stranded pair must be defused by the final invariant pass — ]( broken, content preserved"
);
// Bracket-in-url shapes: "[t](a](b)" declines the pattern (the "(" is
// consumed by the paren group, leaving no outer closer) and the final
// defuse breaks it; "[t](a](b)c)" IS rewritten (url = "a](b)c") and the
// rewrite itself carries a ]( adjacency — proof the defuse must run AFTER
// the rewrite, not instead of it.
assert.equal(
exposed.sanitizeFieldValue("[t](a](b)"),
"[t] (a] (b)",
"a declined bracket-in-url shape must still come out ]( -free"
);
assert.equal(
exposed.sanitizeFieldValue("[t](a](b)c)"),
"t (link: a] (b)c)",
"a rewrite whose url contains ]( must be broken by the final substring defuse"
);
// Corpus-level invariant: every shape this suite exercises must come out
// ]( -free. The pattern rewrite is presentation-quality for recognized
// shapes; the substring defuse is the security guarantee for everything
// else (any declined shape, any bracket-nesting depth).
const corpus = [
"[Server compromised — verify now](https://evil.example)",
"[click](https://evil.example)",
"[a](https://x.example) then [b](HTTPS://y.example)",
"[](https://quiet.example)",
"[a [b] c](https://x.example)",
"[[Server compromised — verify now]](https://evil.example)",
"[a [b [c]]](https://evil.example)",
"[[a](x](url)",
"[text](https://x.example",
"[text]()",
"[text](has space)",
"**bold** and _italic_",
"Array[0] (ok) and [1] ref",
"plain value",
`[${"t".repeat(300)}](https://evil.example)`,
`${"p".repeat(200)} [see this](https://docs.example/guide)`,
"[Free money](https://evil.example/claim(x))",
"[t](a(b)c(d)e)",
"[t](url(x)",
"<@1>(https://evil.example)",
"[x]\x01(https://evil.example)",
"[t](a[b)](evil.example)",
"[t](a](b)",
"[t](a](b)c)",
'{"a":"x](y"}',
];
for (const entry of corpus) {
const out = exposed.sanitizeFieldValue(entry);
assert.ok(!out.includes("]("), `no ]( may survive for ${JSON.stringify(entry)} (got ${JSON.stringify(out)})`);
}
// JSON-serialized details are defused too, and a space inside a JSON string
// keeps the serialization valid.
assert.equal(
exposed.sanitizeFieldValue({ a: "x](y" }),
'{"a":"x] (y"}',
"the defuse must reach inside JSON-serialized details without breaking the JSON"
);
});
test("initial panel open must wait for DOMContentLoaded wiring before loading data", () => {
// Regression: the settings bootstrap (first DOMContentLoaded handler) opened
// the initial panel synchronously, but window._loadWebhooks is assigned in
// a later DOMContentLoaded handler. Landing directly on the webhooks panel
// (saved panel / ?panel= / #hash) therefore skipped its data load and left
// the action tokens unminted (empty panel + 403 on first interaction). The
// bootstrap must yield to a macrotask before waitForSidebarAndOpen().
const settingsJs = fs.readFileSync(SETTINGS_JS, "utf8");
const bootstrapMarker = "await waitForSidebarAndOpen();";
const bootstrapIdx = settingsJs.indexOf(bootstrapMarker);
assert.ok(bootstrapIdx >= 0, "bootstrap must invoke waitForSidebarAndOpen");
const preamble = settingsJs.slice(Math.max(0, bootstrapIdx - 400), bootstrapIdx);
assert.ok(
preamble.includes("setTimeout(resolve") || preamble.includes("setTimeout(resolve,"),
"bootstrap must defer to a macrotask so later DOMContentLoaded handlers finish wiring"
);
const loadWebhooksAssignIdx = settingsJs.indexOf("window._loadWebhooks = loadWebhooks;");
assert.ok(loadWebhooksAssignIdx > bootstrapIdx, "webhooks wiring lives in a later handler; bootstrap must not outrun it");
});