"use strict"; // Tests for the backups relays' session-bound action-token gates. // // The audit finding: the three mutating // backup relays — POST /api/nodes/server/:name/backups, // POST /api/nodes/server/:name/backups/:backupId/restore and // DELETE /api/nodes/server/:name/backups/:backupId — were the last mutating // node relays reachable by cookie-authenticated requests without a session- // bound action token (their old comment leaned on the panel-wide CSRF // middleware alone). Backup RESTORE overwrites every server file from the // archive, so the CSRF_ALLOWED_HOSTS-trusted-origin vector — the one path // sameOriginProtection deliberately permits — applied to it at full force. // // The fix mints the pairs fresh: no panel mirror routes exist (the node // daemon owns backup storage), so GET /permissions mints them, gated on // exactly the perms the performers enforce: // backupCreate "POST /backups" under backups_create (300s, repeatable) // backupRestore "POST /backups/:id/restore" under backups_create (120s, ONE-TIME) // backupDelete "DELETE /backups/:id" under backups_delete (120s, ONE-TIME) // Restore and delete are destructive single-shot operations — the same class // as reinstallServer/fileDelete — so their tokens carry one-time nonces and // the shipped client mints fresh per call. // // This file locks in: // 1. Source parity: each relay's verify action equals its mint action, the // guards mirror the performers' perm checks, the mints sit inside the // executed mint-block region, and the performers keep their own perm // checks (the token gate is session/CSRF binding, NOT the authz boundary). // 2. Executed mint gate per permission combination. // 3. Real-machinery roundtrip INCLUDING the one-time nonce burn: a // backupRestore token verifies exactly once. // 4. Live relay behavior (real nodes.js app against a fake node, same // technique as server-suspension-rest-bridge): fail-closed with no token // hook (403 before 423), pass-through to the 423 suspension gate with a // valid token, 403-before-423 with a rejecting verifier, and live // controls proving each relay still reaches its performer. // 5. Frontend contract: bot.js attaches the right token key to each backup // call and treats restore/delete as one-time (fresh mint per call). 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 http = require("node:http"); const Module = require("node:module"); const express = require("express"); const session = require("express-session"); const ROOT = path.join(__dirname, ".."); const NODES_JS = path.join(ROOT, "nodes.js"); const INDEX_JS = path.join(ROOT, "index.js"); const BOT_JS = path.join(ROOT, "public", "js", "bot.js"); const nodesSource = fs.readFileSync(NODES_JS, "utf8"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const botSource = fs.readFileSync(BOT_JS, "utf8"); // relay route -> [verify action literal, mint key, mint guard perm] const PAIRS = [ ['app.post("/api/nodes/server/:name/backups",', "POST /backups", "backupCreate", "backups_create"], ['app.post("/api/nodes/server/:name/backups/:backupId/restore",', "POST /backups/:id/restore", "backupRestore", "backups_create"], ['app.delete("/api/nodes/server/:name/backups/:backupId",', "DELETE /backups/:id", "backupDelete", "backups_delete"], ]; // --------------------------------------------------------------------------- // 1. Source parity — verify/mint literals, guards, placement, performer perms. // --------------------------------------------------------------------------- for (const [routeMarker, action, mintKey, perm] of PAIRS) { test(`${mintKey}: relay verifies the exact action the mint issues (${action})`, () => { const routeAt = nodesSource.indexOf(routeMarker); assert.ok(routeAt !== -1, `backups relay route not found: ${routeMarker}`); const routeLine = nodesSource.slice(routeAt, nodesSource.indexOf("\n", routeAt)); const gateAction = /requireNodeFileActionToken\("([^"]+)"\)/.exec(routeLine); assert.ok(gateAction, `relay must carry requireNodeFileActionToken: ${routeMarker}`); assert.equal(gateAction[1], action, "relay verify action drifted"); const mintAt = indexSource.indexOf(`${mintKey} = issueActionToken(req, "`); assert.ok(mintAt !== -1, `${mintKey} mint not found in index.js`); const mintAction = /issueActionToken\(req, "([^"]+)"/.exec(indexSource.slice(mintAt, mintAt + 120)); assert.ok(mintAction, "mint action literal not extractable"); assert.equal( mintAction[1], gateAction[1], "mint and verify actions drifted — a minted token would never verify on the relay" ); // The guard wrapping the mint must be the perm the mint mirrors. const guardAt = indexSource.lastIndexOf(`if (perms.${perm}) {`, mintAt); assert.ok(guardAt !== -1, `${perm} guard not found before the ${mintKey} mint`); const between = indexSource.slice(guardAt, mintAt); assert.doesNotMatch(between, /\n \}\n/, `the ${perm} guard must directly wrap the ${mintKey} mint`); // The mint must stay inside the executed mint-block region (before the // store_access section the mint-gates slicing stops at). const storeAt = indexSource.indexOf("if (perms.store_access) {", guardAt); assert.ok(storeAt !== -1, "store_access mint section not found"); assert.ok(mintAt < storeAt, `${mintKey} mint must stay before the store_access section`); }); } test("all three backup relays mount nodeUploadRateLimiterGate FIRST (adpanel:backup-relay-brake, sibling extract/archive/upload pattern)", () => { // The brake: the three mutating backups relays are the same cost-profile // long daemon ops as extract/archive/upload and were the only same-shape // relays without the limiter gate. Pin the exact sibling mounting — the // gate is the FIRST middleware on the route line, before the action-token // gate — and pin the full mounted-relay inventory so neither a sibling // losing its gate nor a future relay silently skipping it can land. const SIBLING_MOUNTS = [ 'app.post("/api/nodes/server/:name/extract", nodeUploadRateLimiterGate,', 'app.post("/api/nodes/server/:name/archive", nodeUploadRateLimiterGate,', 'app.post("/api/nodes/server/:name/upload", nodeUploadRateLimiterGate,', 'app.post("/api/nodes/server/:name/upload-url", nodeUploadRateLimiterGate,', ]; for (const marker of SIBLING_MOUNTS) { assert.ok(nodesSource.includes(marker), `sibling relay lost its limiter gate: ${marker}`); } for (const [routeMarker] of PAIRS) { const routeAt = nodesSource.indexOf(routeMarker); assert.ok(routeAt !== -1, `backups relay route not found: ${routeMarker}`); const routeLine = nodesSource.slice(routeAt, nodesSource.indexOf("\n", routeAt)); assert.match( routeLine, /^app\.(?:post|delete)\("[^"]+", nodeUploadRateLimiterGate, requireNodeFileActionToken\(/, `the limiter gate must be the FIRST middleware on: ${routeMarker}` ); } // 4 pre-existing sibling mounts + the 3 backups relays = 7 gated route lines. const mounted = nodesSource .split("\n") .filter((line) => /^app\.(?:get|post|put|delete)\(.*nodeUploadRateLimiterGate/.test(line)).length; assert.strictEqual( mounted, 7, "gate-mounted node relays drifted: extract, archive, upload, upload-url + the three backups relays" ); }); test("performers keep their own perm checks (the token gate is not the authz boundary)", () => { const create = /async function performPanelCreateBackup[\s\S]*?checkUserPerm\(req, targetServer, "backups_create"\)/.test(nodesSource); const restore = /async function performPanelRestoreBackup[\s\S]*?checkUserPerm\(req, targetServer, "backups_create"\)/.test(nodesSource); const del = /async function performPanelDeleteBackup[\s\S]*?checkUserPerm\(req, targetServer, "backups_delete"\)/.test(nodesSource); assert.ok(create, "create performer must keep its backups_create check"); assert.ok(restore, "restore performer must keep its backups_create check"); assert.ok(del, "delete performer must keep its backups_delete check"); }); // --------------------------------------------------------------------------- // 2. Executed mint gate (same technique as file-action-token-mint-gates). // --------------------------------------------------------------------------- const MINT_START_MARKER = "const actionTokens = {};\n // Mint eligibility mirrors"; const MINT_END_MARKER = "if (perms.store_access) {"; const mintBlock = (() => { const start = indexSource.indexOf(MINT_START_MARKER); assert.ok(start >= 0, "mint block start marker not found (did the mint block move?)"); const end = indexSource.indexOf(MINT_END_MARKER, start); assert.ok(end > start, "mint block end marker not found"); return indexSource.slice(start, end); })(); function runMint(perms) { const sandbox = {}; vm.createContext(sandbox); const mint = vm.runInContext( `(function (perms, issueActionToken, req, serverName) {\n${mintBlock}\n return actionTokens;\n})`, sandbox ); const minted = []; const tokens = mint( perms, (req, action, resource, opts) => { minted.push({ action, resource, opts }); return `tok:${action}`; }, {}, "srv-1" ); return { tokens, minted }; } test("backups_create-only user mints backupCreate and the one-time backupRestore", () => { const { tokens, minted } = runMint({ backups_create: true }); assert.deepEqual(Object.keys(tokens), ["backupCreate", "backupRestore"]); assert.equal(tokens.backupCreate, "tok:POST /backups"); assert.equal(tokens.backupRestore, "tok:POST /backups/:id/restore"); const create = minted.find((m) => m.action === "POST /backups"); const restore = minted.find((m) => m.action === "POST /backups/:id/restore"); assert.equal(create.opts.oneTime, undefined, "create is repeatable — not one-time"); assert.equal(restore.opts.oneTime, true, "restore is destructive single-shot — one-time"); for (const entry of minted) { assert.deepEqual(entry.resource, { serverName: "srv-1" }, `${entry.action} must stay server-scoped`); } }); test("backups_delete-only user mints only the one-time backupDelete", () => { const { tokens, minted } = runMint({ backups_delete: true }); assert.deepEqual(Object.keys(tokens), ["backupDelete"]); assert.equal(tokens.backupDelete, "tok:DELETE /backups/:id"); assert.equal(minted[0].opts.oneTime, true, "delete is unrecoverable single-shot — one-time"); }); test("user with no backup perms mints no backup tokens (fail closed)", () => { const { tokens } = runMint({}); assert.deepEqual(tokens, {}); const noBackupPerms = runMint({ files_write: true, console_write: true }); assert.equal(noBackupPerms.tokens.backupCreate, undefined); assert.equal(noBackupPerms.tokens.backupRestore, undefined); assert.equal(noBackupPerms.tokens.backupDelete, undefined); }); // --------------------------------------------------------------------------- // 3. Real-machinery roundtrip, including the one-time nonce burn (index.js // token helpers in a vm sandbox, same technique as file-action-token-mint-gates). // --------------------------------------------------------------------------- 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" } }, SESSION_REVOKE_TARGET_TOKEN_TTL_MS: 10 * 60 * 1000, redisClient: undefined, getSessionDisplayId: (id) => String(id || ""), }; vm.createContext(sandbox); vm.runInContext(indexSource.slice(claimStart, claimEnd), sandbox); vm.runInContext(indexSource.slice(start, end), sandbox); return sandbox; } test("backupRestore token verifies EXACTLY once (one-time nonce burn); backupCreate verifies repeatedly", async () => { const sandbox = buildTokenSandbox(); const out = await vm.runInContext(` (async () => { const RES = { serverName: "srv-1" }; const req = { session: { user: "admin@example.com" }, sessionID: "sess-1", get: () => null, body: {} }; const restoreToken = issueActionToken(req, "POST /backups/:id/restore", RES, { ttlSeconds: 120, oneTime: true }); const createToken = issueActionToken(req, "POST /backups", RES, { ttlSeconds: 300 }); return ({ restoreFirst: await verifyActionToken(req, restoreToken, "POST /backups/:id/restore", RES), restoreSecond: await verifyActionToken(req, restoreToken, "POST /backups/:id/restore", RES), createFirst: await verifyActionToken(req, createToken, "POST /backups", RES), createSecond: await verifyActionToken(req, createToken, "POST /backups", RES), restoreWrongServer: await verifyActionToken(req, issueActionToken(req, "POST /backups/:id/restore", RES, { ttlSeconds: 120, oneTime: true }), "POST /backups/:id/restore", { serverName: "other" }), }); })() `, sandbox); assert.equal(out.restoreFirst, true, "a fresh restore token must verify once"); assert.equal( out.restoreSecond, false, "the second verify must fail — the durable one-time claim burns the nonce, so a replayed restore is refused" ); assert.equal(out.createFirst, true); assert.equal(out.createSecond, true, "create is repeatable — no nonce burn"); assert.equal(out.restoreWrongServer, false, "restore token must stay bound to its server"); }); // --------------------------------------------------------------------------- // 4. Live relay behavior — the real nodes.js app against a fake node (same // technique as server-suspension-rest-bridge: db stub injected through // Module._load, because nodes.js cannot be exercised through index.js). // --------------------------------------------------------------------------- process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; // fake node runs on loopback const fakeNode = http.createServer((req, res) => { req.resume(); res.statusCode = 404; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ ok: false, error: "not_found" })); }); let fakeNodePort = 0; const TEST_EMAIL = "user@example.com"; let NODE_ROW = null; function nodeRow() { return { id: 1, uuid: "node-uuid-1", name: "node-one", address: "127.0.0.1", ram_mb: 8192, disk_gb: 100, ports: JSON.stringify({ mode: "range", start: 25565, count: 10 }), token_id: "tok-1", token: "test-node-token", token_status: "active", created_at: Date.now(), api_port: fakeNodePort, sftp_port: 2022, max_upload_mb: 10240, port_ok: 1, last_seen: Date.now(), last_check: Date.now(), online: 1, build_config: null, }; } function makeServerRow(overrides = {}) { return Object.assign( { id: 42, name: "Alpha", legacy_id: "alpha-legacy", bot: "alpha-bot", template: "minecraft", start: "java -jar server.jar", node_id: "node-uuid-1", ip: null, port: 25565, status: "running", suspended: 0, suspended_at: null, suspended_by: null, runtime: null, docker: null, acl: JSON.stringify({ users: [] }), resources: null, }, overrides ); } const serversByName = new Map(); function registerServer(row) { for (const key of [row.name, row.legacy_id, row.bot]) { if (key) serversByName.set(String(key).toLowerCase(), row); } } registerServer(makeServerRow()); // live control server registerServer(makeServerRow({ id: 43, name: "Suspended", legacy_id: "suspended-legacy", bot: "suspended-bot", suspended: 1, suspended_at: 1760000000000, suspended_by: "admin@example.com" })); const dbStub = { async query(sql, params = []) { const normalized = String(sql).replace(/\s+/g, " ").trim(); if (/^SELECT \* FROM servers WHERE/i.test(normalized)) { const needle = String(params[0] || "").toLowerCase(); for (const row of new Set(serversByName.values())) { if ( String(row.name).toLowerCase() === needle || String(row.legacy_id || "").toLowerCase() === needle || String(row.bot || "").toLowerCase() === needle ) { return [row]; } } return []; } if (/^SELECT \* FROM nodes WHERE/i.test(normalized)) return [NODE_ROW]; return []; }, pool: { async execute() { return [[]]; }, async query() { return [[]]; }, }, }; const nodesApp = (() => { const originalLoad = Module._load; Module._load = function (request, parent, isMain) { if (request === "./db" && parent && parent.filename === NODES_JS) return dbStub; return originalLoad.apply(this, arguments); }; try { return require(NODES_JS); } finally { Module._load = originalLoad; } })(); nodesApp.setPermissionCheckers( async () => ({ files_read: true, files_write: true, files_create: true, files_upload: true, backups_view: true, backups_create: true, backups_delete: true, }), async () => false, async (_email, serverName) => { const n = String(serverName).toLowerCase(); return n === "alpha" || n === "alpha-legacy" || n === "alpha-bot" || n === "suspended" || n === "suspended-legacy" || n === "suspended-bot"; } ); const parent = express(); parent.use(session({ secret: "test-secret", resave: false, saveUninitialized: true })); parent.use((req, res, next) => { req.isAdmin = false; if (req.session) req.session.user = TEST_EMAIL; next(); }); parent.use(nodesApp); let baseUrl = ""; let httpServer = null; test.before(async () => { await new Promise((resolve) => fakeNode.listen(0, "127.0.0.1", resolve)); fakeNodePort = fakeNode.address().port; NODE_ROW = nodeRow(); await new Promise((resolve) => { httpServer = parent.listen(0, "127.0.0.1", resolve); }); baseUrl = `http://127.0.0.1:${httpServer.address().port}`; }); test.after(() => { return new Promise((resolve) => httpServer.close(() => fakeNode.close(() => resolve())) ); }); async function call(method, route, body) { const res = await fetch(`${baseUrl}${route}`, { method, headers: body === undefined ? {} : { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); const json = await res.json().catch(() => null); return { status: res.status, json }; } function setHooks(hooks) { nodesApp.setUploadPolicyHooks(hooks); } const PASS_THROUGH_LIMITER = (req, res, next) => next(); function permissiveVerifier() { return async () => true; } function rejectingVerifier() { return async (req, res) => { res.status(403).json({ error: "invalid or missing action token", code: "ACTION_TOKEN_INVALID" }); return false; }; } const RELAYS = [ { method: "POST", route: "/api/nodes/server/Suspended/backups", body: { name: "b1", description: "" } }, { method: "POST", route: "/api/nodes/server/Suspended/backups/b1/restore", body: { deleteOldFiles: false } }, { method: "DELETE", route: "/api/nodes/server/Suspended/backups/b1" }, ]; test("fail-closed ladder: fresh module (no hooks) -> 429 gate brake; limiter-only hooks -> 403 ACTION_TOKEN_INVALID before any server state is read", async () => { // Phase 1 — no setUploadPolicyHooks call has happened yet — exactly a // standalone nodes.js module before index.js injects its implementations. // The backups relays now mount nodeUploadRateLimiterGate FIRST (same brake // as the extract/archive/upload siblings, adpanel:backup-relay-brake), so // the gate's own fail-closed 429 is the FIRST thing a request hits — even // on a suspended server and without any action token (the posture the // upload relay pins in server-suspension-rest-bridge). for (const relay of RELAYS) { const result = await call(relay.method, relay.route, relay.body); assert.strictEqual(result.status, 429, `${relay.method} ${relay.route}`); assert.strictEqual(result.json && result.json.error, "Too many upload attempts, slow down.", relay.route); } // Phase 2 — the token gate's own fail-closed posture, unchanged by the // brake in front of it: with ONLY the limiter hook injected, a missing // token hook still 403s before access, suspension or perms are read. setHooks({ uploadRateLimiter: PASS_THROUGH_LIMITER }); try { for (const relay of RELAYS) { const result = await call(relay.method, relay.route, relay.body); assert.strictEqual(result.status, 403, `${relay.method} ${relay.route}`); assert.strictEqual(result.json && result.json.error, "invalid or missing action token", relay.route); assert.strictEqual(result.json && result.json.code, "ACTION_TOKEN_INVALID", relay.route); } } finally { setHooks({}); } }); test("valid token passes the gate through to the 423 suspension gate (all three relays)", async () => { setHooks({ uploadRateLimiter: PASS_THROUGH_LIMITER, requireActionTokenOr403: permissiveVerifier() }); try { for (const relay of RELAYS) { const result = await call(relay.method, relay.route, relay.body); assert.strictEqual(result.status, 423, `${relay.method} ${relay.route}`); assert.strictEqual(result.json && result.json.code, "server-suspended", relay.route); } } finally { setHooks({}); } }); test("rejecting verifier -> 403 ACTION_TOKEN_INVALID before 423 (token gate outranks suspension)", async () => { setHooks({ uploadRateLimiter: PASS_THROUGH_LIMITER, requireActionTokenOr403: rejectingVerifier() }); try { for (const relay of RELAYS) { const result = await call(relay.method, relay.route, relay.body); assert.strictEqual(result.status, 403, `${relay.method} ${relay.route}`); assert.strictEqual(result.json && result.json.code, "ACTION_TOKEN_INVALID", relay.route); } } finally { setHooks({}); } }); test("live controls: valid token reaches each performer (fake node 404 -> per-route 404 passthrough)", async () => { setHooks({ uploadRateLimiter: PASS_THROUGH_LIMITER, requireActionTokenOr403: permissiveVerifier() }); try { // The performers pass the daemon's structured 404 {error} bodies through // verbatim (nodes.js mirrors its 409 passthrough) instead of masking them // as a generic 502 — so the relayed {ok:false, error:"not_found"} body is // itself the proof the performer ran and reached the fake node. const create = await call("POST", "/api/nodes/server/Alpha/backups", { name: "b1", description: "" }); assert.strictEqual(create.status, 404); assert.strictEqual(create.json && create.json.error, "not_found"); const restore = await call("POST", "/api/nodes/server/Alpha/backups/b1/restore", { deleteOldFiles: false }); assert.strictEqual(restore.status, 404); assert.strictEqual(restore.json && restore.json.error, "not_found"); const del = await call("DELETE", "/api/nodes/server/Alpha/backups/b1"); assert.strictEqual(del.status, 404); assert.strictEqual(del.json && del.json.error, "not_found"); } finally { setHooks({}); } }); test("still fail-closed after the ladder: the token hook is gone again -> 403 (not a 423 leak)", async () => { // setHooks({}) in the finally blocks nulled every hook. With every hook // gone the brake's own fail-closed 429 comes first (phase-1 posture of the // fresh-module ladder above); with ONLY the limiter hook restored the token // gate must still fail closed on a suspended target (403 before 423). const braked = await call("POST", "/api/nodes/server/Suspended/backups", { name: "b1", description: "" }); assert.strictEqual(braked.status, 429); assert.strictEqual(braked.json && braked.json.error, "Too many upload attempts, slow down."); setHooks({ uploadRateLimiter: PASS_THROUGH_LIMITER }); try { const result = await call("POST", "/api/nodes/server/Suspended/backups", { name: "b1", description: "" }); assert.strictEqual(result.status, 403); assert.strictEqual(result.json && result.json.code, "ACTION_TOKEN_INVALID"); } finally { setHooks({}); } }); // --------------------------------------------------------------------------- // 5. Frontend contract: bot.js attaches the right token key to each backup // call and treats restore/delete as one-time (fresh mint per call). // --------------------------------------------------------------------------- test("bot.js registers backupRestore/backupDelete as one-time keys (backupCreate stays repeatable)", () => { const set = /const ONE_TIME_SERVER_ACTION_TOKENS = new Set\(\[([^\]]+)\]\)/.exec(botSource); assert.ok(set, "ONE_TIME_SERVER_ACTION_TOKENS declaration not found"); const keys = set[1].split(",").map((k) => k.trim().replace(/^'|'$/g, "")); assert.ok(keys.includes("backupRestore"), "backupRestore must be one-time client-side"); assert.ok(keys.includes("backupDelete"), "backupDelete must be one-time client-side"); assert.ok(!keys.includes("backupCreate"), "backupCreate must stay repeatable client-side"); assert.ok(keys.includes("fileDelete") && keys.includes("reinstallServer"), "pre-existing one-time keys must remain"); }); test("bot.js attaches the matching token key to each backup relay call", () => { assert.match( botSource, /fetchWithServerActionToken\(`\/api\/nodes\/server\/\$\{encodeURIComponent\(bot\)\}\/backups`,\s*\{[\s\S]*?method: 'POST',[\s\S]*?\}, 'backupCreate'\)/, "create must send the backupCreate token" ); assert.match( botSource, /fetchWithServerActionToken\(`\/api\/nodes\/server\/\$\{encodeURIComponent\(bot\)\}\/backups\/\$\{encodeURIComponent\(id\)\}\/restore`, \{[\s\S]*?method: 'POST'[\s\S]*?\}, 'backupRestore', \{ refreshBefore: true \}\)/, "restore must send a freshly minted backupRestore token per call" ); // This test's contract is the fresh-mint-per-call token posture, not the // transport bound: the delete opts may carry further opts (the // adpanel:backups-delete-fetch-bound timeoutMs, pinned with its derivation // in bot-scheduler-fetch-bounds.test.js) — refreshBefore: true must stay. assert.match( botSource, /fetchWithServerActionToken\(`\/api\/nodes\/server\/\$\{encodeURIComponent\(bot\)\}\/backups\/\$\{encodeURIComponent\(id\)\}`, \{ method: 'DELETE' \}, 'backupDelete', \{ refreshBefore: true[^}]*\}\)/, "delete must send a freshly minted backupDelete token per call" ); }); test("bot.js retry loop still re-fetches on ACTION_TOKEN_INVALID (covers burned one-time tokens)", () => { assert.match(botSource, /INVALID_ACTION_TOKEN_ERROR = 'invalid or missing action token'/); assert.match( botSource, /if \(retryOnInvalidToken && response\.status === 403\) \{[\s\S]*?isInvalidActionTokenErrorPayload\(errData\)[\s\S]*?response = await runRequest\(true\);/, "a 403 ACTION_TOKEN_INVALID must trigger one refreshed retry through ensureServerActionToken" ); }); test("bot.js restore flow pre-checks backups_create client-side like its siblings", () => { // createBackup and deleteBackup both alert a permission message before any // request; restore originally skipped this, so a backups_view-only user got // the raw ACTION_TOKEN_INVALID alert instead. The server-side refusal is // unchanged — this is purely the client surfacing the same denial earlier. // The backupOpInFlight double-submit guard sits between the pre-check and // the confirm, so the match tolerates whatever guards precede the confirm // while still pinning both statements in order. assert.match( botSource, /async function restoreBackup\(id\) \{\n if \(!id\) return;[\s\S]*?if \(!hasPerm\('backups_create'\)\) \{\n alert\('You do not have permission to restore backups\.'\);\n return;\n \}[\s\S]*?if \(!confirm\('Restore this backup\? The server will stop and its current files will be replaced\.'\)\) return;/, "restore must pre-check backups_create (same message pattern as create/delete) before the confirm dialog" ); });