Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

@@ -0,0 +1,902 @@
"use strict";
// Tests for audit finding 6 — the periodic action-token refresh and the
// bounded reset-dialog retries.
//
// Finding (pre-fix): refreshSettingsActionTokens() lives in the panel-info
// IIFE but Object.assign'ed the token stores of SIBLING IIFEs directly
// (securityActionTokens, maintenanceActionTokens, sessionsState,
// webhookActionTokens). The first statement threw ReferenceError, the bare
// `catch (_) {}` swallowed it, and the three-minute refresh therefore never
// reached ANY store — including the accountsListEl/serversListEl merges that
// only run after it. Token lifetime is 10 minutes, so an idle tab accumulated
// expired tokens for the 2FA reset and recovery-code reset dialogs, which had
// NO retry at all and died on "invalid or missing action token".
//
// Fix contract:
// 1. An explicit top-level registry (const settingsActionTokenRegistries =
// new Set() + registerSettingsActionTokenRegistry) — no window globals.
// Each owning scope registers its live store right where it is declared.
// Because every section loader REASSIGNS its token binding on each fetch
// (`securityActionTokens = data.actionTokens` and friends), a registered
// store may be a live VIEW (createSettingsActionTokenView) whose writes
// are forwarded to whatever object the owning binding holds at write
// time — identity is preserved across reassignments without touching the
// loaders' existing writes.
// 2. The refresher iterates the registry and Object.assigns the minted pool
// into every registered store, then keeps the existing
// accountsListEl/serversListEl merges, the 3-minute gap guard, the
// visibilitychange hook and the immediate call. The silent catch becomes
// a logged catch (a hidden failure can never again masquerade as a
// refresh).
// 3. Both reset dialogs (confirmQRReset, generateNewRecoveryCodes) reuse the
// established reload-once retry shape (grant-perms / revoke / agent /
// change-password): on the token-invalid error ONLY, await loadAccounts()
// (which re-mints the pool), re-read the token and resend AT MOST ONCE.
// The body was built once from the still-open modal's live inputs, so the
// typed password and TOTP code survive the reload. Step-up challenge
// payloads (password-required / 2fa-required / invalid-*) are NOT token
// errors and must keep opening the challenge modal without any retry.
//
// Harness: the house extraction technique (same as
// tests/audit-l3-l5-access-stepup.test.js for source pins and
// tests/admin-2fa-reset-preflight.test.js / tests/regen-recovery-two-step.test.js
// for vm behavior) — the REAL registry block, the REAL refresher and the REAL
// dialog bodies are extracted from settings.js verbatim and executed against
// stub fetch/document/loadAccounts.
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 ROOT = path.join(__dirname, "..");
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8");
function countOccurrences(haystack, needle) {
return haystack.split(needle).length - 1;
}
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start + startMarker.length);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
// ---------------------------------------------------------------------------
// Extracted REAL source (each slice is a self-contained statement sequence)
// ---------------------------------------------------------------------------
const REGISTRY_BLOCK = sliceBetween(
settingsJsSource,
"const settingsActionTokenRegistries = new Set();",
"const nodesListEl = document.getElementById('nodesList');"
);
const REFRESHER_BLOCK = sliceBetween(
settingsJsSource,
"let _settingsTokenRefreshAt = 0;",
"})();"
);
const QR_RESET_FN = sliceBetween(
settingsJsSource,
"async function confirmQRReset() {",
"if (qrOptionsModalClose) qrOptionsModalClose.addEventListener"
);
const RECOVERY_RESET_FN = sliceBetween(
settingsJsSource,
"async function generateNewRecoveryCodes() {",
"if (recoveryResetModalClose) recoveryResetModalClose.addEventListener"
);
const CREDENTIAL_HELPERS = sliceBetween(
settingsJsSource,
"function collectAccountActionCredentialPayload(",
"function ensureAccountActionPasswordVisible("
);
// ---------------------------------------------------------------------------
// Source pins — the explicit registry, no window globals, no fork
// ---------------------------------------------------------------------------
test("source: the top-level registry block declares the Set, the guarded register helper and the live-view factory — with nothing on window", () => {
assert.ok(
REGISTRY_BLOCK.includes("function registerSettingsActionTokenRegistry(registry)"),
"the register helper must exist at top level"
);
assert.ok(
REGISTRY_BLOCK.includes("if (registry && typeof registry === 'object') settingsActionTokenRegistries.add(registry);"),
"the register helper must guard its argument"
);
assert.ok(
REGISTRY_BLOCK.includes("function createSettingsActionTokenView(getStore)"),
"the live-view factory must exist for scopes whose loaders reassign their binding"
);
assert.ok(
REGISTRY_BLOCK.includes("new Proxy("),
"the live view must forward writes to the current binding"
);
assert.ok(
!REGISTRY_BLOCK.includes("window."),
"the registry must not leak anything onto window"
);
assert.equal(
countOccurrences(settingsJsSource, "const settingsActionTokenRegistries = new Set();"),
1,
"the registry must be declared exactly once"
);
assert.equal(
countOccurrences(settingsJsSource, "registerSettingsActionTokenRegistry("),
6,
"one definition plus exactly five owning-scope registrations"
);
assert.equal(
countOccurrences(settingsJsSource, "createSettingsActionTokenView("),
6,
"one definition plus exactly five live-view registrations"
);
});
test("source: the refresher references NO out-of-scope store and iterates the registry, keeping the el merges", () => {
for (const outOfScope of [
"securityActionTokens",
"maintenanceActionTokens",
"webhookActionTokens",
"_panelInfoTokens",
"sessionsState",
]) {
assert.ok(
!REFRESHER_BLOCK.includes(outOfScope),
`the refresher must not reference the scope-local ${outOfScope} (the pre-fix ReferenceError)`
);
}
assert.ok(
REFRESHER_BLOCK.includes("for (const registry of settingsActionTokenRegistries) {"),
"the refresher must iterate the registry"
);
assert.equal(
countOccurrences(REFRESHER_BLOCK, "Object.assign(registry, tokens);"),
1,
"the registry merge must appear exactly once"
);
assert.ok(
REFRESHER_BLOCK.includes("if (registry && typeof registry === 'object') Object.assign(registry, tokens);"),
"each registered store must be guarded before assignment"
);
assert.ok(
REFRESHER_BLOCK.includes("if (accountsListEl) accountsListEl._actionTokens") &&
REFRESHER_BLOCK.includes("if (serversListEl) serversListEl._actionTokens"),
"the existing accountsListEl/serversListEl merges must stay"
);
assert.ok(
!REFRESHER_BLOCK.includes("catch (_) {"),
"the silent catch must be gone (a hidden failure can no longer masquerade as a refresh)"
);
assert.ok(
REFRESHER_BLOCK.includes("console.error("),
"genuine network failures must be logged, not swallowed"
);
});
test("source: the 3-minute gap guard, interval cadence, visibilitychange reset and immediate call are preserved", () => {
assert.ok(
REFRESHER_BLOCK.includes("if (now - _settingsTokenRefreshAt < 3 * 60 * 1000) return;"),
"the gap guard must stay"
);
assert.ok(
REFRESHER_BLOCK.includes("_settingsTokenRefreshAt = now;"),
"the refresh timestamp must be recorded"
);
assert.ok(
REFRESHER_BLOCK.includes("setInterval(refreshSettingsActionTokens, 3 * 60 * 1000);"),
"the 3-minute interval must stay"
);
assert.ok(
REFRESHER_BLOCK.includes("document.addEventListener('visibilitychange'"),
"the visibilitychange hook must stay"
);
assert.ok(
REFRESHER_BLOCK.includes("_settingsTokenRefreshAt = 0;"),
"becoming visible must reset the gap guard"
);
assert.equal(
countOccurrences(REFRESHER_BLOCK, "refreshSettingsActionTokens();"),
2,
"the visibilitychange handler and the immediate boot call must both invoke the refresher"
);
});
test("source: each owning scope registers its live store right at the declaration", () => {
const cases = [
["let securityActionTokens = {};", "async function loadSecuritySettings() {", "securityActionTokens"],
["let maintenanceActionTokens = {};", "function showFeedback(msg, isError = false) {", "maintenanceActionTokens"],
["const sessionsState = {", "function showSessionsFeedback(message, isError = false) {", "sessionsState.actionTokens"],
["let webhookActionTokens = {};", "const webhookModeSingle = document.getElementById('webhookModeSingle');", "webhookActionTokens"],
["let _panelInfoTokens = {};", "function initializePanelInfoCopyButtons() {", "_panelInfoTokens"],
];
for (const [start, end, storeExpr] of cases) {
const scope = sliceBetween(settingsJsSource, start, end);
assert.ok(
scope.includes(`registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => ${storeExpr}));`),
`${storeExpr} must be registered inside its owning scope as a live view`
);
}
// The sessions registration must follow the const declaration it views.
const sessionsScope = sliceBetween(
settingsJsSource,
"const sessionsState = {",
"function showSessionsFeedback(message, isError = false) {"
);
assert.ok(
sessionsScope.includes("registerSettingsActionTokenRegistry"),
"the sessions registration must sit between the sessionsState declaration and the first sessions function"
);
});
test("source: no window-level token global was introduced anywhere in settings.js", () => {
for (const name of [
"settingsActionTokenRegistries",
"securityActionTokens",
"maintenanceActionTokens",
"webhookActionTokens",
"_panelInfoTokens",
]) {
assert.ok(
!settingsJsSource.includes(`window.${name}`),
`${name} must never be published on window`
);
}
});
// ---------------------------------------------------------------------------
// Source pins — the bounded retry in BOTH reset dialogs (Pattern A reuse)
// ---------------------------------------------------------------------------
test("source: confirmQRReset resends /reset-2fa at most once via loadAccounts on the token-invalid error only", () => {
assert.equal(
countOccurrences(QR_RESET_FN, "'/api/admin/user/reset-2fa'"),
1,
"exactly one fetch site (inside the send helper) may exist"
);
assert.ok(
QR_RESET_FN.includes("let result = await sendReset(getQRResetToken());"),
"the first send must go through the token getter"
);
assert.ok(
QR_RESET_FN.includes("result.data?.error === 'invalid or missing action token'"),
"the retry must match the sibling token-invalid string exactly"
);
assert.equal(
countOccurrences(QR_RESET_FN, "await loadAccounts();"),
1,
"exactly one reload (retry at most once, no loop)"
);
assert.ok(
QR_RESET_FN.includes("const freshToken = getQRResetToken();") &&
QR_RESET_FN.includes("if (freshToken) result = await sendReset(freshToken);"),
"the resend must re-read the re-minted token"
);
const retryAt = QR_RESET_FN.indexOf("invalid or missing action token");
const challengeAt = QR_RESET_FN.indexOf("handleAccountActionCredentialChallenge(");
assert.ok(retryAt >= 0 && challengeAt > retryAt, "the token retry must run BEFORE the challenge handling");
const retrySegment = sliceBetween(
QR_RESET_FN,
"let result = await sendReset(getQRResetToken());",
"const { res, data } = result;"
);
for (const challengeCode of ["2fa-required", "password-required", "invalid-2fa", "isAccountActionChallengeCode"]) {
assert.ok(
!retrySegment.includes(challengeCode),
`the retry segment must not treat the ${challengeCode} challenge as a token error`
);
}
assert.equal(
countOccurrences(QR_RESET_FN, "collectAccountActionCredentialPayload("),
1,
"the body must be built ONCE from the live inputs before any send"
);
const bodyAt = QR_RESET_FN.indexOf("const body = collectAccountActionCredentialPayload(");
const firstSendAt = QR_RESET_FN.indexOf("let result = await sendReset(");
assert.ok(bodyAt >= 0 && bodyAt < firstSendAt, "the body is built before the first send and reused by the resend");
assert.ok(
QR_RESET_FN.includes("body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, body))"),
"the resend must reuse the same credential body object"
);
assert.ok(
QR_RESET_FN.includes("if (handleAccountActionCredentialChallenge(data, {") &&
QR_RESET_FN.includes("onTotpRevealed: () => { qrResetTotpRevealed = true; },") &&
QR_RESET_FN.includes("throw new Error((data && data.error) || 'Failed to reset 2FA');"),
"the step-up challenge handling and the normal error path must be preserved"
);
});
test("source: generateNewRecoveryCodes resends /reset-recovery-codes at most once via loadAccounts on the token-invalid error only", () => {
assert.equal(
countOccurrences(RECOVERY_RESET_FN, "'/api/admin/user/reset-recovery-codes'"),
1,
"exactly one fetch site (inside the send helper) may exist"
);
assert.ok(
RECOVERY_RESET_FN.includes("let result = await sendRecoveryReset(getRecoveryResetToken());"),
"the first send must go through the token getter"
);
assert.ok(
RECOVERY_RESET_FN.includes("result.data?.error === 'invalid or missing action token'"),
"the retry must match the sibling token-invalid string exactly"
);
assert.equal(
countOccurrences(RECOVERY_RESET_FN, "await loadAccounts();"),
1,
"exactly one reload (retry at most once, no loop)"
);
assert.ok(
RECOVERY_RESET_FN.includes("const freshToken = getRecoveryResetToken();") &&
RECOVERY_RESET_FN.includes("if (freshToken) result = await sendRecoveryReset(freshToken);"),
"the resend must re-read the re-minted token"
);
const retryAt = RECOVERY_RESET_FN.indexOf("invalid or missing action token");
const challengeAt = RECOVERY_RESET_FN.indexOf("handleAccountActionCredentialChallenge(");
assert.ok(retryAt >= 0 && challengeAt > retryAt, "the token retry must run BEFORE the challenge handling");
const retrySegment = sliceBetween(
RECOVERY_RESET_FN,
"let result = await sendRecoveryReset(getRecoveryResetToken());",
"const { res, data } = result;"
);
for (const challengeCode of ["2fa-required", "password-required", "invalid-2fa", "isAccountActionChallengeCode"]) {
assert.ok(
!retrySegment.includes(challengeCode),
`the retry segment must not treat the ${challengeCode} challenge as a token error`
);
}
assert.equal(
countOccurrences(RECOVERY_RESET_FN, "collectAccountActionCredentialPayload("),
1,
"the body must be built ONCE from the live inputs before any send"
);
const bodyAt = RECOVERY_RESET_FN.indexOf("const body = collectAccountActionCredentialPayload(");
const firstSendAt = RECOVERY_RESET_FN.indexOf("let result = await sendRecoveryReset(");
assert.ok(bodyAt >= 0 && bodyAt < firstSendAt, "the body is built before the first send and reused by the resend");
assert.ok(
RECOVERY_RESET_FN.includes("body: JSON.stringify(window.ADPanelAccountTargets.payload(accountTarget, body))"),
"the resend must reuse the same credential body object"
);
assert.ok(
RECOVERY_RESET_FN.includes("if (handleAccountActionCredentialChallenge(data, {") &&
RECOVERY_RESET_FN.includes("onTotpRevealed: () => { recoveryResetTotpRevealed = true; },") &&
RECOVERY_RESET_FN.includes("throw new Error(data.error || 'Failed to generate recovery codes');"),
"the step-up challenge handling and the normal error path must be preserved"
);
});
test("source: protected invariants survive the repair untouched", () => {
assert.equal(
countOccurrences(settingsJsSource, "/remove`"),
1,
"exactly one /remove fetch may exist (revokeAccessWithVerification keeps its pinned shape)"
);
assert.equal(
countOccurrences(settingsJsSource, "Array.isArray(data.sessionInvalidationWarnings) && data.sessionInvalidationWarnings.length"),
3,
"exactly the three pre-existing handlers consume the warnings"
);
assert.equal(
countOccurrences(settingsJsSource, "${idx + 1}. ${escapeHtml(code)}"),
1,
"the recovery dialog stays the only code sink and it keeps escaping"
);
});
// ---------------------------------------------------------------------------
// Behavior harness — the REAL registry block + the REAL refresher
// ---------------------------------------------------------------------------
const TOKEN_POOL = {
updateSecurity: "tok-sec",
updateCaptcha: "tok-cap",
enableMaintenance: "tok-men",
disableMaintenance: "tok-mdis",
revokeSession: "tok-rev",
addAccess: "tok-add",
removeAccess: "tok-rem",
setAgentAccess: "tok-agent",
grantPerms: "tok-grant",
changePassword: "tok-pw",
createUser: "tok-create",
reset2fa: "tok-2fa",
confirmReset2fa: "tok-2fa-c",
resetRecoveryCodes: "tok-rc",
saveWebhook: "tok-wh",
testWebhook: "tok-wht",
setAutoUpdate: "tok-au",
};
function makeRefresherHarness() {
const fetchCalls = [];
const intervals = [];
const docListeners = {};
const errors = [];
let clock = 1000000;
let hidden = false;
let pool = { actionTokens: { ...TOKEN_POOL } };
// Simulated owning-scope stores. webhookLive models a loader that REASSIGNS
// its binding (DOMContentLoaded reality); sessionsState models the
// property-reassignment shape of the sessions loader.
const securityStore = {};
const maintenanceStore = {};
const panelInfoStore = {};
const sessionsState = { actionTokens: {} };
let webhookLive = {};
const registrations = [
"registerSettingsActionTokenRegistry(securityStore);",
"registerSettingsActionTokenRegistry(maintenanceStore);",
"registerSettingsActionTokenRegistry(panelInfoStore);",
"registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => sessionsState.actionTokens));",
"registerSettingsActionTokenRegistry(createSettingsActionTokenView(() => webhookLive));",
].join("\n");
const sandbox = {
Date: { now: () => clock },
Promise, Object, String, Number, Array, JSON, Math, Error, Set, Proxy, Reflect, Symbol,
console: { error: (...a) => errors.push(a), log: () => {} },
fetch: async (url, opts) => {
fetchCalls.push({ url, opts, headers: opts && opts.headers });
return { ok: true, json: async () => pool };
},
document: {
get hidden() { return hidden; },
set hidden(v) { hidden = v; },
addEventListener: (type, fn) => { docListeners[type] = fn; },
},
setInterval: (fn, ms) => { intervals.push({ fn, ms }); },
securityStore,
maintenanceStore,
panelInfoStore,
sessionsState,
get webhookLive() { return webhookLive; },
set webhookLive(v) { webhookLive = v; },
// Pre-seeded stale keys prove the el merges stay merges (never replaces).
accountsListEl: { _actionTokens: { staleBeforeRefresh: "old-stale" } },
serversListEl: { _actionTokens: { staleBeforeRefresh: "old-stale" } },
};
const ctx = vm.createContext(sandbox);
vm.runInContext(REGISTRY_BLOCK + "\n" + registrations + "\n" + REFRESHER_BLOCK, ctx, {
filename: "settings.js[refresher]",
});
const flush = () => new Promise((resolve) => setTimeout(resolve, 20));
return {
ctx,
fetchCalls,
intervals,
docListeners,
errors,
flush,
setPool(next) { pool = next; },
advanceClock(ms) { clock += ms; },
setHidden(v) { hidden = v; },
reassignWebhookBinding() { sandbox.webhookLive = {}; },
reassignSessionsProperty() { sandbox.sessionsState.actionTokens = {}; },
};
}
test("behavior: the REAL refresher feeds ALL registered stores with the minted pool — no ReferenceError, nothing swallowed", async () => {
const h = makeRefresherHarness();
await h.flush();
assert.equal(h.fetchCalls.length, 1, "the immediate boot call fetched the pool exactly once");
assert.equal(h.fetchCalls[0].url, "/api/settings/action-tokens");
assert.deepEqual(
h.intervals.map((i) => i.ms),
[3 * 60 * 1000],
"the 3-minute interval cadence is preserved"
);
assert.equal(typeof h.docListeners.visibilitychange, "function", "the visibilitychange hook is registered");
assert.equal(h.errors.length, 0, "no error may be logged on the happy path (nothing silently swallowed)");
// Every registered store — including the two live views — holds the pool.
const security = h.ctx.securityStore;
const maintenance = h.ctx.maintenanceStore;
const panelInfo = h.ctx.panelInfoStore;
const sessionsActionTokens = h.ctx.sessionsState.actionTokens;
const webhook = h.ctx.webhookLive;
for (const [name, store] of [
["securityActionTokens", security],
["maintenanceActionTokens", maintenance],
["_panelInfoTokens", panelInfo],
["sessionsState.actionTokens", sessionsActionTokens],
["webhookActionTokens", webhook],
]) {
assert.equal(typeof store, "object", `${name} must still be an object`);
for (const [key, value] of Object.entries(TOKEN_POOL)) {
assert.equal(store[key], value, `${name}.${key} must receive the refreshed token`);
}
}
// The el merges still merge (never replace): a pre-existing key survives.
const accountsEl = h.ctx.accountsListEl;
const serversEl = h.ctx.serversListEl;
assert.ok(accountsEl && accountsEl._actionTokens, "accountsListEl._actionTokens must exist");
assert.ok(serversEl && serversEl._actionTokens, "serversListEl._actionTokens must exist");
for (const el of [accountsEl, serversEl]) {
assert.equal(el._actionTokens.staleBeforeRefresh, "old-stale", "the merge must not replace the pre-seeded key");
for (const [key, value] of Object.entries(TOKEN_POOL)) {
assert.equal(el._actionTokens[key], value, `el merge must carry ${key}`);
}
}
});
test("behavior: the gap guard holds within 3 minutes and the refresher re-fetches after it", async () => {
const h = makeRefresherHarness();
await h.flush();
assert.equal(h.fetchCalls.length, 1);
h.advanceClock(60 * 1000);
await h.intervals[0].fn();
assert.equal(h.fetchCalls.length, 1, "a tick 1 minute after the last refresh must be gap-guarded");
h.advanceClock(4 * 60 * 1000);
await h.intervals[0].fn();
assert.equal(h.fetchCalls.length, 2, "a tick past the 3-minute gap must fetch again");
assert.equal(h.errors.length, 0);
});
test("behavior: visibilitychange resets the gap guard and re-refreshes; a hidden tab does not refresh", async () => {
const h = makeRefresherHarness();
await h.flush();
assert.equal(h.fetchCalls.length, 1);
h.advanceClock(60 * 1000); // inside the gap window
h.docListeners.visibilitychange();
await h.flush();
assert.equal(h.fetchCalls.length, 2, "becoming visible must bypass the gap guard and refresh immediately");
h.setHidden(true);
h.docListeners.visibilitychange();
await h.flush();
assert.equal(h.fetchCalls.length, 2, "a hidden tab must not refresh");
h.setHidden(false);
});
test("behavior: a registered store that appears LATER (DOMContentLoaded case) is picked up by the next refresh", async () => {
const h = makeRefresherHarness();
await h.flush();
const lateStore = {};
h.ctx.registerSettingsActionTokenRegistry(lateStore);
h.advanceClock(4 * 60 * 1000);
await h.intervals[0].fn();
assert.equal(h.fetchCalls.length, 2);
assert.equal(
lateStore.reset2fa,
TOKEN_POOL.reset2fa,
"a store registered after boot must receive the next minted pool"
);
assert.equal(h.errors.length, 0);
});
test("behavior: live views track REASSIGNED bindings — a loader that replaces its token object still receives fresh tokens", async () => {
const h = makeRefresherHarness();
await h.flush();
assert.equal(h.ctx.webhookLive.saveWebhook, TOKEN_POOL.saveWebhook, "first refresh reaches the initial binding");
assert.equal(h.ctx.sessionsState.actionTokens.revokeSession, TOKEN_POOL.revokeSession);
// The loaders' real shape: reassign the binding/property with a NEW object.
h.reassignWebhookBinding();
h.reassignSessionsProperty();
const staleWebhook = h.ctx.webhookLive;
assert.equal(Object.keys(staleWebhook).length, 0, "the reassignment cleared the old store");
h.advanceClock(4 * 60 * 1000);
await h.intervals[0].fn();
assert.equal(h.fetchCalls.length, 2);
assert.equal(
h.ctx.webhookLive.saveWebhook,
TOKEN_POOL.saveWebhook,
"the refresh must reach the NEW binding object, not the stale snapshot"
);
assert.equal(
h.ctx.sessionsState.actionTokens.revokeSession,
TOKEN_POOL.revokeSession,
"the refresh must reach the reassigned actionTokens property"
);
assert.equal(h.errors.length, 0);
});
test("behavior: a network failure is logged once and never throws out of the interval", async () => {
const h = makeRefresherHarness();
await h.flush();
h.ctx.fetch = async () => { throw new Error("network down"); };
h.advanceClock(4 * 60 * 1000);
await h.intervals[0].fn(); // must not reject
assert.equal(h.errors.length, 1, "the failure must surface through console.error, not vanish");
});
// ---------------------------------------------------------------------------
// Behavior harness — the REAL reset dialogs over stubbed fetch/loadAccounts
// ---------------------------------------------------------------------------
const FRESH_ACCOUNTS_POOL = {
reset2fa: "fresh-2fa-token",
resetRecoveryCodes: "fresh-rc-token",
createUser: "fresh-create-token",
};
function makeElement({ value = "" } = {}) {
return { value, textContent: "", innerHTML: "", style: { display: "" }, disabled: false, focus() {} };
}
function makeDialogHarness({ responses, initialTokens, totpRevealed = false, replacementId = null }) {
const fetchCalls = [];
let loadCalls = 0;
const revealCalls = [];
const logs = [];
const errors = [];
let step = 0;
const accountsListEl = { _actionTokens: { ...(initialTokens || {}) } };
const sandbox = {
Promise, Object, String, Number, Array, JSON, Math, Error, Symbol, Boolean,
console: { log: (...a) => logs.push(a.map(String).join(" ")), error: (...a) => errors.push(a.map(String).join(" ")) },
document: { getElementById: () => null },
window: {},
fetch: async (url, opts) => {
const response = responses[Math.min(step, responses.length - 1)];
step += 1;
fetchCalls.push({ url, headers: opts && opts.headers, body: opts && opts.body });
return { ok: !!response.ok, status: response.status || (response.ok ? 200 : 403), json: async () => response.json };
},
loadAccounts: async () => {
loadCalls += 1;
// The real loader re-mints the pool by REASSIGNING the property.
accountsListEl._actionTokens = { ...FRESH_ACCOUNTS_POOL };
if (replacementId) sandbox.window.ADPanelAccountTargets.update([{ id: replacementId, email: "target@example.test" }]);
},
accountsListEl,
isStepUpGraceActive: () => false,
isAccountActionTotpRevealed: (section) => {
if (section === sandbox.qrResetTotpSection) return sandbox.qrResetTotpRevealed;
if (section === sandbox.recoveryResetTotpSection) return sandbox.recoveryResetTotpRevealed;
return false;
},
ensureAccountActionPasswordVisible: () => false,
revealAccountActionTotpField: (section, input) => revealCalls.push(["reveal", section, input]),
hideAccountActionTotpField: () => revealCalls.push(["hide"]),
closeQRResetModal: () => {},
closeRecoveryResetModal: () => {},
escapeHtml: (s) => String(s),
currentQRResetEmail: "target@example.test",
currentQRResetTarget: { email: "target@example.test", id: 42 },
qrResetCompleted: false,
qrResetTotpRevealed: totpRevealed,
recoveryResetCompleted: false,
recoveryResetTotpRevealed: false,
qrResetCredential: makeElement({ value: "typed-password" }),
qrResetCredentialLabel: makeElement(),
qrResetCredentialHint: makeElement(),
qrResetTotpSection: {},
qrResetTotpInput: makeElement({ value: "654321" }),
qrResetTotpLabel: makeElement(),
qrResetTotpHint: makeElement(),
qrResetConfirmError: makeElement(),
qrResetConfirm: makeElement(),
qrResetLoading: makeElement(),
qrResetContent: makeElement(),
qrResetError: makeElement(),
qrResetDoneBtn: makeElement(),
recoveryResetCredential: makeElement({ value: "typed-password" }),
recoveryResetCredentialLabel: makeElement(),
recoveryResetCredentialHint: makeElement(),
recoveryResetTotpSection: {},
recoveryResetTotpInput: makeElement({ value: "654321" }),
recoveryResetTotpLabel: makeElement(),
recoveryResetTotpHint: makeElement(),
recoveryResetConfirmError: makeElement(),
recoveryResetConfirm: makeElement(),
recoveryResetLoading: makeElement(),
recoveryResetContent: makeElement(),
recoveryResetError: makeElement(),
recoveryResetErrorText: makeElement(),
recoveryCodesList: makeElement(),
recoveryResetDoneBtn: makeElement(),
};
vm.runInNewContext(fs.readFileSync(path.join(ROOT, "public", "js", "settings-account-targets.js"), "utf8"), { window: sandbox.window });
sandbox.window.ADPanelAccountTargets.update([{ id: 42, email: "target@example.test" }]);
const ctx = vm.createContext(sandbox);
vm.runInContext(CREDENTIAL_HELPERS + "\n" + QR_RESET_FN + "\n" + RECOVERY_RESET_FN, ctx, {
filename: "settings.js[dialogs]",
});
return {
ctx,
fetchCalls,
loadCalls: () => loadCalls,
revealCalls,
logs,
errors,
accountsListEl,
sandbox,
};
}
const TOKEN_INVALID = { ok: false, status: 403, json: { error: "invalid or missing action token" } };
test("behavior: token refresh cannot retarget either reset dialog to a recreated account", async () => {
for (const method of ["confirmQRReset", "generateNewRecoveryCodes"]) {
const h = makeDialogHarness({ responses: [TOKEN_INVALID, { ok: true, json: {} }], replacementId: 43 });
await h.ctx[method]();
assert.equal(h.fetchCalls.length, 1, "no credential-bearing resend may target the replacement");
assert.equal(JSON.parse(h.fetchCalls[0].body).expectedTargetId, 42);
assert.equal(h.loadCalls(), 1);
assert.equal(h.ctx.qrResetCompleted, false);
assert.equal(h.ctx.recoveryResetCompleted, false);
}
});
test("behavior: after 10+ idle minutes the 2FA reset reloads the pool via loadAccounts and succeeds on ONE resend", async () => {
const h = makeDialogHarness({
responses: [
TOKEN_INVALID,
{ ok: true, json: { sessionsDestroyed: 2, sessionInvalidationWarnings: [] } },
],
initialTokens: { reset2fa: "stale-expired-token" },
});
await h.ctx.confirmQRReset();
assert.equal(h.fetchCalls.length, 2, "exactly one resend (two requests total)");
assert.equal(h.loadCalls(), 1, "exactly one loadAccounts between the attempts");
assert.equal(h.fetchCalls[0].url, "/api/admin/user/reset-2fa");
assert.equal(h.fetchCalls[0].headers["x-action-token"], "stale-expired-token", "the first attempt sends the stashed token");
assert.equal(h.fetchCalls[1].headers["x-action-token"], "fresh-2fa-token", "the resend carries the re-minted token");
const firstBody = JSON.parse(h.fetchCalls[0].body);
const secondBody = JSON.parse(h.fetchCalls[1].body);
assert.equal(firstBody.currentPassword, "typed-password", "the first attempt carries the typed password");
assert.equal(secondBody.currentPassword, "typed-password", "the resend preserves the typed password");
assert.deepEqual(firstBody, secondBody, "the resend reuses the SAME body (credentials not cleared or rebuilt)");
assert.equal(secondBody.email, "target@example.test");
assert.equal(h.ctx.qrResetCompleted, true, "the reset succeeded after the retry");
assert.equal(h.sandbox.qrResetConfirmError.textContent, "", "no error text on the success path");
assert.equal(
h.sandbox.qrResetDoneBtn.innerHTML,
'<i class="fa-solid fa-check"></i> Done',
"the finally block restores the done button state"
);
assert.deepEqual(h.errors, [], "no console.error on the success path");
});
test("behavior: a second consecutive token-invalid failure surfaces the normal error and does NOT loop", async () => {
const h = makeDialogHarness({
responses: [TOKEN_INVALID, TOKEN_INVALID],
initialTokens: { reset2fa: "stale-expired-token" },
});
await h.ctx.confirmQRReset();
assert.equal(h.fetchCalls.length, 2, "at most one resend — never a loop");
assert.equal(h.loadCalls(), 1, "loadAccounts ran once, not repeatedly");
assert.equal(h.ctx.qrResetCompleted, false, "the reset did not succeed");
assert.equal(
h.sandbox.qrResetConfirmError.textContent,
"invalid or missing action token",
"the normal error path surfaces the server's message"
);
assert.equal(h.sandbox.qrResetDoneBtn.disabled, false, "the finally block re-enables the button");
assert.ok(h.errors.length >= 1, "the catch logs the failure like every other dialog error");
});
test("behavior: a step-up challenge (2fa-required) does NOT trigger a token retry and keeps opening the challenge", async () => {
const h = makeDialogHarness({
responses: [
{ ok: false, status: 403, json: { error: "A valid 6-digit code is required.", code: "2fa-required" } },
],
initialTokens: { reset2fa: "stale-expired-token" },
});
await h.ctx.confirmQRReset();
assert.equal(h.fetchCalls.length, 1, "a challenge must never be retried as a token error");
assert.equal(h.loadCalls(), 0, "no loadAccounts on a challenge");
assert.equal(
h.revealCalls.filter(([kind]) => kind === "reveal").length,
1,
"the challenge modal path reveals the TOTP companion exactly as before"
);
assert.equal(h.sandbox.qrResetConfirmError.textContent, "A valid 6-digit code is required.");
assert.equal(h.ctx.qrResetCompleted, false);
assert.equal(h.ctx.qrResetTotpRevealed, true, "the revealed flag is set for the admin's retry");
});
test("behavior: the revealed-TOTP code travels on both the first attempt and the preserved resend", async () => {
const h = makeDialogHarness({
responses: [
TOKEN_INVALID,
{ ok: true, json: { sessionsDestroyed: 0, sessionInvalidationWarnings: [] } },
],
initialTokens: {},
totpRevealed: true,
});
await h.ctx.confirmQRReset();
assert.equal(h.fetchCalls.length, 2);
for (const call of h.fetchCalls) {
const body = JSON.parse(call.body);
assert.equal(body.currentPassword, "typed-password", "the password survives");
assert.equal(body.twoFactorCode, "654321", "the revealed TOTP code survives");
}
});
test("behavior: after 10+ idle minutes the recovery-code reset reloads the pool and mints codes on ONE resend", async () => {
const h = makeDialogHarness({
responses: [
TOKEN_INVALID,
{ ok: true, json: { recoveryCodes: ["RCODE1", "RCODE2"] } },
],
initialTokens: { resetRecoveryCodes: "stale-expired-token" },
});
await h.ctx.generateNewRecoveryCodes();
assert.equal(h.fetchCalls.length, 2, "exactly one resend (two requests total)");
assert.equal(h.loadCalls(), 1, "exactly one loadAccounts between the attempts");
assert.equal(h.fetchCalls[0].url, "/api/admin/user/reset-recovery-codes");
assert.equal(h.fetchCalls[0].headers["x-action-token"], "stale-expired-token", "the first attempt sends the stashed token");
assert.equal(h.fetchCalls[1].headers["x-action-token"], "fresh-rc-token", "the resend carries the re-minted token");
const firstBody = JSON.parse(h.fetchCalls[0].body);
const secondBody = JSON.parse(h.fetchCalls[1].body);
assert.deepEqual(firstBody, secondBody, "the resend reuses the SAME credential body");
assert.equal(secondBody.currentPassword, "typed-password", "the typed password survives the reload");
assert.equal(h.ctx.recoveryResetCompleted, true, "the reset succeeded after the retry");
assert.ok(
h.sandbox.recoveryCodesList.innerHTML.includes("1. RCODE1") &&
h.sandbox.recoveryCodesList.innerHTML.includes("2. RCODE2"),
"the minted codes render as before"
);
assert.deepEqual(h.errors, [], "no console.error on the success path");
});
test("behavior: a second consecutive token-invalid failure in the recovery dialog surfaces the error without looping", async () => {
const h = makeDialogHarness({
responses: [TOKEN_INVALID, TOKEN_INVALID],
initialTokens: { resetRecoveryCodes: "stale-expired-token" },
});
await h.ctx.generateNewRecoveryCodes();
assert.equal(h.fetchCalls.length, 2, "at most one resend");
assert.equal(h.loadCalls(), 1);
assert.equal(h.ctx.recoveryResetCompleted, false);
assert.equal(
h.sandbox.recoveryResetErrorText.textContent,
"invalid or missing action token",
"the error panel surfaces the server's message"
);
assert.equal(h.sandbox.recoveryResetDoneBtn.disabled, false, "the finally block re-enables the button");
});
test("behavior: a password-required challenge in the recovery dialog does NOT trigger a token retry", async () => {
const h = makeDialogHarness({
responses: [
{ ok: false, status: 403, json: { error: "Password verification required.", code: "password-required" } },
],
initialTokens: { resetRecoveryCodes: "stale-expired-token" },
});
await h.ctx.generateNewRecoveryCodes();
assert.equal(h.fetchCalls.length, 1, "a challenge must never be retried as a token error");
assert.equal(h.loadCalls(), 0, "no loadAccounts on a challenge");
assert.equal(h.sandbox.recoveryResetConfirmError.textContent, "Password verification required.");
assert.equal(h.ctx.recoveryResetCompleted, false);
});