"use strict"; // Per-consumer tests for adpanel:config-stat-revalidation — hot-swapped config // state was worker-local in a multi-worker deployment (the shipped default, // INSTANCES=cores-2): maintenance.json, the captcha .env keys and the global // alerts file were loaded once (or saved writer-locally) and cluster siblings // never saw a toggle until restart — a silent lockdown bypass, an unprotected // login surface, a stale banner. The fix is READ-side revalidation on every // worker through the ONE shared helper (utils/config-revalidation.js), so // these tests simulate TWO workers as two cache instances over ONE temp file // and assert a save on "worker A" reaches "worker B"'s next read. // // index.js boots servers on require, so the disk-read functions under test // are extracted from the source and evaluated against injected dependencies // (the same technique as audit-branding-hardening.test.js); the wiring itself // is locked with source assertions below. 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 { createStatKeyedCache } = require("../utils/config-revalidation"); const { atomicWriteFileSync } = require("../utils/atomic-file"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const HELPER_JS = path.join(ROOT, "utils", "config-revalidation.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const helperSource = fs.readFileSync(HELPER_JS, "utf8"); 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 extractFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found`); const end = endIndexOfFunction(source, startMarker); return source.slice(start, end); } function makeTmpDir(prefix) { return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); } // The writer shape every consumer save uses: atomic tmp+fsync+rename // replacement (rename bumps the shared filesystem's mtime — the cross-worker // signal; explicit here so the test cannot flake on coarse-mtime filesystems). function atomicReplace(file, content) { let fileMode; try { fileMode = fs.statSync(file).mode & 0o777; } catch (_) { fileMode = 0o600; } atomicWriteFileSync(file, content, { mode: fileMode || 0o600 }); } // --------------------------------------------------------------------------- // Wiring source assertions — the three stale consumers + the refactored // dashboard-assistant config all bind the ONE shared helper. // --------------------------------------------------------------------------- test("index.js requires the shared revalidation helper exactly once", () => { const requireMatches = indexSource.match(/require\("\.\/utils\/config-revalidation"\)/g) || []; assert.equal(requireMatches.length, 1); assert.ok(helperSource.includes("adpanel:config-stat-revalidation"), "the helper carries the adpanel tag"); }); test("maintenance.json revalidates through the shared cache on every gate read", () => { assert.ok(indexSource.includes("adpanel:config-stat-revalidation"), "consumer carries the adpanel tag"); const cacheBlock = indexSource.match(/const maintenanceStateCache = createStatKeyedCache\(\{[\s\S]*?\}\);/); assert.ok(cacheBlock, "maintenance binds createStatKeyedCache"); assert.match(cacheBlock[0], /filePath: MAINTENANCE_FILE/); assert.match(cacheBlock[0], /load: readMaintenanceStateFromDisk/); assert.match(cacheBlock[0], /ttlMs: MAINTENANCE_STATE_CACHE_TTL_MS/); // TTL: incident-response control, tighter than the documented 30s bound. assert.match(indexSource, /const MAINTENANCE_STATE_CACHE_TTL_MS = 5 \* 1000;/); // The gate reads go through the cache (re-stat per read), the save seeds it. assert.match(extractFunction(indexSource, "function getMaintenanceState("), /maintenanceStateCache\.get\(\)/); assert.match(extractFunction(indexSource, "function saveMaintenanceState("), /maintenanceStateCache\.put\(state\)/); // The old worker-local module state is gone — memory is a cache of the file. assert.ok(!/^\s*let maintenanceState = null;$/m.test(indexSource), "no parallel worker-local maintenanceState let"); // No fs.watch for this file — the stat-key pattern is the documented-acceptable one. assert.ok(!indexSource.includes("fs.watch(MAINTENANCE_FILE"), "no fs.watch on maintenance.json"); }); test("global alerts revalidate through the shared cache", () => { const alertsRegion = indexSource.slice( indexSource.indexOf("const globalAlertsCache = createStatKeyedCache({") - 800, indexSource.indexOf("const globalAlertsCache = createStatKeyedCache({") + 400 ); assert.ok(alertsRegion.includes("adpanel:config-stat-revalidation")); const cacheBlock = indexSource.match(/const globalAlertsCache = createStatKeyedCache\(\{[\s\S]*?\}\);/); assert.ok(cacheBlock, "alerts bind createStatKeyedCache"); assert.match(cacheBlock[0], /filePath: GLOBAL_ALERT_FILE/); assert.match(cacheBlock[0], /load: loadGlobalAlerts/); assert.match(cacheBlock[0], /ttlMs: GLOBAL_ALERTS_CACHE_TTL_MS/); // Panel-content toggle: the documented 30s bound class. assert.match(indexSource, /const GLOBAL_ALERTS_CACHE_TTL_MS = 30 \* 1000;/); assert.match(extractFunction(indexSource, "function getGlobalAlerts("), /globalAlertsCache\.get\(\)/); assert.match(extractFunction(indexSource, "function saveGlobalAlerts("), /globalAlertsCache\.put\(normalizedAlerts\)/); assert.ok(!/^\s*let cachedAlerts = null;$/m.test(indexSource), "no parallel worker-local cachedAlerts let"); assert.ok(!indexSource.includes("fs.watch(GLOBAL_ALERT_FILE"), "no fs.watch on global-alert.json"); }); test("captcha hot-swap revalidates .env at the enforcement entries", () => { const cacheBlock = indexSource.match(/const captchaEnvCache = createStatKeyedCache\(\{[\s\S]*?\}\);/); assert.ok(cacheBlock, "captcha binds createStatKeyedCache"); assert.match(cacheBlock[0], /filePath: ENV_FILE_PATH/); assert.match(cacheBlock[0], /load: loadCaptchaConfigFromEnvFile/); assert.match(cacheBlock[0], /ttlMs: CAPTCHA_ENV_CACHE_TTL_MS/); // Login-protection control: same tight class as maintenance. assert.match(indexSource, /const CAPTCHA_ENV_CACHE_TTL_MS = 5 \* 1000;/); // Boot seed: the first enforcement read must not re-parse the boot env. assert.match(indexSource, /captchaEnvCache\.put\(\{\s*\n\s*siteKey: process\.env\.SITE_KEY/); // Exactly one revalidate definition, wired at every enforcement entry. assert.equal((indexSource.match(/function revalidateCaptchaConfigFromDisk\(/g) || []).length, 1); const verifyFn = extractFunction(indexSource, "async function verifyExternalCaptcha("); assert.match(verifyFn, /revalidateCaptchaConfigFromDisk\(\)/, "provider verification revalidates"); const verifyRoute = extractFunction(indexSource, 'app.post("/api/captcha/verify"'); assert.match(verifyRoute, /revalidateCaptchaConfigFromDisk\(\)/, "/api/captcha/verify revalidates (outside /login scope)"); const middleware = extractFunction(indexSource, "async function loginAttackMiddleware("); assert.match(middleware, /revalidateCaptchaConfigFromDisk\(\)/, "/login middleware revalidates before the ANY_CAPTCHA_ENABLED gate"); assert.match(indexSource, /adpanel:config-stat-revalidation/g); // The re-apply is a read-only parse: no .env write in the load path (a // concurrently-written non-captcha key must never be clobbered). const loadFn = extractFunction(indexSource, "function loadCaptchaConfigFromEnvFile("); assert.ok(!/\bwriteEnvValue\b|\bwriteFileSync\b|\batomicWriteFileSync\b/.test(loadFn), "the re-apply never writes .env"); assert.match(loadFn, /applyCaptchaConfig\(siteKey, secretKey, provider\)/); // Values are never logged: no template/console statement inside the load. assert.ok(!/console\.\w+\([^)]*\$\{/.test(loadFn), "the re-apply never interpolates values into logs"); assert.ok(!indexSource.includes("fs.watch(ENV_FILE_PATH"), "no fs.watch on .env"); }); test("the dashboard-assistant config no longer carries an inline stat-key copy", () => { assert.ok(!indexSource.includes("statDashboardAssistantConfigKey"), "the inline stat helper was consolidated"); assert.ok(!indexSource.includes("dashboardAssistantConfigCacheKey"), "no parallel key let"); assert.ok(!indexSource.includes("dashboardAssistantConfigCacheAtMs"), "no parallel age let"); const cacheBlock = indexSource.match(/const dashboardAssistantConfigCache = createStatKeyedCache\(\{[\s\S]*?\}\);/); assert.ok(cacheBlock, "dashboard-assistant binds createStatKeyedCache"); assert.match(cacheBlock[0], /filePath: DASHBOARD_ASSISTANT_CONFIG_FILE/); assert.match(cacheBlock[0], /load: loadDashboardAssistantConfigFromDisk/); assert.match(cacheBlock[0], /ttlMs: DASHBOARD_ASSISTANT_CONFIG_CACHE_TTL_MS/); // The documented 30s TTL semantics are preserved. assert.match(indexSource, /const DASHBOARD_ASSISTANT_CONFIG_CACHE_TTL_MS = 30 \* 1000;/); assert.match(extractFunction(indexSource, "function getDashboardAssistantConfig("), /dashboardAssistantConfigCache\.get\(\)/); const saveFn = extractFunction(indexSource, "function saveDashboardAssistantConfig("); assert.match(saveFn, /dashboardAssistantConfigCache\.statKey\(\)/, "readback stat captured through the helper"); assert.match(saveFn, /dashboardAssistantConfigCache\.put\(normalized, key\)/, "verified save seeds with the pre-readback key"); assert.ok(!indexSource.includes("fs.watch(DASHBOARD_ASSISTANT_CONFIG_FILE"), "no fs.watch on dashboard-assistant-config.json"); }); // --------------------------------------------------------------------------- // maintenance.json — two workers over one file // --------------------------------------------------------------------------- function makeMaintenanceWorkers(file) { const readFn = extractFunction(indexSource, "function readMaintenanceStateFromDisk("); const readMaintenanceStateFromDisk = new Function( "fs", "MAINTENANCE_FILE", `${readFn}\nreturn readMaintenanceStateFromDisk;` )(fs, file); const makeWorker = () => createStatKeyedCache({ filePath: file, load: readMaintenanceStateFromDisk, ttlMs: 5 * 1000, label: "[maintenance]", }); // The save shape saveMaintenanceState uses: atomic replace + cache seed. const save = (cache, state) => { atomicReplace(file, JSON.stringify(state, null, 2)); cache.put(state); return true; }; return { makeWorker, save }; } test("maintenance toggle reaches the other worker's gate on its next read", () => { const dir = makeTmpDir("adpanel-maint-"); try { const file = path.join(dir, "maintenance.json"); const { makeWorker, save } = makeMaintenanceWorkers(file); const workerA = makeWorker(); const workerB = makeWorker(); // Both workers boot from the same (missing) file: maintenance off. assert.equal(workerA.get().enabled, false); assert.equal(workerB.get().enabled, false); // Worker A's admin toggles maintenance ON (write + writer-local seed). save(workerA, { enabled: true, scheduled_at: null, enabled_by: "admin@example", enabled_at: new Date().toISOString(), reason: "incident", pre_alert: { show: false, message: null, minutes_before: null }, previous_alert_backup: null }); // Worker B previously kept serving the full authenticated surface until // restart (the silent lockdown bypass). Its next gate read must 503 too. assert.equal(workerB.get().enabled, true); // Toggle OFF on worker A: worker B must stop 503ing on its next read. save(workerA, { enabled: false, scheduled_at: null, enabled_by: null, enabled_at: null, reason: null, pre_alert: { show: false, message: null, minutes_before: null }, previous_alert_backup: null }); assert.equal(workerB.get().enabled, false); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a scheduled maintenance window written by one worker activates on every worker", () => { const dir = makeTmpDir("adpanel-maint-sched-"); try { const file = path.join(dir, "maintenance.json"); const { makeWorker, save } = makeMaintenanceWorkers(file); const workerA = makeWorker(); const workerB = makeWorker(); workerA.get(); workerB.get(); // Worker A's admin schedules maintenance for the (past) window while // worker B's boot snapshot predated the schedule. save(workerA, { enabled: false, scheduled_at: new Date(Date.now() - 60_000).toISOString(), enabled_by: "admin@example", enabled_at: null, reason: "upgrade window", pre_alert: { show: false, message: null, minutes_before: null }, previous_alert_backup: null }); // Worker B's gate (isMaintenanceActive shape, extracted with its real // collaborators) revalidates on read, sees the schedule and activates. const isActiveFn = extractFunction(indexSource, "function isMaintenanceActive("); const isMaintenanceActiveForB = new Function( "getMaintenanceState", "saveMaintenanceState", "console", `${isActiveFn}\nreturn isMaintenanceActive;` )( () => workerB.get(), (state) => save(workerB, state), console ); assert.equal(isMaintenanceActiveForB(), true, "scheduled activation converges on the sibling"); // B's activation was persisted, so worker A sees the same lockdown. assert.equal(workerA.get().enabled, true); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a corrupt maintenance.json stays fail-closed on every worker", () => { const dir = makeTmpDir("adpanel-maint-corrupt-"); try { const file = path.join(dir, "maintenance.json"); const { makeWorker, save } = makeMaintenanceWorkers(file); const workerA = makeWorker(); const workerB = makeWorker(); workerA.get(); workerB.get(); // External interference mid-flight: torn JSON on the shared filesystem. atomicReplace(file, '{"enabled": tr'); // A warm worker reloads on the stat-key change and fails CLOSED... const warm = workerB.get(); assert.equal(warm.enabled, true); assert.equal(warm.reason, "maintenance state unreadable (fail-closed)"); // ...and so does a cold worker (fresh boot over the corrupt file). const cold = workerA.get(); assert.equal(cold.enabled, true); assert.equal(cold.reason, "maintenance state unreadable (fail-closed)"); void save; } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); // --------------------------------------------------------------------------- // captcha (.env) — two workers over one .env // --------------------------------------------------------------------------- function makeCaptchaWorkers(envFile) { const loadFn = extractFunction(indexSource, "function loadCaptchaConfigFromEnvFile("); const revalidateFn = extractFunction(indexSource, "function revalidateCaptchaConfigFromDisk("); // `initialEnv` simulates a deployment that configured captcha through REAL // environment variables (pm2 ecosystem env / systemd / docker) — keys the // .env file may never mention. const makeWorker = (initialEnv) => { // A worker-local facade exactly like applyCaptchaConfig's module lets: // the fake records every re-apply and mirrors the process.env mutations // the extracted loader performs. const applied = []; const fakeProcess = { env: { CAPTCHA_PROVIDER: "", ...(initialEnv || {}) } }; const applyCaptchaConfig = (siteKey, secretKey, provider) => { applied.push({ siteKey, secretKey, provider }); }; const loadCaptchaConfigFromEnvFile = new Function( "fs", "ENV_FILE_PATH", "applyCaptchaConfig", "process", `${loadFn}\nreturn loadCaptchaConfigFromEnvFile;` )(fs, envFile, applyCaptchaConfig, fakeProcess); const cache = createStatKeyedCache({ filePath: envFile, load: loadCaptchaConfigFromEnvFile, ttlMs: 5 * 1000, label: "[captcha]", }); // Boot seed (index.js performs this after the boot applyCaptchaConfig). cache.put({ siteKey: fakeProcess.env.SITE_KEY ?? "", secretKey: fakeProcess.env.SECRET_KEY ?? "", provider: fakeProcess.env.CAPTCHA_PROVIDER ?? "", }); const revalidateCaptchaConfigFromDisk = new Function( "captchaEnvCache", "console", `${revalidateFn}\nreturn revalidateCaptchaConfigFromDisk;` )(cache, console); return { applied, fakeProcess, cache, revalidateCaptchaConfigFromDisk }; }; // The settings route's write shape (writeEnvValueUnderHeldLock: quoted // values, atomic replace under the cluster-serialized mutex). const routeWrite = (entries) => { const lines = Object.entries(entries).map(([key, value]) => { const cleaned = String(value ?? "").replace(/\0/g, "").replace(/[\r\n]+/g, ""); const safeValue = cleaned.includes(" ") || cleaned.includes('"') ? `"${cleaned.replace(/"/g, '\\"')}"` : `"${cleaned}"`; return `${key}=${safeValue}`; }); atomicReplace(envFile, lines.join("\n")); }; return { makeWorker, routeWrite }; } test("captcha enable on one worker re-applies on the sibling's next enforcement read", () => { const dir = makeTmpDir("adpanel-captcha-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const workerA = makeWorker(); const workerB = makeWorker(); // Both workers boot captcha-disabled (no .env): the boot seed pins the // {-1,-1} key, so the first enforcement read must NOT re-parse. workerA.revalidateCaptchaConfigFromDisk(); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerA.applied.length, 0); assert.equal(workerB.applied.length, 0); // Admin enables captcha from Settings on worker A: route writes .env // (cluster-serialized) alongside an unrelated key, then applies locally. routeWrite({ PANEL_PUBLIC_URL: "https://panel.example", SITE_KEY: "0x4AAAAAAA-eXaMpLeKeY01", SECRET_KEY: "sk_eXaMpLeSeCrEt01", }); workerA.applied.push({ siteKey: "0x4AAAAAAA-eXaMpLeKeY01", secretKey: "sk_eXaMpLeSeCrEt01", provider: "" }); // Worker B's login surface was previously left unprotected forever. The // revalidation re-applies ONLY the captcha keys from the file. workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); assert.deepEqual(workerB.applied[0], { siteKey: "0x4AAAAAAA-eXaMpLeKeY01", secretKey: "sk_eXaMpLeSeCrEt01", provider: "", }); assert.equal(workerB.fakeProcess.env.SITE_KEY, "0x4AAAAAAA-eXaMpLeKeY01"); assert.equal(workerB.fakeProcess.env.SECRET_KEY, "sk_eXaMpLeSeCrEt01"); // The unrelated key was read but never rewritten or logged. const onDisk = fs.readFileSync(envFile, "utf8"); assert.match(onDisk, /PANEL_PUBLIC_URL="https:\/\/panel\.example"/); assert.doesNotMatch(onDisk, /0x4AAAAAAA-eXaMpLeKeY01.*0x4AAAAAAA-eXaMpLeKeY01/s); void workerA; // Idempotent: an unchanged stat key re-applies nothing. workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("captcha disable propagates to the sibling and wipes the mirrored env keys", () => { const dir = makeTmpDir("adpanel-captcha-off-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const workerA = makeWorker(); const workerB = makeWorker(); workerA.revalidateCaptchaConfigFromDisk(); workerB.revalidateCaptchaConfigFromDisk(); routeWrite({ SITE_KEY: "0x4AAAAAAA-eXaMpLeKeY01", SECRET_KEY: "sk_eXaMpLeSeCrEt01" }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); // Disable from Settings on worker A: the route writes empty keys. routeWrite({ SITE_KEY: "", SECRET_KEY: "" }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 2); assert.deepEqual(workerB.applied[1], { siteKey: "", secretKey: "", provider: "" }); assert.ok(!("SITE_KEY" in workerB.fakeProcess.env), "mirrored SITE_KEY deleted like the route does"); assert.ok(!("SECRET_KEY" in workerB.fakeProcess.env), "mirrored SECRET_KEY deleted like the route does"); void workerA; } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a failing .env re-read keeps the sibling's working captcha config (fail-safe + one warn)", () => { const dir = makeTmpDir("adpanel-captcha-failsafe-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const workerB = makeWorker(); workerB.revalidateCaptchaConfigFromDisk(); routeWrite({ SITE_KEY: "0x4AAAAAAA-eXaMpLeKeY01", SECRET_KEY: "sk_eXaMpLeSeCrEt01" }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); assert.equal(workerB.fakeProcess.env.SITE_KEY, "0x4AAAAAAA-eXaMpLeKeY01"); // The .env vanishes (external interference / broken mount): the re-apply // must keep the last known-good config — a torn read must never fail the // login surface OPEN by applying empty keys. const warnings = []; const originalWarn = console.warn; console.warn = (...args) => warnings.push(args.join(" ")); try { fs.rmSync(envFile, { force: true }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1, "no re-apply on read failure"); assert.equal(workerB.fakeProcess.env.SITE_KEY, "0x4AAAAAAA-eXaMpLeKeY01", "mirrored env preserved"); assert.equal(warnings.length, 1, "one warn per failure episode"); assert.match(warnings[0], /\[captcha\]/); assert.ok(!warnings[0].includes("0x4AAAAAAA"), "the warn never leaks key values"); // Still failing: the episode stays silent. workerB.revalidateCaptchaConfigFromDisk(); assert.equal(warnings.length, 1); } finally { console.warn = originalWarn; } } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); // --------------------------------------------------------------------------- // captcha (.env) — merge semantics: file-present keys are the file-level // truth, file-ABSENT keys defer to the boot environment (real pm2/systemd/ // docker env survives unrelated .env writes) // --------------------------------------------------------------------------- test("an unrelated .env write never strips real-env captcha config (boot-env keys stand)", () => { const dir = makeTmpDir("adpanel-captcha-realenv-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); // Operator configured captcha via REAL environment variables; .env does // not exist at boot. The boot seed pins the boot-env values. const workerB = makeWorker({ SITE_KEY: "pm2-env-site-key-01", SECRET_KEY: "pm2-env-secret-key-01", }); assert.equal(workerB.fakeProcess.env.SITE_KEY, "pm2-env-site-key-01"); // An unrelated .env write (the AI-key save batch shape) creates the file // WITHOUT any captcha key and re-keys the cache. routeWrite({ OPENAI_API_KEY: "sk-ai-key", PANEL_PUBLIC_URL: "https://panel.example" }); workerB.revalidateCaptchaConfigFromDisk(); // File-ABSENT keys defer to the boot environment: nothing is deleted and // the re-applied effective config is still the operator's real env, so // captcha stays enabled instead of silently failing open on this worker. assert.equal(workerB.applied.length, 1); assert.deepEqual(workerB.applied[0], { siteKey: "pm2-env-site-key-01", secretKey: "pm2-env-secret-key-01", provider: "", }); assert.equal(workerB.fakeProcess.env.SITE_KEY, "pm2-env-site-key-01", "real-env SITE_KEY survives the reload"); assert.equal(workerB.fakeProcess.env.SECRET_KEY, "pm2-env-secret-key-01", "real-env SECRET_KEY survives the reload"); // The unrelated key was read but never rewritten, and no captcha key was // invented into the file (the load is a read-only parse). const onDisk = fs.readFileSync(envFile, "utf8"); assert.match(onDisk, /OPENAI_API_KEY="sk-ai-key"/); assert.doesNotMatch(onDisk, /SITE_KEY|SECRET_KEY/); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("an explicit empty file key disables captcha even when the real env configured it", () => { const dir = makeTmpDir("adpanel-captcha-filedisable-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const workerB = makeWorker({ SITE_KEY: "pm2-env-site-key-01", SECRET_KEY: "pm2-env-secret-key-01", }); // No file yet: the seed key {-1,-1} matches, no reload, boot env intact. workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 0); assert.equal(workerB.fakeProcess.env.SITE_KEY, "pm2-env-site-key-01"); // The disable route's file shape (writeEnvValue("SITE_KEY","") produces // the explicitly-empty quoted lines): the operator's FILE-level disable // must win over the boot environment. routeWrite({ SITE_KEY: "", SECRET_KEY: "" }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); assert.deepEqual(workerB.applied[0], { siteKey: "", secretKey: "", provider: "" }); assert.ok(!("SITE_KEY" in workerB.fakeProcess.env), "file-level disable deletes the mirrored SITE_KEY"); assert.ok(!("SECRET_KEY" in workerB.fakeProcess.env), "file-level disable deletes the mirrored SECRET_KEY"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a file-present captcha key overrides the boot environment", () => { const dir = makeTmpDir("adpanel-captcha-override-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const workerB = makeWorker({ SITE_KEY: "pm2-env-site-key-01", SECRET_KEY: "pm2-env-secret-key-01", }); // The settings save writes new keys to .env: the file is the file-level // truth and its non-empty values mirror over the boot-env values. routeWrite({ SITE_KEY: "0x4AAAAAAA-nEwKeY01234", SECRET_KEY: "sk_nEwSeCrEt01" }); workerB.revalidateCaptchaConfigFromDisk(); assert.equal(workerB.applied.length, 1); assert.deepEqual(workerB.applied[0], { siteKey: "0x4AAAAAAA-nEwKeY01234", secretKey: "sk_nEwSeCrEt01", provider: "", }); assert.equal(workerB.fakeProcess.env.SITE_KEY, "0x4AAAAAAA-nEwKeY01234", "file value mirrors over the boot-env value"); assert.equal(workerB.fakeProcess.env.SECRET_KEY, "sk_nEwSeCrEt01"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("the CAPTCHA_PROVIDER merge semantics are unchanged", () => { const dir = makeTmpDir("adpanel-captcha-provider-"); try { const envFile = path.join(dir, ".env"); const { makeWorker, routeWrite } = makeCaptchaWorkers(envFile); const worker = makeWorker({ CAPTCHA_PROVIDER: "recaptcha" }); // File value wins when the provider line is present. routeWrite({ SITE_KEY: "0x4AAAAAAA-nEwKeY01234", SECRET_KEY: "sk_nEwSeCrEt01", CAPTCHA_PROVIDER: "hcaptcha" }); worker.revalidateCaptchaConfigFromDisk(); assert.equal(worker.applied.length, 1); assert.equal(worker.applied[0].provider, "hcaptcha"); // Absent from the file: the boot environment stands (no mirroring change // — the loader never writes CAPTCHA_PROVIDER). routeWrite({ SITE_KEY: "0x4AAAAAAA-nEwKeY01234", SECRET_KEY: "sk_nEwSeCrEt01", PANEL_PUBLIC_URL: "https://panel.example" }); worker.revalidateCaptchaConfigFromDisk(); assert.equal(worker.applied.length, 2); assert.equal(worker.applied[1].provider, "recaptcha"); assert.equal(worker.fakeProcess.env.CAPTCHA_PROVIDER, "recaptcha"); // Explicitly empty in the file: the existing || semantics defer to the // boot environment (deliberately NOT the SITE_KEY/SECRET_KEY empty rule). routeWrite({ SITE_KEY: "0x4AAAAAAA-nEwKeY01234", SECRET_KEY: "sk_nEwSeCrEt01", CAPTCHA_PROVIDER: "" }); worker.revalidateCaptchaConfigFromDisk(); assert.equal(worker.applied.length, 3); assert.equal(worker.applied[2].provider, "recaptcha"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); // --------------------------------------------------------------------------- // global alerts — two workers over one file // --------------------------------------------------------------------------- function makeAlertsWorkers(alertFile) { const sanitizeFn = extractFunction(indexSource, "function sanitizeGlobalAlertMessage("); const normalizeFn = extractFunction(indexSource, "function normalizeGlobalAlert("); const loadFn = extractFunction(indexSource, "function loadGlobalAlerts("); const sandbox = new Function( "fs", "GLOBAL_ALERT_FILE", "GLOBAL_ALERT_MAX_MESSAGE_LENGTH", `${sanitizeFn}\n${normalizeFn}\n${loadFn}\nreturn { loadGlobalAlerts, normalizeGlobalAlert };` )(fs, alertFile, 500); const makeWorker = () => createStatKeyedCache({ filePath: alertFile, load: sandbox.loadGlobalAlerts, ttlMs: 30 * 1000, label: "[global-alerts]", }); // The saveGlobalAlerts shape: normalize → write (0o600) → chmod → seed. const save = (cache, alerts) => { const normalized = (Array.isArray(alerts) ? alerts : []).map(sandbox.normalizeGlobalAlert).filter(Boolean); fs.writeFileSync(alertFile, JSON.stringify(normalized, null, 2), { encoding: "utf8", mode: 0o600 }); try { fs.chmodSync(alertFile, 0o600); } catch (e) { } cache.put(normalized); return true; }; return { makeWorker, save, normalizeGlobalAlert: sandbox.normalizeGlobalAlert }; } test("a global alert added on one worker renders on the sibling's next read", () => { const dir = makeTmpDir("adpanel-alerts-"); try { const file = path.join(dir, "global-alert.json"); const { makeWorker, save, normalizeGlobalAlert } = makeAlertsWorkers(file); const workerA = makeWorker(); const workerB = makeWorker(); // Both boot with no alert. assert.deepEqual(workerA.get(), []); assert.deepEqual(workerB.get(), []); // Worker A's admin adds the banner (the maintenance pre-alert injection // rides the same path). const alert = normalizeGlobalAlert({ id: "maint-1", message: "Scheduled maintenance today at 3pm", date: new Date().toISOString(), createdAt: new Date().toISOString(), }); assert.ok(save(workerA, [alert])); // Worker B previously never saw it until restart. const seen = workerB.get(); assert.equal(seen.length, 1); assert.equal(seen[0].id, "maint-1"); assert.equal(seen[0].message, "Scheduled maintenance today at 3pm"); // Removal (pre-alert restore) converges too. assert.ok(save(workerA, [])); assert.deepEqual(workerB.get(), []); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("a corrupt alerts file keeps the loader's fail-empty contract on a warm worker", () => { const dir = makeTmpDir("adpanel-alerts-corrupt-"); try { const file = path.join(dir, "global-alert.json"); const { makeWorker, save } = makeAlertsWorkers(file); const workerA = makeWorker(); const workerB = makeWorker(); workerA.get(); workerB.get(); const alert = { id: "a1", message: "hello", date: new Date().toISOString(), createdAt: new Date().toISOString() }; assert.ok(save(workerA, [alert])); assert.equal(workerB.get().length, 1); atomicReplace(file, "not json at all"); // loadGlobalAlerts resolves read errors to the empty list it always has — // banners are content, not a gate, so the existing fail-empty contract // (never throws) is preserved through the shared cache. assert.deepEqual(workerB.get(), []); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); // --------------------------------------------------------------------------- // dashboard-assistant config — the refactored loader keeps its behavior // --------------------------------------------------------------------------- test("the extracted dashboard-assistant loader keeps deny-by-default + chmod repair", () => { const dir = makeTmpDir("adpanel-dash-cfg-"); try { const file = path.join(dir, "dashboard-assistant-config.json"); const normalizeFn = extractFunction(indexSource, "function normalizeDashboardAssistantConfig("); const readJsonFn = extractFunction(indexSource, "function readJson("); const loadFn = extractFunction(indexSource, "function loadDashboardAssistantConfigFromDisk("); const loadFromDisk = new Function( "fs", "DASHBOARD_ASSISTANT_CONFIG_FILE", "readJson", "normalizeDashboardAssistantConfig", "console", `${normalizeFn}\n${readJsonFn}\n${loadFn}\nreturn loadDashboardAssistantConfigFromDisk;` )(fs, file, null, null, console); // A legacy world-readable file is tightened in place and its content // normalized (the exact pre-refactor behavior). fs.writeFileSync(file, JSON.stringify({ allowNormalUsers: true, updatedAt: "u1", updatedBy: "a1" }), { mode: 0o644 }); const loaded = loadFromDisk(); assert.deepEqual(loaded, { allowNormalUsers: true, updatedAt: "u1", updatedBy: "a1" }); assert.equal(fs.statSync(file).mode & 0o777, 0o600, "mode repair still runs inside the shared load step"); // Missing file → the deny-by-default shape readJson's fallback produces. fs.rmSync(file, { force: true }); assert.deepEqual(loadFromDisk(), { allowNormalUsers: false, updatedAt: null, updatedBy: null }); // Corrupt file → same deny-by-default (a revocation can never be re-enabled). fs.writeFileSync(file, "{oops", "utf8"); assert.deepEqual(loadFromDisk(), { allowNormalUsers: false, updatedAt: null, updatedBy: null }); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("the dashboard-assistant get/save go through the shared cache end-to-end", () => { const dir = makeTmpDir("adpanel-dash-e2e-"); try { const file = path.join(dir, "dashboard-assistant-config.json"); const normalizeFn = extractFunction(indexSource, "function normalizeDashboardAssistantConfig("); const readJsonFn = extractFunction(indexSource, "function readJson("); const loadFn = extractFunction(indexSource, "function loadDashboardAssistantConfigFromDisk("); const loadFromDisk = new Function( "fs", "DASHBOARD_ASSISTANT_CONFIG_FILE", "readJson", "normalizeDashboardAssistantConfig", "console", `${normalizeFn}\n${readJsonFn}\n${loadFn}\nreturn loadDashboardAssistantConfigFromDisk;` )(fs, file, null, null, console); // Worker A revokes normal-user access; worker B (cold boot) must see the // revocation on its first read — the cross-worker invalidation the inline // copy used to provide is preserved by the shared helper. atomicReplace(file, JSON.stringify({ allowNormalUsers: false, updatedAt: "t", updatedBy: "admin" })); const workerB = createStatKeyedCache({ filePath: file, load: loadFromDisk, ttlMs: 30 * 1000, label: "[dashboard-assistant]" }); assert.equal(workerB.get().allowNormalUsers, false); atomicReplace(file, JSON.stringify({ allowNormalUsers: true, updatedAt: "t2", updatedBy: "admin" })); assert.equal(workerB.get().allowNormalUsers, true); } finally { fs.rmSync(dir, { recursive: true, force: true }); } });