"use strict"; // Tests for audit finding P3.1: read-modify-write race on webhooks-config.json. // // The POST/DELETE /api/settings/webhooks handlers ran load → mutate → save // with no locking, and the load could happen long before the save (the // step-up auth between them awaits). Two concurrent administrative // modifications — or two pm2 cluster workers, since the generated ecosystem // scales instances with CPU cores — could overwrite each other and silently // drop one update. // // Remediation contract locked here: // - Write cycles run through withWebhooksConfigWriteLock: an in-process // FIFO queue plus a cross-process lock file (atomic O_EXCL create). // - The mutation is applied to a fresh from-disk read // (loadWebhooksConfigFresh), never to the 500ms read cache, so a save // that landed while this request awaited its step-up is preserved. // - Contention fails closed (lock timeout), never an unlocked fallback. // - Locks held by dead workers (pm2 SIGKILL, OOM) are stolen via the owner // PID plus its recorded process start time: a recycled PID (alive process, // different start ticks) and unreaped zombies are detected immediately // instead of reading as "alive" until the hard age TTL, which stays the // last resort and the fail-safe direction for every ambiguous case. // - release() never unlinks a lock this writer does not own. // // Audit 2026-09-06 update — webhook secrets are now encrypted at rest // (enc:v1::: envelopes, key scrypt-derived from SESSION_SECRET): // - Disk assertions compare through decryptWebhookSecret instead of // matching plaintext; a raw-disk check additionally asserts the URL // never appears in the file at all. // - saveWebhooksConfig encrypts before any file I/O; without key material // it fails closed (no file written, save reports false). // - The boot migration rewrites legacy plaintext files under the same // write lock; loads accept legacy plaintext until then. // // 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 // webhook-dispatch-hardening.test.js). Unlike that suite, these tests run // the real file layer inside a temp directory via __dirname. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const vm = require("node:vm"); const crypto = require("node:crypto"); const childProcess = require("node:child_process"); const INDEX_JS = path.join(__dirname, "..", "index.js"); const CANONICAL_URL = "https://discord.com/api/webhooks/123456789012345678/AbCdEf-gh_Ijklmnop"; 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}`); } function buildLockedWebhookModule(existingTmpDir) { // The slice reads the real process.env: production requires SESSION_SECRET // (index.js exits without it), so the encryption layer is allowed to demand // it. Provide a deterministic test value when the runner has none. if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) { process.env.SESSION_SECRET = "adpanel-webhook-lock-test-secret-0123456789abcdef"; } const source = fs.readFileSync(INDEX_JS, "utf8"); const slice = source.slice( source.indexOf("const WEBHOOKS_CONFIG_PATH"), endIndexOfFunction(source, "function dispatchWebhookForActivity") ); for (const marker of [ "loadWebhooksConfigFresh", "withWebhooksConfigWriteLock", "acquireWebhooksConfigFileLock", "releaseWebhooksConfigFileLock", ]) { assert.ok(slice.includes(marker), `slice must contain ${marker}`); } const tmpDir = existingTmpDir || fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-webhook-lock-")); const exposed = {}; const errors = []; const warnings = []; const sandbox = { fs, path, crypto, process, Buffer, Date, Set, Map, console: { log() { }, warn: (...args) => warnings.push(args.join(" ")), debug() { }, error: (...args) => errors.push(args.join(" ")) }, setInterval: () => ({ unref() { } }), setTimeout, clearTimeout, AbortController, fetch: async () => ({ ok: true, status: 200, headers: { get: () => null } }), __dirname: tmpDir, __exports: (obj) => Object.assign(exposed, obj), }; const context = vm.createContext(sandbox); vm.runInContext( `${slice}\n;__exports({ WEBHOOKS_CONFIG_PATH, VALID_CATEGORY_IDS, WEBHOOKS_LOCK_STALE_MS, WEBHOOK_SECRET_ENC_PREFIX, sanitizeWebhooksConfig, loadWebhooksConfig, loadWebhooksConfigFresh, saveWebhooksConfig, withWebhooksConfigWriteLock, acquireWebhooksConfigFileLock, releaseWebhooksConfigFileLock, encryptWebhookSecret, decryptWebhookSecret, isEncryptedWebhookSecretValue, migrateWebhooksConfigToEncryptedAtRest, WEBHOOK_CARRIED_SEALED_ENVELOPES, webhooksConfigHasCarriedEnvelope, forgetCarriedWebhookEnvelope, writeCategory: (categoryId, url) => withWebhooksConfigWriteLock(() => { // Mirrors the POST /api/settings/webhooks critical section: fresh // read, mutate, save — fully synchronous. const config = loadWebhooksConfigFresh(); if (!config.multiple) config.multiple = Object.create(null); config.multiple[categoryId] = url; return saveWebhooksConfig(config); }), saveSingle: (url) => withWebhooksConfigWriteLock(() => { const config = loadWebhooksConfigFresh(); config.single = url; return saveWebhooksConfig(config); }), saveFallback: (fallbackToSingle) => withWebhooksConfigWriteLock(() => { // Mirrors the POST route's non-URL mutation branch (mode/fallback // change only): fresh read, mutate, save — no URL re-entry. const config = loadWebhooksConfigFresh(); config.fallbackToSingle = fallbackToSingle; return saveWebhooksConfig(config); }), deleteCategory: (categoryId) => withWebhooksConfigWriteLock(() => { // Mirrors the DELETE /api/settings/webhooks critical section for a // category, including the adpanel:webhook-envelope-preservation // carried-envelope awareness (an undecryptable target reads as // unconfigured in memory but stays deletable by id). const config = loadWebhooksConfigFresh(); // (Plain string concat: this whole export block is itself a template // literal — an inner backtick template would terminate it.) if (!(config.multiple && config.multiple[categoryId]) && !webhooksConfigHasCarriedEnvelope(config, "multiple:" + categoryId)) return { notFound: true }; if (config.multiple) delete config.multiple[categoryId]; forgetCarriedWebhookEnvelope(config, "multiple:" + categoryId); return saveWebhooksConfig(config) ? { config } : null; }), deleteSingle: () => withWebhooksConfigWriteLock(() => { // Mirrors the DELETE route for the single target, same carried // awareness. const config = loadWebhooksConfigFresh(); if (!config.single && !webhooksConfigHasCarriedEnvelope(config, "single")) return { notFound: true }; config.single = null; forgetCarriedWebhookEnvelope(config, "single"); return saveWebhooksConfig(config) ? { config } : null; }), testSetCache: (value) => { _webhooksConfigCache = value; _webhooksConfigCacheMtime = -1; _webhooksConfigCacheLastCheck = Date.now(); }, });`, context, { filename: "webhook-lock-slice.js" } ); exposed.readConfigFromDisk = () => JSON.parse(fs.readFileSync(path.join(tmpDir, "webhooks-config.json"), "utf8")); exposed.configPath = path.join(tmpDir, "webhooks-config.json"); exposed.lockPath = path.join(tmpDir, "webhooks-config.json.lock"); exposed.writeLockFile = (owner) => fs.writeFileSync(exposed.lockPath, JSON.stringify(owner), "utf8"); exposed.readLockFile = () => JSON.parse(fs.readFileSync(exposed.lockPath, "utf8")); exposed.lockFileExists = () => fs.existsSync(exposed.lockPath); exposed.tmpDir = tmpDir; exposed.errors = errors; exposed.warnings = warnings; return exposed; } async function spawnDeadPid() { const child = childProcess.spawn(process.execPath, ["-e", ""], { stdio: "ignore" }); await new Promise((resolve) => child.on("exit", resolve)); return child.pid; } // Start-ticks detection (PID recycle / zombie owners) is /proc-backed; on // platforms without a readable /proc the kill(2) fallback governs and these // tests have nothing to assert. const canReadProc = (() => { try { fs.readFileSync("/proc/self/stat", "utf8"); return true; } catch (_) { return false; } })(); function readProcStartTicks(pid) { const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8"); // Field 2 (comm) may contain spaces/parens; after the last ")", fields start // at field 3 (state), so starttime (field 22) sits at index 19. const fields = stat.slice(stat.lastIndexOf(")") + 2).trim().split(" "); return Number(fields[19]); } async function withModule(fn) { const mod = buildLockedWebhookModule(); try { await fn(mod); } finally { fs.rmSync(mod.tmpDir, { recursive: true, force: true }); } } // Asserts a stored-at-rest value is a well-formed sealed envelope // (enc:v1:::, all base64) — i.e. the plaintext URL never // reached the disk in any recognizable form. function assertEncryptedEnvelope(mod, value, label) { assert.ok( typeof value === "string" && value.startsWith(mod.WEBHOOK_SECRET_ENC_PREFIX), `${label} must be stored as an encrypted envelope` ); const parts = value.slice(mod.WEBHOOK_SECRET_ENC_PREFIX.length).split(":"); assert.equal(parts.length, 3, `${label} envelope must be iv:tag:ciphertext`); for (const part of parts) { assert.ok(part.length > 0 && /^[A-Za-z0-9+/=]+$/.test(part), `${label} envelope parts must be base64`); } } test("P3.1: a write cycle applies its mutation on top of the current on-disk state, not the stale read cache", async () => { await withModule(async (mod) => { // Another worker saved category A to disk after this worker's 500ms read // cache was populated — the cache is now a stale snapshot missing A. The // file deliberately holds LEGACY PLAINTEXT values: this exercises the // decrypt-on-load pass-through for pre-migration files too. const diskState = mod.sanitizeWebhooksConfig({ mode: "multiple", multiple: { server_create: CANONICAL_URL }, }); fs.writeFileSync(mod.configPath, JSON.stringify(diskState), "utf8"); mod.testSetCache(mod.sanitizeWebhooksConfig({ mode: "single" })); // The pre-fix flow mutated the cached snapshot and saved it back, which // dropped the other worker's category. The locked fresh-read cycle must // land its mutation on top of the on-disk state instead. const ok = await mod.writeCategory("server_delete", CANONICAL_URL); assert.equal(ok, true, "the locked write cycle must succeed"); const final = mod.readConfigFromDisk(); assert.equal( mod.decryptWebhookSecret(final.multiple.server_create), CANONICAL_URL, "the other worker's category must survive" ); assert.equal( mod.decryptWebhookSecret(final.multiple.server_delete), CANONICAL_URL, "this writer's category must be applied" ); assert.equal(final.mode, "multiple"); }); }); test("P3.1: concurrent write cycles all persist — no lost updates", async () => { await withModule(async (mod) => { const categories = [...mod.VALID_CATEGORY_IDS].slice(0, 10); const lockSeenDuringSection = { value: false }; // One writer must observe the lock file present while its section runs, // proving the cross-process lock (not just the queue) is held. const probeCycle = mod.withWebhooksConfigWriteLock(() => { lockSeenDuringSection.value = mod.lockFileExists(); const config = mod.loadWebhooksConfigFresh(); if (!config.multiple) config.multiple = Object.create(null); config.multiple.server_create = CANONICAL_URL; return mod.saveWebhooksConfig(config); }); const others = categories.slice(1).map((id) => mod.writeCategory(id, CANONICAL_URL)); await Promise.all([probeCycle, ...others]); assert.equal(lockSeenDuringSection.value, true, "the lock file must exist inside the critical section"); const final = mod.readConfigFromDisk(); for (const id of categories) { assert.equal( mod.decryptWebhookSecret(final.multiple[id]), CANONICAL_URL, `category ${id} must have survived the concurrency` ); } assert.equal(mod.lockFileExists(), false, "the lock file must be released after all writers finish"); }); }); // --- Audit 2026-09-06: webhook secrets encrypted at rest --------------------- test("at rest: saved URLs are sealed envelopes, never plaintext, and round-trip decrypt", async () => { await withModule(async (mod) => { const ok = await mod.saveSingle(CANONICAL_URL); assert.equal(ok, true, "the save must succeed"); const rawDisk = fs.readFileSync(mod.configPath, "utf8"); assert.ok(!rawDisk.includes("discord.com"), "the raw disk file must not contain the webhook host in plaintext"); assert.ok(!rawDisk.includes("AbCdEf"), "the raw disk file must not contain the webhook token in plaintext"); const stored = mod.readConfigFromDisk(); assertEncryptedEnvelope(mod, stored.single, "single webhook URL"); assert.notEqual(stored.single, CANONICAL_URL, "the ciphertext must not equal the plaintext URL"); // In-memory round trip: the config layer hands the plaintext back. assert.equal(mod.loadWebhooksConfigFresh().single, CANONICAL_URL, "a fresh load must decrypt the URL back"); assert.equal(mod.loadWebhooksConfig().single, CANONICAL_URL, "the cached load must decrypt the URL back"); // GCM nonces: re-saving the same URL must produce a different envelope // (fresh random IV per write), so identical secrets are not linkable // across rewrites. await mod.saveSingle(CANONICAL_URL); const resaved = mod.readConfigFromDisk(); assertEncryptedEnvelope(mod, resaved.single, "re-saved single webhook URL"); assert.notEqual(resaved.single, stored.single, "each write must seal with a fresh IV"); assert.equal(mod.decryptWebhookSecret(resaved.single), CANONICAL_URL, "the re-sealed value must decrypt back"); }); }); test("at rest: the boot migration rewrites a legacy plaintext file under the lock, idempotently", async () => { await withModule(async (mod) => { // Pre-migration state exactly as old panels wrote it. const legacy = mod.sanitizeWebhooksConfig({ mode: "multiple", fallbackToSingle: false, single: CANONICAL_URL, multiple: { server_start: CANONICAL_URL }, }); fs.writeFileSync(mod.configPath, JSON.stringify(legacy), "utf8"); // Legacy plaintext must keep working BEFORE the migration runs (the // panel may boot with the new code before the migration has happened). assert.equal(mod.loadWebhooksConfig().single, CANONICAL_URL, "legacy plaintext must load until migrated"); await mod.migrateWebhooksConfigToEncryptedAtRest(); const stored = mod.readConfigFromDisk(); assertEncryptedEnvelope(mod, stored.single, "migrated single webhook URL"); assertEncryptedEnvelope(mod, stored.multiple.server_start, "migrated category webhook URL"); assert.equal(mod.decryptWebhookSecret(stored.single), CANONICAL_URL, "the migrated single URL must decrypt back"); assert.equal(mod.decryptWebhookSecret(stored.multiple.server_start), CANONICAL_URL, "the migrated category URL must decrypt back"); assert.equal(stored.mode, "multiple", "migration must preserve the mode"); assert.equal(stored.fallbackToSingle, false, "migration must preserve fallbackToSingle"); // Idempotent: a second boot reads ciphertext only and must not rewrite // (the envelopes keep their original IVs). await mod.migrateWebhooksConfigToEncryptedAtRest(); const afterSecondBoot = mod.readConfigFromDisk(); assert.equal(afterSecondBoot.single, stored.single, "the second migration run must be a no-op"); assert.equal(mod.loadWebhooksConfigFresh().multiple.server_start, CANONICAL_URL, "config stays usable after migration"); }); }); test("at rest: an undecryptable envelope is dropped and read as unconfigured, not a crash", async () => { await withModule(async (mod) => { // A well-formed envelope that fails GCM verification — exactly what a // SESSION_SECRET rotation leaves behind, or a tampered row. const corrupt = `${mod.WEBHOOK_SECRET_ENC_PREFIX}AAAAAA==:AAAAAAAAAAAAAAAAAAAAAA==:AAAAAAAAAA==`; fs.writeFileSync(mod.configPath, JSON.stringify({ mode: "single", fallbackToSingle: true, single: corrupt, multiple: {}, }), "utf8"); const config = mod.loadWebhooksConfigFresh(); assert.equal(config.single, null, "the undecryptable entry must be treated as unconfigured"); assert.equal(config.mode, "single", "the rest of the config must survive"); const cached = mod.loadWebhooksConfig(); assert.equal(cached.single, null, "the cached load must agree"); }); }); test("at rest: saving without key material fails closed and writes nothing", async () => { await withModule(async (mod) => { // Fresh module context: no key has been derived yet in this slice, so // removing the env var makes the sealing step unavailable. The save must // refuse rather than write plaintext (production exits at boot without // SESSION_SECRET, so this only guards degraded environments). const prevSecret = process.env.SESSION_SECRET; delete process.env.SESSION_SECRET; try { const ok = await mod.withWebhooksConfigWriteLock(() => { const config = mod.loadWebhooksConfigFresh(); config.single = CANONICAL_URL; return mod.saveWebhooksConfig(config); }); assert.equal(ok, false, "the save must fail closed without key material"); assert.ok(!fs.existsSync(mod.configPath), "no config file may be written when encryption is unavailable"); assert.ok(!fs.readdirSync(mod.tmpDir).some((f) => f.endsWith(".tmp")), "no tmp file may be left behind"); } finally { process.env.SESSION_SECRET = prevSecret; } }); }); test("lock lifecycle: acquire creates an owner-stamped lock file, release removes it", async () => { await withModule(async (mod) => { const token = await mod.acquireWebhooksConfigFileLock(); assert.ok(mod.lockFileExists(), "the lock file must exist while held"); const owner = mod.readLockFile(); assert.equal(owner.pid, process.pid); assert.equal(owner.token, token); assert.ok(Number.isFinite(owner.acquiredAt) && Date.now() - owner.acquiredAt < 5000); mod.releaseWebhooksConfigFileLock(token); assert.equal(mod.lockFileExists(), false, "release must remove the lock file"); }); }); test("contention fails closed: a live foreign lock rejects the acquisition instead of writing unlocked", async () => { await withModule(async (mod) => { mod.writeLockFile({ pid: process.pid, token: "foreign-writer", acquiredAt: Date.now() }); await assert.rejects( () => mod.acquireWebhooksConfigFileLock(120), (err) => { assert.equal(err.code, "WEBHOOKS_LOCK_TIMEOUT"); return true; } ); assert.equal(mod.readLockFile().token, "foreign-writer", "the foreign lock must be left untouched"); }); }); test("a lock orphaned by a dead process is stolen promptly (pm2 SIGKILL recovery)", async () => { await withModule(async (mod) => { const deadPid = await spawnDeadPid(); mod.writeLockFile({ pid: deadPid, token: "dead-writer", acquiredAt: Date.now() }); const token = await mod.acquireWebhooksConfigFileLock(); assert.equal(mod.readLockFile().token, token, "the dead writer's lock must have been stolen"); mod.releaseWebhooksConfigFileLock(token); }); }); test("lock acquisition records the owner's real start ticks, and a matching live owner is never stolen from", async () => { if (!canReadProc) return; await withModule(async (mod) => { const token = await mod.acquireWebhooksConfigFileLock(); const owner = mod.readLockFile(); assert.ok(Number.isFinite(owner.startTicks), "the lock must record the owner's start ticks on /proc platforms"); assert.equal(owner.startTicks, readProcStartTicks(process.pid), "the recorded start ticks must be the acquirer's real ones"); // A concurrent acquirer must wait the live owner out, not steal: same PID, // same start ticks, fresh lock. await assert.rejects( () => mod.acquireWebhooksConfigFileLock(120), (err) => { assert.equal(err.code, "WEBHOOKS_LOCK_TIMEOUT"); return true; }, "a live owner with matching start ticks must hold the lock" ); assert.equal(mod.readLockFile().token, token, "the live owner's lock must be untouched"); mod.releaseWebhooksConfigFileLock(token); }); }); test("a lock whose recorded start ticks no longer match its PID is stolen (PID recycle recovery)", async () => { if (!canReadProc) return; await withModule(async (mod) => { // Same (alive) PID, different start ticks than recorded: exactly what a // recycled PID looks like. The old kill(pid, 0) probe answered success // here (same uid) and read the lock as alive until the hard TTL. mod.writeLockFile({ pid: process.pid, token: "recycled-owner", acquiredAt: Date.now(), startTicks: readProcStartTicks(process.pid) + 1000, }); const token = await mod.acquireWebhooksConfigFileLock(); assert.equal(mod.readLockFile().token, token, "the recycled-PID lock must be stolen promptly"); mod.releaseWebhooksConfigFileLock(token); }); }); test("a live foreign process holding the lock with matching start ticks is not stolen from", async () => { if (!canReadProc) return; await withModule(async (mod) => { const child = childProcess.spawn(process.execPath, ["-e", "setInterval(() => {}, 250)"], { stdio: "ignore" }); try { let ticks = NaN; for (let i = 0; i < 100 && !Number.isFinite(ticks); i += 1) { try { ticks = readProcStartTicks(child.pid); } catch (_) { } if (!Number.isFinite(ticks)) await new Promise((resolve) => setTimeout(resolve, 20)); } assert.ok(Number.isFinite(ticks), "the child must be visible in /proc"); // A foreign lock that is genuinely alive: kill(pid, 0) succeeds AND the // start ticks match what the owner recorded. No premature steal. mod.writeLockFile({ pid: child.pid, token: "live-foreign-owner", acquiredAt: Date.now(), startTicks: ticks }); await assert.rejects( () => mod.acquireWebhooksConfigFileLock(120), (err) => { assert.equal(err.code, "WEBHOOKS_LOCK_TIMEOUT"); return true; }, "a live foreign owner with matching start ticks must hold the lock" ); assert.equal(mod.readLockFile().token, "live-foreign-owner", "the live foreign lock must be untouched"); } finally { child.kill("SIGKILL"); } }); }); test("a lock past the hard age TTL is stolen even from a live-looking owner", async () => { await withModule(async (mod) => { mod.writeLockFile({ pid: process.pid, // alive (this test process), but the lock is ancient token: "wedged-writer", acquiredAt: Date.now() - mod.WEBHOOKS_LOCK_STALE_MS - 1000, }); const token = await mod.acquireWebhooksConfigFileLock(); assert.equal(mod.readLockFile().token, token, "the wedged writer's lock must have been stolen"); mod.releaseWebhooksConfigFileLock(token); }); }); test("a half-written (empty) lock file is never stolen — the acquirer waits the owner out", async () => { await withModule(async (mod) => { // Reproduces the create/content window: openSync('wx') makes the lock // file visible before its owner info is written. A concurrent acquirer // that read the empty file as "stale garbage" would steal the lock and // break mutual exclusion between the two writers. fs.writeFileSync(mod.lockPath, "", "utf8"); // empty = owner info not yet written await assert.rejects( () => mod.acquireWebhooksConfigFileLock(120), (err) => { assert.equal(err.code, "WEBHOOKS_LOCK_TIMEOUT"); return true; }, "a fresh unreadable lock must be treated as held, not stolen" ); // Once the garbage ages past the TTL (self-heal path for a writer that // died between create and write), it is stolen via the file mtime. const ancient = new Date(Date.now() - mod.WEBHOOKS_LOCK_STALE_MS - 1000); fs.utimesSync(mod.lockPath, ancient, ancient); const token = await mod.acquireWebhooksConfigFileLock(); assert.equal(mod.readLockFile().token, token, "aged-out garbage must be stolen"); mod.releaseWebhooksConfigFileLock(token); }); }); test("release never removes a lock this writer does not own", async () => { await withModule(async (mod) => { mod.writeLockFile({ pid: process.pid, token: "foreign-writer", acquiredAt: Date.now() }); mod.releaseWebhooksConfigFileLock("not-the-owner"); assert.equal(mod.lockFileExists(), true, "a foreign lock must survive someone else's release call"); assert.equal(mod.readLockFile().token, "foreign-writer"); }); }); // --- adpanel:webhook-envelope-preservation (2026-11 campaign) ---------------- // // The 2026-09-06 at-rest rewrite had a collateral data-loss path: every file // write serialized the SANITIZED in-memory config, and a load that could not // decrypt an envelope (rotated/wrong sealing key, hand edit, backup restore) // had already dropped that target from memory — so the boot migration (which // rewrites when a fresh parse saw ANY legacy plaintext) and every admin save // permanently destroyed the coexisting undecryptable envelope. The webhook // URL is a bearer secret with no re-derivation path: irreversible operator // data loss on a legitimate path. // // Remediation locked here (NEVER DOWNGRADE CIPHERTEXT): // - A fresh parse keeps the raw on-disk envelope of every target the // current key cannot open aside (non-enumerable Symbol on the returned // config object — the in-memory/HTTP shape is unchanged) and every file // rewrite re-emits those envelopes verbatim, unless the admin explicitly // re-entered that target (a fresh seal under the current key replaces the // carried envelope) or deleted it (delete-by-id works even though the UI // cannot display the target — the documented escape hatch). // - Migration semantics for legacy plaintext are byte-identical to the // 2026-09-06 fix; only its collateral destruction of coexisting // undecryptable envelopes is closed. // // Cross-key fixtures build several modules on ONE temp dir; each vm context // derives and caches its own key at first use, so the env must hold the // intended key input during every operation of a given module (operations are // strictly sequenced per module below). const WRONG_SEALING_OVERRIDE = "adpanel-envelope-preservation-wrong-key-0123456789abcdef"; // A well-formed envelope that fails GCM verification under any key used here — // exactly what a rotated key, a hand edit or a backup restore leaves behind. const UNDECRYPTABLE_ENVELOPE = "enc:v1:AAAAAA==:AAAAAAAAAAAAAAAAAAAAAA==:AAAAAAAAAA=="; test("preservation: a mixed file migrates its legacy plaintext AND carries the undecryptable envelope byte-identically", async () => { await withModule(async (mod) => { fs.writeFileSync(mod.configPath, JSON.stringify({ mode: "multiple", fallbackToSingle: false, single: UNDECRYPTABLE_ENVELOPE, multiple: { server_start: CANONICAL_URL }, }), "utf8"); await mod.migrateWebhooksConfigToEncryptedAtRest(); const stored = mod.readConfigFromDisk(); assert.equal(stored.single, UNDECRYPTABLE_ENVELOPE, "the undecryptable envelope must be carried verbatim, byte-identical"); assertEncryptedEnvelope(mod, stored.multiple.server_start, "migrated category webhook URL"); assert.equal(mod.decryptWebhookSecret(stored.multiple.server_start), CANONICAL_URL, "the legacy plaintext beside it must still be migrated to a working seal"); assert.equal(stored.mode, "multiple", "migration must preserve the mode"); assert.equal(stored.fallbackToSingle, false, "migration must preserve fallbackToSingle"); // The carried target still reads as "not configured" in memory — the // in-memory/HTTP representation is unchanged by preservation — while the // raw envelope rides on the parsed config object for the next rewrite, // hidden from every plain-shape consumer. const config = mod.loadWebhooksConfigFresh(); assert.equal(config.single, null, "the carried target must stay unconfigured in memory"); assert.equal(config.multiple.server_start, CANONICAL_URL); assert.equal(Object.keys(config).length, 4, "no carried state may leak into the enumerable config shape"); assert.ok(!JSON.stringify(config).includes("enc:v1:"), "no envelope may leak into a JSON serialization of the config"); assert.equal(mod.webhooksConfigHasCarriedEnvelope(config, "single"), true, "the carried envelope rides on the parsed config object"); }); }); test("preservation: an undecryptable-only file is not migrated — the rewrite still fires only on legacy plaintext", async () => { await withModule(async (mod) => { fs.writeFileSync(mod.configPath, JSON.stringify({ mode: "single", fallbackToSingle: true, single: UNDECRYPTABLE_ENVELOPE, multiple: {}, }), "utf8"); const before = fs.readFileSync(mod.configPath, "utf8"); await mod.migrateWebhooksConfigToEncryptedAtRest(); assert.equal( fs.readFileSync(mod.configPath, "utf8"), before, "without legacy plaintext the migration must not rewrite the file at all (2026-09-06 semantics unchanged)" ); }); }); test("preservation: an admin save under a rotated key carries every undecryptable envelope it loaded", async () => { await withModule(async (mod) => { // Sealed under the module's (correct) key. assert.equal(await mod.saveSingle(CANONICAL_URL), true); assert.equal(await mod.writeCategory("server_create", CANONICAL_URL), true); const before = mod.readConfigFromDisk(); // Simulate the rotation: a worker deriving its key from a different // input can no longer open either envelope — both read as unconfigured. process.env.WEBHOOK_SEALING_KEY = WRONG_SEALING_OVERRIDE; try { const rotated = buildLockedWebhookModule(mod.tmpDir); assert.equal(rotated.loadWebhooksConfigFresh().single, null, "the rotated key reads the single target as unconfigured"); assert.equal(rotated.loadWebhooksConfigFresh().multiple.server_create, undefined, "the rotated key reads the category target as unconfigured"); // An admin save that does NOT re-enter any URL (mode/fallback change // only) must not destroy what it cannot read. assert.equal(await rotated.saveFallback(false), true, "the save must succeed"); const after = rotated.readConfigFromDisk(); assert.equal(after.single, before.single, "the undecryptable single envelope must be carried verbatim"); assert.equal(after.multiple.server_create, before.multiple.server_create, "the undecryptable category envelope must be carried verbatim"); assert.equal(after.fallbackToSingle, false, "the admin's own change must still land"); assert.ok( rotated.warnings.some((w) => w.includes("Preserved the sealed webhook entry") && w.includes('"single"')), "the save must advise the operator that the file still holds seals the current key cannot open" ); } finally { delete process.env.WEBHOOK_SEALING_KEY; } }); }); test("preservation: restoring the correct sealing key revives the carried envelope as a configured webhook", async () => { await withModule(async (mod) => { assert.equal(await mod.saveSingle(CANONICAL_URL), true); const before = mod.readConfigFromDisk(); process.env.WEBHOOK_SEALING_KEY = WRONG_SEALING_OVERRIDE; try { const rotated = buildLockedWebhookModule(mod.tmpDir); assert.equal(await rotated.saveFallback(false), true, "the rotated-key save preserves the envelope"); assert.equal(rotated.readConfigFromDisk().single, before.single, "carried verbatim through the rotated save"); } finally { delete process.env.WEBHOOK_SEALING_KEY; } // The correct key returns (same SESSION_SECRET derivation as mod): the // preserved envelope decrypts again and the target is configured — with // NO admin action, and a mere load must not rewrite the file. const revived = buildLockedWebhookModule(mod.tmpDir); const config = revived.loadWebhooksConfigFresh(); assert.equal(config.single, CANONICAL_URL, "the carried envelope must revive under the correct key"); assert.equal(revived.readConfigFromDisk().single, before.single, "a mere load must not rewrite the file"); }); }); test("preservation: explicitly re-entering the URL under the current key replaces the carried envelope", async () => { await withModule(async (mod) => { assert.equal(await mod.saveSingle(CANONICAL_URL), true); const before = mod.readConfigFromDisk(); process.env.WEBHOOK_SEALING_KEY = WRONG_SEALING_OVERRIDE; try { const rotated = buildLockedWebhookModule(mod.tmpDir); assert.equal(await rotated.saveFallback(false), true); // carries the envelope // Re-entry: the admin pastes the URL again (the UI shows the target as // unconfigured under the wrong key). The fresh seal under the CURRENT // key must replace the carried envelope. assert.equal(await rotated.saveSingle(CANONICAL_URL), true); const after = rotated.readConfigFromDisk(); assert.notEqual(after.single, before.single, "the fresh seal must replace the carried envelope"); assert.equal(rotated.decryptWebhookSecret(after.single), CANONICAL_URL, "the replacement must be usable under the current key"); assert.equal( rotated.webhooksConfigHasCarriedEnvelope(rotated.loadWebhooksConfigFresh(), "single"), false, "the replaced target is no longer carried" ); } finally { delete process.env.WEBHOOK_SEALING_KEY; } }); }); test("preservation: delete-by-id removes a carried envelope the panel cannot display", async () => { await withModule(async (mod) => { assert.equal(await mod.saveSingle(CANONICAL_URL), true); assert.equal(await mod.writeCategory("server_create", CANONICAL_URL), true); const before = mod.readConfigFromDisk(); process.env.WEBHOOK_SEALING_KEY = WRONG_SEALING_OVERRIDE; try { const rotated = buildLockedWebhookModule(mod.tmpDir); assert.equal(await rotated.saveFallback(false), true); // both envelopes carried // The category reads as unconfigured in memory, yet the delete by id // must land — a 404 here would make the preserved envelope an // unremovable tombstone. const deletedCategory = await rotated.deleteCategory("server_create"); assert.ok(deletedCategory && !deletedCategory.notFound, "delete-by-id must work for a carried (undisplayable) target"); const afterCategoryDelete = rotated.readConfigFromDisk(); assert.equal(afterCategoryDelete.multiple.server_create, undefined, "the deleted carried envelope must be gone from disk"); assert.equal(afterCategoryDelete.single, before.single, "an untouched carried envelope must survive the delete cycle"); const deletedSingle = await rotated.deleteSingle(); assert.ok(deletedSingle && !deletedSingle.notFound, "delete-by-id must work for the carried single target"); const afterSingleDelete = rotated.readConfigFromDisk(); assert.equal(afterSingleDelete.single, null, "the carried single envelope must be removed"); assert.deepEqual(Object.keys(afterSingleDelete.multiple), [], "no carried envelope may resurrect after explicit deletes"); } finally { delete process.env.WEBHOOK_SEALING_KEY; } }); }); test("handler contract: the DELETE route keeps carried (undecryptable) targets deletable and forgets them on delete", () => { const source = fs.readFileSync(INDEX_JS, "utf8"); const deleteStart = source.indexOf('app.delete("/api/settings/webhooks"'); assert.ok(deleteStart >= 0, "webhook DELETE route must exist"); const deleteEnd = source.indexOf('app.post("/api/settings/webhooks/test"', deleteStart); assert.ok(deleteEnd > deleteStart, "webhook DELETE handler slice must be bounded"); const del = source.slice(deleteStart, deleteEnd); const lockAt = del.indexOf("withWebhooksConfigWriteLock("); const precheckAt = del.indexOf("webhooksConfigHasCarriedEnvelope(precheckConfig"); const lockedAt = del.indexOf("webhooksConfigHasCarriedEnvelope(config"); const forgetAt = del.indexOf("forgetCarriedWebhookEnvelope(config"); assert.ok(precheckAt > -1 && precheckAt < lockAt, "the pre-check must consult carried envelopes (a carried target must not 404 before its token is even checked)"); assert.ok(lockedAt > lockAt, "the authoritative carried check must run inside the lock"); assert.ok(forgetAt > lockAt, "an explicit delete must forget the carried envelope inside the lock, or the save would splice it straight back"); // The constraint comment exists at BOTH required sites: the carry-forward // mechanism (saveWebhooksConfig splice) and the migration site. const tag = "adpanel:webhook-envelope-preservation"; const saveEnd = endIndexOfFunction(source, "function saveWebhooksConfig"); const saveAt = source.indexOf("function saveWebhooksConfig"); assert.ok(saveEnd > saveAt, "saveWebhooksConfig must be sliceable"); assert.ok( source.slice(saveAt, saveEnd).includes(tag), "the constraint comment exists at the carry-forward mechanism" ); const migrateBlockAt = source.indexOf("// Audit 2026-09-06: one-time migration of legacy plaintext webhook URLs"); const migrateEnd = endIndexOfFunction(source, "async function migrateWebhooksConfigToEncryptedAtRest"); assert.ok(migrateBlockAt > -1 && migrateEnd > migrateBlockAt, "the migration block must be sliceable"); assert.ok( source.slice(migrateBlockAt, migrateEnd).includes(tag), "the constraint comment exists at the migration site" ); }); test("handler contract: both write routes run their mutation under the lock with a fresh read", () => { const source = fs.readFileSync(INDEX_JS, "utf8"); const postStart = source.indexOf('app.post("/api/settings/webhooks"'); assert.ok(postStart >= 0, "webhook POST route must exist"); const postEnd = endIndexOfFunction(source.slice(postStart), "async (req, res) => {") + postStart; const post = source.slice(postStart, postEnd); assert.ok(post.includes("withWebhooksConfigWriteLock("), "POST must serialize its write cycle"); assert.ok(post.includes("loadWebhooksConfigFresh()"), "POST must mutate a fresh from-disk read"); assert.ok( !post.includes("loadWebhooksConfig()"), "POST must not mutate the possibly-stale cached config object" ); assert.ok( post.indexOf("withWebhooksConfigWriteLock(") > post.indexOf("requireDestructiveActionStepUp"), "the lock must be taken after the step-up awaits so the critical section stays synchronous" ); assert.ok( post.includes("WEBHOOKS_LOCK_TIMEOUT") && post.includes("status(503)"), "POST must fail closed with 503 when the lock cannot be acquired" ); const deleteStart = source.indexOf('app.delete("/api/settings/webhooks"'); assert.ok(deleteStart >= 0, "webhook DELETE route must exist"); const deleteEnd = source.indexOf('app.post("/api/settings/webhooks/test"', deleteStart); assert.ok(deleteEnd > deleteStart, "webhook DELETE handler slice must be bounded"); const del = source.slice(deleteStart, deleteEnd); assert.ok(del.includes("withWebhooksConfigWriteLock("), "DELETE must serialize its write cycle"); assert.ok(del.includes("loadWebhooksConfigFresh()"), "DELETE must mutate a fresh from-disk read"); const lockAt = del.indexOf("withWebhooksConfigWriteLock("); const notFoundRecheckAt = del.indexOf("return { notFound: true };"); assert.ok( notFoundRecheckAt > lockAt, "DELETE must re-verify existence inside the lock so it cannot resurrect deleted state" ); assert.ok( del.includes("WEBHOOKS_LOCK_TIMEOUT") && del.includes("status(503)"), "DELETE must fail closed with 503 when the lock cannot be acquired" ); // The lock file must be protected from file-manager tampering, breaking // serialization for every worker. const protectedAt = source.indexOf('const PROTECTED_FILES = new Set(['); const protectedSlice = source.slice(protectedAt, source.indexOf("]);", protectedAt)); assert.ok(protectedSlice.includes('"webhooks-config.json.lock"'), "the lock file must be in PROTECTED_FILES"); });