"use strict"; // Tests for the F1 remediation: the admin template-change route // (POST /api/settings/servers/:name/template — a full wipe-and-reinstall) and // the transfer route (POST /api/settings/servers/:name/transfer) sat behind an // admin-session check only, while delete/suspend already required an action // token plus a destructive-action step-up. A hijacked admin session — the exact // threat the step-up exists for — could wipe a server or move it between nodes // with zero friction, and create (POST /api/servers/create) had neither a // step-up (unlike node create) nor a dedicated rate limiter. // // The remediation locks each gate in, and this file pins every one of them: // - template change: sessionRevoke2faRateLimiter + a dedicated // serverTemplateChangeRateLimiter, a session+server-bound action token // (templateChangeToken, minted by GET /api/settings/servers), and step-up // with persistGrant:false — the same policy as the F2 user reinstall. // - transfer: a dedicated serverTransferRateLimiter (F3: the step-up grace // window means sessionRevoke2faRateLimiter alone only bounds // credential-bearing requests), sessionRevoke2faRateLimiter, transferToken, // and a server-scoped step-up with the default grace persistence — the // same policy as suspend. // - create: a dedicated serverCreateRateLimiter plus a step-up with NO // scopeKey (mirrors node create: the grant stays unbound so the wizard's // follow-ups and short batches inside the grace window do not re-prompt). // - webhook test (P2.1): POST /api/settings/webhooks/test sat behind the // admin gate only. It now mounts sessionRevoke2faRateLimiter plus a // dedicated webhookTestRateLimiter (the credential limiter only counts // credential-bearing requests, and the internal 1/sec dispatch limiter is // keyed per action+server+URL, so every category refills its own bucket), // verifies the testWebhook action token, and runs the same destructive- // action step-up as the webhook save/delete — after the no-op 400 so an // empty config cannot burn a grace use. settings.js rides // sendGuardedRequestWithStepUp with one token refresh+retry. // - webhook delete (P5.1): the single multi-use deleteWebhook token (empty // resource) was a universal, replayable delete key for the whole webhook // config within its TTL. Delete tokens are now one-time and pinned per // target ({ target: "single" / "" }), minted by the shared // buildWebhookSettingsActionTokens helper in the section GET and every // write success response; POST/DELETE mount a dedicated write-budget // limiter (the credential limiter only counts credential-bearing // requests) and GET mounts a read limiter, since every GET mints one // one-time token per delete target. settings.js picks the per-target // token and performs one refresh+retry on a token rejection. // - DOM token exposure (P2.2): server delete/suspension and account // delete/suspension tokens were rendered into data-* attributes. They now // live only in the per-list JS Maps (the webhook-token handling model), // and the getters no longer fall back to dataset reads. // - modern fs mutator brake (W2): the four /api/servers/:name/files/* // mutation routes (write/mkdir/delete/rename) mount the same // serverFsMutateRateLimiter the legacy /extract //archive //create // //rename routes already carried — same responsibility (fs mutation), // one abuse-brake posture, so a scripted loop cannot shop between the // modern and legacy spellings of the same write. // - always-on read brakes: the planner GET and the four file GET routes // (list/read/stream/download) mount dedicated read limiters // (plannerReadRateLimiter / serverFsReadRateLimiter) constructed exactly // like their mutate siblings (always-on, per-account email key, // fail-open store, DISTINCT Redis prefixes "rlpr:"/"rlfsr:") — every // file GET dial holds a node connection for its full timeout, so an // unbraked read loop amplifies unboundedly while the global throttles // stay no-ops unless security.rate_limiting is enabled. // Frontend contract: settings.js sends the x-action-token header through // sendServerRowActionWithGuards (with one token-refresh retry on a stale token // and the shared step-up modal), the create wizard rides // window.sendGuardedRequestWithStepUp, and dashboard.js implements a // self-contained challenge/retry for /api/servers/create. 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 crypto = require("node:crypto"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js"); const WIZARD_JS = path.join(ROOT, "public", "js", "create-server-wizard.js"); const DASHBOARD_JS = path.join(ROOT, "public", "js", "dashboard.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8"); const wizardSource = fs.readFileSync(WIZARD_JS, "utf8"); const dashboardSource = fs.readFileSync(DASHBOARD_JS, "utf8"); // Slice a `{ ... }`-balanced block starting at startMarker, including any // trailing call syntax (`});`) so `const x = rateLimit({...});` stays parseable. 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}`); while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) { i += 1; if (source[i - 1] === ";") break; } return source.slice(start, i); } 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); } // --------------------------------------------------------------------------- // Backend wiring // --------------------------------------------------------------------------- test("template change route: limiters, action token gate, and no-mint step-up before the reinstall claim", () => { const route = extractRoute( indexSource, 'app.post("/api/settings/servers/:name/template"', 'app.post("/api/servers/:name/reinstall"' ); assert.match( route, /app\.post\("\/api\/settings\/servers\/:name\/template", sessionRevoke2faRateLimiter, serverTemplateChangeRateLimiter, async/, "route must mount the credential limiter and the dedicated template-change limiter" ); assert.match(route, /res\.set\("Cache-Control", "no-store"\)/, "token-bearing gate responses must be uncacheable"); assert.match( route, /requireActionTokenOr403\(req, res, "POST \/api\/settings\/servers\/:name\/template", \{ serverName: name \}\)/, "route must verify the session+server-bound action token" ); const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/servers/:name/template"'); const targetIdx = route.indexOf("requireServerSettingsTarget(req, res, entry)"); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); const claimIdx = route.indexOf("claimReinstallOperation(claimName, entry)"); assert.ok(targetIdx > tokenIdx, "the selected row must be checked after the token gate"); assert.ok(stepUpIdx > targetIdx, "step-up must come after the selected row check"); assert.ok(claimIdx > stepUpIdx, "the reinstall claim must come after the step-up gate"); const stepUpCall = route.slice(stepUpIdx, claimIdx); assert.match(stepUpCall, /scopeKey: `server:\$\{name\}`/, "step-up must be scoped to the server"); assert.match(stepUpCall, /persistGrant: false/, "a wipe must not mint a reusable grace grant"); }); test("transfer route: limiter, action token gate, and scoped step-up before any state claim", () => { const route = extractRoute( indexSource, 'app.post("/api/settings/servers/:name/transfer"', "function getSshTerminalWsTarget(req)" ); assert.match( route, /app\.post\("\/api\/settings\/servers\/:name\/transfer", serverTransferRateLimiter, sessionRevoke2faRateLimiter, async/, "route must mount the dedicated transfer volume limiter and the credential limiter" ); assert.match(route, /res\.set\("Cache-Control", "no-store"\)/); assert.match( route, /requireActionTokenOr403\(req, res, "POST \/api\/settings\/servers\/:name\/transfer", \{ serverName: name \}\)/, "route must verify the session+server-bound action token" ); const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/servers/:name/transfer"'); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); const lockIdx = route.indexOf("withReinstallSuspensionLock(serverEntry.name, busy, async () => {"); assert.ok(stepUpIdx > tokenIdx, "step-up must come after the token gate"); assert.ok(lockIdx > stepUpIdx, "the suspension lock / state claims must come after the step-up gate"); const stepUpCall = route.slice(stepUpIdx, lockIdx); assert.match(stepUpCall, /scopeKey: `server:\$\{name\}`/, "step-up must be scoped to the server"); assert.doesNotMatch(stepUpCall, /persistGrant/, "transfer keeps the default grace persistence (like suspend)"); }); test("create route: dedicated limiter and unscoped step-up before the create lock", () => { const route = extractRoute( indexSource, 'app.post("/api/servers/create"', 'app.delete("/api/settings/servers/:name"' ); assert.match( route, /app\.post\("\/api\/servers\/create", serverCreateRateLimiter, sessionRevoke2faRateLimiter, async/, "route must mount the dedicated create limiter and the credential limiter" ); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); // M4 replaced the wholesale-cleared Set with a TTL lock (acquireServerCreateLock); // the invariant under test is unchanged: step-up must run before the create lock. const lockIdx = route.indexOf("acquireServerCreateLock(name)"); assert.ok(stepUpIdx > 0 && lockIdx > stepUpIdx, "step-up must run before the create lock is taken"); const stepUpCall = route.slice(stepUpIdx, lockIdx); assert.match(stepUpCall, /`Server create "\$\{name\}"`\)/, "create step-up mirrors node create"); assert.doesNotMatch(stepUpCall, /scopeKey/, "no scopeKey: the minted grant stays unbound (node-create parity)"); }); test("GET /api/settings/servers mints templateChangeToken and transferToken bound to the route actions", () => { const listRoute = extractRoute( indexSource, 'app.get("/api/settings/servers"', 'app.get("/api/my-servers"' ); assert.match( listRoute, /templateChangeToken: issueActionToken\(\s*req,\s*"POST \/api\/settings\/servers\/:name\/template",\s*\{ serverName: String\(item\.name \|\| ""\)\.trim\(\) \},\s*\{ ttlSeconds: 600 \}\s*\)/, "the list must mint the template-change token with the exact action string the POST verifies" ); assert.match( listRoute, /transferToken: issueActionToken\(\s*req,\s*"POST \/api\/settings\/servers\/:name\/transfer",\s*\{ serverName: String\(item\.name \|\| ""\)\.trim\(\) \},\s*\{ ttlSeconds: 600 \}\s*\)/, "the list must mint the transfer token with the exact action string the POST verifies" ); const limiterAt = indexSource.indexOf("const settingsRateLimiters = createSettingsRateLimiters("); const routeAt = indexSource.indexOf('app.post("/api/settings/servers/:name/template"'); assert.ok(limiterAt >= 0 && routeAt > limiterAt, "template-change limiter must be defined before the route uses it"); const createLimiterAt = limiterAt; const createRouteAt = indexSource.indexOf('app.post("/api/servers/create"'); assert.ok(createLimiterAt >= 0 && createRouteAt > createLimiterAt, "create limiter must be defined before the route uses it"); const transferLimiterAt = limiterAt; const transferRouteAt = indexSource.indexOf('app.post("/api/settings/servers/:name/transfer"'); assert.ok(transferLimiterAt >= 0 && transferRouteAt > transferLimiterAt, "transfer limiter must be defined before the route uses it"); }); // --------------------------------------------------------------------------- // New rate limiters (executed in a vm sandbox with a stubbed express-rate-limit) // --------------------------------------------------------------------------- function runLimiter(marker) { let captured = null; const name = /const (\w+) =/.exec(marker)?.[1]; const policies = require("../services/settings-rate-limiters"); if (policies.SETTINGS_OPERATION_POLICIES[name]) { const options = []; policies.createSettingsRateLimiters({ rateLimit: (config) => { options.push(config); return () => {}; }, securityLog() {} }); const policyNames = Object.keys(policies.SETTINGS_OPERATION_POLICIES); return options[policyNames.indexOf(name) * 2 + 1]; } const sandbox = { ...require("../utils/destructive-action-credentials"), rateLimit: (config) => { captured = config; return function middleware() { }; }, getRequestIp: () => "203.0.113.7", securityLog: () => { }, console: { log() { }, warn() { }, error() { } }, // adpanel:per-limiter-redis-stores — the swept limiters reference the // boot-time Redis client and the store factory. The harness has no // Redis: a null client ⇒ `store: undefined` ⇒ the same MemoryStore // fallback a Redis-less boot takes, so the assertions below keep // pinning windowMs/max/keyGenerator exactly as before. redisClient: null, buildSharedRateLimitRedisStore: () => undefined, buildAssistantRedisStore: () => undefined, }; vm.createContext(sandbox); vm.runInContext(extractBlock(indexSource, marker), sandbox); assert.ok(captured, `${marker} did not run`); return captured; } test("credential limiter admission and strict verification agree across numeric codes and multiple sessions", async () => { const express = require("express"); const rateLimit = require("express-rate-limit"); const { parseDestructiveActionCredentials } = require("../utils/destructive-action-credentials"); const account = rateLimit(runLimiter("const sessionRevoke2faEmailRateLimiter = rateLimit(")); const session = rateLimit(runLimiter("const sessionRevoke2faSessionRateLimiter = rateLimit(")); const app = express(); let verifications = 0; app.use(express.json()); app.use((req, _res, next) => { req.session = { user: "admin@example.test" }; req.sessionID = req.get("x-test-session") || "one"; next(); }); app.post("/verify", account, session, (req, res) => { const credentials = parseDestructiveActionCredentials(req.body); if (!credentials.invalidType && credentials.twoFactorCode) verifications += 1; res.status(403).json({ error: "verification refused" }); }); const server = app.listen(0, "127.0.0.1"); await new Promise((resolve) => server.once("listening", resolve)); const request = async (code, sid) => { const response = await fetch(`http://127.0.0.1:${server.address().port}/verify`, { method: "POST", headers: { "Content-Type": "application/json", "x-test-session": sid }, body: JSON.stringify({ twoFactorCode: code }) }); await response.arrayBuffer(); return response.status; }; try { for (let attempt = 0; attempt < 12; attempt += 1) assert.equal(await request(123456, "one"), 403); assert.equal(verifications, 0, "uncounted numeric payloads never reach credential verification"); for (const sid of ["one", "two", "three"]) { for (let attempt = 0; attempt < 8; attempt += 1) assert.equal(await request("012345", sid), 403); } assert.equal(verifications, 24); assert.equal(await request("012345", "four"), 429, "account-wide budget survives session changes"); assert.equal(verifications, 24); } finally { await new Promise((resolve) => server.close(resolve)); } }); test("serverTemplateChangeRateLimiter: 5 per 10 minutes keyed per account+session", () => { const limiter = runLimiter("const serverTemplateChangeRateLimiter = rateLimit("); assert.equal(limiter.windowMs, 10 * 60 * 1000); assert.equal(limiter.max, 5); assert.equal(limiter.skip({ session: null }), true); assert.equal(limiter.skip({ session: { user: "user@example.com" } }), false); const req = { session: { user: "User@Example.com" }, sessionID: "sid-1" }; assert.equal(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, ip: "198.51.100.2" })); assert.notEqual(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, sessionID: "other" })); let statusCode = 0; let payload = null; const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } }; limiter.handler(req, res); assert.equal(statusCode, 429); assert.equal(payload.code, "template-change-rate-limit"); }); test("serverCreateRateLimiter: 10 per 10 minutes keyed per account+session", () => { const limiter = runLimiter("const serverCreateRateLimiter = rateLimit("); assert.equal(limiter.windowMs, 10 * 60 * 1000); assert.equal(limiter.max, 10); assert.equal(limiter.skip({ session: null }), true); assert.equal(limiter.skip({ session: { user: "user@example.com" } }), false); const req = { session: { user: "User@Example.com" }, sessionID: "sid-2" }; assert.equal(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, ip: "198.51.100.2" })); assert.notEqual(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, sessionID: "other" })); let statusCode = 0; let payload = null; const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } }; limiter.handler(req, res); assert.equal(statusCode, 429); assert.equal(payload.code, "create-rate-limit"); }); test("serverTransferRateLimiter: 5 per 10 minutes keyed per account+session", () => { const limiter = runLimiter("const serverTransferRateLimiter = rateLimit("); assert.equal(limiter.windowMs, 10 * 60 * 1000); assert.equal(limiter.max, 5); assert.equal(limiter.skip({ session: null }), true); assert.equal(limiter.skip({ session: { user: "user@example.com" } }), false); const req = { session: { user: "User@Example.com" }, sessionID: "sid-3" }; assert.equal(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, ip: "198.51.100.2" })); assert.notEqual(limiter.keyGenerator(req), limiter.keyGenerator({ ...req, sessionID: "other" })); let statusCode = 0; let payload = null; const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } }; limiter.handler(req, res); assert.equal(statusCode, 429); assert.equal(payload.code, "transfer-rate-limit"); }); // --------------------------------------------------------------------------- // Token machinery with the exact mint/verify pairs of the three routes // --------------------------------------------------------------------------- // The token helpers (safeCompare .. requireActionTokenOr403) form one // contiguous region in index.js ending right before readJson. One-time // nonces are claimed through the durable consumed-token machinery // (claimActionNonce → claimSessionRevokeTargetToken), so that region is // eval'd too, with the globals it reads injected (values mirror index.js: // SESSION_REVOKE_TARGET_TOKEN_TTL_MS = 10 min; no redisClient in the sandbox // routes the claim through the process-local Map path). function buildTokenSandbox() { const start = indexSource.indexOf("function safeCompare(a, b) {"); const endMarker = "function readJson(file, fallback) {"; const end = indexSource.indexOf(endMarker); assert.ok(start >= 0 && end > start, "token helper region not found"); const claimStart = indexSource.indexOf('const CONSUMED_ACTION_TOKEN_REDIS_PREFIX ='); const claimEndMarker = "// Single-use consumption."; const claimEnd = indexSource.indexOf(claimEndMarker); assert.ok(claimStart >= 0 && claimEnd > claimStart, "consumed-token claim region not found"); const sandbox = { crypto, Buffer, Date, console: { log() { }, warn() { }, error() { } }, process: { env: { ACTION_TOKEN_SECRET: "test-action-token-secret", SESSION_SECRET: "test-session-secret" } }, // Globals the durable claim slice reads at definition/runtime time. SESSION_REVOKE_TARGET_TOKEN_TTL_MS: 10 * 60 * 1000, redisClient: undefined, getSessionDisplayId: (id) => String(id || ""), }; vm.createContext(sandbox); // Claim machinery first: claimActionNonce in the token slice resolves it. vm.runInContext(indexSource.slice(claimStart, claimEnd), sandbox); vm.runInContext(indexSource.slice(start, end), sandbox); return sandbox; } test("settings list tokens verify against the guarded routes and nothing else", async () => { const sandbox = buildTokenSandbox(); const out = await vm.runInContext(` (async () => { const reqOk = { session: { user: "admin@example.com" }, sessionID: "sess-1", get: () => null, body: {} }; const tplToken = issueActionToken(reqOk, "POST /api/settings/servers/:name/template", { serverName: "alpha" }, { ttlSeconds: 600 }); const xferToken = issueActionToken(reqOk, "POST /api/settings/servers/:name/transfer", { serverName: "alpha" }, { ttlSeconds: 600 }); const stranger = { session: { user: "admin@example.com" }, sessionID: "sess-2", get: () => null, body: {} }; return ({ tplOk: await verifyActionToken(reqOk, tplToken, "POST /api/settings/servers/:name/template", { serverName: "alpha" }), tplOtherServer: await verifyActionToken(reqOk, issueActionToken(reqOk, "POST /api/settings/servers/:name/template", { serverName: "beta" }, { ttlSeconds: 600 }), "POST /api/settings/servers/:name/template", { serverName: "alpha" }), tplUserRouteAction: await verifyActionToken(reqOk, issueActionToken(reqOk, "POST /api/servers/:bot/template", { serverName: "alpha" }, { ttlSeconds: 600 }), "POST /api/settings/servers/:name/template", { serverName: "alpha" }), tplWrongSession: await verifyActionToken(stranger, tplToken, "POST /api/settings/servers/:name/template", { serverName: "alpha" }), xferOk: await verifyActionToken(reqOk, xferToken, "POST /api/settings/servers/:name/transfer", { serverName: "alpha" }), xferWrongAction: await verifyActionToken(reqOk, xferToken, "POST /api/settings/servers/:name/template", { serverName: "alpha" }), missing: await verifyActionToken(reqOk, null, "POST /api/settings/servers/:name/transfer", { serverName: "alpha" }), }); })() `, sandbox); assert.equal(out.tplOk, true, "a minted template-change token must verify on the guarded route"); assert.equal(out.tplOtherServer, false, "token bound to another server must fail"); assert.equal(out.tplUserRouteAction, false, "the user template-store token must NOT authorize the admin wipe route"); assert.equal(out.tplWrongSession, false, "token bound to another session must fail"); assert.equal(out.xferOk, true, "a minted transfer token must verify on the guarded route"); assert.equal(out.xferWrongAction, false, "transfer token must not verify as the template action"); assert.equal(out.missing, false, "missing token must fail"); }); test("account resource tokens reject a recreated row at the same email and remain single-use", async () => { const sandbox = buildTokenSandbox(); const result = await vm.runInContext(`(async () => { const req = { session: { user: "admin@example.test" }, sessionID: "one", get: () => null }; const action = "DELETE /api/settings/accounts/:email"; const resource = { targetEmail: "target@example.test", targetId: 42 }; const token = issueActionToken(req, action, resource, { ttlSeconds: 600, oneTime: true }); return { replacement: await verifyActionToken(req, token, action, { ...resource, targetId: 43 }), original: await verifyActionToken(req, token, action, resource), replay: await verifyActionToken(req, token, action, resource) }; })()`, sandbox); assert.equal(result.replacement, false); assert.equal(result.original, true); assert.equal(result.replay, false); }); // --------------------------------------------------------------------------- // F1 follow-up: node disk add/remove (infrastructure mutations, node-guard parity) // --------------------------------------------------------------------------- test("node disk add route: credential limiter and scoped step-up before the node call", () => { const route = extractRoute( indexSource, 'app.post("/api/nodes/:id/disks"', 'app.delete("/api/nodes/:id/disks/:diskId"' ); assert.match( route, /app\.post\("\/api\/nodes\/:id\/disks", sessionRevoke2faRateLimiter, async/, "disk add must mount the credential limiter" ); const validateIdx = route.indexOf("validateDiskMountPathPanel(req.body?.mountPath)"); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); const callIdx = route.indexOf("callNodeUpdateApi(node, \"/v1/disks\""); assert.ok(validateIdx > 0 && stepUpIdx > validateIdx, "step-up must come after the payload validation"); assert.ok(callIdx > stepUpIdx, "the node call must come after the step-up gate"); const stepUpCall = route.slice(stepUpIdx, callIdx); assert.match(stepUpCall, /scopeKey: nodeStepUpScopeKey\(node, nodeId\)/, "disk add must be scoped to the node"); }); test("node disk remove route: credential limiter and scoped step-up before the node call", () => { const route = extractRoute( indexSource, 'app.delete("/api/nodes/:id/disks/:diskId"', 'app.get("/api/settings/node-update/info"' ); assert.match( route, /app\.delete\("\/api\/nodes\/:id\/disks\/:diskId", sessionRevoke2faRateLimiter, async/, "disk remove must mount the credential limiter" ); const primaryIdx = route.indexOf('cannot remove primary disk'); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); const callIdx = route.indexOf("callNodeUpdateApi(node, \"/v1/disks\""); assert.ok(primaryIdx > 0 && stepUpIdx > primaryIdx, "step-up must come after the primary-disk refusal"); assert.ok(callIdx > stepUpIdx, "the node call must come after the step-up gate"); const stepUpCall = route.slice(stepUpIdx, callIdx); assert.match(stepUpCall, /scopeKey: nodeStepUpScopeKey\(node, nodeId\)/, "disk remove must be scoped to the node"); }); test("settings.js: disk UI rides the step-up helper and the dead legacy quick-creator is gone", () => { const diskAddIdx = settingsSource.indexOf("async function addNodeDisk()"); const diskRemoveIdx = settingsSource.indexOf("async function removeNodeDisk(diskId)"); assert.ok(diskAddIdx > 0 && diskRemoveIdx > diskAddIdx); const addBody = settingsSource.slice(diskAddIdx, diskRemoveIdx); const removeBody = settingsSource.slice(diskRemoveIdx, diskRemoveIdx + 1500); assert.match(addBody, /sendNodeWriteWithStepUp\(/, "disk add must ride the step-up modal"); assert.match(removeBody, /sendNodeWriteWithStepUp\(/, "disk remove must ride the step-up modal"); assert.doesNotMatch(settingsSource, /createServerBtn|createServerName/, "the dead legacy quick-creator references must be removed from settings.js"); assert.doesNotMatch(settingsSource, /fetch\('\/api\/settings\/servers',/, "settings.js must not POST to the non-existent /api/settings/servers route"); }); // --------------------------------------------------------------------------- // Frontend contract // --------------------------------------------------------------------------- test("settings.js sends the x-action-token header through the guarded wrapper and retries a stale token", () => { assert.match(settingsSource, /async function sendServerRowActionWithGuards\(/, "wrapper must exist"); assert.match(settingsSource, /headers: \{ 'x-action-token': token \}/, "the guarded call must carry the token header"); assert.match(settingsSource, /\/action token\/i\.test\(String\(data\?\.error \|\| ''\)\)/, "a 403 token rejection must be detected for the refresh+retry path"); const tplCall = settingsSource.indexOf("sendServerRowActionWithGuards(\n `/api/settings/servers/${encodeURIComponent(server)}/template`"); assert.ok(tplCall > 0, "the template-change submit must go through the guarded wrapper"); const xferCall = settingsSource.indexOf("sendServerRowActionWithGuards(\n `/api/settings/servers/${encodeURIComponent(serverName)}/transfer`"); assert.ok(xferCall > 0, "the transfer submit must go through the guarded wrapper"); assert.match(settingsSource, /function getServerTemplateChangeToken\(/); assert.match(settingsSource, /function getServerTransferToken\(/); assert.match(settingsSource, /_templateTokensByName/); assert.match(settingsSource, /_transferTokensByName/); assert.match(settingsSource, /templateChangeToken \|\| ''/, "the list render must read the minted template token"); assert.match(settingsSource, /transferToken \|\| ''/, "the list render must read the minted transfer token"); }); test("settings template change: losing a verified request ends step-up without offering another submit", async () => { let requests = 0; let confirm; let rejectResponse; const sandbox = { Response, window: {}, nodeSecretModalOverlay: { classList: { remove() {} }, setAttribute() {} }, nodeSecretCredential: { value: "test-credential" }, nodeSecretModalConfirm: { disabled: false }, nodeSecretRevealState: {}, STEP_UP_GRACE_CREDENTIAL: "no-credential", appendStepUpCredentialPayload() {}, isStepUpChallengeResponse: (data) => data.code === "password-required", setNodeSecretModalError: (message) => assert.equal(message, ""), validateStepUpCredential: (input) => input.value, fetch: async () => { requests += 1; if (requests === 1) return { status: 403, json: async () => ({ code: "password-required" }) }; return new Promise((_resolve, reject) => { rejectResponse = reject; }); }, openNodeSecretModal: (context, kind, _action, options) => { Object.assign(sandbox.nodeSecretRevealState, { context, kind, ...options }); confirm = sandbox.confirmNodeSecretReveal(); }, requestNodeSecret: (_context, _kind, credential) => sandbox.nodeSecretRevealState.customRequest(credential), }; vm.runInNewContext(extractRoute(settingsSource, "async function sendGuardedRequestWithStepUp(", "async function sendNodeWriteWithStepUp(") + extractBlock(settingsSource, "function closeNodeSecretModal()") + extractBlock(settingsSource, "async function confirmNodeSecretReveal()"), sandbox); const message = "Check the server state before retrying."; const result = sandbox.sendGuardedRequestWithStepUp("/test-template-change", "POST", {}, { unconfirmedMessage: message }); await new Promise(setImmediate); assert.equal(requests, 2); assert.equal(sandbox.nodeSecretModalConfirm.disabled, true); sandbox.closeNodeSecretModal(); assert.equal(sandbox.nodeSecretRevealState.kind, "custom"); await sandbox.confirmNodeSecretReveal(); assert.equal(requests, 2); rejectResponse(new Error("Disconnected")); const { res, data } = await result; await confirm; assert.equal(res.ok, false); assert.equal(data.code, "reinstall-result-unconfirmed"); assert.equal(data.error, message); assert.equal(sandbox.nodeSecretRevealState.kind, null); }); for (const reapply of [false, true]) { test(`settings template ${reapply ? "reapply" : "change"}: a completed rebuild awaiting EULA cannot be resubmitted`, async () => { let submit; let requests = 0; let closes = 0; let confirmations = 0; const sandbox = { serverTemplateDone: { addEventListener: (_event, handler) => { submit = handler; } }, serverTemplateFeedback: { style: {} }, serverTemplateModal: { dataset: { server: "alpha" } }, serverTemplateCancel: null, serverTemplateClose: null, templatePickerState: { selected: "minecraft", originalTemplate: reapply ? "minecraft" : "nodejs" }, renderServerTemplateAction() {}, normalizeTemplateIdClient: (value) => value, closeServerTemplateModal: () => { closes += 1; }, findServerRowByName: () => null, confirm: (message) => { assert.match(message, /REINSTALL/); confirmations += 1; return true; }, sendServerRowActionWithGuards: async (url, method, body, options) => { assert.equal(confirmations, 1); assert.equal(url, "/api/settings/servers/alpha/template"); assert.equal(method, "POST"); assert.equal(body.templateId, "minecraft"); assert.equal(body.reapply, reapply ? true : undefined); assert.equal(typeof options.refreshToken, "function"); requests += 1; return { res: { ok: true }, data: { ok: true, eulaRequired: true } }; }, setTimeout: () => assert.fail("the EULA notice should remain visible"), }; vm.runInNewContext(extractBlock(settingsSource, "if (serverTemplateDone) {"), sandbox); await submit(); assert.match(sandbox.serverTemplateFeedback.textContent, /Accept the Minecraft EULA/); assert.equal(closes, 0); await submit(); assert.equal(requests, 1); assert.equal(closes, 1); }); } test("create wizard rides the shared step-up modal with a safe fallback", () => { assert.match(wizardSource, /window\.sendGuardedRequestWithStepUp/, "wizard must prefer the shared guarded helper"); assert.match(wizardSource, /password-required/, "fallback must recognise the step-up challenge instead of surfacing a generic error"); }); test("the create submit rides the shared step-up modal with a challenge-aware fallback", () => { // The server-create UI moved from dashboard.js (old resources confirm // handler + local createServerWithStepUp) to create-server-wizard.js, // which owns the create flow end-to-end. The submit must prefer the shared // guarded helper against /api/servers/create — the shared modal collects // password/2FA and retries in place — and its no-helper fallback must // recognise the step-up challenge codes instead of surfacing a generic // error. assert.match(wizardSource, /window\.sendGuardedRequestWithStepUp\('\/api\/servers\/create', 'POST', payload/, "the create submit must ride the shared guarded helper"); assert.match(wizardSource, /\['password-required', '2fa-required'\]\.includes\(String\(j\?\.code \|\| ''\)\)/, "the fallback must recognise the step-up challenge codes"); assert.doesNotMatch(dashboardSource, /resourcesConfirm\?\.addEventListener\('click', async \(\) => \{/, "dashboard.js must not retain the relocated create confirm handler"); }); test("the shared step-up helper maps the retry credential to the right field", () => { // Successor pin of the relocated dashboard.js create step-up test: every // client of the shared step-up modal — the create wizard included — retries // through appendStepUpCredentialPayload, so the credential→field mapping // must stay exact or a retry sends the secret to the wrong payload field. const block = extractBlock(settingsSource, "function appendStepUpCredentialPayload(body, credential) {"); assert.match( block, /credential === STEP_UP_GRACE_CREDENTIAL\) return body;/, "the grace placeholder must never be sent as a credential" ); assert.match(block, /getCurrentStepUpMode\(\) === 'password'/, "the password branch must be gated on the current step-up mode"); assert.match(block, /body\.currentPassword = credential;/, "password retry must ride currentPassword"); assert.match(block, /body\.twoFactorCode = credential;/, "TOTP retry must ride twoFactorCode"); }); // --------------------------------------------------------------------------- // P2.1: webhook test route (admin gate is NOT the protection model) // --------------------------------------------------------------------------- test("webhook test route: credential + dedicated limiters, token gate, no-op check, then step-up before dispatch", () => { const route = extractRoute( indexSource, 'app.post("/api/settings/webhooks/test"', 'app.get("/api/settings/alert"' ); assert.match( route, /app\.post\("\/api\/settings\/webhooks\/test", sessionRevoke2faRateLimiter, webhookTestRateLimiter, async/, "route must mount the credential limiter and the dedicated webhook-test limiter" ); assert.match( route, /requireActionTokenOr403\(req, res, "POST \/api\/settings\/webhooks\/test"\)/, "route must verify the testWebhook action token" ); const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/webhooks/test"'); const noOpIdx = route.indexOf('"No valid webhook URL configured"'); const stepUpIdx = route.indexOf('requireDestructiveActionStepUp(req, res, currentUser, "Webhook test")'); const dispatchIdx = route.indexOf("dispatchDiscordWebhook(webhookUrl"); assert.ok(noOpIdx > tokenIdx, "the no-op 400 must come after the token gate"); assert.ok(stepUpIdx > noOpIdx, "step-up must come after the no-op check so an empty config cannot burn a grace use"); assert.ok(dispatchIdx > stepUpIdx, "the outbound dispatch must come after the step-up gate"); assert.match( route, /actionTokens: buildWebhookSettingsActionTokens\(req\)/, "a successful test must hand back fresh webhook settings tokens (repeatable save/test, one-time per-target delete)" ); const limiterAt = indexSource.indexOf("const webhookTestRateLimiter = rateLimit("); const routeAt = indexSource.indexOf('app.post("/api/settings/webhooks/test"'); assert.ok(limiterAt >= 0 && routeAt > limiterAt, "webhook-test limiter must be defined before the route uses it"); }); test("webhook delete route: write budget limiter and one-time per-target token verification", () => { const route = extractRoute( indexSource, 'app.delete("/api/settings/webhooks"', 'app.post("/api/settings/webhooks/test"' ); assert.match( route, /app\.delete\("\/api\/settings\/webhooks", sessionRevoke2faRateLimiter, webhookConfigWriteRateLimiter, async/, "route must mount the credential limiter and the dedicated write-budget limiter" ); assert.match( route, /requireActionTokenOr403\(req, res, "DELETE \/api\/settings\/webhooks", \{ target: deleteTarget \}\)/, "route must verify the one-time token pinned to the exact delete target" ); // Ordering: input validation and the no-op 404 probe run BEFORE the token // verification (a garbage target or an absent webhook must never burn a // one-time token), authorization runs before the not-found probe, and the // step-up comes after the token gate. const invalidIdx = route.indexOf('"Invalid category"'); const adminIdx = route.indexOf("currentUser.admin"); const notFoundIdx = route.indexOf('"No single webhook is configured"'); const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "DELETE /api/settings/webhooks"'); const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser"); assert.ok(invalidIdx > 0 && invalidIdx < tokenIdx, "input validation must run before the token check"); assert.ok(adminIdx > 0 && adminIdx < notFoundIdx, "authorization must run before the not-found probe (no config-state leak)"); assert.ok(notFoundIdx > 0 && notFoundIdx < tokenIdx, "the no-op 404 must run before the token check so it cannot burn a one-time token"); assert.ok(stepUpIdx > tokenIdx, "step-up must come after the token gate"); }); test("webhook tokens: shared mint helper issues per-target one-time delete tokens; refresh endpoint excludes them", () => { const helperAt = indexSource.indexOf("function buildWebhookSettingsActionTokens(req)"); assert.ok(helperAt >= 0, "the shared webhook token mint helper must exist"); const minted = indexSource.match(/actionTokens: buildWebhookSettingsActionTokens\(req\)/g) || []; assert.ok( minted.length >= 4, "GET /api/settings/webhooks and the POST/DELETE/test success responses must all embed the shared mint" ); const helperEnd = indexSource.indexOf('app.get("/api/settings/webhooks"'); const helperSource = indexSource.slice(helperAt, helperEnd); assert.match( helperSource, /saveWebhook: issueActionToken\(req, "POST \/api\/settings\/webhooks", \{\}, \{ ttlSeconds: 300 \}\)/, "the helper must mint saveWebhook with the exact action string the POST verifies" ); assert.match( helperSource, /testWebhook: issueActionToken\(req, "POST \/api\/settings\/webhooks\/test", \{\}, \{ ttlSeconds: 300 \}\)/, "the helper must mint testWebhook with the exact action string the test route verifies" ); assert.match( helperSource, /deleteWebhook_single: issueActionToken\(req, "DELETE \/api\/settings\/webhooks", \{ target: "single" \}, \{ ttlSeconds: 300, oneTime: true \}\)/, "the helper must mint a one-time delete token pinned to the single-webhook target" ); assert.match( helperSource, /actionTokens\[`deleteWebhook_\$\{cat\.id\}`\] = issueActionToken\(req, "DELETE \/api\/settings\/webhooks", \{ target: cat\.id \}, \{ ttlSeconds: 300, oneTime: true \}\)/, "the helper must mint a one-time delete token per category, pinned to that category" ); const refreshStart = indexSource.indexOf('app.get("/api/settings/action-tokens"'); assert.ok(refreshStart >= 0, "token refresh endpoint must exist"); const refreshEnd = indexSource.indexOf("app.post(\"/api/settings/maintenance\"", refreshStart); const refresh = indexSource.slice(refreshStart, refreshEnd); assert.ok( !refresh.includes("deleteWebhook"), "the refresh endpoint must not mint the one-time per-target delete tokens (they refresh via the section GET)" ); assert.match( refresh, /saveWebhook: issueActionToken\(req, "POST \/api\/settings\/webhooks", \{\}, \{ ttlSeconds: 300 \}\)/, "the refresh endpoint must still refresh the repeatable saveWebhook token" ); }); test("webhookConfigWrite/ReadRateLimiters: bounded budgets keyed per user+session (no IP)", () => { const writeSession = runLimiter("const webhookConfigWriteSessionRateLimiter = rateLimit("); assert.equal(writeSession.windowMs, 5 * 60 * 1000); assert.equal(writeSession.max, 40); assert.equal(writeSession.skip({ session: null }), true); assert.equal(writeSession.skip({ session: { user: "user@example.com" } }), false); const writeReq = { session: { user: "User@Example.com" }, sessionID: "sid-w" }; assert.equal(writeSession.keyGenerator(writeReq), "webhook-config-write:user@example.com:sid-w"); let statusCode = 0; let payload = null; writeSession.handler(writeReq, { status(c) { statusCode = c; return { json(p) { payload = p; } }; } }); assert.equal(statusCode, 429); assert.equal(payload.code, "webhook-config-write-rate-limit"); const writeAccount = runLimiter("const webhookConfigWriteAccountRateLimiter = rateLimit("); assert.equal(writeAccount.windowMs, 5 * 60 * 1000); assert.equal(writeAccount.max, 120); const accountReq = { session: { user: "User@Example.com" }, sessionID: "sid-w2" }; assert.equal(writeAccount.keyGenerator(accountReq), "webhook-config-write-account:user@example.com"); const read = runLimiter("const webhookConfigReadRateLimiter = rateLimit("); assert.equal(read.windowMs, 5 * 60 * 1000); assert.equal(read.max, 60); const readReq = { session: { user: "User@Example.com" }, sessionID: "sid-r" }; assert.equal(read.keyGenerator(readReq), "webhook-config-read:user@example.com:sid-r"); }); test("webhookTestRateLimiter: 15 per 5 minutes keyed per user+session (no IP)", () => { const limiter = runLimiter("const webhookTestRateLimiter = rateLimit("); assert.equal(limiter.windowMs, 5 * 60 * 1000); assert.equal(limiter.max, 15); assert.equal(limiter.skip({ session: null }), true); assert.equal(limiter.skip({ session: { user: "user@example.com" } }), false); const req = { session: { user: "User@Example.com" }, sessionID: "sid-4" }; assert.equal(limiter.keyGenerator(req), "webhook-test:user@example.com:sid-4"); let statusCode = 0; let payload = null; const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } }; limiter.handler(req, res); assert.equal(statusCode, 429); assert.equal(payload.code, "webhook-test-rate-limit"); }); test("webhook token mint/verify pairs: actions are mutually exclusive and delete tokens are one-time per target", async () => { const sandbox = buildTokenSandbox(); const out = await vm.runInContext(` (async () => { const reqOk = { session: { user: "admin@example.com" }, sessionID: "sess-1", get: () => null, body: {} }; const testToken = issueActionToken(reqOk, "POST /api/settings/webhooks/test", {}, { ttlSeconds: 300 }); const deleteToken = issueActionToken(reqOk, "DELETE /api/settings/webhooks", { target: "single" }, { ttlSeconds: 300, oneTime: true }); const categoryToken = issueActionToken(reqOk, "DELETE /api/settings/webhooks", { target: "server_create" }, { ttlSeconds: 300, oneTime: true }); const saveToken = issueActionToken(reqOk, "POST /api/settings/webhooks", {}, { ttlSeconds: 300 }); return ({ ok: await verifyActionToken(reqOk, testToken, "POST /api/settings/webhooks/test", {}), asSave: await verifyActionToken(reqOk, testToken, "POST /api/settings/webhooks", {}), asDelete: await verifyActionToken(reqOk, testToken, "DELETE /api/settings/webhooks", { target: "single" }), saveTokenAsTest: await verifyActionToken(reqOk, saveToken, "POST /api/settings/webhooks/test", {}), deleteOk: await verifyActionToken(reqOk, deleteToken, "DELETE /api/settings/webhooks", { target: "single" }), deleteReplay: await verifyActionToken(reqOk, deleteToken, "DELETE /api/settings/webhooks", { target: "single" }), categoryTokenOnOtherTarget: await verifyActionToken(reqOk, categoryToken, "DELETE /api/settings/webhooks", { target: "server_delete" }), categoryTokenOnSingle: await verifyActionToken(reqOk, categoryToken, "DELETE /api/settings/webhooks", { target: "single" }), categoryOk: await verifyActionToken(reqOk, issueActionToken(reqOk, "DELETE /api/settings/webhooks", { target: "server_delete" }, { ttlSeconds: 300, oneTime: true }), "DELETE /api/settings/webhooks", { target: "server_delete" }), saveRepeatable: await verifyActionToken(reqOk, saveToken, "POST /api/settings/webhooks", {}), saveRepeatableAgain: await verifyActionToken(reqOk, saveToken, "POST /api/settings/webhooks", {}), }); })() `, sandbox); assert.equal(out.ok, true, "a minted testWebhook token must verify on the test route"); assert.equal(out.asSave, false, "testWebhook token must NOT authorize the save route"); assert.equal(out.asDelete, false, "testWebhook token must NOT authorize the delete route"); assert.equal(out.saveTokenAsTest, false, "saveWebhook token must NOT authorize the test route"); assert.equal(out.deleteOk, true, "a delete token must verify for its pinned target"); assert.equal(out.deleteReplay, false, "a one-time delete token must not verify twice (replay protection)"); assert.equal(out.categoryTokenOnOtherTarget, false, "a delete token pinned to one category must NOT delete another category"); assert.equal(out.categoryTokenOnSingle, false, "a category delete token must NOT delete the single webhook"); assert.equal(out.categoryOk, true, "a category delete token must verify for its own target"); assert.equal(out.saveRepeatable, true, "saveWebhook stays a repeatable multi-use token"); assert.equal(out.saveRepeatableAgain, true, "saveWebhook must remain usable twice (repeatable setter)"); }); test("settings.js: webhook test rides the guarded step-up flow and action tokens never touch the DOM", () => { assert.match(settingsSource, /async function sendWebhookTestWithGuards\(/, "guarded webhook test wrapper must exist"); assert.match( settingsSource, /sendGuardedRequestWithStepUp\('\/api\/settings\/webhooks\/test', 'POST'/, "the test call must ride the shared step-up helper" ); assert.match( settingsSource, /'x-action-token': webhookActionTokens\.testWebhook \|\| ''/, "the test call must carry the minted testWebhook token" ); // P2.2: delete/suspend tokens live in the JS Maps only — no DOM attributes. assert.doesNotMatch(settingsSource, /data-delete-token=/, "delete tokens must not be rendered into DOM attributes"); assert.doesNotMatch(settingsSource, /data-suspension-token=/, "suspension tokens must not be rendered into DOM attributes"); assert.doesNotMatch(settingsSource, /dataset\.deleteToken|dataset\.suspensionToken/, "token getters must not read DOM attributes"); assert.match(settingsSource, /_deleteTokensByName/); assert.match(settingsSource, /_suspensionTokensByName/); assert.match(settingsSource, /_deleteTokensByEmail/); assert.match(settingsSource, /_suspensionTokensByEmail/); }); // --------------------------------------------------------------------------- // W2: the modern fs mutator twins carry the legacy routes' abuse brake // --------------------------------------------------------------------------- test("modern fs mutator routes mount serverFsMutateRateLimiter in their middleware list", () => { assert.ok( indexSource.includes("const serverFsMutateRateLimiter = rateLimit("), "serverFsMutateRateLimiter must stay defined" ); // Each modern route must carry the limiter as route middleware (running // before the handler), exactly like the legacy twins — same responsibility // (fs mutation), one abuse-brake posture. A missing limiter on either twin // lets a scripted loop shop between the modern and legacy spellings of the // same write. const modernRoutes = [ ["PUT files/write", 'app.put("/api/servers/:name/files/write", serverFsMutateRateLimiter, async'], ["POST files/mkdir", 'app.post("/api/servers/:name/files/mkdir", serverFsMutateRateLimiter, async'], ["DELETE files/delete", 'app.delete("/api/servers/:name/files/delete", serverFsMutateRateLimiter, async'], ["POST files/rename", 'app.post("/api/servers/:name/files/rename", serverFsMutateRateLimiter, async'], ]; for (const [label, registration] of modernRoutes) { assert.ok( indexSource.includes(registration), `${label} must mount serverFsMutateRateLimiter as route middleware` ); } // The legacy twins keep theirs too — the brake is extended, never moved. const legacyRoutes = [ ["POST /extract", 'app.post("/extract", serverFsMutateRateLimiter, async'], ["POST /archive", 'app.post("/archive", serverFsMutateRateLimiter, async'], ["POST /create", 'app.post("/create", serverFsMutateRateLimiter, async'], ["POST /rename", 'app.post("/rename", serverFsMutateRateLimiter, async'], ]; for (const [label, registration] of legacyRoutes) { assert.ok( indexSource.includes(registration), `${label} must keep its serverFsMutateRateLimiter middleware` ); } }); // --------------------------------------------------------------------------- // Always-on read brakes: planner GET + the four file GET routes // --------------------------------------------------------------------------- test("planner GET and the four file GET routes mount their always-on read limiters", () => { // Both read limiters must stay defined — their mutate siblings are not a // substitute: the mutate limiter counts only mutating verbs, and the read // routes pin node connections for their full dial timeout (see the // fs-read-brake comment in index.js). assert.ok( indexSource.includes("const plannerReadRateLimiter = rateLimit({"), "plannerReadRateLimiter must stay defined — the planner GET re-reads the server's full items table per dial and needs its own always-on brake" ); assert.ok( indexSource.includes("const serverFsReadRateLimiter = rateLimit({"), "serverFsReadRateLimiter must stay defined — the four file GET routes hold a node connection for their full dial timeout and need their own always-on brake" ); // Same always-on posture as plannerMutateRateLimiter: the store is built // eagerly (never gated on security.rate_limiting), fails open on store // errors, and keys authenticated traffic per ACCOUNT email. It does NOT // skip sessionless requests: the shipped security.json sets rate_limiting // false, so the old "the global limiter owns anon traffic" premise was // false and an anonymous flood hit no brake at all — sessionless requests // share this same limiter under a per-IP bucket instead. for (const [label, prefix, family] of [["plannerReadRateLimiter", '"rlpr:"', "planner-read"], ["serverFsReadRateLimiter", '"rlfsr:"', "fs-read"]]) { const declAt = indexSource.indexOf(`const ${label} = rateLimit({`); const decl = indexSource.slice(declAt, declAt + 2200); assert.ok( decl.includes(`buildSharedRateLimitRedisStore(${prefix}, 10 * 60 * 1000)`), `${label} must use its own dedicated shared Redis store with the ${prefix} prefix (one store instance + distinct prefix per limiter — never a shared store instance or a shared key space)` ); assert.ok( decl.includes("passOnStoreError: true"), `${label} must fail open on store errors — it is an abuse brake, not an auth control` ); assert.ok( decl.includes('String(req.session?.user || "").trim().toLowerCase()'), `${label} must key authenticated traffic per ACCOUNT (session email alone) — an IP half would let one account multiply its budget across rotating source addresses` ); assert.ok( !decl.includes("skip: (req)"), `${label} must NOT skip sessionless requests — with security.rate_limiting false on the shipped default the global limiter owns nothing, so a skip left an anonymous flood unbraked` ); assert.ok( decl.includes(`return email ? \`${family}:\${email}\` : \`${family}:ip:\${ipKeyGenerator(String(req.ip || "unknown"))}\`;`), `${label} must fall back to a per-IP bucket (${family}:ip:...) for sessionless traffic — ipKeyGenerator keeps IPv4 exact and collapses IPv6 into /56 subnets so address rotation cannot mint fresh buckets (and express-rate-limit v8 refuses a keyGenerator that reads req.ip without it)` ); } // The prefixes must be distinct from each other AND from the mutate // limiters' ("rlp:" planner-mutate, "fs-mutate:") so the budgets never // share keys. const prefixes = [...indexSource.matchAll(/buildSharedRateLimitRedisStore\("(rlp:|rlpr:|rlfsr:|fs-mutate:|fs-upload:)"/g)].map(m => m[1]); assert.strictEqual(new Set(prefixes).size, prefixes.length, "rate-limit store prefixes must stay distinct — two limiters sharing a prefix share one budget"); // The planner GET mounts its read limiter as route middleware, next to // rejectCrossSiteRead and before any handler code (the same convention as // the activity/permissions GET routes). assert.ok( indexSource.includes('app.get("/api/servers/:name/planner", rejectCrossSiteRead, plannerReadRateLimiter, async'), "the planner GET route must mount plannerReadRateLimiter as route middleware" ); // All four file GET routes mount the shared read limiter — a route left // unbraked is the unbounded-amplification hole this brake exists to close. const readRoutes = [ ["GET files/list", 'app.get("/api/servers/:name/files/list", rejectCrossSiteRead, serverFsReadRateLimiter, async'], ["GET files/read", 'app.get("/api/servers/:name/files/read", rejectCrossSiteRead, serverFsReadRateLimiter, async'], ["GET files/stream", 'app.get("/api/servers/:name/files/stream", rejectCrossSiteRead, serverFsReadRateLimiter, async'], ["GET files/download", 'app.get("/api/servers/:name/files/download", rejectCrossSiteRead, serverFsReadRateLimiter, async'], ]; for (const [label, registration] of readRoutes) { assert.ok( indexSource.includes(registration), `${label} must mount serverFsReadRateLimiter as route middleware` ); } });