508 lines
29 KiB
JavaScript
508 lines
29 KiB
JavaScript
"use strict";
|
|
|
|
// Tests for the dashboard assistant delete path remediation.
|
|
//
|
|
// POST /api/dashboard-assistant/confirm-delete used to re-check admin only:
|
|
// no action token, no destructive-action step-up, no rate limiter, no
|
|
// server-side pending-intent state, and a thin audit record. A hijacked admin
|
|
// session (or XSS on the dashboard) therefore held a standing "delete any
|
|
// server, no second factor" capability — unlike every other destructive route
|
|
// (admin server delete, suspension, template change, transfer, webhooks,
|
|
// nodes), which require a session-bound action token plus a fresh
|
|
// password/2FA credential (or a scoped grace grant) behind a shared credential
|
|
// rate limiter.
|
|
//
|
|
// The remediation gives the assistant flow the same gate stack, and this file
|
|
// pins every layer:
|
|
// - POST /api/dashboard-assistant/delete-intent (new): the server-side
|
|
// pending-intent mint. Admin + JSON-only + dedicated per email+session
|
|
// rate limiter; mints a SHORT-TTL ONE-TIME action token bound to the
|
|
// exact intentId+chatId+serverName triple and registers the pending
|
|
// intent in the admin's session (bounded store).
|
|
// - POST /api/dashboard-assistant/confirm-delete: shared step-up credential
|
|
// limiter, admin, JSON-only, session pending-intent validation BEFORE any
|
|
// single-use artifact is burned, one-time token verify, intent
|
|
// consumption, destructive-action step-up scoped to server:<name> with
|
|
// failureResponseExtras re-mint, and a hardened service layer (chat
|
|
// validated before the irreversible delete, full audit parity: per-server
|
|
// + _system records with deletedBy/stepUp/via and a trusted-proxy IP).
|
|
// - The gate deps are hard requirements: a missing token verifier or
|
|
// step-up aborts the route (500) instead of silently skipping the gate.
|
|
// - The AI tool layer keeps pushing a capability-free client action and is
|
|
// instructed never to claim a delete succeeded and never to collect
|
|
// credentials in chat.
|
|
// - The browser modal fetches the intent, sends the x-action-token header
|
|
// plus the credential, and renders the password/2FA field from the
|
|
// server-provided revokeSecurity state (fails closed to password mode).
|
|
|
|
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 ROUTER_JS = path.join(ROOT, "routes", "dashboard-assistant.js");
|
|
const SERVICE_JS = path.join(ROOT, "utils", "dashboard-assistant-service.js");
|
|
const TOOLS_JS = path.join(ROOT, "utils", "dashboard-assistant-tools.js");
|
|
const CLIENT_JS = path.join(ROOT, "public", "js", "dashboard-assistant.js");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const INDEX_EJS = path.join(ROOT, "views", "index.ejs");
|
|
// Maintainer design snapshot only: moved out of public/ so express.static can
|
|
// never serve the ungated UI again; the markup-parity assertions below read it
|
|
// from here.
|
|
const INDEX_REAL_HTML = path.join(ROOT, "dev-templates", "index-real.html");
|
|
|
|
const routerSource = fs.readFileSync(ROUTER_JS, "utf8");
|
|
const serviceSource = fs.readFileSync(SERVICE_JS, "utf8");
|
|
const toolsSource = fs.readFileSync(TOOLS_JS, "utf8");
|
|
const clientSource = fs.readFileSync(CLIENT_JS, "utf8");
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const indexEjsSource = fs.readFileSync(INDEX_EJS, "utf8");
|
|
const indexRealHtmlSource = fs.readFileSync(INDEX_REAL_HTML, "utf8");
|
|
|
|
function assertContains(haystack, needle, label) {
|
|
assert.ok(haystack.includes(needle), `expected to find: ${label || needle}`);
|
|
}
|
|
|
|
// Slice from startMarker up to (excluding) endMarker. Function bodies with
|
|
// destructured parameters defeat brace-matching from the first `{`, so the
|
|
// functions under test are delimited by the next sibling declaration instead.
|
|
function extractSlice(source, startMarker, endMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
const end = endMarker ? source.indexOf(endMarker, start) : source.length;
|
|
assert.ok(end > start, `end marker not found after ${startMarker}: ${endMarker}`);
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
// Slice a `{ ... }`-balanced block starting at startMarker (for const x =
|
|
// rateLimit({...}) style declarations where the first `{` opens the body).
|
|
function extractBlock(source, startMarker) {
|
|
const start = source.indexOf(startMarker);
|
|
assert.ok(start >= 0, `marker not found: ${startMarker}`);
|
|
const bodyStart = source.indexOf("{", start);
|
|
let depth = 0;
|
|
let i = bodyStart;
|
|
for (; i < source.length; i += 1) {
|
|
if (source[i] === "{") depth += 1;
|
|
else if (source[i] === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
i += 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`);
|
|
return source.slice(start, i);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Service layer: pending intent + hardened delete
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("service: pending-intent constants are short-TTL, bounded, and exported", () => {
|
|
assertContains(serviceSource, "const DELETE_INTENT_TTL_MS = 2 * 60 * 1000;", "DELETE_INTENT_TTL_MS is 120s");
|
|
assertContains(
|
|
serviceSource,
|
|
"const DELETE_INTENT_MAX_PENDING_PER_SESSION = 3;",
|
|
"pending intent store is capped per session"
|
|
);
|
|
const match = serviceSource.match(
|
|
/const ASSISTANT_DELETE_CONFIRM_ACTION = "(POST \/api\/dashboard-assistant\/confirm-delete)";/
|
|
);
|
|
assert.ok(match, "ASSISTANT_DELETE_CONFIRM_ACTION is bound to the confirm-delete route");
|
|
assertContains(serviceSource, "DELETE_INTENT_TTL_MS,", "module exports DELETE_INTENT_TTL_MS");
|
|
assertContains(serviceSource, "ASSISTANT_DELETE_CONFIRM_ACTION,", "module exports ASSISTANT_DELETE_CONFIRM_ACTION");
|
|
});
|
|
|
|
test("service: intent token is minted one-time, short-TTL, and bound to intent+chat+server", () => {
|
|
const mintBlock = extractSlice(
|
|
serviceSource,
|
|
"function mintDeleteIntent(",
|
|
"async function createDeleteIntent("
|
|
);
|
|
assertContains(mintBlock, "crypto.randomBytes(16).toString(\"hex\")", "intentId is a random 128-bit id");
|
|
assertContains(mintBlock, "ASSISTANT_DELETE_CONFIRM_ACTION", "token action is the confirm-delete route");
|
|
assertContains(mintBlock, "{ intentId, chatId, serverName: resolvedName }", "token resource pins intent+chat+server");
|
|
assertContains(mintBlock, "oneTime: true", "token is single-use");
|
|
assertContains(mintBlock, "assistantDeleteIntents[intentId] = {", "pending intent is registered in the session");
|
|
assertContains(mintBlock, "DELETE_INTENT_TTL_MS", "token TTL matches the intent TTL window");
|
|
});
|
|
|
|
test("service: createDeleteIntent validates admin, chat ownership, and canonical server name", () => {
|
|
const createBlock = extractSlice(
|
|
serviceSource,
|
|
"async function createDeleteIntent(",
|
|
"async function confirmDeleteServer("
|
|
);
|
|
const adminCheckAt = createBlock.indexOf("!(currentUser && currentUser.admin)");
|
|
const chatCheckAt = createBlock.indexOf("await getChatById(userEmail, chatId)");
|
|
const mintAt = createBlock.indexOf("mintDeleteIntent({");
|
|
assert.ok(adminCheckAt >= 0, "admin is re-verified server-side");
|
|
assert.ok(chatCheckAt > adminCheckAt, "chat ownership is validated after the admin check");
|
|
assert.ok(mintAt > chatCheckAt, "the intent is minted only after validation");
|
|
assertContains(createBlock, "loadServersIndex", "server is resolved against the servers index");
|
|
assertContains(createBlock, "getDestructiveActionSecurityAsync", "revokeSecurity is attached for the modal");
|
|
});
|
|
|
|
test("service: confirmDeleteServer validates the chat BEFORE the irreversible delete", () => {
|
|
const confirmBlock = extractSlice(
|
|
serviceSource,
|
|
"async function confirmDeleteServer(",
|
|
"async function completeClientFollowUp("
|
|
);
|
|
const chatCheckAt = confirmBlock.indexOf("await getChatById(userEmail, chatId)");
|
|
const deleteAt = confirmBlock.indexOf("await deps.deleteServerByName(");
|
|
assert.ok(chatCheckAt >= 0, "chat lookup happens");
|
|
assert.ok(deleteAt > chatCheckAt, "chat validation strictly precedes deleteServerByName");
|
|
});
|
|
|
|
test("service: confirmDeleteServer writes full audit parity (per-server + _system, deletedBy, stepUp, via) and flushes caches", () => {
|
|
const confirmBlock = extractSlice(
|
|
serviceSource,
|
|
"async function confirmDeleteServer(",
|
|
"async function completeClientFollowUp("
|
|
);
|
|
const auditAt = confirmBlock.indexOf("deps.recordActivity(normalizedName, \"server_delete\"");
|
|
const systemAuditAt = confirmBlock.indexOf("deps.recordActivity(\"_system\", \"server_delete\"");
|
|
assert.ok(auditAt >= 0, "per-server server_delete record exists");
|
|
assert.ok(systemAuditAt > auditAt, "_system server_delete record exists");
|
|
assertContains(confirmBlock, "deletedBy: actorEmail", "audit carries deletedBy");
|
|
assertContains(confirmBlock, "via: \"dashboard-assistant\"", "audit marks the assistant path");
|
|
assertContains(confirmBlock, "stepUp: authMethod", "audit records how the step-up was satisfied");
|
|
assertContains(confirmBlock, "invalidateServerIndexCache", "server index cache is invalidated");
|
|
assertContains(confirmBlock, "deleteStatusCacheEntry", "status cache entry is flushed");
|
|
});
|
|
|
|
test("service: pruneDeleteIntents keeps the session store bounded and fresh", () => {
|
|
const pruneBlock = extractSlice(
|
|
serviceSource,
|
|
"function pruneDeleteIntents(",
|
|
"function mintDeleteIntent("
|
|
);
|
|
assertContains(pruneBlock, "Number(entry.expiresAt || 0) <= now", "expired intents are dropped");
|
|
assertContains(pruneBlock, "DELETE_INTENT_MAX_PENDING_PER_SESSION", "store is capped at the configured limit");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Router layer: the gated endpoints
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("router: delete-intent mounts the dedicated limiter, admin gate, JSON-only, and no-store", () => {
|
|
const intentRoute = extractSlice(routerSource, "router.post(\"/delete-intent\"", "router.post(\"/confirm-delete\"");
|
|
assertContains(intentRoute, "deps.dashboardAssistantDeleteIntentRateLimiter", "dedicated intent rate limiter is mounted");
|
|
assertContains(intentRoute, "requireAssistantAdmin(req, res)", "admin gate");
|
|
assertContains(intentRoute, "req.is(\"application/json\")", "JSON body enforced (CSRF hardening)");
|
|
assertContains(intentRoute, "Cache-Control\", \"no-store", "no-store on token-bearing responses");
|
|
assertContains(intentRoute, "service.createDeleteIntent", "delegates to the service mint");
|
|
});
|
|
|
|
test("router: confirm-delete mounts the shared step-up credential limiter and admin gate", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
assertContains(confirmRoute, "deps.sessionRevoke2faRateLimiter", "shared step-up credential limiter is mounted");
|
|
assertContains(confirmRoute, "requireAssistantAdmin(req, res)", "admin gate");
|
|
assertContains(confirmRoute, "req.is(\"application/json\")", "JSON body enforced");
|
|
assertContains(confirmRoute, "Cache-Control\", \"no-store", "no-store");
|
|
});
|
|
|
|
test("router: confirm-delete validates the session pending intent BEFORE burning single-use artifacts", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
const intentLookupAt = confirmRoute.indexOf("store[intentId]");
|
|
const expiryAt = confirmRoute.indexOf("Number(pendingIntent.expiresAt || 0) <= Date.now()");
|
|
const serverMatchAt = confirmRoute.indexOf("requestedServer !== String(pendingIntent.serverName || \"\")");
|
|
const chatMatchAt = confirmRoute.indexOf("Number(pendingIntent.chatId) !== Number(requestedChatId)");
|
|
const tokenVerifyAt = confirmRoute.indexOf("deps.requireActionTokenOr403(req, res");
|
|
// lastIndexOf: the expiry branch also deletes the entry (cleanup); the
|
|
// consumption under test is the one after token verification.
|
|
const consumeAt = confirmRoute.lastIndexOf("delete store[intentId];");
|
|
const stepUpAt = confirmRoute.indexOf("deps.requireDestructiveActionStepUp(");
|
|
|
|
assert.ok(intentLookupAt >= 0, "pending intent is read from the session (server-side state)");
|
|
assert.ok(expiryAt > intentLookupAt, "intent expiry is enforced");
|
|
assert.ok(serverMatchAt > expiryAt, "server binding is checked before any artifact burns");
|
|
assert.ok(chatMatchAt > serverMatchAt, "chat binding is checked before any artifact burns");
|
|
assert.ok(tokenVerifyAt > chatMatchAt, "the one-time token is verified after body binding checks");
|
|
assert.ok(consumeAt > tokenVerifyAt, "the intent is consumed after token verification");
|
|
assert.ok(stepUpAt > consumeAt, "step-up runs after intent consumption");
|
|
|
|
assertContains(confirmRoute, "DELETE_INTENT_ID_PATTERN.test(intentId)", "intentId shape is validated before any lookup");
|
|
assertContains(confirmRoute, "ASSISTANT_DELETE_CONFIRM_ACTION", "token is verified against the canonical action");
|
|
const confirmRouteFlat = confirmRoute.replace(/\s+/g, " ");
|
|
assertContains(
|
|
confirmRouteFlat,
|
|
"ASSISTANT_DELETE_CONFIRM_ACTION, { intentId, chatId: pendingIntent.chatId, serverName: pendingIntent.serverName, }",
|
|
"token resource is built from the session intent, not raw body values"
|
|
);
|
|
});
|
|
|
|
test("router: confirm-delete step-up is scoped to server:<name> and re-mints the intent on credential failure", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
assertContains(confirmRoute, "scopeKey: `server:${pendingIntent.serverName}`", "grace grant is scoped to the target server");
|
|
assertContains(confirmRoute, "failureResponseExtras", "failure extras hook is used");
|
|
assertContains(confirmRoute, "service.mintDeleteIntent", "failure extras re-mint a fresh pending intent");
|
|
assertContains(confirmRoute, "Assistant server delete", "step-up subject names the assistant path");
|
|
});
|
|
|
|
test("router: the token and step-up gates are hard dependencies — missing gate aborts, never skips", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
assertContains(
|
|
confirmRoute,
|
|
"if (typeof deps.requireActionTokenOr403 !== \"function\") {",
|
|
"missing token verifier throws"
|
|
);
|
|
assertContains(
|
|
confirmRoute,
|
|
"if (typeof deps.requireDestructiveActionStepUp !== \"function\") {",
|
|
"missing step-up throws"
|
|
);
|
|
assert.ok(
|
|
!confirmRoute.includes(": { ok: true, graceExpiresAt: 0, usedFreshVerification: false }"),
|
|
"no fail-open fallback for the step-up result"
|
|
);
|
|
});
|
|
|
|
test("router: audit IP uses the trusted-proxy resolver, and queued deletes answer 202", () => {
|
|
const confirmRoute = extractSlice(routerSource, "router.post(\"/confirm-delete\"", "return router;");
|
|
assertContains(confirmRoute, "deps.getRequestIp(req)", "trusted-proxy-aware IP for the audit trail");
|
|
assertContains(confirmRoute, "result.deleting ? 202 : 200", "queued deletes answer 202 like the admin route");
|
|
assertContains(confirmRoute, "graceExpiresAt", "response reports the grace window to the client");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Wiring: the gate primitives reach the router
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("index.js wires the full gate stack into the assistant router deps", () => {
|
|
const wiringAt = indexSource.indexOf("app.use(\"/api/dashboard-assistant\", createDashboardAssistantRouter({");
|
|
assert.ok(wiringAt >= 0, "assistant router wiring exists");
|
|
const wiringEnd = indexSource.indexOf("}));", wiringAt);
|
|
const wiring = indexSource.slice(wiringAt, wiringEnd);
|
|
for (const dep of [
|
|
"requireDestructiveActionStepUp",
|
|
"getDestructiveActionSecurityAsync",
|
|
"getVerifiedSessionRevokeGraceState",
|
|
"sessionRevoke2faRateLimiter",
|
|
"dashboardAssistantDeleteIntentRateLimiter",
|
|
"getRequestIp",
|
|
"invalidateServerIndexCache",
|
|
"deleteStatusCacheEntry",
|
|
]) {
|
|
assertContains(wiring, dep, `wiring passes ${dep}`);
|
|
}
|
|
});
|
|
|
|
test("index.js defines the dedicated delete-intent limiter keyed per email+session (no IP)", () => {
|
|
const limiter = extractBlock(indexSource, "const dashboardAssistantDeleteIntentRateLimiter = rateLimit(");
|
|
assertContains(limiter, "assistant-delete-intent:${email}:${sid}", "keyed per account+session");
|
|
assertContains(limiter, "skip: (req) => !req.session?.user", "skips anonymous requests");
|
|
assertContains(limiter, "status(429)", "answers 429 when exhausted");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// AI tool layer: no standing capability, no credential collection in chat
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("tools: request_delete_server stays capability-free and the prompt pins the modal+verification contract", () => {
|
|
const toolBlock = extractSlice(
|
|
toolsSource,
|
|
"case \"request_delete_server\":",
|
|
"case \"list_files\":"
|
|
);
|
|
assertContains(toolBlock, "type: \"confirm_delete_server\"", "client action still carries no token/secret");
|
|
assert.ok(!toolBlock.includes("actionToken"), "tool client action must not embed any action token");
|
|
assertContains(
|
|
toolsSource,
|
|
"Use request_delete_server first so the browser can show a confirmation modal with a security verification",
|
|
"system prompt requires the modal + verification flow"
|
|
);
|
|
assertContains(
|
|
toolsSource,
|
|
"Never ask for a password or 2FA code in chat and never claim a delete succeeded before the modal flow reports it.",
|
|
"system prompt forbids credential collection and premature success claims"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Browser layer: intent fetch, token header, credential step-up UI
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("client: modal fetches a delete intent and sends the x-action-token header + intentId", () => {
|
|
assertContains(clientSource, "/api/dashboard-assistant/delete-intent", "intent mint endpoint is called");
|
|
const confirmFn = extractSlice(clientSource, "async function confirmDeleteModal(", "async function submitMessage(");
|
|
const confirmFetch = extractBlock(confirmFn, "const sendConfirm = async (currentIntent)");
|
|
assertContains(confirmFetch, "\"x-action-token\": String(currentIntent.actionToken || \"\")", "token rides the x-action-token header");
|
|
assertContains(confirmFetch, "intentId: currentIntent.intentId", "intentId is sent");
|
|
assertContains(confirmFetch, "currentPassword:", "password step-up field is sent when required");
|
|
assertContains(confirmFetch, "twoFactorCode:", "2FA step-up field is sent when required");
|
|
});
|
|
|
|
test("client: step-up failures render the credential field from revokeSecurity and store the re-minted intent", () => {
|
|
const confirmFn = extractSlice(clientSource, "async function confirmDeleteModal(", "async function submitMessage(");
|
|
assertContains(confirmFn, "data?.revokeSecurity", "step-up failure branch keys off revokeSecurity");
|
|
assertContains(confirmFn, "state.pendingDeleteIntent = data.intent || null", "re-minted intent replaces the consumed one");
|
|
assertContains(confirmFn, "configureDeleteCredentialField()", "credential field is re-rendered on failure");
|
|
assertContains(confirmFn, "intent-invalid", "stale-intent 403s are recognized and fail closed");
|
|
});
|
|
|
|
test("client: credential field fails closed without server security state", () => {
|
|
const configureFn = extractSlice(
|
|
clientSource,
|
|
"function configureDeleteCredentialField(",
|
|
"async function requestDeleteIntent("
|
|
);
|
|
assertContains(configureFn, "const requiresVerification = security", "security state drives the field");
|
|
assertContains(configureFn, ": !localGraceActive", "without security state the field is shown unless a known grace is live");
|
|
assertContains(configureFn, "state.deleteCredentialRequired = requiresVerification;", "requirement is recorded on state");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Markup: both page templates carry the step-up UI
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("modal markup in both templates carries the credential verification block", () => {
|
|
for (const [label, source] of [["views/index.ejs", indexEjsSource], ["dev-templates/index-real.html", indexRealHtmlSource]]) {
|
|
assertContains(source, "dashboardAssistantDeleteVerify", `${label}: verify block present`);
|
|
assertContains(source, "dashboardAssistantDeleteCredential", `${label}: credential input present`);
|
|
assertContains(source, "dashboardAssistantDeleteFeedback", `${label}: feedback line present`);
|
|
assertContains(source, "autocomplete=\"current-password\"", `${label}: password autocomplete semantics`);
|
|
}
|
|
});
|
|
|
|
test("cache-busting versions were bumped so browsers pick up the gated client", () => {
|
|
assertContains(indexEjsSource, "dashboard-assistant.js?v=20261006-assistant-audit-fixes-v54", "index.ejs version bumped");
|
|
// dev-templates/index-real.html is a frozen design snapshot, not a served
|
|
// template: it no longer tracks client versions (and is asserted absent
|
|
// from public/ below).
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Static snapshot: index-real.html must never be served from public/
|
|
// ---------------------------------------------------------------------------
|
|
|
|
// A static copy can never enforce the canUserAccessDashboardAssistant gate,
|
|
// so express.static serving it exposed the assistant UI to every user (plus
|
|
// admin-only provider key-config markup, baked-in server data, and placeholder
|
|
// nonce="x" attributes that miss every CSP fix landing in views/index.ejs).
|
|
// It is retained only as a maintainer design snapshot under dev-templates/.
|
|
test("the static index-real.html snapshot is no longer served from public/", () => {
|
|
assert.ok(
|
|
!fs.existsSync(path.join(ROOT, "public", "index-real.html")),
|
|
"public/index-real.html must never come back: express.static would serve the ungated assistant UI, admin-only provider key markup and placeholder nonces to any user — the snapshot lives in dev-templates/"
|
|
);
|
|
assert.ok(
|
|
fs.existsSync(path.join(ROOT, "dev-templates", "index-real.html")),
|
|
"the maintainer design snapshot is retained at dev-templates/index-real.html"
|
|
);
|
|
});
|
|
|
|
// The L4 client fix: a grace window is scoped to the server that earned it.
|
|
// Opening the modal for a different server clears the stale window, and a
|
|
// confirmed delete re-pairs the fresh window with the confirmed server name.
|
|
test("client: delete grace window is owner-scoped on modal open and re-paired on confirm success", () => {
|
|
const openFn = extractSlice(clientSource, "function openDeleteModal(", "function closeDeleteModal(");
|
|
const openFnFlat = openFn.replace(/\s+/g, " ");
|
|
assertContains(
|
|
openFnFlat,
|
|
"if (String(state.pendingDeleteServer?.server || \"\").trim() !== String(state.deleteGraceServer || \"\")) { state.deleteGraceExpiresAt = 0; state.deleteGraceServer = \"\"; }",
|
|
"opening the modal clears a grace window owned by a different server"
|
|
);
|
|
const confirmFn = extractSlice(clientSource, "async function confirmDeleteModal(", "async function submitMessage(");
|
|
const confirmFnFlat = confirmFn.replace(/\s+/g, " ");
|
|
assertContains(
|
|
confirmFnFlat,
|
|
"state.deleteGraceExpiresAt = Number(data.graceExpiresAt || 0); state.deleteGraceServer = serverName;",
|
|
"confirm success stores the grace window paired with the confirmed server"
|
|
);
|
|
});
|
|
|
|
// The stale delete-intent race fix: every mint/confirm step is pinned to the
|
|
// modal context it started in (deleteIntentEpoch + server name), a late
|
|
// response for a closed or retargeted modal is discarded before it can touch
|
|
// shared state, a confirm only sends an intent whose canonical server
|
|
// matches the server the user actually saw in the modal, a second open is
|
|
// refused while a confirm is in flight, and a stale-artifact 403 fails
|
|
// closed without an automatic destructive re-send.
|
|
test("client: delete intent is epoch-bound to the modal context and fail-closed against the displayed server", () => {
|
|
const requestFn = extractSlice(clientSource, "async function requestDeleteIntent(", "async function ensureDeleteIntent(");
|
|
assertContains(requestFn, "const epoch = state.deleteIntentEpoch;", "mint pins the modal epoch");
|
|
assertContains(requestFn, "deleteMintContextCurrent", "mint guards every shared-state write on the live context");
|
|
assertContains(requestFn, "if (!deleteMintContextCurrent()) return null;", "late mint responses are discarded");
|
|
const openFn = extractSlice(clientSource, "function openDeleteModal(", "function closeDeleteModal(");
|
|
assertContains(openFn, "state.deleteIntentEpoch += 1;", "opening the modal retargets the epoch");
|
|
assertContains(openFn, "els.deleteCancel.disabled = false;", "opening the modal re-arms the cancel action");
|
|
const openFnFlat = openFn.replace(/\s+/g, " ");
|
|
assertContains(
|
|
openFnFlat,
|
|
"if (state.deletingServer || state.deleteIntentLoading) { setStatus(\"A server delete is already in progress.\", \"warning\"); return; }",
|
|
"a second open is refused while a delete confirm or its intent mint is in flight"
|
|
);
|
|
const closeFn = extractSlice(clientSource, "function closeDeleteModal(", "function updateComposerAvailability(");
|
|
assertContains(closeFn, "state.deleteIntentEpoch += 1;", "closing the modal retargets the epoch");
|
|
const confirmFn = extractSlice(clientSource, "async function confirmDeleteModal(", "async function submitMessage(");
|
|
// Site-specific flattened pin: the post-mint abort is the only guard with
|
|
// this exact condition text, so the flattened substring is unambiguous.
|
|
const confirmFnFlat = confirmFn.replace(/\s+/g, " ");
|
|
assertContains(
|
|
confirmFnFlat,
|
|
"!state.pendingDeleteServer || String(state.pendingDeleteServer.server || \"\").trim() !== serverName || state.deleteIntentEpoch !== epoch",
|
|
"confirm re-validates its context after the mint await"
|
|
);
|
|
// The stale-artifact 403 contract: exactly ONE destructive request goes
|
|
// out. The client clears the dead intent, asks for a manual re-confirm
|
|
// (the next Delete click re-mints through ensureDeleteIntent) and never
|
|
// re-sends on its own. The full flattened guard is pinned so losing the
|
|
// epoch or server invariant cannot go unnoticed.
|
|
assertContains(
|
|
confirmFnFlat,
|
|
"if ( staleArtifact && state.deleteIntentEpoch === epoch && String(state.pendingDeleteServer?.server || \"\").trim() === serverName ) { state.pendingDeleteIntent = null; showDeleteFeedback(\"Your delete confirmation expired. Please click Delete again.\", true); return; }",
|
|
"a stale-artifact 403 for the owning context clears the intent, shows re-confirm feedback and sends nothing more"
|
|
);
|
|
assert.strictEqual(
|
|
confirmFnFlat.split("await sendConfirm(").length - 1,
|
|
1,
|
|
"exactly one destructive confirm send exists — no automatic re-send"
|
|
);
|
|
assert.ok(
|
|
!clientSource.includes("deleteRetryCount"),
|
|
"the auto-retry counter is gone together with the automatic re-send"
|
|
);
|
|
assertContains(
|
|
confirmFn,
|
|
"intentServerName.toLowerCase() !== serverName.toLowerCase()",
|
|
"confirm is fail-closed unless the intent matches the displayed server"
|
|
);
|
|
assertContains(confirmFn, "liveStepUp.requiresVerification", "credential is re-checked against the live step-up mode");
|
|
});
|
|
|
|
// The push-to-talk fix: the hotkey belongs to the open assistant panel, never
|
|
// steals keys from text-entry surfaces, stays silent while the delete modal
|
|
// overlays the panel, and an armed bind cannot outlive the closed panel.
|
|
test("client: push-to-talk hotkey is gated on the open panel and text-entry targets", () => {
|
|
assertContains(clientSource, "function isTextInputTarget(node)", "text-entry target helper exists");
|
|
const keydownFn = extractSlice(clientSource, "document.addEventListener(\"keydown\"", "document.addEventListener(\"keyup\"");
|
|
assertContains(keydownFn, "if (!state.open) return;", "hotkey never starts capture from a closed panel");
|
|
// Order pin: presence of the guard is not enough — the open guard, the
|
|
// text-entry guard and the delete-modal guard must all run BEFORE the key is
|
|
// claimed with preventDefault, or a closed panel would still swallow F5.
|
|
const openGuardAt = keydownFn.indexOf("if (!state.open) return;");
|
|
const textTargetGuardAt = keydownFn.indexOf("isTextInputTarget(event.target)", openGuardAt);
|
|
const deleteModalGuardAt = keydownFn.indexOf("els.deleteModal?.classList.contains(\"show\")", openGuardAt);
|
|
const pttPreventDefaultAt = keydownFn.indexOf("event.preventDefault();", openGuardAt);
|
|
assert.ok(
|
|
openGuardAt >= 0 &&
|
|
textTargetGuardAt > openGuardAt &&
|
|
deleteModalGuardAt > openGuardAt &&
|
|
pttPreventDefaultAt > textTargetGuardAt &&
|
|
pttPreventDefaultAt > deleteModalGuardAt,
|
|
"all three PTT guards run before the key is claimed with preventDefault"
|
|
);
|
|
assertContains(
|
|
keydownFn,
|
|
"isTextInputTarget(event.target) || isTextInputTarget(document.activeElement)",
|
|
"input/textarea/select/contenteditable targets keep their keys"
|
|
);
|
|
assertContains(keydownFn, "els.deleteModal?.classList.contains(\"show\")", "no capture while the delete modal overlays the panel");
|
|
assertContains(keydownFn, "if (!state.open) {", "an armed PTT bind cannot outlive the closed panel");
|
|
});
|