"use strict"; // adpanel:webhook-sealing-key-override — pins for the Discord webhook URL // seal's key-input override. The finding: the AES-256-GCM key that seals // webhooks-config.json URLs (bearer secrets) was scrypt(SESSION_SECRET, // fixed-salt) inside index.js getWebhookSecretCipherKey with no independent // key env and no re-seal path, so rotating SESSION_SECRET made every stored // URL undecryptable — the load layer drops them with a warning and reads them // as "not configured", so the admin loses every configured webhook until each // is re-entered. The fix adds WEBHOOK_SEALING_KEY, mirroring the // TOTP_SEALING_KEY mechanics (env override || derived fallback), with ONE // hard invariant the pins below lock: // // - Unset/empty override → the KDF input is process.env.SESSION_SECRET, // BYTE-IDENTICAL to the pre-override algorithm (same scryptSync, same // WEBHOOK_SECRET_KDF_SALT, same 32-byte length, same default params): // every existing seal stays decryptable. Proven by cross-decryption // against an INDEPENDENTLY computed scrypt key — GCM tag verification // only succeeds under the exact key bytes, so a successful authenticated // open in BOTH directions is a key-equality proof, not a circumstantial // one (a param drift — cost, salt, length — breaks the cross-open). // - Set override → different key material; seal/open roundtrips succeed // only under the same override. // - NO fallback: a seal minted under one input can never be opened under // the other (decryptWebhookSecret returns null — read as "not // configured"; the ledger-pinned fail-closed posture, untouched by this // change). A wrong/rotated key must never fall back to any other // derivation; a silent fallback would convert key rotation/tampering // into a spam/phishing-channel repointing primitive. // - Source pins: the boot check routes WEBHOOK_SEALING_KEY through the ONE // shared requireStrongSecretOverride helper beside its siblings (same // 32-char floor, real helper body driven in a sandbox); the constraint // comment exists at BOTH the boot-check call and the derivation site; and // the sandboxed-slice typeof process guard is preserved (vm harnesses // evaluate this slice without a real process object). // // Harness: index.js boots servers on require, so the webhook crypto slice is // extracted and evaluated in a fresh vm context per derivation scenario (each // evaluation re-declares the module-scoped _webhookSecretKeyCache, so every // scenario derives from its own env) — the same technique as // tests/webhook-config-write-lock.test.js, but with a minimal crypto-only // slice. const test = require("node:test"); const assert = require("node:assert"); const crypto = require("node:crypto"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const ENC_PREFIX = "enc:v1:"; const SALT = "adpanel-webhook-secret-v1"; const SESSION_SECRET = "adpanel-webhook-sealing-test-session-secret-0123456789abcdef"; const OVERRIDE = "webhook-sealing-override-key-0123456789abcdef-zyxwvu"; const URL_PLAINTEXT = "https://discord.com/api/webhooks/123456789012345678/AbCdEf-gh_Ijklmnop"; const indexSource = fs.readFileSync(INDEX_JS, "utf8"); if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) { process.env.SESSION_SECRET = SESSION_SECRET; } 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}`); } // Extracts the REAL index.js webhook crypto slice exactly once; every // scenario evaluates it in a FRESH vm context (fresh key cache) under that // scenario's env. const CRYPTO_SLICE = (() => { const start = indexSource.indexOf("const WEBHOOK_SECRET_ENC_PREFIX"); const end = endIndexOfFunction(indexSource, "function decryptWebhookSecret"); assert.ok(start !== -1 && end !== -1 && start < end, "webhook crypto slice not found in index.js"); return indexSource.slice(start, end); })(); function freshModule(env, sandboxOverrides) { delete process.env.SESSION_SECRET; delete process.env.WEBHOOK_SEALING_KEY; for (const [name, value] of Object.entries(env || {})) { if (value !== undefined) process.env[name] = value; } const exposed = {}; const sandbox = Object.assign({ crypto, Buffer, // The REAL host process: the slice reads env through it, exactly like // tests/webhook-config-write-lock.test.js does. process, console: { log() { }, warn() { }, debug() { }, error() { } }, __exports: (obj) => Object.assign(exposed, obj), }, sandboxOverrides || {}); const context = vm.createContext(sandbox); vm.runInContext( `${CRYPTO_SLICE}\n;__exports({ WEBHOOK_SECRET_KDF_SALT, WEBHOOK_SECRET_ENC_PREFIX, isEncryptedWebhookSecretValue, encryptWebhookSecret, decryptWebhookSecret });`, context, { filename: "webhook-sealing-key-slice.js" } ); return exposed; } // Independent envelope machinery — deliberately NOT the code under test, so // the cross-decryption pins below compare against a from-scratch AES-256-GCM // implementation of the documented envelope format. function sealWithKey(key, plaintext) { const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv("aes-256-gcm", key, iv, { authTagLength: 16 }); const ct = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]); return `${ENC_PREFIX}${iv.toString("base64")}:${cipher.getAuthTag().toString("base64")}:${ct.toString("base64")}`; } function openWithKey(key, envelope) { const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":"); const decipher = crypto.createDecipheriv("aes-256-gcm", key, Buffer.from(ivB64, "base64"), { authTagLength: 16 }); decipher.setAuthTag(Buffer.from(tagB64, "base64")); return Buffer.concat([decipher.update(Buffer.from(ctB64, "base64")), decipher.final()]).toString("utf8"); } function derivedSessionKey() { // The pre-override algorithm, computed independently in the test. return crypto.scryptSync(SESSION_SECRET, SALT, 32); } test("unset override: the sealing key stays byte-identical to the pre-override derivation — scrypt(SESSION_SECRET, salt, 32)", () => { const mod = freshModule({ SESSION_SECRET }); const expectedKey = derivedSessionKey(); // Direction 1: a manual envelope under the independently computed key must // open through the shipped slice — GCM verification only passes under the // exact key bytes, so this proves the slice derived exactly that key. assert.strictEqual( mod.decryptWebhookSecret(sealWithKey(expectedKey, URL_PLAINTEXT)), URL_PLAINTEXT, "slice opens an envelope sealed with the independent pre-override key" ); // Direction 2: the slice's own seal must open under the independently // computed key — proving no other input (and no param drift) feeds the KDF. const sealed = mod.encryptWebhookSecret(URL_PLAINTEXT); assert.ok(mod.isEncryptedWebhookSecretValue(sealed)); assert.strictEqual( openWithKey(expectedKey, sealed), URL_PLAINTEXT, "the independent pre-override key opens the slice's seal" ); }); test("set override: seal+unseal roundtrip succeeds under the same override, with key material distinct from the SESSION_SECRET derivation", () => { const mod = freshModule({ SESSION_SECRET, WEBHOOK_SEALING_KEY: OVERRIDE }); const sealed = mod.encryptWebhookSecret(URL_PLAINTEXT); assert.ok(mod.isEncryptedWebhookSecretValue(sealed), "the seal is a v1 envelope"); assert.strictEqual(mod.decryptWebhookSecret(sealed), URL_PLAINTEXT, "roundtrip under the same override"); // Distinct material: the override-sealed envelope must NOT open under the // scrypt(SESSION_SECRET) key — the decipher fails authentication. assert.throws( () => openWithKey(derivedSessionKey(), sealed), "the override key material differs from the SESSION_SECRET derivation" ); // And the KDF input is the OVERRIDE, not the session secret: an // independently computed scrypt(OVERRIDE, salt, 32) key opens the seal. const overrideKey = crypto.scryptSync(OVERRIDE, SALT, 32); assert.strictEqual( mod.decryptWebhookSecret(sealWithKey(overrideKey, URL_PLAINTEXT)), URL_PLAINTEXT, "the slice derives from the override input" ); }); test("fail-closed: a seal minted under one derivation can NEVER be opened under the other (no fallback)", () => { // Sealed under the derived key (override unset)… const sealer = freshModule({ SESSION_SECRET }); const sealedDerived = sealer.encryptWebhookSecret(URL_PLAINTEXT); // …an override-keyed slice must fail CLOSED — null ("not configured"), // never the URL. const opener = freshModule({ SESSION_SECRET, WEBHOOK_SEALING_KEY: OVERRIDE }); assert.strictEqual( opener.decryptWebhookSecret(sealedDerived), null, "derived-key seal under the override decrypts to null (fail-closed, no fallback)" ); // And the reverse direction: sealed under the override… const sealedOverride = opener.encryptWebhookSecret(URL_PLAINTEXT); // …a derived-key slice must also fail closed. const derivedOpener = freshModule({ SESSION_SECRET }); assert.strictEqual( derivedOpener.decryptWebhookSecret(sealedOverride), null, "override seal under the derived key decrypts to null (fail-closed, no fallback)" ); }); test("empty-string override is treated exactly like unset, matching the boot check's `override !== \"\"` guard", () => { const unsetMod = freshModule({ SESSION_SECRET }); const sealed = unsetMod.encryptWebhookSecret(URL_PLAINTEXT); const emptyMod = freshModule({ SESSION_SECRET, WEBHOOK_SEALING_KEY: "" }); assert.strictEqual( emptyMod.decryptWebhookSecret(sealed), URL_PLAINTEXT, "an empty override keeps the SESSION_SECRET-derived key" ); // Same proof in the encryption direction: the empty-override slice's seal // opens under the independently computed pre-override key. assert.strictEqual(openWithKey(derivedSessionKey(), emptyMod.encryptWebhookSecret(URL_PLAINTEXT)), URL_PLAINTEXT); }); test("the fail-closed decrypt posture is untouched: a tampered envelope decrypts to null under either derivation", () => { const derived = freshModule({ SESSION_SECRET }); const override = freshModule({ SESSION_SECRET, WEBHOOK_SEALING_KEY: OVERRIDE }); const tamper = (envelope) => { const [ivB64, tagB64, ctB64] = envelope.slice(ENC_PREFIX.length).split(":"); const tag = Buffer.from(tagB64, "base64"); tag[0] ^= 0xff; return `${ENC_PREFIX}${ivB64}:${tag.toString("base64")}:${ctB64}`; }; assert.strictEqual(derived.decryptWebhookSecret(tamper(override.encryptWebhookSecret(URL_PLAINTEXT))), null); assert.strictEqual(override.decryptWebhookSecret(tamper(derived.encryptWebhookSecret(URL_PLAINTEXT))), null); }); test("the sandboxed-slice typeof guard is preserved: without a process object the slice evaluates but fails CLOSED on use", () => { // vm harnesses evaluate this slice WITHOUT a real process object (see // tests/webhook-dispatch-hardening.test.js) — the typeof guard must keep // module evaluation working there and keep the no-key path a loud // fail-closed throw, never a fallback derivation. const mod = freshModule({}, { process: undefined }); assert.strictEqual(mod.isEncryptedWebhookSecretValue("enc:v1:x:y:z"), true, "envelope format checks still work without process"); assert.throws( () => mod.encryptWebhookSecret(URL_PLAINTEXT), (err) => err && err.message.includes("webhook-secret-crypto: SESSION_SECRET is not set"), "without any key material the seal fails closed with the loud error" ); }); // ─── Source pins: boot-check wiring and constraint comments ─── test("source-pin: WEBHOOK_SEALING_KEY is checked through the shared boot-check helper beside its siblings", () => { const callAt = indexSource.indexOf('requireStrongSecretOverride("WEBHOOK_SEALING_KEY")'); assert.ok(callAt > -1, "WEBHOOK_SEALING_KEY must be checked through the shared helper"); const totpCallAt = indexSource.indexOf('requireStrongSecretOverride("TOTP_SEALING_KEY")'); assert.ok(callAt > totpCallAt, "WEBHOOK_SEALING_KEY sits beside the sibling calls"); const helperAt = indexSource.indexOf("function requireStrongSecretOverride(name)"); assert.ok(helperAt > -1, "the shared helper exists"); assert.strictEqual( indexSource.indexOf("function requireStrongSecretOverride(name)", helperAt + 1), -1, "the helper stays defined exactly once — the new override is a call, not a copy" ); assert.ok( indexSource.includes("adpanel:webhook-sealing-key-override"), "the constraint comment exists at the boot-check site" ); }); test("source-pin: the real helper body enforces the 32-char floor on WEBHOOK_SEALING_KEY (short → exit(1); unset/empty → legal)", () => { const helper = indexSource.slice( indexSource.indexOf("function requireStrongSecretOverride(name)"), endIndexOfFunction(indexSource, "function requireStrongSecretOverride(name)") ); const run = (env) => { const context = vm.createContext({ process: { env, exit: (code) => { throw new Error(`__exit__:${code}`); } }, console: { error: () => {} }, }); return vm.runInContext(`${helper}\nrequireStrongSecretOverride`, context); }; assert.doesNotThrow(() => run({ WEBHOOK_SEALING_KEY: "a".repeat(32) })("WEBHOOK_SEALING_KEY"), "32 chars must be accepted"); assert.throws(() => run({ WEBHOOK_SEALING_KEY: "a".repeat(31) })("WEBHOOK_SEALING_KEY"), (err) => err.message === "__exit__:1", "31 chars must exit(1)"); assert.doesNotThrow(() => run({})("WEBHOOK_SEALING_KEY"), "unset must stay legal (keeps the derived key)"); assert.doesNotThrow(() => run({ WEBHOOK_SEALING_KEY: "" })("WEBHOOK_SEALING_KEY"), "empty must stay legal (keeps the derived key)"); }); test("source-pin: the boot advisory fires only when the override is ACTIVE, after the boot check", () => { const advisoryAt = indexSource.indexOf("[config] WEBHOOK_SEALING_KEY override active"); assert.ok(advisoryAt > -1, "the boot advisory is present"); // Conscious pin update (advisory blast-radius amendment): the advisory now // names ALL THREE at-rest seals of the shared cipher, not just webhook // URLs — the original pin's fail-closed re-entry consequence is preserved // verbatim as the first clause, extended with the pgAdmin and MySQL // co-consumer consequences and the retained set-once guidance. assert.ok( indexSource.includes("can no longer be decrypted and are dropped until re-entered in Settings → Webhooks. The same cipher key also seals the pgAdmin bootstrap credentials — their reveal endpoint then answers 404 until pgAdmin recovery is re-run — and the MySQL dedicated admin credential, which its privileged bootstrap job re-provisions; both fail closed and self-heal. Set the override once and keep it stable"), "the advisory names the fail-closed re-entry consequence AND the full shared-cipher blast radius (webhook URLs, pgAdmin bootstrap credentials, MySQL dedicated admin credential)" ); const gateAt = indexSource.lastIndexOf("if (process.env.WEBHOOK_SEALING_KEY)", advisoryAt); assert.ok(gateAt > -1, "the advisory is gated on the override being set"); const bootCallAt = indexSource.indexOf('requireStrongSecretOverride("WEBHOOK_SEALING_KEY")'); assert.ok(gateAt > bootCallAt, "the advisory runs after the strength check (a short override exits before any advisory)"); }); test("source-pin: the derivation site changes only the KDF input and keeps the sandboxed-slice typeof guard", () => { assert.strictEqual( indexSource.split("process.env.WEBHOOK_SEALING_KEY || process.env.SESSION_SECRET").length - 1, 1, "exactly ONE derivation site — the ||-fallback replaces the bare SESSION_SECRET read" ); assert.ok( indexSource.includes('typeof process !== "undefined" ? String(process.env.WEBHOOK_SEALING_KEY || process.env.SESSION_SECRET || "") : ""'), "the typeof guard survives: sandboxed vm evaluations of this slice run without a real process object" ); assert.ok( indexSource.includes("adpanel:webhook-sealing-key-override"), "the constraint comment exists at the derivation site" ); assert.ok( indexSource.includes('const WEBHOOK_SECRET_KDF_SALT = "adpanel-webhook-secret-v1";'), "the webhook-specific salt is pinned" ); assert.ok( indexSource.includes("_webhookSecretKeyCache = crypto.scryptSync(secret, WEBHOOK_SECRET_KDF_SALT, 32)"), "the KDF call keeps its salt and 32-byte length" ); });