"use strict"; // adpanel:node-token-sealing-key-override — unit pins for the node-token // sealing module's key-input override. The finding: the AES-256-GCM key that // seals nodes.token bearer tokens was scrypt(SESSION_SECRET, fixed-salt) with // no independent key env and no re-seal path, so rotating SESSION_SECRET // invalidated every stored node token at once (sealed decrypt fails → // decryptNodeToken null / classifyStoredNodeToken "corrupt" → the startup // integrity gate flags rotate_required → every node re-paired). The fix adds // NODE_TOKEN_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 // salt, same 32-byte length, same default params): every seal minted // before this change 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/unseal roundtrips succeed // only under the same override. // - NO fallback: a seal minted under one input can never be opened under // the other (decryptNodeToken returns null and classifyStoredNodeToken // reports "corrupt" — 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 node-takeover primitive. // - Source pins: the boot check routes NODE_TOKEN_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 standalone consumer (scripts/verify-node-token-integrity.js) seals // too, so it carries the same mirrored strength guard create-user got. 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 MODULE_PATH = require.resolve("./node-token-crypto"); const INDEX_JS = path.join(ROOT, "index.js"); const MODULE_JS = path.join(ROOT, "utils", "node-token-crypto.js"); const VERIFY_SCRIPT = path.join(ROOT, "scripts", "verify-node-token-integrity.js"); const ENC_PREFIX = "enc:v1:"; // Pinned independently of the module (which does not export its salt): the // derivation-site source pin below locks the same literal in the source. const SALT = "adpanel-node-token-v1"; const SESSION_SECRET = "adpanel-node-token-test-session-secret-0123456789abcdef"; const OVERRIDE = "node-token-sealing-override-key-0123456789abcdef-zyxwvu"; const TOKEN = "adpnt_test-node-bearer-token-0123456789"; // The module caches its derived key at module level (_keyCache) for the // process lifetime, so every derivation scenario loads a FRESH instance under // that scenario's env — the same isolation mechanism the reference // implementation's pins use (utils/totp-secret-crypto.test.js); no reset API // is added to the shipped module. node --test runs this file in its own // process, so env mutation here cannot leak into other test files, and every // scenario deletes-then-sets both variables so it is self-contained. function freshModule(env) { delete process.env.SESSION_SECRET; delete process.env.NODE_TOKEN_SEALING_KEY; for (const [name, value] of Object.entries(env || {})) { if (value !== undefined) process.env[name] = value; } delete require.cache[MODULE_PATH]; return require(MODULE_PATH); } // Independent envelope machinery — deliberately NOT the module 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 module — GCM verification only passes under the exact // key bytes, so this proves the module derived exactly that key. assert.strictEqual( mod.decryptNodeToken(sealWithKey(expectedKey, TOKEN)), TOKEN, "module opens an envelope sealed with the independent pre-override key" ); // Direction 2: the module's own seal must open under the independently // computed key — proving no other input (and no param drift) feeds the KDF. const sealed = mod.encryptNodeToken(TOKEN); assert.ok(mod.isEncryptedNodeToken(sealed)); assert.strictEqual( openWithKey(expectedKey, sealed), TOKEN, "the independent pre-override key opens the module'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, NODE_TOKEN_SEALING_KEY: OVERRIDE }); const sealed = mod.encryptNodeToken(TOKEN); assert.ok(mod.isEncryptedNodeToken(sealed), "the seal is a v1 envelope"); assert.strictEqual(mod.decryptNodeToken(sealed), TOKEN, "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.decryptNodeToken(sealWithKey(overrideKey, TOKEN)), TOKEN, "the module 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.encryptNodeToken(TOKEN); // …an override-keyed module must fail CLOSED — null, never the token. const opener = freshModule({ SESSION_SECRET, NODE_TOKEN_SEALING_KEY: OVERRIDE }); assert.strictEqual( opener.decryptNodeToken(sealedDerived), null, "derived-key seal under the override decrypts to null (fail-closed, no fallback)" ); assert.strictEqual( opener.classifyStoredNodeToken(sealedDerived).state, "corrupt", "the integrity gate's classifier reports corrupt under the override (rotate_required path, not a pass-through)" ); // And the reverse direction: sealed under the override… const sealedOverride = opener.encryptNodeToken(TOKEN); // …a derived-key module must also fail closed. const derivedOpener = freshModule({ SESSION_SECRET }); assert.strictEqual( derivedOpener.decryptNodeToken(sealedOverride), null, "override seal under the derived key decrypts to null (fail-closed, no fallback)" ); assert.strictEqual( derivedOpener.classifyStoredNodeToken(sealedOverride).state, "corrupt", "the classifier reports corrupt in the reverse direction too" ); }); test("empty-string override is treated exactly like unset, matching the boot check's `override !== \"\"` guard", () => { const unsetMod = freshModule({ SESSION_SECRET }); const sealed = unsetMod.encryptNodeToken(TOKEN); const emptyMod = freshModule({ SESSION_SECRET, NODE_TOKEN_SEALING_KEY: "" }); assert.strictEqual( emptyMod.decryptNodeToken(sealed), TOKEN, "an empty override keeps the SESSION_SECRET-derived key" ); // Same proof in the encryption direction: the empty-override module's seal // opens under the independently computed pre-override key. assert.strictEqual(openWithKey(derivedSessionKey(), emptyMod.encryptNodeToken(TOKEN)), TOKEN); }); 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, NODE_TOKEN_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.decryptNodeToken(tamper(override.encryptNodeToken(TOKEN))), null); assert.strictEqual(override.decryptNodeToken(tamper(derived.encryptNodeToken(TOKEN))), null); }); // ─── Source pins: boot-check wiring, constraint comments, standalone guard ─── 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}`); } test("source-pin: NODE_TOKEN_SEALING_KEY is checked through the shared boot-check helper beside its siblings", () => { const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const callAt = indexSource.indexOf('requireStrongSecretOverride("NODE_TOKEN_SEALING_KEY")'); assert.ok(callAt > -1, "NODE_TOKEN_SEALING_KEY must be checked through the shared helper"); const totpCallAt = indexSource.indexOf('requireStrongSecretOverride("TOTP_SEALING_KEY")'); assert.ok(callAt > totpCallAt, "NODE_TOKEN_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:node-token-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 NODE_TOKEN_SEALING_KEY (short → exit(1); unset/empty → legal)", () => { const indexSource = fs.readFileSync(INDEX_JS, "utf8"); 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({ NODE_TOKEN_SEALING_KEY: "a".repeat(32) })("NODE_TOKEN_SEALING_KEY"), "32 chars must be accepted"); assert.throws(() => run({ NODE_TOKEN_SEALING_KEY: "a".repeat(31) })("NODE_TOKEN_SEALING_KEY"), (err) => err.message === "__exit__:1", "31 chars must exit(1)"); assert.doesNotThrow(() => run({})("NODE_TOKEN_SEALING_KEY"), "unset must stay legal (keeps the derived key)"); assert.doesNotThrow(() => run({ NODE_TOKEN_SEALING_KEY: "" })("NODE_TOKEN_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 indexSource = fs.readFileSync(INDEX_JS, "utf8"); const advisoryAt = indexSource.indexOf("[config] NODE_TOKEN_SEALING_KEY override active"); assert.ok(advisoryAt > -1, "the boot advisory is present"); assert.ok( indexSource.includes("can no longer be decrypted and the startup integrity gate will flag them rotate_required, requiring re-pairing of every node; set the override once and keep it stable"), "the advisory names the fail-closed re-pairing consequence" ); const gateAt = indexSource.lastIndexOf("if (process.env.NODE_TOKEN_SEALING_KEY)", advisoryAt); assert.ok(gateAt > -1, "the advisory is gated on the override being set"); const bootCallAt = indexSource.indexOf('requireStrongSecretOverride("NODE_TOKEN_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 carries the constraint comment", () => { const moduleSource = fs.readFileSync(MODULE_JS, "utf8"); assert.strictEqual( moduleSource.split("process.env.NODE_TOKEN_SEALING_KEY || process.env.SESSION_SECRET").length - 1, 1, "exactly ONE derivation site — the ||-fallback replaces the bare SESSION_SECRET read" ); assert.ok( moduleSource.includes('process.env.NODE_TOKEN_SEALING_KEY || process.env.SESSION_SECRET || ""'), "the override || SESSION_SECRET fallback feeds the same scrypt input" ); assert.ok( moduleSource.includes("adpanel:node-token-sealing-key-override"), "the constraint comment exists at the derivation site" ); assert.ok( moduleSource.includes('const SALT = "adpanel-node-token-v1";'), "the node-token-specific salt is pinned" ); assert.ok( moduleSource.includes("crypto.scryptSync(secret, SALT, 32)"), "the KDF call keeps its salt and 32-byte length" ); }); test("source-pin: the standalone sealing consumer (scripts/verify-node-token-integrity.js) carries the mirrored strength guard before its first seal", () => { const scriptSource = fs.readFileSync(VERIFY_SCRIPT, "utf8"); assert.ok( scriptSource.includes("adpanel:node-token-sealing-key-override"), "the constraint comment exists at the standalone guard" ); const messageAt = scriptSource.indexOf("[config] NODE_TOKEN_SEALING_KEY is set but too short. Set a random 32+ chars secret in env.NODE_TOKEN_SEALING_KEY, or leave it unset to derive one from SESSION_SECRET."); assert.ok(messageAt > -1, "the guard message is byte-parity with the boot check's renderer"); // The guard's rejection predicate matches the shared helper exactly: // set, non-empty, shorter than 32. const guardAt = scriptSource.indexOf("nodeTokenSealingKeyOverride.length < 32"); assert.ok(guardAt > -1, "the guard enforces the same 32-char floor"); assert.ok( scriptSource.includes('nodeTokenSealingKeyOverride !== undefined && nodeTokenSealingKeyOverride !== ""'), "the guard treats unset and empty exactly like the boot check does" ); // It must run BEFORE the module is loaded (and therefore before any seal): // the require of node-token-crypto appears after the guard. const requireAt = scriptSource.indexOf('require("../utils/node-token-crypto")'); assert.ok(requireAt > guardAt, "the guard precedes the crypto module require and every seal"); });