"use strict"; // The admin account-deletion route (DELETE /api/settings/accounts/:email) was // the only destructive action that never revoked the target's sessions: // suspend, admin password reset and admin 2FA reset all evict sessions + // remember-me tokens and disconnect the target's sockets, but delete removed // the user row and left the adpanel.sid cookie valid in the store for up to // the 365-day session TTL. With the row gone every auth check fails closed so // the session goes dormant — and re-arms the moment the same email is // re-created (e.g. credential rotation after a compromise), handing the // holder of the stale cookie a fully authenticated session on the new // account, remember-me included. // // Because a delete is irreversible (the reversible siblings mutate first and // evict after, since their mutation is retryable), the eviction is confirmed // BEFORE the commit and the request aborts with nothing deleted when eviction // cannot be confirmed; a defensive post-commit sweep catches sessions created // between the gate and the commit. This file pins that ordering and the // response contract. It reads index.js as text, like the other audit tests. 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 indexSource = fs.readFileSync(INDEX_JS, "utf8"); function extractRoute(source, routeMarker, nextRouteMarker) { const start = source.indexOf(routeMarker); assert.ok(start >= 0, `route marker not found: ${routeMarker}`); const end = source.indexOf(nextRouteMarker, start); assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`); return source.slice(start, end); } const HANDLER_START = 'app.delete("/api/settings/accounts/:email"'; const HANDLER_END = 'app.post("/api/settings/accounts/:email/change-password"'; // adpanel:last-admin-guard — the call now carries the acting admin's id into // the transaction ({ actingAdminId: currentUser.id }) for the transactional // administrator-survival guard; the pinned string was consciously extended to // the new exact call text because the old pin included the closing paren and // could not survive any argument append. Every assertion below keeps its // original intent: this anchor still marks the irreversible commit that the // eviction gate must precede and the defensive sweep must follow. const DELETE_CALL = "deleteUserAccountAtomically(targetUser.id, targetEmailLower, { actingAdminId: currentUser.id, actingAdminEpoch: currentUser.session_epoch })"; const EVICT_CALL = "destroyBrowserSessionsForUser(targetUser)"; const DISCONNECT_CALL = 'disconnectSocketsForUser(targetEmailLower, "account-deleted", { accountId: targetUser.id })'; const handler = extractRoute(indexSource, HANDLER_START, HANDLER_END); // destroyBrowserSessionsForUser(targetUser) must appear exactly three times: // gate pass, gate retry, post-commit sweep. indexOf-based cursors rely on it. function findEvictOccurrences() { const at = []; let cursor = 0; for (; ; ) { const at2 = handler.indexOf(EVICT_CALL, cursor); if (at2 < 0) break; at.push(at2); cursor = at2 + EVICT_CALL.length; } return at; } test("account delete handler evicts the target's sessions BEFORE the atomic delete", () => { const deleteIdx = handler.indexOf(DELETE_CALL); assert.ok(deleteIdx >= 0, "the handler must still delete via deleteUserAccountAtomically"); const evictAt = findEvictOccurrences(); assert.equal( evictAt.length, 3, "destroyBrowserSessionsForUser(targetUser) must appear exactly three times (gate, retry, sweep)" ); const [gateIdx, retryIdx, sweepIdx] = evictAt; assert.ok( gateIdx < deleteIdx, "the eviction gate must run before the irreversible commit, not after it" ); assert.ok(retryIdx < deleteIdx, "the gate's retry pass must also run before the commit"); assert.ok(sweepIdx > deleteIdx, "the defensive sweep must run after the commit"); // The gate rides the suspension handler's bounded-retry pattern: one retry // after a short settle delay, merged like the sibling (destroyed counts add // up, remember-me revocation is idempotent). const gateBlock = handler.slice(gateIdx, deleteIdx); assert.match(gateBlock, /setTimeout\(resolve,\s*250\)/, "the retry must wait before re-scanning the store"); assert.match( gateBlock, /destroyed:\s*sessionInvalidation\.destroyed\s*\+\s*retryResult\.destroyed/, "the retry must accumulate destroyed counts like the suspension handler" ); assert.match( gateBlock, /rememberLoginsRevoked:\s*Math\.max\(\s*sessionInvalidation\.rememberLoginsRevoked,\s*retryResult\.rememberLoginsRevoked\s*\)/, "the retry must merge remember-me revocation with Math.max (idempotent)" ); }); test("account delete aborts with nothing deleted when eviction cannot be confirmed", () => { const deleteIdx = handler.indexOf(DELETE_CALL); const abortIdx = handler.indexOf("sessionEvictionFailed: true"); assert.ok(abortIdx >= 0, "the abort response must flag sessionEvictionFailed"); assert.ok( abortIdx < deleteIdx, "the abort response must be returned before the atomic delete runs" ); const abortBlock = handler.slice(handler.indexOf(EVICT_CALL), deleteIdx); assert.match(abortBlock, /ok:\s*false/, "the abort response must not report ok"); assert.match(abortBlock, /sessionEvictionFailed:\s*true/, "the abort response must carry the eviction-failure flag"); assert.match(abortBlock, /Nothing was deleted/i, "the abort error must tell the admin nothing was deleted"); assert.match(abortBlock, /email:\s*targetEmailLower/, "the abort response must identify the target"); assert.match(abortBlock, /graceExpiresAt/, "the abort response must keep the grace contract"); // The one-time delete token was consumed by the token check; the client // refreshes it and the step-up grace covers the retry, so the abort must // not re-mint anything. assert.doesNotMatch(abortBlock, /issueActionToken/, "the abort response must not re-mint action tokens"); assert.match( handler, /\[SECURITY\] Account delete aborted/, "an aborted delete must be logged as a loud [SECURITY] error" ); }); test("account delete disconnects sockets and re-sweeps sessions after the commit", () => { const deleteIdx = handler.indexOf(DELETE_CALL); const disconnectIdx = handler.indexOf(DISCONNECT_CALL); assert.ok(disconnectIdx >= 0, "the handler must disconnect the target's sockets post-commit"); assert.ok(disconnectIdx > deleteIdx, "socket eviction must run after the atomic delete"); // Sweep errors are defense-in-depth signals: they surface as warnings and // must not fail a request whose delete already committed. const postCommitBlock = handler.slice(deleteIdx); assert.match( postCommitBlock, /sessionInvalidationWarnings = \[\.\.\.sessionInvalidation\.errors, \.\.\.finalSweep\.errors\]/, "sweep errors must surface as sessionInvalidationWarnings, not fail the request" ); assert.match( postCommitBlock, /Post-delete session sweep/, "a failing sweep must be logged as a warning, not a request failure" ); // Post-delete cleanup must use the original account identity. assert.match(postCommitBlock, /cancelSchedulesCreatedBy\(targetUser, \{ reason: "account deleted" \}\)/); }); test("account delete success response reports the sibling-standard eviction fields", () => { const responseIdx = handler.indexOf('message: "User deleted successfully"'); assert.ok(responseIdx >= 0, "the success message must be preserved"); const resJsonStart = handler.lastIndexOf("return res.json({", responseIdx); assert.ok(resJsonStart >= 0, "the success response must be a res.json payload"); const responseBody = handler.slice(resJsonStart, handler.indexOf("});", responseIdx)); assert.match(responseBody, /ok:\s*true/, "the success response must keep ok: true"); assert.match(responseBody, /graceExpiresAt/, "the success response must keep graceExpiresAt"); assert.match(responseBody, /sessionsDestroyed/, "the success response must report sessionsDestroyed"); assert.match(responseBody, /socketsDisconnected/, "the success response must report socketsDisconnected"); assert.match(responseBody, /rememberLoginsRevoked/, "the success response must report rememberLoginsRevoked"); assert.match(responseBody, /sessionInvalidationWarnings/, "the success response must report sessionInvalidationWarnings"); assert.match( handler, /\[SECURITY\] Account deleted \| Admin: \$\{stripLogControlChars\(currentUser\.email\)\} \| Target: \$\{stripLogControlChars\(targetEmailLower\)\} \| Sessions destroyed: \$\{sessionsDestroyed\} \| Sockets disconnected: \$\{socketsDisconnected\} \| Remember-me revoked: \$\{rememberLoginsRevoked\} \| IP: \$\{getRequestIp\(req\)\}/, "the audit log must record admin, target, eviction counts and IP (identity stripped via adpanel:log-email-control-chars)" ); assert.doesNotMatch( handler, /Target proof/, "the audit log must no longer record a peer-admin target proof" ); }); test("account delete keeps the pre-existing validation ordering before the gate", () => { const sequence = [ ["if (!req.session || !req.session.user)", "authentication gate"], ["isAdmin(req)", "admin gate"], ['requireActionTokenOr403(req, res, "DELETE /api/settings/accounts/:email"', "action-token gate"], ["cannot delete yourself", "self-delete rejection"], ["findUserByEmail(targetEmail)", "target fetch"], ["requireDestructiveActionStepUp(req, res, currentUser", "step-up authentication"], ['credentialFlow: "password-then-totp"', "password-first step-up flow"], ["getVerifiedSessionRevokeGraceState(req, currentUser)", "grace state"], ]; let cursor = 0; for (const [marker, label] of sequence) { const at = handler.indexOf(marker, cursor); assert.ok(at >= 0, `the delete handler must keep the ${label}`); cursor = at + marker.length; } const gateIdx = handler.indexOf(EVICT_CALL); assert.ok( gateIdx > cursor, "the eviction gate must sit after the full pre-existing validation chain" ); // The peer-admin target proof (which demanded the TARGET admin's 2FA code or // password) was removed by product decision: it is unworkable UX and lets a // rogue or departed admin block removal of their own account. The delete // route must rely solely on the acting admin's password-first step-up. assert.ok( !handler.includes("requireTargetAdminCredentialProof"), "the delete handler must no longer demand the target admin's credential proof" ); assert.ok( !indexSource.includes("requireTargetAdminCredentialProof"), "the peer-admin target-proof helper must be gone from index.js entirely" ); });