Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,273 @@
|
||||
"use strict";
|
||||
|
||||
// Regression tests for the Sessions revoke-token cap and the Sessions-tab UX
|
||||
// guards. Reads index.js and public/js/settings.js as text, like the other
|
||||
// audit tests.
|
||||
//
|
||||
// Issue 7 (backend): search-mode GET /api/settings/sessions returns ALL
|
||||
// matches and mints one single-use revokeToken per returned row into the
|
||||
// admin's session map (sessionRevokeTargets). That map is capped at
|
||||
// SESSION_REVOKE_TARGET_TOKEN_MAX with lowest-issuedAt eviction, so an
|
||||
// unbounded search response used to evict the earliest rows' tokens before
|
||||
// the response shipped — those revoke buttons always failed with
|
||||
// session-action-expired. The invariant restored here: every token minted in
|
||||
// a single response must still be in the map when the client clicks, while
|
||||
// the map stays bounded. Search results are now capped server-side
|
||||
// (ACTIVE_BROWSER_SESSION_SEARCH_MAX) with the truncation signaled to the
|
||||
// client, and the token cap stays a clear margin above the worst-case
|
||||
// per-response mint count. Eviction remains fail-safe: expired entries are
|
||||
// dropped before the cap is enforced and consumed tokens are deleted on use,
|
||||
// so only live tokens are ever evicted.
|
||||
//
|
||||
// Issue 8 (frontend): the 2FA input's Enter keydown handler dispatched the
|
||||
// one-time-token verification actions without checking the in-flight flag
|
||||
// that only the confirm button carried (sessionRevokeModalConfirm.disabled,
|
||||
// set at entry and reset in each action's finally). Double-tapping Enter
|
||||
// fired two concurrent revokes with the same single-use token.
|
||||
//
|
||||
// Issue 9 (frontend): loadSessions wrote the server's lowercased/truncated
|
||||
// search echo back into the (possibly focused) input, so a stale in-flight
|
||||
// response could revert what the admin just typed.
|
||||
|
||||
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 indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
||||
|
||||
function extractRegion(source, startMarker, endMarker, label) {
|
||||
const start = source.indexOf(startMarker);
|
||||
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
|
||||
const end = source.indexOf(endMarker, start);
|
||||
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
|
||||
return source.slice(start, end);
|
||||
}
|
||||
|
||||
function readNumericConst(source, name) {
|
||||
const match = source.match(new RegExp(`const ${name} = (\\d+);`));
|
||||
assert.ok(match, `missing numeric const: ${name}`);
|
||||
return Number(match[1]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 7 — backend bounds and cap invariant
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("revoke token cap stays a clear margin above the worst-case per-response mint count", () => {
|
||||
const tokenMax = readNumericConst(indexSource, "SESSION_REVOKE_TARGET_TOKEN_MAX");
|
||||
const searchMax = readNumericConst(indexSource, "ACTIVE_BROWSER_SESSION_SEARCH_MAX");
|
||||
const pageSize = readNumericConst(indexSource, "ACTIVE_BROWSER_SESSION_PAGE_SIZE");
|
||||
|
||||
// Worst case single-response mints: one search response (bounded by
|
||||
// ACTIVE_BROWSER_SESSION_SEARCH_MAX; the paginated listing mints at most
|
||||
// ACTIVE_BROWSER_SESSION_PAGE_SIZE rows) plus the single re-issue attached
|
||||
// to a failed revoke. The cap must exceed that with margin — 2x the search
|
||||
// bound — so the latest response's tokens always survive eviction.
|
||||
assert.ok(searchMax > pageSize, "search bound should exceed the listing page size to be the binding worst case");
|
||||
assert.ok(tokenMax >= 2 * searchMax, `SESSION_REVOKE_TARGET_TOKEN_MAX (${tokenMax}) must be at least 2x ACTIVE_BROWSER_SESSION_SEARCH_MAX (${searchMax})`);
|
||||
assert.ok(tokenMax > pageSize, "cap must exceed the listing page size");
|
||||
});
|
||||
|
||||
test("search mode is bounded server-side and signals truncation instead of silently dropping rows", () => {
|
||||
const route = extractRegion(
|
||||
indexSource,
|
||||
'app.get("/api/settings/sessions"',
|
||||
'app.post("/api/settings/sessions/revoke"',
|
||||
"sessions listing route"
|
||||
);
|
||||
|
||||
// The search slice is capped before minting tokens per row.
|
||||
assert.ok(
|
||||
route.includes("const searchTruncated = searchActive && total > ACTIVE_BROWSER_SESSION_SEARCH_MAX;"),
|
||||
"search truncation must be computed against ACTIVE_BROWSER_SESSION_SEARCH_MAX"
|
||||
);
|
||||
assert.ok(
|
||||
route.includes("const visibleSessions = searchTruncated"),
|
||||
"visible sessions must be derived from the truncation decision"
|
||||
);
|
||||
// Items (and therefore per-row revokeToken mints) come from the capped
|
||||
// slice, never the full unbounded match list.
|
||||
assert.ok(route.includes("const items = visibleSessions"), "items must be built from the capped visibleSessions slice");
|
||||
assert.ok(!route.includes("const items = filteredSessions"), "items must not be built from the unbounded filteredSessions");
|
||||
// The response flags the truncation and reports a truthful `to` bound while
|
||||
// keeping the true match count in `total`.
|
||||
assert.ok(/\bsearchTruncated,/.test(route), "response must include the searchTruncated flag");
|
||||
assert.ok(
|
||||
route.includes("searchActive ? visibleSessions.length : endIndex"),
|
||||
"search-mode `to` must reflect the rows actually returned"
|
||||
);
|
||||
});
|
||||
|
||||
test("pruneSessionRevokeTargetTokens drops dead entries before enforcing the cap (eviction prefers live-token survival)", () => {
|
||||
const prune = extractRegion(
|
||||
indexSource,
|
||||
"function pruneSessionRevokeTargetTokens(req) {",
|
||||
"function normalizeSessionRevokeTarget(target) {",
|
||||
"pruneSessionRevokeTargetTokens"
|
||||
);
|
||||
|
||||
const expiredSkip = prune.indexOf("expiresAt <= now) continue;");
|
||||
const capLoop = prune.indexOf("while (entries.length > SESSION_REVOKE_TARGET_TOKEN_MAX)");
|
||||
const oldestFirstSort = prune.indexOf(".sort((a, b) => Number(a[1].issuedAt || 0)");
|
||||
|
||||
assert.ok(expiredSkip >= 0, "expired entries must be skipped before normalization");
|
||||
assert.ok(capLoop >= 0, "cap enforcement loop not found");
|
||||
assert.ok(oldestFirstSort >= 0, "lowest-issuedAt eviction sort not found");
|
||||
// Dead (expired/invalid) tokens never count against the cap: they are
|
||||
// filtered out before the cap loop runs, so only live tokens are ever
|
||||
// evicted, oldest issuedAt first.
|
||||
assert.ok(expiredSkip < capLoop, "expired-entry skip must run before the cap loop");
|
||||
assert.ok(oldestFirstSort < capLoop, "oldest-first sort must run before the cap loop");
|
||||
});
|
||||
|
||||
test("consumed revoke tokens are deleted on use, not left to occupy cap space", () => {
|
||||
const consume = extractRegion(
|
||||
indexSource,
|
||||
"function consumeSessionRevokeTargetToken(req, token) {",
|
||||
"const STEALTH_MODE",
|
||||
"consumeSessionRevokeTargetToken"
|
||||
);
|
||||
assert.ok(consume.includes("delete targets["), "single-use consumption must delete the entry");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 8 — Enter path respects the confirm button's in-flight guard
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("2FA input Enter handler checks the in-flight flag before dispatching any one-time-token action", () => {
|
||||
const handler = extractRegion(
|
||||
settingsSource,
|
||||
"sessionRevokeTwoFactorInput.addEventListener('keydown'",
|
||||
"sessionRevokeModalConfirm.addEventListener('click'",
|
||||
"2FA input keydown handler"
|
||||
);
|
||||
|
||||
const guard = handler.indexOf("if (e.key === 'Enter' && sessionRevokeModalConfirm?.disabled) return;");
|
||||
assert.ok(guard >= 0, "Enter path must check sessionRevokeModalConfirm.disabled (the confirm button's in-flight flag)");
|
||||
|
||||
// The guard must precede EVERY action dispatch in the handler — the first
|
||||
// one (database install) is the earliest dispatch in source order.
|
||||
const firstDispatch = handler.indexOf("verifyDatabaseInstallWithCredential(");
|
||||
assert.ok(firstDispatch >= 0, "keydown handler action dispatches not found");
|
||||
assert.ok(guard < firstDispatch, "in-flight guard must run before the first Enter dispatch");
|
||||
|
||||
// The guarded flag is the exact one the confirm button sets at entry.
|
||||
assert.ok(
|
||||
settingsSource.includes("sessionRevokeModalConfirm.disabled = true;"),
|
||||
"confirm-button in-flight flag site not found"
|
||||
);
|
||||
});
|
||||
|
||||
test("every one-time-token verification action resets the in-flight flag in a finally block", () => {
|
||||
const TRUE_FLAG = "sessionRevokeModalConfirm.disabled = true;";
|
||||
const FALSE_FLAG = "sessionRevokeModalConfirm.disabled = false;";
|
||||
|
||||
const flags = [];
|
||||
let cursor = 0;
|
||||
for (;;) {
|
||||
const atTrue = settingsSource.indexOf(TRUE_FLAG, cursor);
|
||||
const atFalse = settingsSource.indexOf(FALSE_FLAG, cursor);
|
||||
if (atTrue < 0 && atFalse < 0) break;
|
||||
if (atTrue >= 0 && (atFalse < 0 || atTrue < atFalse)) {
|
||||
flags.push({ set: true, at: atTrue });
|
||||
cursor = atTrue + TRUE_FLAG.length;
|
||||
} else {
|
||||
flags.push({ set: false, at: atFalse });
|
||||
cursor = atFalse + FALSE_FLAG.length;
|
||||
}
|
||||
}
|
||||
|
||||
assert.ok(flags.length > 0, "no in-flight flag sites found");
|
||||
assert.ok(flags.length % 2 === 0, "every flag set must have a matching reset");
|
||||
for (let i = 0; i < flags.length; i += 2) {
|
||||
assert.ok(flags[i].set, `flag site ${i} must be a set (disabled = true)`);
|
||||
assert.ok(!flags[i + 1].set, `flag site ${i + 1} must be a reset (disabled = false)`);
|
||||
const body = settingsSource.slice(flags[i].at, flags[i + 1].at);
|
||||
assert.ok(
|
||||
body.includes("} finally {"),
|
||||
`verification action #${i / 2 + 1} must reset the in-flight flag in a finally block (covers success, error and exception)`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("grace-mode row revoke button respects the same in-flight guard", () => {
|
||||
const listClick = extractRegion(
|
||||
settingsSource,
|
||||
"if (sessionsList) {",
|
||||
"if (sessionRevokeModalClose)",
|
||||
"sessions list click handler"
|
||||
);
|
||||
|
||||
const graceBlock = listClick.indexOf("if (isGraceActive()) {");
|
||||
assert.ok(graceBlock >= 0, "grace-mode direct revoke path not found");
|
||||
const guard = listClick.indexOf("if (sessionRevokeModalConfirm?.disabled) return;", graceBlock);
|
||||
const dispatch = listClick.indexOf("revokeSession(revokeToken", graceBlock);
|
||||
assert.ok(dispatch >= 0, "grace-mode revokeSession dispatch not found");
|
||||
assert.ok(guard >= 0 && guard < dispatch, "grace-mode direct revoke must check the in-flight flag before invoking revokeSession");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Issue 9 — server search echo never clobbers a focused input or a stale response
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("loadSessions captures the requested search before awaiting and guards the echo write-back", () => {
|
||||
const loadSessions = extractRegion(
|
||||
settingsSource,
|
||||
"async function loadSessions(",
|
||||
"function setSecurityModalPresentation(",
|
||||
"loadSessions"
|
||||
);
|
||||
|
||||
const requestedCapture = loadSessions.indexOf("const requestedSearch = sessionsState.search;");
|
||||
const fetchAwait = loadSessions.indexOf("await fetch(");
|
||||
assert.ok(requestedCapture >= 0, "requested search must be captured for staleness comparison");
|
||||
assert.ok(fetchAwait >= 0, "loadSessions fetch not found");
|
||||
assert.ok(requestedCapture < fetchAwait, "requested search must be captured before the request is issued");
|
||||
|
||||
// The write-back is skipped for a focused input and for responses that do
|
||||
// not correspond to the current query.
|
||||
const echo = loadSessions.slice(loadSessions.indexOf("if (sessionsSearchInput) {"));
|
||||
assert.ok(echo.includes("!searchInputFocused"), "echo write-back must be skipped while the input is focused");
|
||||
assert.ok(
|
||||
echo.includes("document.activeElement === sessionsSearchInput"),
|
||||
"focus detection must compare document.activeElement against the search input"
|
||||
);
|
||||
assert.ok(echo.includes("echoMatchesRequest"), "echo must be compared against the query the request was issued with");
|
||||
assert.ok(echo.includes("inputStillHoldsRequest"), "echo must be skipped when the input already holds newer text");
|
||||
assert.ok(echo.includes("requestedSearch.toLowerCase()"), "staleness comparison must be case-insensitive (server lowercases the echo)");
|
||||
assert.ok(echo.includes("sessionsSearchInput.value = echoedSearch;"), "echo write-back must apply the server echo");
|
||||
// The final gate must be case-insensitive too: a pure case difference
|
||||
// between the input and the echo must never rewrite the admin's typed case.
|
||||
assert.ok(
|
||||
echo.includes("String(sessionsSearchInput.value || '').trim().toLowerCase() !== echoedSearch.toLowerCase()"),
|
||||
"echo write-back must be skipped when the input already equals the echo modulo case"
|
||||
);
|
||||
// The old unconditional clobber is gone.
|
||||
assert.ok(
|
||||
!settingsSource.includes("sessionsSearchInput.value = sessionsState.search;"),
|
||||
"unconditional server-echo write-back must not remain anywhere in settings.js"
|
||||
);
|
||||
});
|
||||
|
||||
test("search truncation is surfaced to the admin, not silently dropped", () => {
|
||||
assert.ok(
|
||||
settingsSource.includes("sessionsState.searchTruncated = !!data.searchTruncated;"),
|
||||
"loadSessions must adopt the server's searchTruncated flag"
|
||||
);
|
||||
const summary = extractRegion(
|
||||
settingsSource,
|
||||
"function renderSessionsSummary(",
|
||||
"function renderEmptySessionsState(",
|
||||
"renderSessionsSummary"
|
||||
);
|
||||
assert.ok(
|
||||
summary.includes("sessionsState.searchTruncated") && summary.includes("showing the first"),
|
||||
"search summary must tell the admin when the match list was truncated"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user