"use strict"; // Tests for the interactive backup create relay's cap refusal and its // name/description control-character strip. // // adpanel:backup-count-cap (2026-11 semantics change): the interactive relay // (nodes.js performPanelCreateBackup, including the AI create_backup tool // that routes through it) previously PRUNED to the cap after a successful // create — fire-and-forget deletes of the oldest backups. Removed: the // relay's actor proves only backups_create, and a backups_create holder must // never be able to destroy other users' (or scheduled) backups — deleting // backups is backups_delete's job. The relay now counts via the shared // listServerBackupsForHygiene helper BEFORE the create and refuses with 409 // backup_cap_reached at MAX_BACKUPS_PER_SERVER, matching the scheduler's // pre-create count check (index.js case "backup") and the daemon's opt-in // backupsMax quota: all three ceilings refuse, none prune. The count check // fails OPEN (warn + proceed) after the helper's internal retry, identical // precedence to the scheduler's — backup availability beats the cap. // // adpanel:log-injection-backup-name: the backup name/description reach // console.log, recordActivity (→ the Discord webhook dispatcher) and daemon // storage verbatim, so BOTH panel clamp copies (the interactive relay and // the scheduler fire path — plus the AI arg pre-clamp in index.js // sanitizeBotToolArgs) strip C0/C1 controls and collapse whitespace runs // BEFORE the length cap, mirroring adpanel:log-injection-task-name. // // nodes.js and index.js boot servers on require and cannot be loaded // in-process, so — same technique as scheduler-backup-count-cap.test.js — // the REAL performer body, the REAL hygiene list helper and the REAL cap // constants are sliced from source and evaluated with injected fakes. 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 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"); // Strip full-line comments so prose mentioning the markers cannot satisfy // the source-level assertions. function stripFullLineComments(src) { return src .split("\n") .filter((line) => !/^\s*\/\//.test(line)) .join("\n"); } const nodesCode = stripFullLineComments(nodesSource); const indexCode = stripFullLineComments(indexSource); function sliceFrom(source, startMarker, endMarker, label) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start); assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`); return source.slice(start, end); } // --------------------------------------------------------------------------- // The REAL hygiene list helper (nodes.js listServerBackupsForHygiene) and the // REAL cap constants, evaluated from source like the scheduler test does. // --------------------------------------------------------------------------- const hygieneHelperSrc = sliceFrom( nodesSource, "async function listServerBackupsForHygiene", "\nfunction relayPanelResult", "nodes.js hygiene list helper" ); const makeListServerBackupsForHygiene = new Function( "nodeUrl", "httpJson", "nodeHeaders", `"use strict"; ${hygieneHelperSrc} return listServerBackupsForHygiene;` ); function evalNodesCap() { return new Function( sliceFrom( nodesSource, "const MAX_BACKUPS_PER_SERVER", "// GET the server's backup list", "nodes.js backup cap constant" ) + "\nreturn MAX_BACKUPS_PER_SERVER;" )(); } function evalIndexCap() { return new Function( sliceFrom( indexSource, "const SCHEDULER_MAX_BACKUPS_PER_SERVER", "\nfunction scheduleToCron(", "index.js backup cap constant" ) + "\nreturn SCHEDULER_MAX_BACKUPS_PER_SERVER;" )(); } // The shipped default cap, read from source — not a test-local copy. The // shared env override (SCHEDULER_MAX_BACKUPS_PER_SERVER) must be unset for // the default evaluation; restored around every env-touching test. delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; const REAL_CAP = evalNodesCap(); assert.strictEqual(REAL_CAP, 50, "shipped default cap must be 50"); // --------------------------------------------------------------------------- // The REAL interactive performer (nodes.js performPanelCreateBackup), run // with injected fakes; the listing goes through the REAL helper over the // stubbed transport so the retry/fail-open semantics are exercised for real. // --------------------------------------------------------------------------- const createPerformerSrc = sliceFrom( nodesSource, "async function performPanelCreateBackup", "\nasync function performPanelRestoreBackup", "panel create backup performer" ); const makeCreateBackup = new Function( "checkServerAccess", "resolveIfServerSuspended", "checkUserPerm", "remoteContext", "listServerBackupsForHygiene", "MAX_BACKUPS_PER_SERVER", "nodeUrl", "httpJson", "nodeHeaders", "isNodeQuota507", "recordActivity", "getRequestIp", "getCanonicalServerName", `"use strict"; ${createPerformerSrc} return performPanelCreateBackup;` ); const listOk = (count) => ({ status: 200, json: { ok: true, backups: Array.from({ length: count }, (_, i) => ({ id: `bk-${i}` })) }, }); function makeCreateHarness({ backupsInListing, listResponses, helperCrash, cap }) { const httpCalls = []; const activities = []; const warnings = []; const nodeUrl = (node, p) => `${node.baseUrl}${p}`; const nodeHeaders = (node) => ({ Authorization: `Bearer ${node.token}` }); const httpJson = async (url, opts) => { httpCalls.push({ url, opts }); if (opts.method === "GET") { const next = listResponses ? listResponses.shift() : (backupsInListing !== undefined ? listOk(backupsInListing) : { status: 200, json: { ok: true, backups: [] } }); if (next === undefined) return { status: 503, json: { ok: false, error: "node_backup_list_failed" } }; if (next instanceof Error) throw next; return next; } return { status: 200, json: { ok: true, backup: { id: "bk-new", name: opts.body.name } } }; }; const realHelper = makeListServerBackupsForHygiene(nodeUrl, httpJson, nodeHeaders); const createBackup = makeCreateBackup( async () => ({ ok: true }), async () => null, async () => true, async () => ({ exists: true, remote: true, node: { baseUrl: "http://node.example:8081", token: "node-token", name: "node-one", uuid: "node-uuid-1" }, nodeServerName: "srv01", server: { name: "srv01" }, }), helperCrash ? async () => { throw helperCrash; } : realHelper, cap === undefined ? REAL_CAP : cap, nodeUrl, httpJson, nodeHeaders, () => false, (serverName, type, detail) => activities.push({ serverName, type, detail }), () => "127.0.0.1", (server, fallback) => (server && server.name) || fallback ); return { run: async ({ backupName, description, serverName = "srv01" } = {}) => { const originalWarn = console.warn; console.warn = (...args) => warnings.push(args.join(" ")); try { return await createBackup({ session: { user: "user@example.com" } }, serverName, backupName, description); } finally { console.warn = originalWarn; } }, httpCalls, activities, warnings, }; } // --------------------------------------------------------------------------- // 1. Refuse-at-cap behavior (adpanel:backup-count-cap) // --------------------------------------------------------------------------- test("the interactive create refuses with 409 backup_cap_reached BEFORE any create POST when the server is at the cap", async () => { const { run, httpCalls, activities } = makeCreateHarness({ backupsInListing: REAL_CAP }); const result = await run({ backupName: "Nightly", description: "d" }); assert.strictEqual(result.status, 409); assert.strictEqual(result.body.error, "backup_cap_reached"); assert.match( result.body.detail, new RegExp(`^Server already has ${REAL_CAP} backups \\(limit ${REAL_CAP}\\)\\. Delete backups to make room \\(requires the backups_delete permission\\)\\.$`) ); assert.strictEqual(httpCalls.length, 1, "only the listing GET may leave the panel"); assert.strictEqual(httpCalls[0].opts.method, "GET"); assert.ok(httpCalls[0].url.endsWith("/v1/servers/srv01/backups"), httpCalls[0].url); assert.strictEqual(activities.length, 0, "a cap refusal must not record backup_create"); }); test("at cap-1 the create proceeds: exactly one listing GET then the create POST, then the audit record", async () => { const { run, httpCalls, activities } = makeCreateHarness({ backupsInListing: REAL_CAP - 1 }); const result = await run({ backupName: "Nightly", description: "d" }); assert.strictEqual(result.status, 200); assert.ok(result.body.ok); assert.strictEqual(httpCalls.length, 2, "count check (GET) then create (POST)"); assert.strictEqual(httpCalls[0].opts.method, "GET"); assert.strictEqual(httpCalls[1].opts.method, "POST"); // adpanel:backup-cap-fallback — the fallback cap travels as a request // HEADER, never a JSON body field: the daemon's readJSON rejects unknown // body fields, so a body field would break the create on an older daemon // during a rolling upgrade (unknown headers are ignored instead). assert.strictEqual( httpCalls[1].opts.headers["X-ADPanel-Backups-Max"], String(REAL_CAP), "the create POST must carry the panel cap in the X-ADPanel-Backups-Max header" ); assert.ok(!("backupsMax" in httpCalls[1].opts.body), "the create body must not carry a backupsMax field (breaks older daemons)"); assert.strictEqual(activities.length, 1, "the successful create is still audited"); assert.strictEqual(activities[0].type, "backup_create"); }); // adpanel:backup-dial-canonical — the daemon derives storage from the URL // key (sanitizeName), so both the count-check GET and the create POST must // dial the resolved canonical storage name (ctx.nodeServerName), never the // request alias: a legacy_id/bot alias landing in the URL otherwise reads // and writes a nonexistent storage name (empty list / spurious 404s). test("the count GET and the create POST dial the canonical storage name, not the request alias", async () => { const { run, httpCalls } = makeCreateHarness({ backupsInListing: 1 }); // "srv01-legacy" plays a legacy_id/bot alias: the performer must resolve // the row and dial its canonical storage form (srv01) on BOTH node calls. const result = await run({ backupName: "Nightly", description: "d", serverName: "srv01-legacy" }); assert.strictEqual(result.status, 200); assert.strictEqual(httpCalls.length, 2, "count check (GET) then create (POST)"); assert.ok(httpCalls[0].url.endsWith("/v1/servers/srv01/backups"), `count GET must dial the canonical name: ${httpCalls[0].url}`); assert.ok(httpCalls[1].url.endsWith("/v1/servers/srv01/backups"), `create POST must dial the canonical name: ${httpCalls[1].url}`); }); test("a listing failure fails OPEN after the helper's retry: warn naming the server, then the create POST", async () => { // First attempt 502, retry (queued undefined -> 503): both non-200, so the // helper returns { ok: false } and the performer must warn and proceed. const { run, httpCalls, warnings } = makeCreateHarness({ listResponses: [{ status: 502, json: { ok: false, error: "node_backup_list_failed" } }, undefined], }); const result = await run({ backupName: "Nightly", description: "d" }); assert.strictEqual(result.status, 200, "backup availability beats the cap — identical precedence to the scheduler"); assert.strictEqual(httpCalls.length, 3, "listing GET, one retry, then the create POST"); assert.strictEqual(httpCalls[2].opts.method, "POST"); assert.ok( warnings.some((w) => w.includes("Backup count check unavailable for srv01")), "the fail-open path must warn with the server name" ); }); test("an unexpected list-helper crash still fails OPEN (defensive catch mirrors the scheduler)", async () => { const { run, httpCalls, warnings } = makeCreateHarness({ helperCrash: new Error("helper exploded") }); const result = await run({ backupName: "Nightly", description: "d" }); assert.strictEqual(result.status, 200); assert.strictEqual(httpCalls.length, 1); assert.strictEqual(httpCalls[0].opts.method, "POST", "create must proceed when the count check itself throws"); assert.ok( warnings.some((w) => w.includes("Backup count check failed for srv01: helper exploded")), "the catch branch must warn with the underlying error" ); }); // --------------------------------------------------------------------------- // 2. Source structure: the guard is in the performer, before the create POST, // and the destructive prune is gone everywhere. // --------------------------------------------------------------------------- test("the performer enforces the cap through the named constant before the create POST", () => { const performer = stripFullLineComments(createPerformerSrc); assert.ok(performer.includes("MAX_BACKUPS_PER_SERVER"), "must reference the named constant, not a magic number"); assert.ok(performer.includes("backup_cap_reached"), "the refusal must carry the machine-readable error code"); assert.ok( performer.includes("if (existingBackupCount !== null && existingBackupCount >= MAX_BACKUPS_PER_SERVER)"), "the refusal must only trigger on a successfully counted listing" ); // adpanel:backup-dial-canonical — the helper call passes the resolved // canonical storage name (ctx.nodeServerName), not the request alias. const listPos = performer.indexOf("listServerBackupsForHygiene(ctx.node, ctx.nodeServerName)"); const capPos = performer.indexOf("existingBackupCount >= MAX_BACKUPS_PER_SERVER"); const createPos = performer.indexOf('method: "POST"'); assert.ok(listPos >= 0, "the performer must list backups via the shared hygiene helper"); assert.ok(capPos > listPos, "the count must be taken before it is compared to the cap"); assert.ok(createPos > capPos, "the cap check must run BEFORE the create POST"); assert.ok(performer.includes("Backup count check unavailable for"), "non-200 listings warn and proceed"); assert.ok(performer.includes("Backup count check failed for"), "thrown listing errors warn and proceed"); }); test("the destructive prune is gone from nodes.js and the repo: no pruneServerBackupsToCap, no pickBackupsToPrune, no backup-hygiene module", () => { assert.doesNotMatch(nodesCode, /pruneServerBackupsToCap/, "the prune function must be removed from nodes.js"); assert.doesNotMatch(nodesCode, /pickBackupsToPrune/, "the prune picker must be unimported from nodes.js"); assert.doesNotMatch(nodesCode, /backup-hygiene/, "nodes.js must not reference the removed module"); assert.ok(!fs.existsSync(path.join(ROOT, "utils", "backup-hygiene.js")), "utils/backup-hygiene.js must be deleted (its only export was the destructive picker)"); assert.ok(!fs.existsSync(path.join(ROOT, "utils", "backup-hygiene.test.js")), "utils/backup-hygiene.test.js must be deleted with the feature it pinned"); for (const src of [nodesCode, indexCode]) { assert.doesNotMatch(src, /pruneServerBackupsToCap|pickBackupsToPrune/, "no prune reference may remain in either monolith"); } }); test("MAX_BACKUPS_PER_SERVER (nodes.js) stays in lockstep with SCHEDULER_MAX_BACKUPS_PER_SERVER (index.js)", () => { const original = process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; try { delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; assert.strictEqual(evalNodesCap(), evalIndexCap(), "default caps must match"); process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = "7"; assert.strictEqual(evalNodesCap(), 7); assert.strictEqual(evalNodesCap(), evalIndexCap(), "env override must apply to both sides identically"); process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = "0"; assert.strictEqual(evalNodesCap(), evalIndexCap(), "garbage env must fall back to 50 on both sides"); assert.strictEqual(evalNodesCap(), 50); } finally { if (original === undefined) delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER; else process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = original; } }); // --------------------------------------------------------------------------- // 3. adpanel:log-injection-backup-name — the strip at ALL THREE clamp copies. // String.raw keeps the \uXXXX sequences as source text to match against. // --------------------------------------------------------------------------- const STRIP_NAME = String.raw`.trim().replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 120)`; const STRIP_DESC_500 = String.raw`.trim().replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 500)`; const STRIP_DESC_280 = String.raw`.trim().replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 280)`; test("the strip+cap chain appears verbatim at all three backup name/description clamp copies", () => { // Copy 1 — the interactive relay (nodes.js performPanelCreateBackup). assert.ok( nodesCode.includes(`const safeName = String(backupName || "")${STRIP_NAME};`), "nodes.js safeName must strip C0/C1 controls and collapse whitespace BEFORE the 120 cap" ); assert.ok( nodesCode.includes(`const safeDescription = String(description || "")${STRIP_DESC_500};`), "nodes.js safeDescription must strip before the 500 cap" ); // Copy 2 — the scheduler fire path (index.js case "backup"). assert.ok( indexCode.includes(`const safeBackupName = String(backupName || "")${STRIP_NAME};`), "index.js scheduler safeBackupName must carry the identical strip" ); assert.ok( indexCode.includes(`const safeDescription = String(description || "")${STRIP_DESC_500};`), "index.js scheduler safeDescription must carry the identical strip" ); // Copy 3 — the AI arg pre-clamp (index.js sanitizeBotToolArgs, create_backup). assert.ok( indexCode.includes(`name: String(args.name || "")${STRIP_NAME},`), "sanitizeBotToolArgs create_backup name must carry the identical strip" ); assert.ok( indexCode.includes(`description: String(args.description || "")${STRIP_DESC_280},`), "sanitizeBotToolArgs create_backup description must carry the identical strip" ); // The old strip-free clamps must be gone. assert.doesNotMatch(nodesCode, /String\(backupName \|\| ""\)\.trim\(\)\.slice\(0, 120\)/); assert.doesNotMatch(indexCode, /String\(backupName \|\| ""\)\.trim\(\)\.slice\(0, 120\)/); // Both monoliths carry the adpanel tag (checked against the RAW source — // the tag lives on a comment line); the mirror reference to the task-name // precedent stays intact. assert.ok(nodesSource.includes("adpanel:log-injection-backup-name"), "nodes.js must document the constraint"); assert.ok(indexSource.includes("adpanel:log-injection-backup-name"), "index.js must document the constraint"); assert.ok(indexSource.includes("adpanel:log-injection-task-name"), "the task-name precedent this strip mirrors"); }); // --------------------------------------------------------------------------- // 4. adpanel:log-injection-backup-name — behavioral: the daemon-bound body // (and therefore console.log/recordActivity inputs) carry the STRIPPED // values, with the empty-after-strip and cap-after-strip semantics. // --------------------------------------------------------------------------- test("the daemon-bound body uses the stripped name/description: controls become spaces, runs collapse", async () => { const { run, httpCalls } = makeCreateHarness({ backupsInListing: 0 }); const result = await run({ backupName: "Nightly\u0000Backup\nSecond\u001f", description: "line1\nline2\u007f\ttail", }); assert.strictEqual(result.status, 200); const post = httpCalls.find((c) => c.opts.method === "POST"); assert.ok(post, "the create POST must happen"); assert.strictEqual(post.opts.body.name, "Nightly Backup Second"); assert.strictEqual(post.opts.body.description, "line1 line2 tail"); }); test("a name/description that is empty after stripping stays empty (daemon defaults the name)", async () => { const { run, httpCalls } = makeCreateHarness({ backupsInListing: 0 }); const result = await run({ backupName: "\u0000\n\t\u001f", description: "\u0007" }); assert.strictEqual(result.status, 200); const post = httpCalls.find((c) => c.opts.method === "POST"); assert.strictEqual(post.opts.body.name, "", "the daemon's 'Backup ' default must still engage"); assert.strictEqual(post.opts.body.description, ""); }); test("the length cap is applied AFTER the strip: control-padded names cannot slip by", async () => { const { run, httpCalls } = makeCreateHarness({ backupsInListing: 0 }); // 30 newlines + 130 x's: strip-then-cap yields 120 chars; cap-then-strip // (the old buggy order) would have yielded 101. const result = await run({ backupName: "\n".repeat(30) + "x".repeat(130), description: "" }); assert.strictEqual(result.status, 200); const post = httpCalls.find((c) => c.opts.method === "POST"); assert.strictEqual(post.opts.body.name.length, 120, "the cap must bite on the stripped value"); assert.ok(!/[\u0000-\u001f\u007f-\u009f]/.test(post.opts.body.name), "no control character may reach the daemon"); }); // --------------------------------------------------------------------------- // 5. The bot.js create-backup 409 branch — the UI surface of // adpanel:backup-count-cap. bot.js is a browser IIFE (DOM + fetch bound // at module scope), so — same technique as the bot-*.test.js files — the // branch is pinned structurally on a source window, not executed: it must // prefer the relay's err.detail, keep an actionable static fallback, and // leave the daemon's op-lock 409 falling through to the generic branch. // --------------------------------------------------------------------------- test("the bot.js create-backup 409 branch prefers err.detail, keeps an actionable fallback, and leaves the daemon op-lock 409 to the generic branch", () => { const startAnchor = "const res = await fetchWithServerActionToken(`/api/nodes/server/${encodeURIComponent(bot)}/backups`"; const start = botSource.indexOf(startAnchor); assert.ok(start >= 0, "bot.js create-backup submit fetch not found"); const end = botSource.indexOf("closeBackupCreateModal();", start + startAnchor.length); assert.ok(end > start, "bot.js create-backup success close not found after the fetch"); const submitWindow = stripFullLineComments(botSource.slice(start, end)); // The cap branch exists, keyed on BOTH the status and the machine-readable // error code — and it is the ONLY 409 special case in the submit path. const branchAnchor = "if (res.status === 409 && err.error === 'backup_cap_reached')"; const branchAt = submitWindow.indexOf(branchAnchor); assert.ok(branchAt >= 0, "the 409 branch must be keyed on the backup_cap_reached error code"); assert.strictEqual( submitWindow.split("res.status === 409").length - 1, 1, "the cap branch must be the only 409 special case in the submit path — the daemon's op-lock 409 (error 'backup operation in progress', relayed verbatim by nodes.js) cannot match the error-code key and must keep falling through" ); // Detail preferred; the static fallback stays actionable and mirrors the // relay's 409 detail: the remediation names the permission that deletes // backups (a backups_create holder cannot remediate the cap themselves). const throwAt = submitWindow.indexOf("throw new Error(err.detail ||", branchAt); assert.ok(throwAt >= 0, "the branch must surface err.detail first — the server's count/limit detail beats any client copy"); const fallbackAt = submitWindow.indexOf("'This server has reached its backup limit. Delete backups to make room (requires the backups_delete permission).'", throwAt); assert.ok(fallbackAt >= 0, "the static fallback must stay actionable: name the remediation (delete backups) and the permission it requires"); // The generic branch still follows: every other non-OK response (the // op-lock 409 included) surfaces the relayed error code, never the cap // copy — and no client-side op-lock special case may drift from the // daemon's wording. const genericAt = submitWindow.indexOf("throw new Error(err.error || 'Failed to create backup')", branchAt); assert.ok(genericAt > throwAt, "the generic error branch must follow the cap branch"); assert.ok(!submitWindow.includes("backup operation in progress"), "the op-lock 409 must stay on the generic branch — no client-side special case to drift from the daemon's wording"); });