"use strict"; // Tests for the template-store sync backoff (audit finding: "Failed store // syncs re-trigger on every admin read, forever, with no backoff"). // // A failed sync throws before writing the manifest, so manifest.syncedAt — // and with it the `stale` check in ensureTemplateStoreCacheFresh — stayed old // permanently. While TEMPLATE_STORE_TRUST.autoUpdate was on, every admin // GET /api/settings/template-store/categories and /:category then fired a // fresh syncTemplateStoreCache("stale-refresh"): one upstream listing plus up // to ~500 per-file fetches, each retried against GitHub then jsDelivr with // 15s timeouts. Any persistently failing sync (GitHub outage, no egress, an // enforce-mode key-rotation window where syncs fail closed for a release // cycle) turned routine store browsing into repeated full upstream fetch // bursts — and since these are top-level SameSite=Lax GETs, an external page // could drive that loop through a logged-in admin's browser via navigations. // // The remediation under test: // 1. syncTemplateStoreCache stamps templateStoreLastSyncAttemptAt (wall // clock) on every STARTED attempt, success or failure — after the // in-flight dedupe early-return (a deduped call must not refresh it) and // before the promise assignment (no await between the statements, so the // ordering is race-free). // 2. The stale-refresh auto-trigger only fires when no attempt was ever // made (attemptAt === 0) or the last attempt is older than // TEMPLATE_STORE_SYNC_INTERVAL_MS — failures back off for the full sync // interval instead of retrying on every admin read. // 3. The step-up-protected manual forced sync (force: true) and the // !hasCache first-load path stay UNgated: a forced sync is an explicit // admin action after review, and without a cache the store can never // populate (first syncs fail fast on the listing fetch and dedupe while // in-flight). // 4. Both admin cache payloads (per-category read and the categories // listing route) expose lastAttemptAt additively so operators can see // the backoff state. // // index.js boots servers on require, so syncTemplateStoreCache and // ensureTemplateStoreCacheFresh are sliced out of the source and evaluated in // a vm sandbox with stubbed I/O (same technique as // template-store-sync-limits.test.js), alongside source assertions in the // extract-and-regex style of tests/destructive-route-guards.test.js. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const INDEX_JS = path.join(__dirname, "..", "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const INTERVAL = 60 * 60 * 1000; function endIndexOfFunction(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker ${startMarker} not found in index.js`); 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 sliceBetween(source, startMarker, endMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start); assert.ok(end > start, `end marker not found after start: ${endMarker}`); return source.slice(start, end); } function buildBackoffCode() { // The size-limit constants the real listing pre-flight reads (env-driven, // same slice boundaries as template-store-sync-limits.test.js). const constStart = indexSource.indexOf("const TEMPLATE_STORE_FILE_MAX_BYTES"); assert.ok(constStart >= 0, "template store size constants not found"); const constEnd = indexSource.indexOf("// Template images (installer AND runtime)"); assert.ok(constEnd > constStart, "size constants block boundary not found"); const limitsStart = indexSource.indexOf("function evaluateTemplateStoreListingLimits"); const limitsEnd = endIndexOfFunction(indexSource, "function evaluateTemplateStoreListingLimits"); const syncStart = indexSource.indexOf("async function syncTemplateStoreCache"); const syncEnd = endIndexOfFunction(indexSource, "async function syncTemplateStoreCache"); // ensureTemplateStoreCacheFresh destructures its params ({ waitForFirstSync // = true, force = false }), so the brace-count extractor would stop at the // parameter list — slice to the next top-level statement instead. const ensureCode = sliceBetween( indexSource, "async function ensureTemplateStoreCacheFresh", "const TEMPLATE_STORE_UPSTREAM_SOURCES" ); // Module-level state the sliced functions close over in index.js — kept in // lockstep with the real declarations next to TEMPLATE_STORE_CATEGORY_IDS // so a drift in index.js fails loudly here. const prelude = [ "let templateStoreSyncPromise = null;", 'let templateStoreLastSyncError = "";', 'let templateStoreLastSyncWarning = "";', "let templateStoreLastSyncAttemptAt = 0;", ].join("\n"); return [ prelude, indexSource.slice(constStart, constEnd), indexSource.slice(limitsStart, limitsEnd), indexSource.slice(syncStart, syncEnd), ensureCode, ].join("\n"); } const BACKOFF_CODE = buildBackoffCode(); // A fresh sandbox per scenario: silent console, stubbed I/O that fails the // test by default, and the store trust config an individual test overrides. // The module-level `let` bindings live in the context's global lexical // environment (not on the sandbox object), so tests read/write them through // vm.runInContext expressions via the get()/set() helpers below. function buildSandbox(stubs = {}) { const sandbox = { console: { log() { }, warn() { }, error() { } }, process: { env: {} }, Buffer, crypto: require("node:crypto"), path, fsp: { mkdir: async () => { } }, TEMPLATE_STORE_CATEGORIES: [ { id: "games", label: "Games" }, { id: "communication", label: "Communication" }, { id: "development", label: "Development" }, { id: "hosting", label: "Hosting" }, { id: "media", label: "Media" }, ], TEMPLATE_STORE_CACHE_DIR: "/tmp/adpanel-sync-backoff-test/cache", TEMPLATE_STORE_MANIFEST_FILE: "/tmp/adpanel-sync-backoff-test/cache/manifest.json", TEMPLATE_STORE_REPO: "example/store", TEMPLATE_STORE_REF: "main", TEMPLATE_STORE_LOCAL_OVERRIDES_ENABLED: false, TEMPLATE_STORE_LOCAL_OVERRIDE_DIR: "/tmp/adpanel-sync-backoff-test/overrides", TEMPLATE_STORE_SYNC_INTERVAL_MS: INTERVAL, // autoUpdate defaults to ON — the only mode in which the stale-refresh // trigger exists; individual tests override it to prove the ungated paths // do not depend on it. TEMPLATE_STORE_TRUST: { mode: "warn", key: null, keyPinned: false, autoUpdate: true }, readTemplateStoreManifest: async () => null, templateStoreHasCachedFiles: async () => true, listTemplateStoreRemoteFiles: async () => ({ files: [], source: "github" }), fetchTemplateStoreFileRaw: async () => { throw new Error("fetch stub must not be reached"); }, verifyListedContentHash: () => ({ verified: true }), verifyStoreSignature: () => ({ verified: true, digest: "", generatedAt: "", reason: "" }), fetchTemplateStoreSignatureFile: async () => ({ signatureFile: null, warning: "" }), readTemplateStoreTrustState: async () => null, writeTemplateStoreTrustState: async () => { }, writeFileAtomic: async () => { }, readTemplateStoreLocalOverrides: async () => [], selectTemplateStoreLocalOverrideDisposition: () => ({ apply: false, reason: "test stub" }), pruneTemplateStoreCategory: async () => { }, buildStoreSyncDiff: () => ({}), normalizeTemplateDefinition: (template) => template, ...stubs, }; vm.createContext(sandbox); vm.runInContext(BACKOFF_CODE, sandbox); return sandbox; } const get = (sandbox, expr) => vm.runInContext(expr, sandbox); // Host-level macrotask tick: lets microtasks queued by the vm-realm stubs // drain (vm contexts have no timers of their own). const tick = (ms = 10) => new Promise((resolve) => setTimeout(resolve, ms)); // --------------------------------------------------------------------------- // Behavioral tests (real sliced functions executed against stubbed I/O) // --------------------------------------------------------------------------- test("a failed sync stamps templateStoreLastSyncAttemptAt, records the error, writes no manifest, and rethrows", async () => { const writes = []; const sandbox = buildSandbox({ listTemplateStoreRemoteFiles: async () => { throw new Error("github unreachable"); }, writeFileAtomic: async (target, content) => { writes.push({ target, content }); }, }); await assert.rejects( get(sandbox, "syncTemplateStoreCache('stale-refresh')"), /github unreachable/, "the sync must keep its fail-loud rethrow" ); const attemptAt = get(sandbox, "templateStoreLastSyncAttemptAt"); assert.ok(attemptAt > 0, "a failed attempt must still stamp the attempt timestamp"); assert.ok(Math.abs(Date.now() - attemptAt) < 5000, "the stamp must be wall-clock now"); assert.equal(get(sandbox, "templateStoreLastSyncError"), "github unreachable"); assert.equal(get(sandbox, "templateStoreSyncPromise"), null, "the in-flight dedupe slot must be cleared after the failure"); assert.equal(writes.length, 0, "a failed sync must not write a manifest — which is exactly why syncedAt alone cannot back off retries"); }); test("a successful sync also stamps the attempt timestamp", async () => { const sandbox = buildSandbox(); await get(sandbox, "syncTemplateStoreCache('scheduled')"); const attemptAt = get(sandbox, "templateStoreLastSyncAttemptAt"); assert.ok(attemptAt > 0, "successes stamp the attempt too — the gate keys on the last TRY, not the last failure"); assert.ok(Math.abs(Date.now() - attemptAt) < 5000); assert.equal(get(sandbox, "templateStoreLastSyncError"), "", "a successful sync clears the error"); }); test("a deduped call while a sync is in flight does not refresh the attempt timestamp", async () => { let listingCalls = 0; let releaseListing; const listingGate = new Promise((resolve) => { releaseListing = resolve; }); const sandbox = buildSandbox({ listTemplateStoreRemoteFiles: async () => { listingCalls += 1; await listingGate; return { files: [], source: "github" }; }, }); const first = get(sandbox, "syncTemplateStoreCache('scheduled')"); // syncTemplateStoreCache is an async function, so its return value is a // per-call wrapper; the DEDUPE state is the inner chained promise stored // in templateStoreSyncPromise — that is what must be shared, not the // wrapper identity. const innerPromise = get(sandbox, "templateStoreSyncPromise"); assert.ok(innerPromise, "the first sync must be in flight"); const stampedAt = get(sandbox, "templateStoreLastSyncAttemptAt"); assert.ok(stampedAt > 0, "the first attempt stamps synchronously"); const second = get(sandbox, "syncTemplateStoreCache('manual')"); assert.equal(get(sandbox, "templateStoreSyncPromise"), innerPromise, "a deduped call must not replace the in-flight sync promise"); assert.equal(get(sandbox, "templateStoreLastSyncAttemptAt"), stampedAt, "a deduped call must NOT refresh the attempt timestamp"); releaseListing(); const [firstResult, secondResult] = await Promise.all([first, second]); await tick(); assert.equal(firstResult, secondResult, "both callers must receive the same sync result"); assert.equal(listingCalls, 1, "dedupe must not start a second upstream listing"); }); test("stale auto-refresh backs off while the last attempt is fresh, retries once the attempt ages past the interval", async () => { let listingCalls = 0; const writes = []; const staleManifest = { syncedAt: new Date(Date.now() - 2 * INTERVAL).toISOString(), categories: {} }; const sandbox = buildSandbox({ readTemplateStoreManifest: async () => staleManifest, listTemplateStoreRemoteFiles: async () => { listingCalls += 1; return { files: [], source: "github" }; }, writeFileAtomic: async (target, content) => { writes.push(JSON.parse(content)); }, }); // Fresh failure moments ago: the attempt timestamp must suppress the // auto-retry even though the manifest is far past the sync interval. get(sandbox, "templateStoreLastSyncAttemptAt = Date.now()"); const heldBack = await get(sandbox, "ensureTemplateStoreCacheFresh({ waitForFirstSync: false })"); assert.equal(heldBack, staleManifest, "the read must fall through to the last manifest"); assert.equal(listingCalls, 0, "a fresh failed attempt must suppress the stale-refresh fetch burst"); assert.equal(get(sandbox, "!!templateStoreSyncPromise"), false, "no sync may be left in flight while backing off"); // Once the attempt is older than TEMPLATE_STORE_SYNC_INTERVAL_MS, the next // stale read fires exactly one auto-retry. get(sandbox, "templateStoreLastSyncAttemptAt -= (TEMPLATE_STORE_SYNC_INTERVAL_MS + 1000)"); await get(sandbox, "ensureTemplateStoreCacheFresh({ waitForFirstSync: false })"); await get(sandbox, "templateStoreSyncPromise || Promise.resolve()"); await tick(); assert.equal(listingCalls, 1, "an aged-out attempt must allow exactly one stale-refresh"); assert.equal(writes[0]?.reason, "stale-refresh", "the retried sync must complete and write the manifest"); }); test("attemptAt === 0 (never attempted) lets the stale auto-refresh fire immediately", async () => { let listingCalls = 0; const staleManifest = { syncedAt: new Date(Date.now() - 2 * INTERVAL).toISOString(), categories: {} }; const sandbox = buildSandbox({ readTemplateStoreManifest: async () => staleManifest, listTemplateStoreRemoteFiles: async () => { listingCalls += 1; return { files: [], source: "github" }; }, }); assert.equal(get(sandbox, "templateStoreLastSyncAttemptAt"), 0); await get(sandbox, "ensureTemplateStoreCacheFresh({ waitForFirstSync: false })"); await get(sandbox, "templateStoreSyncPromise || Promise.resolve()"); await tick(); assert.equal(listingCalls, 1, "a panel that never attempted a sync must not be backed off on its first stale read"); }); test("the step-up-protected manual forced sync stays unconditional despite a fresh attempt and a fresh manifest", async () => { let listingCalls = 0; const writes = []; const freshManifest = { syncedAt: new Date().toISOString(), categories: {} }; const sandbox = buildSandbox({ TEMPLATE_STORE_TRUST: { mode: "warn", key: null, keyPinned: false, autoUpdate: false }, readTemplateStoreManifest: async () => freshManifest, listTemplateStoreRemoteFiles: async () => { listingCalls += 1; return { files: [], source: "github" }; }, writeFileAtomic: async (target, content) => { writes.push(JSON.parse(content)); }, }); get(sandbox, "templateStoreLastSyncAttemptAt = Date.now()"); // an attempt moments ago await get(sandbox, "ensureTemplateStoreCacheFresh({ force: true, waitForFirstSync: false })"); assert.equal(listingCalls, 1, "force: true must bypass the attempt backoff — it is the admin's explicit reviewed action"); assert.equal(writes[0]?.reason, "manual"); }); test("the !hasCache first-load path stays retry-eager even with a fresh failed attempt", async () => { let listingCalls = 0; const writes = []; const sandbox = buildSandbox({ TEMPLATE_STORE_TRUST: { mode: "warn", key: null, keyPinned: false, autoUpdate: false }, readTemplateStoreManifest: async () => null, templateStoreHasCachedFiles: async () => false, listTemplateStoreRemoteFiles: async () => { listingCalls += 1; return { files: [], source: "github" }; }, writeFileAtomic: async (target, content) => { writes.push(JSON.parse(content)); }, }); get(sandbox, "templateStoreLastSyncAttemptAt = Date.now()"); // an attempt moments ago await get(sandbox, "ensureTemplateStoreCacheFresh({ waitForFirstSync: false })"); assert.equal(listingCalls, 1, "first-load must not be attempt-gated: without a cache the store can never populate"); assert.equal(writes[0]?.reason, "first-load"); }); // --------------------------------------------------------------------------- // Source assertions (the payload/scheduler wiring is not cheap to execute in // isolation, so it is pinned against the extracted source, per the // destructive-route-guards.test.js convention) // --------------------------------------------------------------------------- test("source: index.js declares templateStoreLastSyncAttemptAt beside the other sync globals", () => { const globals = sliceBetween(indexSource, "let templateStoreSyncPromise = null;", "function safeTemplateStoreCategoryId"); assert.match(globals, /let templateStoreLastSyncError = "";/); assert.match(globals, /let templateStoreLastSyncWarning = "";/); assert.match(globals, /let templateStoreLastSyncAttemptAt = 0;/, "the attempt timestamp must be declared next to the sync globals"); assert.match(globals, /TEMPLATE_STORE_SYNC_INTERVAL_MS/, "the rationale comment must reference the real interval constant"); }); test("source: syncTemplateStoreCache stamps the attempt after the dedupe early-return and before the promise assignment", () => { const sync = sliceBetween(indexSource, "async function syncTemplateStoreCache", "async function ensureTemplateStoreCacheFresh"); const dedupe = sync.indexOf("if (templateStoreSyncPromise) return templateStoreSyncPromise;"); const stamp = sync.indexOf("templateStoreLastSyncAttemptAt = Date.now();"); const assign = sync.indexOf("templateStoreSyncPromise = (async () => {"); assert.ok(dedupe >= 0, "the in-flight dedupe early-return must still exist"); assert.ok(stamp >= 0, "the attempt stamp is missing"); assert.ok(assign >= 0, "the promise assignment is missing"); assert.ok(dedupe < stamp, "a deduped call must return before the timestamp is refreshed"); assert.ok(stamp < assign, "the attempt must be stamped before the in-flight promise exists"); }); test("source: the stale-refresh trigger is gated on the attempt timestamp and the interval constant", () => { const ensure = sliceBetween(indexSource, "async function ensureTemplateStoreCacheFresh", "const TEMPLATE_STORE_UPSTREAM_SOURCES"); const gate = ensure.indexOf("templateStoreLastSyncAttemptAt === 0"); assert.ok(gate >= 0, "the gate must special-case a never-attempted store"); assert.match( ensure, /\(Date\.now\(\) - templateStoreLastSyncAttemptAt\) >= TEMPLATE_STORE_SYNC_INTERVAL_MS/, "failures must back off for the full sync interval — derived from the constant, never a hardcoded ms value" ); const autoUpdateGate = ensure.indexOf("if (TEMPLATE_STORE_TRUST.autoUpdate) {"); const trigger = ensure.indexOf('syncTemplateStoreCache("stale-refresh")'); assert.ok(autoUpdateGate >= 0 && autoUpdateGate < gate && gate < trigger, "the attempt gate must sit inside the autoUpdate review gate, wrapping only the stale-refresh call"); assert.match(ensure, /Review gate: with auto-update off/, "the existing autoUpdate rationale comment must survive"); assert.match(ensure, /without a cache the store can never populate/, "the first-load path must carry its retry-eager rationale"); assert.match(ensure, /templateStoreSyncPromise/, "the in-flight dedupe must still be part of the trigger condition"); }); test("source: the manual forced sync and first-load paths are NOT wrapped in the attempt gate", () => { const ensure = sliceBetween(indexSource, "async function ensureTemplateStoreCacheFresh", "const TEMPLATE_STORE_UPSTREAM_SOURCES"); const firstAttemptRef = ensure.indexOf("templateStoreLastSyncAttemptAt"); assert.ok(firstAttemptRef >= 0, "the gate must reference the attempt timestamp"); const manualReturn = ensure.indexOf('return syncTemplateStoreCache("manual")'); const firstLoad = ensure.indexOf('syncTemplateStoreCache("first-load")'); assert.ok(manualReturn >= 0 && manualReturn < firstAttemptRef, "force: true must return before any attempt-gate logic"); assert.ok(firstLoad >= 0 && firstLoad < firstAttemptRef, "first-load must fire before any attempt-gate logic"); }); test("source: both admin cache payloads expose lastAttemptAt additively alongside the existing fields", () => { const field = "lastAttemptAt: templateStoreLastSyncAttemptAt ? new Date(templateStoreLastSyncAttemptAt).toISOString() : null"; const perCategory = sliceBetween(indexSource, "async function readTemplateStoreCategoryFromCache", "function scheduleTemplateStoreSync"); const categoriesRoute = sliceBetween( indexSource, 'app.get("/api/settings/template-store/categories"', 'app.post("/api/settings/template-store/sync"' ); for (const [name, payload] of [["per-category", perCategory], ["categories route", categoriesRoute]]) { assert.ok(payload.includes(field), `${name} payload must expose lastAttemptAt`); assert.match(payload, /syncing: !!templateStoreSyncPromise/, `${name} payload must keep the syncing field`); assert.match(payload, /error: templateStoreLastSyncError \|\| ""/, `${name} payload must keep the error field`); assert.match(payload, /warning: templateStoreLastSyncWarning \|\| ""/, `${name} payload must keep the warning field`); } }); test("source: the scheduled interval still routes through ensureTemplateStoreCacheFresh on the real constant", () => { const scheduler = sliceBetween(indexSource, "function scheduleTemplateStoreSync", "scheduleTemplateStoreSync();"); assert.match(scheduler, /ensureTemplateStoreCacheFresh\(\{ waitForFirstSync: false \}\)/, "scheduled syncs must keep going through the gated read path"); assert.match(scheduler, /TEMPLATE_STORE_SYNC_INTERVAL_MS/, "the interval must stay derived from the constant"); });