"use strict"; // Tests for audit findings L1, L2, L4 and L6. // // L1: the admin credentials modal and the recovery-reset dialog interpolated // each recovery code into innerHTML unescaped. Codes are server-generated // from a safe alphabet today, but the sink is a latent XSS footgun if the // source ever changes; the remaining sink escapes via the panel-wide // escapeHtml helper. The 2026-09-08 create-flow 2FA remediation // (tests/admin-create-2fa-nonrepudiation.test.js) removed the credentials // modal's code sink and the download's secret interpolation entirely, so only // the recovery-reset dialog still renders codes. // // L2: the accounts list/search UI in settings.ejs rendered for every visitor // of the page while the backing API is admin-only, so a non-admin opening the // Account panel got a permanent "Failed to load accounts" from a doomed 403 // request. The section is now gated on user.admin in the template (matching // GET /settings's own admin gate, as defense in depth), and settings.js // no-ops every accounts UI code path when the section is absent. // // L4: POST /api/settings/accounts/:email/agent-access ran an ALTER TABLE on // every request and swallowed all failures. Schema provisioning belongs to // the startup migration, which already adds the same column once at boot; the // per-request ALTER is gone and the base schema now carries the column too. // // L6: confirm-2fa-reset was a full copy of the privileged reset-2fa handler // and had already drifted (no recordActivity audit call, no [SECURITY] // evictions log, no email field in the response). Both routes now share one // hardened implementation; they stay separately registered because action // tokens are bound to the exact action string. (2026-11: the shared handler // moved into services/admin-2fa-reset.js together with the pre-flight guard // — Express 4 cannot catch handler rejections, so the whole awaited pipeline // is guarded there; see tests/admin-2fa-reset-preflight.test.js. The index.js // registrations stay thin delegating arrows with their own action scopes.) // // index.js boots servers on require, so route-level behavior is locked with // source assertions (same technique as audit-p32-p41-p42.test.js). const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js"); const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs"); const SCHEMA_SQL = path.join(ROOT, "mysql-schema.sql"); const RESET_MODULE_JS = path.join(ROOT, "services", "admin-2fa-reset.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const resetModuleSource = fs.readFileSync(RESET_MODULE_JS, "utf8"); const commitSource = fs.readFileSync(path.join(ROOT, "services", "account-credentials.js"), "utf8"); const settingsJsSource = fs.readFileSync(SETTINGS_JS, "utf8"); const settingsEjsSource = fs.readFileSync(SETTINGS_EJS, "utf8"); const schemaSqlSource = fs.readFileSync(SCHEMA_SQL, "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); } // --------------------------------------------------------------------------- // L1 — recovery codes are escaped before hitting innerHTML // --------------------------------------------------------------------------- test("L1: the recovery-reset dialog is the only code sink and it escapes via escapeHtml(code)", () => { assert.equal( countOccurrences(settingsJsSource, "${idx + 1}. ${escapeHtml(code)}"), 1, "only the recovery-reset dialog still renders codes, and it must escape them" ); const recoveryResetSink = sliceBetween( settingsJsSource, "recoveryCodesList.innerHTML =", ").join('');" ); assert.ok(!recoveryResetSink.includes("${code}"), "the recovery-reset dialog must not interpolate raw code values"); assert.ok(recoveryResetSink.includes("${escapeHtml(code)}"), "the recovery-reset dialog must escape code values"); }); test("L1: the credentials dialog has no code sink at all (create flow never returns 2FA material)", () => { assert.ok(!settingsJsSource.includes("credentialsRecoveryCodes"), "the credentials dialog's recovery-code sink must be gone"); const credentialsModal = sliceBetween( settingsJsSource, "function openCredentialsModal", "function closeCredentialsModal" ); assert.ok(!credentialsModal.includes("innerHTML"), "the credentials dialog must not build any HTML"); assert.ok(!credentialsModal.includes("data.secret") && !credentialsModal.includes("qrCodeUrl"), "the credentials dialog must not touch the TOTP seed or QR data URL"); }); test("L1: the credential download note contains no 2FA material", () => { const downloadFn = sliceBetween( settingsJsSource, "function downloadCredentials", "if (openCreateUserBtn)" ); assert.ok(!downloadFn.includes("${code}"), "the plaintext download must not interpolate codes"); assert.ok(!downloadFn.includes("data.secret"), "the plaintext download must not include the TOTP seed"); assert.ok(!downloadFn.includes("qrCodeUrl"), "the plaintext download must not include a QR data URL"); }); // --------------------------------------------------------------------------- // L2 — the accounts UI is admin-only in the template and null-safe in JS // --------------------------------------------------------------------------- test("L2: settings.ejs renders the accounts section only for admins", () => { const gateRegex = /<% if \(user && user\.admin\) \{ %>\s*
", gateStart); assert.ok(blockEnd > gateStart, "the gated block must be closed"); const block = settingsEjsSource.slice(gateStart, blockEnd); assert.ok(block.includes('id="openCreateUserBtn"'), "the Create User button lives inside the gate"); assert.ok(block.includes('id="accountsSearchInput"'), "the search input lives inside the gate"); assert.ok(block.includes('id="accountsList"'), "the accounts list lives inside the gate"); assert.ok( !block.slice(block.indexOf("
{ const fnSource = sliceBetween( settingsJsSource, "async function loadAccounts() {", "window.applyRevokeSecurityFromPayload" ); const guardAt = fnSource.indexOf("if (!accountsListEl) return;"); const fetchAt = fnSource.indexOf("fetch('/api/settings/accounts')"); assert.ok(guardAt >= 0, "loadAccounts must guard on the list element"); assert.ok(fetchAt >= 0, "loadAccounts must still fetch for admins"); assert.ok(guardAt < fetchAt, "the guard must run before any request is fired"); }); test("L2: renderAccounts no-ops when the section is absent", () => { const fnSource = sliceBetween( settingsJsSource, "function renderAccounts(accounts, bots, searchQuery = '') {", "let filtered =" ); assert.ok( fnSource.includes("if (!accountsListEl) return;"), "renderAccounts must guard on the list element before touching innerHTML" ); }); test("Accounts shows the Agent grant only when the feature is enabled, including filtered rows", () => { const source = sliceBetween(settingsJsSource, "function renderAccounts(", "function getAccountDeleteToken("); const rows = []; const list = { dataset: {}, appendChild: (row) => rows.push(row), set innerHTML(_markup) { rows.length = 0; } }; const render = new Function("accountsListEl", "document", "window", "escapeHtml", `${source}\nreturn renderAccounts;`)( list, { createElement: () => ({}) }, { __brandName: "ADPanel" }, (text) => text ); const account = { email: "operator@example.test", agent_access: true }; for (const enabled of [false, true, false]) { list.dataset.agentEnabled = String(enabled); for (const search of ["", "operator"]) { render([account], [], search); assert.equal(rows.length, 1); const markup = rows[0].innerHTML; assert.equal(markup.includes('class="agent-access-toggle"'), enabled); assert.ok(markup.includes("manage-access") && markup.includes("change-password-btn")); } } assert.equal(account.agent_access, true); }); test("L2: the account-list click and change handlers are registered behind a null guard", () => { const openManageAt = settingsJsSource.indexOf("async function openManageAccessModal(email) {"); assert.ok(openManageAt > 0, "the openManageAccessModal marker must exist"); const regionStart = settingsJsSource.indexOf("if (accountsListEl) {"); assert.ok(regionStart >= 0 && regionStart < openManageAt, "a guard must precede the handlers"); const region = settingsJsSource.slice(regionStart, openManageAt); assert.equal( countOccurrences(region, "accountsListEl.addEventListener('click'"), 1, "the click handler must be registered exactly once, inside the guard" ); assert.equal( countOccurrences(region, "accountsListEl.addEventListener('change'"), 1, "the change handler must be registered exactly once, inside the guard" ); assert.match( region, /addEventListener\('change'[\s\S]*\}\);\s*\}\s*$/, "the guard must close after the change handler" ); }); // --------------------------------------------------------------------------- // L4 — agent_access provisioning stays out of the request path // --------------------------------------------------------------------------- test("L4: the agent-access endpoint no longer runs ALTER TABLE per request", () => { const handler = sliceBetween( indexSource, 'app.post("/api/settings/accounts/:email/agent-access"', 'app.get("/api/settings/accounts/:email/perms"' ); assert.ok(handler.includes("setAccountAgentAccess(db, currentUser, targetUser, enabled)"), "the endpoint must persist the loaded target through the shared setter"); assert.ok(fs.readFileSync(path.join(ROOT, "services", "account-actions.js"), "utf8").includes("UPDATE users SET agent_access = ? WHERE id = ? AND admin = 0"), "the shared flag write must remain immutable and non-admin-only"); assert.ok(!handler.includes("ALTER TABLE"), "no schema mutation may run on the request hot path"); }); test("L4: the startup migration remains the single provisioning point", () => { assert.equal( countOccurrences(indexSource, "ALTER TABLE users ADD COLUMN agent_access"), 1, "exactly one provisioning ALTER may exist (the startup migration)" ); assert.ok( indexSource.includes("SHOW COLUMNS FROM users LIKE 'agent_access'"), "the startup check-and-add migration must stay" ); }); test("L4: the base schema carries the agent_access column on users only", () => { const usersTable = sliceBetween( schemaSqlSource, "CREATE TABLE IF NOT EXISTS users (", "CREATE TABLE IF NOT EXISTS nodes (" ); assert.ok( usersTable.includes("agent_access TINYINT(1) NOT NULL DEFAULT 0"), "fresh installs must get the column from mysql-schema.sql" ); const serversTable = sliceBetween( schemaSqlSource, "CREATE TABLE IF NOT EXISTS servers (", "CREATE TABLE IF NOT EXISTS destructive_action_grants (" ); assert.ok(!serversTable.includes("agent_access"), "agent_access must not leak into other tables"); }); // --------------------------------------------------------------------------- // L6 — one hardened implementation behind both 2FA reset routes // --------------------------------------------------------------------------- test("L6: handleAdmin2faReset is the single shared implementation (one true home: services/admin-2fa-reset.js)", () => { assert.equal( countOccurrences(resetModuleSource, "async function handleAdmin2faReset("), 1, "exactly one shared handler may exist (in the service module)" ); assert.equal( countOccurrences(indexSource, "async function handleAdmin2faReset("), 0, "no inline copy of the shared handler may remain in index.js" ); // adpanel:credential-generation — the destructive clear bumps the account's // session epoch IN THE SAME statement (a generation committed separately // from its credential leaves a window where the stale credential // authenticates against the new generation). // adpanel:admin-reset-target-pinning — the destructive clear pins the // LOADED row's immutable id (an email-keyed write could silently land on a // replacement row recreated with the same email between the lookup and the // write); the epoch bump stays IN THE SAME statement. assert.equal( countOccurrences(commitSource, "UPDATE users SET secret = NULL, recovery_codes = NULL, session_epoch = ? WHERE id = ?"), 1, "the destructive clear must exist exactly once, id-keyed, revoking recovery codes with the in-statement epoch bump" ); assert.equal( countOccurrences(resetModuleSource, "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)"), 0, "the epoch-free shape must be gone from the service module (replaced, not duplicated)" ); assert.equal( countOccurrences(indexSource, "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)"), 0, "no copy of the email-keyed destructive clear may remain in index.js" ); assert.deepEqual( indexSource.match(/UPDATE users SET secret = NULL[^"\r\n]*/g) || [], ["UPDATE users SET secret = NULL WHERE secret = ''"], "only startup empty-secret normalization may remain in index.js, never an admin reset copy" ); }); test("L6: both routes are registered against the shared handler with their own action scope", () => { for (const route of ["/api/admin/user/reset-2fa", "/api/admin/user/confirm-2fa-reset"]) { const registration = sliceBetween( indexSource, `app.post("${route}", sessionRevoke2faRateLimiter`, "}));" ); assert.ok( registration.includes("(req, res) => handleAdmin2faReset(req, res, {"), `${route} must delegate to the shared handler` ); assert.ok( registration.includes(`action: "POST ${route}"`), `${route} must keep its own action-token scope string` ); } // Tokens are minted for both scopes (canonical + alias) at both issue sites. assert.equal( countOccurrences(indexSource, 'issueActionToken(req, "POST /api/admin/user/reset-2fa"'), 2, "both token-minting sites must still mint the canonical scope" ); assert.equal( countOccurrences(indexSource, 'issueActionToken(req, "POST /api/admin/user/confirm-2fa-reset"'), 2, "both token-minting sites must still mint the alias scope" ); }); test("L6: the shared handler keeps the full privileged sequence", () => { // The handler moved into services/admin-2fa-reset.js (pre-flight guard // consolidation); the sequence pin follows it there. The slice is bounded // by the handler's definition and the factory's return, i.e. the whole // guarded pipeline. const fnStart = resetModuleSource.indexOf("async function handleAdmin2faReset("); const handlerEnd = resetModuleSource.indexOf("return { handleAdmin2faReset };"); assert.ok(fnStart >= 0 && handlerEnd > fnStart, "the handler must be bounded inside the service factory"); const handler = resetModuleSource.slice(fnStart, handlerEnd); const sequence = [ ["isAdmin(req)", "admin gate"], ["requireActionTokenOr403(req, res, action)", "action-token gate"], ["normalizeAdminTargetEmail(email)", "target email validation"], ["Cannot reset your own 2FA through admin panel", "self-reset rejection"], ["requireDestructiveActionStepUp(req, res, actingAdmin", "step-up authentication"], ['credentialFlow: "password-then-totp"', "password-first step-up flow"], ["resetAccountTwoFactor(db, targetUser, actingAdmin)", "actor-guarded 2FA secret clear"], ["destroyBrowserSessionsForUser(targetUser)", "session eviction"], ["disconnectSocketsForUser(targetUser.email", "socket eviction"], ['recordActivity("_system", "admin_reset_2fa"', "audit trail"], ["rememberLoginsRevoked", "remember-me revocation reporting"], ]; let cursor = 0; for (const [marker, label] of sequence) { const at = handler.indexOf(marker, cursor); assert.ok(at >= 0, `the shared handler must keep the ${label}`); cursor = at + marker.length; } // The peer-admin target proof was removed by product decision (unworkable // UX, and a rogue or departed admin could block removal of their own // account); the shared handler must rely solely on the acting admin's // password-first step-up. assert.ok( !handler.includes("requireTargetAdminCredentialProof"), "the shared handler must no longer demand the target admin's credential proof" ); });