"use strict"; // adpanel:config-stat-revalidation — hot-swapped config state is worker-local // in a multi-worker deployment (the shipped default: scripts/generate-ecosystem.sh // sets INSTANCES to cores-2, and Redis mode permits multi-worker — the // file-store cluster guard exits only for file-store mode). A worker that // loads a config once at boot and then trusts its own memory silently // diverges from every sibling: a maintenance toggle landing on worker A // leaves B..N serving the full authenticated surface (a silent lockdown // bypass, and the reverse direction 503s them until restart), a captcha // enable leaves the login surface unprotected on B..N, a global alert never // renders there. This module is the ONE home of the cross-worker // revalidation pattern every such consumer must use: stat the backing file // (mtime+size+device/inode) on every read and reload through the caller's `load` callback // when the key changes. Every writer these configs have replaces the file via // atomic rename (or, for .env, atomicWriteFileSync), so a changed mtime OR // size is a valid cross-worker "someone else saved" signal; size hardens the // old mtime-only check against coarse (1s) mtime granularity where two // distinct saves can land on one mtime value. Device/inode identity detects // same-size atomic replacements even when their modification times collide. // Worker-local memory is a CACHE // of the file, never the source of truth for these controls. // // fs.watch is deliberately NOT used here: the stat-key pattern is the // documented-acceptable one for hot-swapped config; SECURITY_FILE's fs.watch // remains the only watcher in the panel (do not extend that pattern). const fs = require("fs"); // The TTL is a force-reload BACKSTOP, not the primary signal: it closes the // residual hole no stat can see — an in-place same-size rewrite with a hidden // modification-time change retains file identity too. `ttlMs: 0` disables the backstop // (stat-key-only revalidation) for consumers where same-key content changes // are impossible; a TTL that expires does at most one extra read+parse per // window per worker, so security-relevant consumers pick a small value // (the panel's own precedent: 30s documented acceptable for the // dashboard-assistant toggle, tighter bounds chosen for gate-adjacent ones). // // `load(filePath)` is the caller's read+parse contract and must be INTERNALLY // fail-safe — a parse failure resolves to whatever fail-closed/fail-empty // default that config's loader already defines (every consumer in index.js // does). If it throws anyway, the previous cache survives untouched and one // warn per failure episode is emitted, so a torn file or a failing disk can // never wipe working in-memory config (the get() path then keeps serving the // last known-good value until a reload succeeds again). // // A load that returns null is treated as a cold cache (re-read on every // get()): consumers return objects/arrays, never null. function createStatKeyedCache({ filePath, load, ttlMs = 0, label = "[config]" }) { if (typeof filePath !== "string" || !filePath) { throw new Error("createStatKeyedCache: filePath is required"); } if (typeof load !== "function") { throw new Error("createStatKeyedCache: load callback is required"); } let cachedValue = null; // adpanel:config-replacement-identity - atomic rename changes the file's // identity even when a coarse timestamp and equal byte length do not. let cachedKey = null; // Wall-clock age of the cache, for the TTL backstop above. let cachedAtMs = 0; // One warn per failure episode: a stat/read/parse error warns once, not // once per request; a successful reload re-arms it for the next episode. let loadFailedEpisode = false; // { mtimeMs: -1, size: -1 } when the file is missing/unstatable: a loaded // cache recorded real values, so -1 mismatches on either field and forces // a reload attempt (whose read error then fails safe). Must never throw // through callers. function statKey() { try { const st = fs.statSync(filePath); return { mtimeMs: st.mtimeMs, size: st.size, dev: st.dev, ino: st.ino }; } catch { return { mtimeMs: -1, size: -1 }; } } function warnLoadFailure(err) { if (loadFailedEpisode) return; loadFailedEpisode = true; // Never logs file content or config values — only the error message. console.warn( `${label} Failed to revalidate config from ${filePath} — keeping the last known-good in-memory state:`, (err && err.message) || err ); } // Unconditional reload. Stat BEFORE reading: a write landing between the // stat and the read leaves the recorded key older than the file's, so the // next get() reloads (spurious). Statting after the read could pin newer // content as already-seen while the cache holds the previous one. function reload() { const key = statKey(); const atMs = Date.now(); let value; try { value = load(filePath); } catch (err) { // Fail-safe: keep the previous cached value/key exactly as they were // (never pair a fresh key with stale-or-absent content) and warn. warnLoadFailure(err); throw err; } loadFailedEpisode = false; cachedKey = key; cachedAtMs = atMs; cachedValue = value; return value; } function get() { if (cachedValue === null) { return reload(); } // Cross-worker invalidation: another pm2 cluster sibling may have // replaced the file. A timestamp, size, or file-identity mismatch — or the file // vanishing — re-reads it, so a sibling's save takes effect within one // read on every worker instead of never. const key = statKey(); if ( !cachedKey || key.mtimeMs !== cachedKey.mtimeMs || key.size !== cachedKey.size || (cachedKey.dev !== undefined && key.dev !== cachedKey.dev) || (cachedKey.ino !== undefined && key.ino !== cachedKey.ino) || (ttlMs > 0 && Date.now() - cachedAtMs >= ttlMs) ) { try { return reload(); } catch (err) { // Warm-cache reload failure: keep serving the last known-good value // (the episode warn already fired in reload). return cachedValue; } } return cachedValue; } // Seed/overwrite the cache after a save THIS worker performed (writer-local // immediate visibility — the file is this worker's own write, so the value // is known-good without a re-read). `key` defaults to a fresh stat taken // here, i.e. AFTER the caller's write landed; pass the stat captured // immediately before a readback verification to avoid pairing the seeded // value with a sibling's newer key (the dashboard-assistant save's race). function put(value, key) { cachedValue = value; cachedKey = key || statKey(); cachedAtMs = Date.now(); loadFailedEpisode = false; return value; } return { get, reload, put, statKey }; } module.exports = { createStatKeyedCache };