"use strict"; // Unit + structural tests for Wave 2 Step B1 (adpanel:relay-helper-consolidation) // of the relay consolidation campaign: the JSON file-relay UPSTREAM pipeline — // services/node-fs-relay.js's relayFsJson (dial + transport-neutral // classification) and the per-op renderFs*Outcome renderers — and the index.js // GET file routes migrated onto them. // // Wave 2 Step B2 extends both halves to the MUTATING ops: the eight index.js // routes (PUT /files/write, POST /files/mkdir, DELETE /files/delete, // POST /files/rename, POST /extract, POST /archive, legacy POST /create, // legacy POST /rename) dial through relayFsJson and render through the new // per-op renderers, and the relay-variant rows (spec §3) are pinned here ahead // of Step B3 consuming them. // // Wave 2 Step B3 migrates nodes.js's nine server-scoped fs relays onto the // SAME core/renderers: the relay-variant rows below are now the live wire // contract of /api/nodes/server/:name/{entries,file(POST),delete,delete-batch, // rename,extract,archive,create}. renderFsDeleteBatchOutcome is added as the // one RELAY-ONLY op (spec D29 — the daemon's /v1/fs/delete-batch has no panel // route), and the B3 structural section pins the nodes.js route windows // (dial through the shared core, render the relay variant, keep the per-route // guards that deliberately stayed route-side). // // Pinned here: // 1. The wire-contract parity table (spec .campaign/spec-relay.md §2 panel / // §3 relay): every classification trigger → HTTP status → BYTE-EXACT body // (or TEXT body for the legacy routes) for BOTH variants. Bodies are // written as literals in this file, so a change on either the renderer or // this table trips the suite. // 2. relayFsJson's classification over a real loopback dial: ok / failed / // not_found / too_large (16 MiB cap) / offline (refused dial, null base // URL, hard timer), the verbatim payload passthrough, and the maxBytes // pass-through. // 3. Structural: the index.js file routes dial through relayFsJson with the // parity timeouts (list 60000, read/stream 120000; B2: write/mkdir/delete/ // rename/create 120000, rename probes 60000, extract 630000, archive // 330000 — the +30s relay slack over the daemon's extractCallerWaitBudget/ // archiveCallerWaitBudget, same doctrine as the backup relays) and render // with variant "panel"; the download route stays a raw // stream proxy this wave (spec §5/D-notes: not merged); the per-route // guards (pre-dial 413, root refusals, input validation, the canonical // archive URL segment, the probe's byte-identical list body) stayed put. // 4. (B3) Structural: the nodes.js relays dial through relayFsJson via // NODES_FS_RELAY_DEPS and render the "relay" variants; the route-side // pieces that deliberately stayed (D8 body-only delete input, D9 rename // newName fallback sanitizer, D11 create name sanitizer, D23 canonical // archive segment, D29 ≤500/root-refusal batch guards, the recordActivity // file_* calls) are pinned in place. const test = require("node:test"); const assert = require("node:assert"); const http = require("node:http"); const fs = require("node:fs"); const path = require("node:path"); process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const NODES_JS = path.join(ROOT, "nodes.js"); const { relayFsJson, classifyNodeJsonResult, buildFsListPayload, buildFsCreatePayload, renderFsListOutcome, renderFsReadOutcome, renderFsStreamOutcome, renderFsWriteOutcome, renderFsMkdirOutcome, renderFsDeleteOutcome, renderFsDeleteBatchOutcome, renderFsRenameOutcome, renderFsExtractOutcome, renderFsArchiveOutcome, renderFsCreateLegacyOutcome, renderFsCreateOutcome, renderFsRenameLegacyOutcome, } = require("../services/node-fs-relay"); // --------------------------------------------------------------------------- // relayFsJson — classification over a real loopback dial // --------------------------------------------------------------------------- function startServer(handler) { return new Promise((resolve, reject) => { const server = http.createServer(handler); server.on("error", reject); server.listen(0, "127.0.0.1", () => resolve({ server, port: server.address().port })); }); } function stopServer(server) { if (!server) return; if (typeof server.closeAllConnections === "function") server.closeAllConnections(); server.close(); } const NODE_AUTH = { "Content-Type": "application/json", Authorization: "Bearer t", "X-Node-Token": "t", }; // buildNodeBaseUrl receives the node verbatim; buildNodeAuthHeaders too. test("relayFsJson passes the node to the deps builders and dials POST ", async () => { let seenBaseNode = null; let seenHeaderNode = null; let seenUrl = null; let seenMethod = null; let seenBody = null; let seenHeaders = null; const { server, port } = await startServer((req, res) => { seenUrl = req.url; seenMethod = req.method; seenHeaders = req.headers; let raw = ""; req.on("data", (d) => { raw += d; }); req.on("end", () => { seenBody = JSON.parse(raw || "null"); res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ ok: true })); }); }); try { const deps = { buildNodeBaseUrl: (node) => { seenBaseNode = node; return `http://127.0.0.1:${port}`; }, buildNodeAuthHeaders: (node) => { seenHeaderNode = node; return NODE_AUTH; }, }; const payload = { path: "/vols/srv01/world", server: "srv01" }; const outcome = await relayFsJson(deps, { token: "t" }, "/v1/fs/list", payload, 10000); assert.deepStrictEqual(seenBaseNode, { token: "t" }, "buildNodeBaseUrl must receive the node"); assert.strictEqual(outcome.kind, "ok"); assert.strictEqual(seenHeaderNode, seenBaseNode, "buildNodeAuthHeaders must receive the same node"); assert.strictEqual(seenUrl, "/v1/fs/list"); assert.strictEqual(seenMethod, "POST"); assert.deepStrictEqual(seenBody, payload, "the payload must go upstream verbatim"); assert.strictEqual(seenHeaders["x-node-token"], "t", "the deps-built auth headers must ride the dial"); } finally { stopServer(server); } }); test("classifyNodeJsonResult: ok requires status 200 + truthy ok flag (the former route guard)", () => { assert.deepStrictEqual(classifyNodeJsonResult({ status: 200, json: { ok: true, entries: [] } }).kind, "ok"); assert.strictEqual(classifyNodeJsonResult({ status: 200, json: { ok: false } }).kind, "failed"); assert.strictEqual(classifyNodeJsonResult({ status: 200, json: null }).kind, "failed"); assert.strictEqual(classifyNodeJsonResult({ status: 204, json: { ok: true } }).kind, "failed"); assert.strictEqual(classifyNodeJsonResult({ status: 404, json: { error: "x" } }).kind, "not_found"); assert.strictEqual(classifyNodeJsonResult({ status: 503, json: { error: "x" } }).kind, "failed"); assert.deepStrictEqual(classifyNodeJsonResult({ status: 0, json: null, tooLarge: true }), { kind: "too_large", status: 0, json: null }); assert.deepStrictEqual(classifyNodeJsonResult({ status: 0, json: null }), { kind: "offline", status: 0, json: null }); }); test("relayFsJson classifies an over-cap response (16 MiB Content-Length pre-check) as too_large", async () => { const CAP = 16 * 1024 * 1024; const { server, port } = await startServer((req, res) => { res.writeHead(200, { "Content-Length": String(2 * CAP) }); res.end("x"); }); try { const deps = { buildNodeBaseUrl: () => `http://127.0.0.1:${port}`, buildNodeAuthHeaders: () => NODE_AUTH }; const outcome = await relayFsJson(deps, { token: "t" }, "/v1/fs/list", { path: "x", server: "s" }, 15000); assert.deepStrictEqual(outcome, { kind: "too_large", status: 0, json: null }); } finally { stopServer(server); } }); test("relayFsJson forwards maxBytes to the dial (per-call cap pass-through)", async () => { const { server, port } = await startServer((req, res) => { res.writeHead(200, { "Content-Length": String(2 * 1024 * 1024) }); res.end("x"); }); try { const deps = { buildNodeBaseUrl: () => `http://127.0.0.1:${port}`, buildNodeAuthHeaders: () => NODE_AUTH }; const outcome = await relayFsJson(deps, { token: "t" }, "/v1/fs/list", { path: "x", server: "s" }, 15000, { maxBytes: 1024 * 1024 }); assert.deepStrictEqual(outcome, { kind: "too_large", status: 0, json: null }, "a body over the per-call maxBytes must classify as too_large"); } finally { stopServer(server); } }); test("relayFsJson classifies a refused dial as offline", async () => { // Port 1 is closed on the test host (same precedent as node-fs-relay.test.js). const deps = { buildNodeBaseUrl: () => "http://127.0.0.1:1", buildNodeAuthHeaders: () => NODE_AUTH }; const outcome = await relayFsJson(deps, { token: "t" }, "/v1/fs/list", { path: "x", server: "s" }, 5000); assert.deepStrictEqual(outcome, { kind: "offline", status: 0, json: null }); }); test("relayFsJson classifies a null base URL as offline WITHOUT dialing", async () => { let dialed = false; const outcome = await relayFsJson( { httpRequestJson: async () => { dialed = true; return { status: 200, json: { ok: true } }; }, buildNodeBaseUrl: () => null, buildNodeAuthHeaders: () => NODE_AUTH }, { token: "t" }, "/v1/fs/list", { path: "x", server: "s" }, 5000 ); assert.deepStrictEqual(outcome, { kind: "offline", status: 0, json: null }); assert.strictEqual(dialed, false, "an unbuildable node URL must not reach the dialer"); }); test("relayFsJson's hard timer settles an unresponsive node as offline", async () => { const { server, port } = await startServer(() => { /* never respond */ }); try { const deps = { buildNodeBaseUrl: () => `http://127.0.0.1:${port}`, buildNodeAuthHeaders: () => NODE_AUTH }; const outcome = await relayFsJson(deps, { token: "t" }, "/v1/fs/read", { path: "x", server: "s", encoding: "base64" }, 250); assert.deepStrictEqual(outcome, { kind: "offline", status: 0, json: null }); } finally { stopServer(server); } }); test("relayFsJson refuses to dial without the per-caller deps", async () => { await assert.rejects( () => relayFsJson({}, { token: "t" }, "/v1/fs/list", {}, 1000), /deps\.buildNodeBaseUrl and deps\.buildNodeAuthHeaders/ ); }); // --------------------------------------------------------------------------- // buildFsListPayload — spec D3: depth:1 is relay-only, key order byte-stable // --------------------------------------------------------------------------- test("buildFsListPayload keeps both surfaces' exact payload shapes", () => { assert.deepStrictEqual(buildFsListPayload("/vols/srv01/world", "srv01", "panel"), { path: "/vols/srv01/world", server: "srv01" }); assert.deepStrictEqual(buildFsListPayload("/vols/srv01/world", "srv01", "relay"), { path: "/vols/srv01/world", server: "srv01", depth: 1 }); assert.deepStrictEqual(buildFsListPayload("/vols/srv01/world", "srv01"), { path: "/vols/srv01/world", server: "srv01" }, "panel is the default variant"); assert.deepStrictEqual(Object.keys(buildFsListPayload("/d", "s", "relay")), ["path", "server", "depth"], "relay key order matches the former nodes.js body literal"); }); // --------------------------------------------------------------------------- // renderFsListOutcome — spec §2 (panel) and §3 (relay) wire bodies // --------------------------------------------------------------------------- const LIST_TOO_LARGE_BODY = { error: "node_response_too_large", message: "The directory listing is too large for the panel to display: the node's response exceeded the panel's response size limit. Open a subdirectory instead.", }; test("renderFsListOutcome panel variant: byte-exact bodies for every trigger (spec §2)", () => { // Success: entries verbatim, truncated forwarded, ok:true first. assert.deepStrictEqual( renderFsListOutcome({ kind: "ok", status: 200, json: { ok: true, entries: [{ name: "a", isDir: false }], truncated: false } }, "world", { variant: "panel" }), { status: 200, json: { ok: true, path: "world", entries: [{ name: "a", isDir: false }], truncated: false } } ); assert.deepStrictEqual( renderFsListOutcome({ kind: "ok", status: 200, json: { ok: true, entries: [], truncated: true } }, "world", { variant: "panel" }).json, { ok: true, path: "world", entries: [], truncated: true } ); // A non-array entries field maps to [] (the former route's Array.isArray guard). assert.deepStrictEqual( renderFsListOutcome({ kind: "ok", status: 200, json: { ok: true, entries: null } }, "w", { variant: "panel" }).json.entries, [] ); // too_large: 502 with the panel's listing message (never node_offline). assert.deepStrictEqual( renderFsListOutcome({ kind: "too_large", status: 0, json: null }, "w", { variant: "panel" }), { status: 502, json: LIST_TOO_LARGE_BODY } ); // offline: the panel-only node_offline body (spec D5). assert.deepStrictEqual( renderFsListOutcome({ kind: "offline", status: 0, json: null }, "w", { variant: "panel" }), { status: 502, json: { error: "node_offline", message: "Cannot connect to server node. The node may be offline." } } ); // failed: detail from the daemon error, else "status ". assert.deepStrictEqual( renderFsListOutcome({ kind: "failed", status: 503, json: { error: "disk busy" } }, "w", { variant: "panel" }), { status: 502, json: { error: "node_list_failed", detail: "disk busy" } } ); assert.deepStrictEqual( renderFsListOutcome({ kind: "failed", status: 503, json: null }, "w", { variant: "panel" }), { status: 502, json: { error: "node_list_failed", detail: "status 503" } } ); // A daemon 404 is a listing failure like any other (the former route had no // 404 branch on list). assert.deepStrictEqual( renderFsListOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, "w", { variant: "panel" }), { status: 502, json: { error: "node_list_failed", detail: "x" } } ); }); test("renderFsListOutcome relay variant: no ok:true, mapped entries, no node_offline (spec §3/D3-D5)", () => { const entryMapper = (entries) => entries.map((e) => ({ name: e.name, isDir: !!e.isDir })); // Success: { path, entries (mapped), truncated } — no ok:true (spec D4). assert.deepStrictEqual( renderFsListOutcome( { kind: "ok", status: 200, json: { ok: true, entries: [{ name: "a", isDir: true, extra: "dropped" }], truncated: true } }, "world", { variant: "relay", entryMapper } ), { status: 200, json: { path: "world", entries: [{ name: "a", isDir: true }], truncated: true } } ); // The former nodes.js route mapped json.entries || [] before the mapper. assert.deepStrictEqual( renderFsListOutcome({ kind: "ok", status: 200, json: { ok: true, entries: null } }, "w", { variant: "relay", entryMapper }).json.entries, [] ); // offline collapses into the plain node_list_failed body (spec D5). assert.deepStrictEqual( renderFsListOutcome({ kind: "offline", status: 0, json: null }, "w", { variant: "relay", entryMapper }), { status: 502, json: { error: "node_list_failed" } } ); assert.deepStrictEqual( renderFsListOutcome({ kind: "failed", status: 503, json: { error: "disk busy" } }, "w", { variant: "relay", entryMapper }), { status: 502, json: { error: "node_list_failed" } }, "the relay body carries no detail field" ); // too_large is SHARED verbatim with the panel (nodes.js adopted the wording). assert.deepStrictEqual( renderFsListOutcome({ kind: "too_large", status: 0, json: null }, "w", { variant: "relay", entryMapper }), { status: 502, json: LIST_TOO_LARGE_BODY } ); // The relay variant without an entryMapper is a programming error: silently // relaying verbatim entries would break the §3 contract (D4). assert.throws(() => renderFsListOutcome({ kind: "ok", status: 200, json: { ok: true, entries: [] } }, "w", { variant: "relay" }), /entryMapper/); }); // --------------------------------------------------------------------------- // renderFsReadOutcome — spec §2 (panel) and §3 (relay) wire bodies // --------------------------------------------------------------------------- test("renderFsReadOutcome panel variant: byte-exact bodies for every trigger (spec §2)", () => { // Daemon 404 → 404 { error: "file not found" } (panel-only branch). assert.deepStrictEqual( renderFsReadOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, "server.properties", { variant: "panel" }), { status: 404, json: { error: "file not found" } } ); // too_large: the read-specific 502 message. assert.deepStrictEqual( renderFsReadOutcome({ kind: "too_large", status: 0, json: null }, "f", { variant: "panel" }), { status: 502, json: { error: "node_response_too_large", message: "This file is too large to open in the editor: the node's response exceeded the panel's response size limit. Download the file instead." } } ); // failed: 502 node_read_failed. assert.deepStrictEqual( renderFsReadOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, "f", { variant: "panel" }), { status: 502, json: { error: "node_read_failed" } } ); // Success: base64 content strictly decoded — text keeps { ok, path, content }. const text = Buffer.from("hello", "utf8").toString("base64"); assert.deepStrictEqual( renderFsReadOutcome({ kind: "ok", status: 200, json: { ok: true, content: text } }, "f", { variant: "panel" }), { status: 200, json: { ok: true, path: "f", content: "hello" } } ); // Binary bytes → { ok, path, binary: true } with NO content field. const binary = Buffer.from([0xff, 0xfe, 0x01]).toString("base64"); assert.deepStrictEqual( renderFsReadOutcome({ kind: "ok", status: 200, json: { ok: true, content: binary } }, "f", { variant: "panel" }), { status: 200, json: { ok: true, path: "f", binary: true } } ); // A non-string content field is treated as "" (the former route's typeof guard). assert.deepStrictEqual( renderFsReadOutcome({ kind: "ok", status: 200, json: { ok: true, content: null } }, "f", { variant: "panel" }), { status: 200, json: { ok: true, path: "f", content: "" } } ); }); test("renderFsReadOutcome relay variant: NO 404 branch, no ok:true (spec §3)", () => { // The former nodes.js /file relay had no 404 branch — a missing file is // node_read_failed there. Pinned so a naive "unify on the panel shape" // cannot change the relay's contract. assert.deepStrictEqual( renderFsReadOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, "f", { variant: "relay" }), { status: 502, json: { error: "node_read_failed" } } ); // Success shapes without ok:true. const text = Buffer.from("hello", "utf8").toString("base64"); assert.deepStrictEqual( renderFsReadOutcome({ kind: "ok", status: 200, json: { ok: true, content: text } }, "f", { variant: "relay" }), { status: 200, json: { path: "f", content: "hello" } } ); const binary = Buffer.from([0xff, 0xfe, 0x01]).toString("base64"); assert.deepStrictEqual( renderFsReadOutcome({ kind: "ok", status: 200, json: { ok: true, content: binary } }, "f", { variant: "relay" }), { status: 200, json: { path: "f", binary: true } } ); // failed + too_large are shared with the panel bodies. assert.deepStrictEqual( renderFsReadOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, "f", { variant: "relay" }), { status: 502, json: { error: "node_read_failed" } } ); assert.deepStrictEqual( renderFsReadOutcome({ kind: "too_large", status: 0, json: null }, "f", { variant: "relay" }), { status: 502, json: { error: "node_response_too_large", message: "This file is too large to open in the editor: the node's response exceeded the panel's response size limit. Download the file instead." } } ); }); // --------------------------------------------------------------------------- // renderFsStreamOutcome — the panel-only text/plain end() contract (spec §2) // --------------------------------------------------------------------------- test("renderFsStreamOutcome keeps the exact plain-text bodies and the 200 text contract", () => { assert.deepStrictEqual( renderFsStreamOutcome({ kind: "not_found", status: 404, json: null }), { status: 404, text: "file not found" } ); assert.deepStrictEqual( renderFsStreamOutcome({ kind: "too_large", status: 0, json: null }), { status: 502, text: "This file is too large to stream: the node's response exceeded the panel's response size limit." } ); // failed AND offline fall to the generic body: the former route had no // node_offline branch (status 0 fell through `status !== 200`). assert.deepStrictEqual( renderFsStreamOutcome({ kind: "failed", status: 500, json: { error: "boom" } }), { status: 502, text: "node-read-failed" } ); assert.deepStrictEqual( renderFsStreamOutcome({ kind: "offline", status: 0, json: null }), { status: 502, text: "node-read-failed" } ); // Success: the raw utf8 content (empty string preserved), served by the // route with Content-Type text/plain; charset=utf-8 on the 200 path only. assert.deepStrictEqual( renderFsStreamOutcome({ kind: "ok", status: 200, json: { ok: true, content: "line1\nline2" } }), { status: 200, text: "line1\nline2" } ); assert.deepStrictEqual( renderFsStreamOutcome({ kind: "ok", status: 200, json: { ok: true, content: null } }), { status: 200, text: "" } ); // There is NO relay stream contract (spec §3 has no stream relay) — a relay // request is a programming error, not an inventable body. assert.throws(() => renderFsStreamOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "relay" }), /no relay-variant stream contract/); }); // --------------------------------------------------------------------------- // renderFsWriteOutcome — spec §2 (panel) and §3 (relay) wire bodies // --------------------------------------------------------------------------- const WRITE_LIMIT_413 = { error: "File exceeds the 10 MB editor limit — upload the file instead.", message: "File exceeds the 10 MB editor limit — upload the file instead.", code: "file_too_large", limit_mb: 10, }; const WRITE_BASE64_413 = { error: "Binary file exceeds the ~7.4 MB editor save limit (base64 content must fit the node's 10 MB request body) — upload the file instead.", message: "Binary file exceeds the ~7.4 MB editor save limit (base64 content must fit the node's 10 MB request body) — upload the file instead.", code: "file_too_large", limit_mb: 7.4, }; const QUOTA_JSON = { ok: false, error: "disk_limit_exceeded" }; test("renderFsWriteOutcome panel variant: byte-exact bodies for every trigger (spec §2)", () => { // Success: { ok: true }. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "ok", status: 200, json: { ok: true, existed: true } }, { variant: "panel" }), { status: 200, json: { ok: true } } ); // 507 quota passthrough: the daemon's body relayed verbatim. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant: "panel" }), { status: 507, json: QUOTA_JSON } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 507, json: { ok: false, error: "disk_capacity_exceeded" } }, { variant: "panel" }).json.error, "disk_capacity_exceeded" ); // Daemon-400 "content too large" marker → the same 413 as the pre-dial // check; the message tracks the encoding. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 400, json: { error: "content too large (max 10MB)" } }, { variant: "panel" }), { status: 413, json: WRITE_LIMIT_413 } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 400, json: { error: "content too large (max 10MB)" } }, { variant: "panel", base64: true }), { status: 413, json: WRITE_BASE64_413 } ); // A daemon 400 WITHOUT the marker is a generic failure (502), never a 413. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 400, json: { error: "invalid JSON body" } }, { variant: "panel" }), { status: 502, json: { error: "node_write_failed" } } ); // 409 → 403 files_write permission shape ("not authorized" on the panel). assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 409, json: { error: "exists" } }, { variant: "panel" }), { status: 403, json: { error: "not authorized", permission: "files_write", detail: "overwriting existing files requires the files_write permission" } } ); // 404 + existed === false → 403 files_create permission shape. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "not_found", status: 404, json: { existed: false } }, { variant: "panel" }), { status: 403, json: { error: "not authorized", permission: "files_create", detail: "creating new files requires the files_create permission" } } ); // A 404 WITHOUT existed === false is a generic failure (the former route's // `status !== 200 || !json || !json.ok` fall-through). assert.deepStrictEqual( renderFsWriteOutcome({ kind: "not_found", status: 404, json: { error: "nope" } }, { variant: "panel" }), { status: 502, json: { error: "node_write_failed" } } ); // failed / offline / too_large dials → 502 node_write_failed. assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant: "panel" }), { status: 502, json: { error: "node_write_failed" } } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "offline", status: 0, json: null }, { variant: "panel" }), { status: 502, json: { error: "node_write_failed" } } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "too_large", status: 0, json: null }, { variant: "panel" }), { status: 502, json: { error: "node_write_failed" } } ); }); test("renderFsWriteOutcome relay variant: permission-denied bodies (spec §3/D6), shared 413/507/success", () => { // 409 → 403 "permission denied" (the relay's wording). assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 409, json: { error: "exists" } }, { variant: "relay" }), { status: 403, json: { error: "permission denied", permission: "files_write", detail: "overwriting existing files requires the files_write permission" } } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "not_found", status: 404, json: { existed: false } }, { variant: "relay" }), { status: 403, json: { error: "permission denied", permission: "files_create", detail: "creating new files requires the files_create permission" } } ); // 413/507/502/success bodies are shared with the panel (the *_NODES // constant twins were consolidated in Step A). assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 400, json: { error: "content too large (max 10MB)" } }, { variant: "relay", base64: true }), { status: 413, json: WRITE_BASE64_413 } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant: "relay" }), { status: 507, json: QUOTA_JSON } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "relay" }), { status: 200, json: { ok: true } } ); assert.deepStrictEqual( renderFsWriteOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant: "relay" }), { status: 502, json: { error: "node_write_failed" } } ); }); // --------------------------------------------------------------------------- // renderFsMkdirOutcome — panel-only (the relay's folder creation is POST // /create, rendered by renderFsCreateOutcome) // --------------------------------------------------------------------------- test("reviewed writes and deletes distinguish an old node's refusal from an unconfirmed transport failure", () => { const opts = { variant: "panel", reviewed: true, versionChecked: true }; for (const [render, error] of [[renderFsWriteOutcome, "invalid JSON body"], [renderFsWriteOutcome, "bad json or content too large (max 10MB)"], [renderFsDeleteOutcome, "bad json"]]) { assert.deepStrictEqual(render({ kind: "failed", status: 400, json: { error } }, opts), { status: 409, json: { error: "node_review_update_required" } }); assert.equal(render({ kind: "offline", status: 0, json: null }, opts).status, 502); assert.deepStrictEqual(render({ kind: "failed", status: 403, json: { error: "private node detail" } }, opts), { status: 403, json: { error: "review_file_rejected" } }); } }); test("renderFsMkdirOutcome panel variant: 409 → already_exists, no 404 branch, 507 passthrough", () => { assert.deepStrictEqual( renderFsMkdirOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "panel" }), { status: 200, json: { ok: true } } ); assert.deepStrictEqual( renderFsMkdirOutcome({ kind: "failed", status: 409, json: { error: "exists" } }, { variant: "panel" }), { status: 400, json: { error: "already_exists" } } ); // A daemon 404 on the .keep write is a generic mkdir failure — NOT the // write renderer's 403 files_create mapping. assert.deepStrictEqual( renderFsMkdirOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, { variant: "panel" }), { status: 502, json: { error: "node_mkdir_failed" } } ); assert.deepStrictEqual( renderFsMkdirOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant: "panel" }), { status: 507, json: QUOTA_JSON } ); assert.deepStrictEqual( renderFsMkdirOutcome({ kind: "offline", status: 0, json: null }, { variant: "panel" }), { status: 502, json: { error: "node_mkdir_failed" } } ); // No relay-variant mkdir contract exists (spec §3): the relay's folder // creation is POST /create. assert.throws(() => renderFsMkdirOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "relay" }), /no relay-variant mkdir contract/); }); // --------------------------------------------------------------------------- // renderFsDeleteOutcome — byte-identical on both surfaces (verified), no 404 // and no 507 branch // --------------------------------------------------------------------------- test("renderFsDeleteOutcome: any non-ok outcome is 502 node_delete_failed on BOTH variants", () => { for (const variant of ["panel", "relay"]) { assert.deepStrictEqual( renderFsDeleteOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant }), { status: 200, json: { ok: true } } ); assert.deepStrictEqual( renderFsDeleteOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant }), { status: 502, json: { error: "node_delete_failed" } } ); // No 404 branch: a missing path is a delete failure like any other. assert.deepStrictEqual( renderFsDeleteOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, { variant }), { status: 502, json: { error: "node_delete_failed" } } ); // No 507 branch: the daemon does not quota a delete (neither former route // mapped one — a 507 must NOT pass through verbatim here). assert.deepStrictEqual( renderFsDeleteOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant }), { status: 502, json: { error: "node_delete_failed" } } ); assert.deepStrictEqual( renderFsDeleteOutcome({ kind: "offline", status: 0, json: null }, { variant }), { status: 502, json: { error: "node_delete_failed" } } ); } }); // --------------------------------------------------------------------------- // renderFsDeleteBatchOutcome — the RELAY-ONLY op (spec D29): keyed on status // 200 + parseable body (NOT the daemon's ok flag — a partial-success envelope // relays verbatim), everything else 502 node_batch_delete_failed // --------------------------------------------------------------------------- test("renderFsDeleteBatchOutcome: 200 envelope relays verbatim (ok:false included), non-200 is 502 node_batch_delete_failed", () => { // The daemon's 200 body is a per-item results envelope whose top-level // ok:false means PARTIAL success — the client must receive it verbatim, so // the renderer is keyed on status + parseable body, not on the ok flag. const partial = { ok: false, results: [{ path: "a.txt", ok: true }, { path: "b.txt", ok: false, error: "delete failed" }], success: 1, failed: 1 }; assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "failed", status: 200, json: partial }, { variant: "relay" }), { status: 200, json: partial } ); assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "ok", status: 200, json: { ok: true, results: [], success: 2, failed: 0 } }, { variant: "relay" }).json.failed, 0 ); // Every non-200 (daemon 404/400/5xx, offline, too-large) → 502. assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant: "relay" }), { status: 502, json: { error: "node_batch_delete_failed" } } ); assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "not_found", status: 404, json: { error: "x" } }, { variant: "relay" }), { status: 502, json: { error: "node_batch_delete_failed" } } ); assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "offline", status: 0, json: null }, { variant: "relay" }), { status: 502, json: { error: "node_batch_delete_failed" } } ); assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "too_large", status: 0, json: null }, { variant: "relay" }), { status: 502, json: { error: "node_batch_delete_failed" } } ); // A 200 with an unparseable body is a failure (the former route's `!json`). assert.deepStrictEqual( renderFsDeleteBatchOutcome({ kind: "failed", status: 200, json: null }, { variant: "relay" }), { status: 502, json: { error: "node_batch_delete_failed" } } ); // Relay-only: the panel has no delete-batch route to preserve (spec D29) — // a "panel" request is a programming error, not an inventable contract. assert.throws( () => renderFsDeleteBatchOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "panel" }), /delete-batch is a relay-only op/ ); }); // --------------------------------------------------------------------------- // renderFsRenameOutcome — byte-identical on both surfaces (verified); the // status-code OR error-text predicates and their precedence over ok // --------------------------------------------------------------------------- test("renderFsRenameOutcome: 409/404/400 mappings, error-text predicates, no 507 branch", () => { for (const variant of ["panel", "relay"]) { assert.deepStrictEqual( renderFsRenameOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant }), { status: 200, json: { ok: true } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 409, json: { error: "destination_exists" } }, { variant }), { status: 409, json: { error: "destination_exists" } } ); // The error-text predicate runs at ANY status, with precedence over ok — // matching the former routes' branch order. assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 500, json: { error: "destination_exists" } }, { variant }), { status: 409, json: { error: "destination_exists" } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "not_found", status: 404, json: { error: "source_not_found" } }, { variant }), { status: 404, json: { error: "source_not_found" } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 503, json: { error: "source_not_found" } }, { variant }), { status: 404, json: { error: "source_not_found" } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 400, json: { error: "bad" } }, { variant }), { status: 400, json: { error: "invalid path" } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant }), { status: 502, json: { error: "node_rename_failed" } } ); assert.deepStrictEqual( renderFsRenameOutcome({ kind: "offline", status: 0, json: null }, { variant }), { status: 502, json: { error: "node_rename_failed" } } ); // No 507 branch (neither former route mapped one). assert.deepStrictEqual( renderFsRenameOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant }), { status: 502, json: { error: "node_rename_failed" } } ); } }); // --------------------------------------------------------------------------- // renderFsExtractOutcome — D20: shared skipped>0 wording, per-surface // skipped===0 wording // --------------------------------------------------------------------------- test("renderFsExtractOutcome panel variant: shared skipped>0 msg, 'Extracted successfully' at 0", () => { assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true, skipped: 3 } }, { variant: "panel" }), { status: 200, json: { ok: true, msg: "Extracted with 3 existing file(s) skipped", skipped: 3 } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true, skipped: 0, msg: "daemon msg" } }, { variant: "panel" }), { status: 200, json: { ok: true, msg: "Extracted successfully", skipped: 0 } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true } }, { variant: "panel" }).json.skipped, 0, "a missing skipped field counts as 0 (Number(undefined || 0))" ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant: "panel" }), { status: 502, json: { error: "node_extract_failed" } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "offline", status: 0, json: null }, { variant: "panel" }), { status: 502, json: { error: "node_extract_failed" } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant: "panel" }), { status: 507, json: QUOTA_JSON } ); }); test("renderFsExtractOutcome relay variant: json.msg || 'Extracted' at skipped 0 (spec D20)", () => { assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true, skipped: 3 } }, { variant: "relay" }), { status: 200, json: { ok: true, msg: "Extracted with 3 existing file(s) skipped", skipped: 3 } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true, skipped: 0, msg: "daemon msg" } }, { variant: "relay" }), { status: 200, json: { ok: true, msg: "daemon msg", skipped: 0 } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "ok", status: 200, json: { ok: true, skipped: 0 } }, { variant: "relay" }), { status: 200, json: { ok: true, msg: "Extracted", skipped: 0 } } ); assert.deepStrictEqual( renderFsExtractOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, { variant: "relay" }), { status: 502, json: { error: "node_extract_failed" } } ); }); // --------------------------------------------------------------------------- // renderFsArchiveOutcome — byte-identical on both surfaces (verified): the // failure body relays the daemon's own error text // --------------------------------------------------------------------------- test("renderFsArchiveOutcome: daemon error text relayed on failure, { ok, path, name } on success", () => { for (const variant of ["panel", "relay"]) { assert.deepStrictEqual( renderFsArchiveOutcome({ kind: "ok", status: 200, json: { ok: true, path: "backups/w.zip", name: "w.zip" } }, { variant }), { status: 200, json: { ok: true, path: "backups/w.zip", name: "w.zip" } } ); assert.deepStrictEqual( renderFsArchiveOutcome({ kind: "failed", status: 500, json: { error: "7zip missing" } }, { variant }), { status: 502, json: { error: "7zip missing" } } ); assert.deepStrictEqual( renderFsArchiveOutcome({ kind: "failed", status: 500, json: null }, { variant }), { status: 502, json: { error: "archive failed" } } ); assert.deepStrictEqual( renderFsArchiveOutcome({ kind: "offline", status: 0, json: null }, { variant }), { status: 502, json: { error: "archive failed" } } ); assert.deepStrictEqual( renderFsArchiveOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, { variant }), { status: 507, json: QUOTA_JSON } ); } }); // --------------------------------------------------------------------------- // renderFsCreateLegacyOutcome (panel text) and renderFsCreateOutcome (relay // JSON) — spec §2/D10 vs §3 // --------------------------------------------------------------------------- test("renderFsCreateLegacyOutcome: TEXT bodies (already_exists, masked Create failed), JSON success", () => { assert.deepStrictEqual( renderFsCreateLegacyOutcome({ kind: "ok", status: 200, json: { ok: true } }, "world/notes.txt"), { status: 200, json: { ok: true, path: "world/notes.txt" } } ); assert.deepStrictEqual( renderFsCreateLegacyOutcome({ kind: "failed", status: 409, json: { error: "exists" } }, "w"), { status: 400, text: "already_exists" } ); // Generic failure: the former route threw Error("node-create-failed") into // the masked catch, whose raw-message fallback (spec D13) put exactly this // text on the wire. adpanel:path-error-mask removed the raw fallback, so the // generic failure now answers the route's masked default "Create failed" — // still through the shared masker, never the raw error text. assert.deepStrictEqual( renderFsCreateLegacyOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, "w"), { status: 400, text: "Create failed" } ); assert.deepStrictEqual( renderFsCreateLegacyOutcome({ kind: "offline", status: 0, json: null }, "w"), { status: 400, text: "Create failed" } ); assert.deepStrictEqual( renderFsCreateLegacyOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, "w"), { status: 507, json: QUOTA_JSON }, "the 507 quota passthrough stays JSON even on the text route" ); assert.throws( () => renderFsCreateLegacyOutcome({ kind: "ok", status: 200, json: { ok: true } }, "w", { variant: "relay" }), /legacy create text contract is panel-only/ ); }); test("renderFsCreateOutcome relay variant: JSON existence/failure bodies, no 409 special case", () => { assert.deepStrictEqual( renderFsCreateOutcome({ kind: "ok", status: 200, json: { ok: true } }, "world/notes.txt", { variant: "relay", type: "file" }), { status: 200, json: { ok: true, path: "world/notes.txt" } } ); // The daemon's existence error text (either spelling) → 400 already_exists // with the type-bearing message. assert.deepStrictEqual( renderFsCreateOutcome({ kind: "failed", status: 409, json: { error: "file already exists" } }, "w", { variant: "relay", type: "file" }), { status: 400, json: { error: "already_exists", message: "A file with that name already exists" } } ); assert.deepStrictEqual( renderFsCreateOutcome({ kind: "failed", status: 500, json: { error: "EEXIST" } }, "w", { variant: "relay", type: "folder" }), { status: 400, json: { error: "already_exists", message: "A folder with that name already exists" } } ); assert.deepStrictEqual( renderFsCreateOutcome({ kind: "failed", status: 500, json: { error: "disk full" } }, "w", { variant: "relay", type: "folder" }), { status: 502, json: { error: "node_create_failed", message: "Failed to create folder. It may already exist." } } ); assert.deepStrictEqual( renderFsCreateOutcome({ kind: "offline", status: 0, json: null }, "w", { variant: "relay", type: "file" }), { status: 502, json: { error: "node_create_failed", message: "Failed to create file. It may already exist." } } ); assert.deepStrictEqual( renderFsCreateOutcome({ kind: "failed", status: 507, json: QUOTA_JSON }, "w", { variant: "relay", type: "file" }), { status: 507, json: QUOTA_JSON } ); assert.throws( () => renderFsCreateOutcome({ kind: "ok", status: 200, json: { ok: true } }, "w", { variant: "panel" }), /JSON create contract is the relay's/ ); }); test("renderFsRenameLegacyOutcome: TEXT bodies incl. the 500 'Rename failed' generic", () => { assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "ok", status: 200, json: { ok: true } }, "world/renamed.txt"), { status: 200, json: { ok: true, path: "world/renamed.txt" } } ); assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "failed", status: 409, json: { error: "destination_exists" } }, "w"), { status: 409, text: "A file with that name already exists" } ); assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "not_found", status: 404, json: { error: "source_not_found" } }, "w"), { status: 404, text: "Source not found" } ); assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "failed", status: 400, json: { error: "bad" } }, "w"), { status: 400, text: "Invalid path" } ); // Note the legacy route's own generic: 500 "Rename failed", not 502. assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "failed", status: 500, json: { error: "boom" } }, "w"), { status: 500, text: "Rename failed" } ); assert.deepStrictEqual( renderFsRenameLegacyOutcome({ kind: "offline", status: 0, json: null }, "w"), { status: 500, text: "Rename failed" } ); assert.throws( () => renderFsRenameLegacyOutcome({ kind: "ok", status: 200, json: { ok: true } }, "w", { variant: "relay" }), /legacy rename text contract is panel-only/ ); }); // --------------------------------------------------------------------------- // Structural: the index.js GET routes ride the shared core; download does not // --------------------------------------------------------------------------- const INDEX_SRC = fs.readFileSync(INDEX_JS, "utf8"); function routeWindow(regPrefix, label) { const start = INDEX_SRC.indexOf(regPrefix); assert.notStrictEqual(start, -1, `${label}: route anchor not found: ${regPrefix}`); const re = /^app\.(?:get|post|put|delete|patch|all|use)\s*\(/gm; re.lastIndex = start + 1; let end = INDEX_SRC.length; let m; while ((m = re.exec(INDEX_SRC)) !== null) { end = m.index; break; } return INDEX_SRC.slice(start, end); } test("index.js /files/list dials through relayFsJson (60000 parity) and renders variant panel", () => { const w = routeWindow('app.get("/api/servers/:name/files/list"', "files list"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/list"[\s\S]{0,400}?,\s*60_?000\s*[,)]/, "the list relay must keep the 60000 timeout parity"); assert.match(w, /buildFsListPayload\(dir, ctx\.serverName, "panel"\)/); assert.match(w, /renderFsListOutcome\(outcome, rel, \{ variant: "panel" \}\)/); assert.ok(!w.includes("nodeFsPost("), "the list route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/read dials through relayFsJson (120000 parity) and renders variant panel", () => { const w = routeWindow('app.get("/api/servers/:name/files/read"', "files read"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/read"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the read relay must keep the 120000 timeout parity"); assert.match(w, /encoding: "base64"/); assert.match(w, /renderFsReadOutcome\(outcome, rel, \{ variant: "panel" \}\)/); assert.ok(!w.includes("nodeFsPost("), "the read route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/stream dials through relayFsJson (120000 parity) and renders variant panel", () => { const w = routeWindow('app.get("/api/servers/:name/files/stream"', "files stream"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/read"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the stream relay must keep the 120000 timeout parity"); assert.match(w, /encoding: "utf8"/); assert.match(w, /renderFsStreamOutcome\(outcome, \{ variant: "panel" \}\)/); assert.match(w, /Content-Type", "text\/plain; charset=utf-8"/, "the 200 path keeps the route-side text/plain header"); assert.ok(!w.includes("nodeFsPost("), "the stream route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/download stays the raw stream proxy this wave (not on the JSON core)", () => { const w = routeWindow('app.get("/api/servers/:name/files/download"', "files download"); assert.ok(!w.includes("relayFsJson"), "the download proxy is a raw stream, not a JSON relay — its migration is a later step and must be done consciously"); assert.match(w, /assertNodeUrlHostAllowed\(/, "the raw proxy keeps its own SSRF pre-flight"); }); // --------------------------------------------------------------------------- // Structural (Wave 2 Step B2): the eight mutating fs routes ride the shared // core; their per-route guards stayed put // --------------------------------------------------------------------------- test("index.js /files/write dials through relayFsJson (120000 parity), renders variant panel, keeps the pre-dial 413 check", () => { const w = routeWindow('app.put("/api/servers/:name/files/write"', "files write"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/write"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the write relay must keep the 120000 timeout parity"); assert.match(w, /nodeFsWritePayloadTooLarge\(writePayload\)/, "the pre-dial 413 payload check stays in the route (input validation, not response mapping)"); assert.match(w, /renderFsWriteOutcome\(outcome, \{ variant: "panel", base64: !!contentBase64, editorGuard: !!writePayload\.editorBaseSha256 \}\)/); assert.ok(!w.includes("nodeFsPost("), "the write route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/mkdir dials through relayFsJson (120000 parity) and keeps its byte-exact .keep payload", () => { const w = routeWindow('app.post("/api/servers/:name/files/mkdir"', "files mkdir"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/write"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the mkdir relay must keep the 120000 write-timeout parity"); assert.match( w, /buildFsCreatePayload\(full, ctx\.serverName, \{ directory: true \}\)/, "the mkdir route uses the shared create-only directory payload" ); assert.strictEqual(JSON.stringify(buildFsCreatePayload("/vols/srv/folder", "srv", { directory: true })), '{"path":"/vols/srv/folder/.keep","server":"srv","content":"","encoding":"utf8","mode":"create"}'); assert.match(w, /renderFsMkdirOutcome\(outcome, \{ variant: "panel" \}\)/); assert.ok(!w.includes("nodeFsPost("), "the mkdir route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/delete dials through relayFsJson (120000 parity) and keeps its root refusal", () => { const w = routeWindow('app.delete("/api/servers/:name/files/delete"', "files delete"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/delete"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the delete relay must keep the 120000 timeout parity"); assert.match(w, /isServerRootResolvedPath\(ctx\.baseDir, full\)/, "the root refusal stays per-route"); assert.match(w, /renderFsDeleteOutcome\(outcome, \{ variant: "panel" \}\)/); assert.ok(!w.includes("nodeFsPost("), "the delete route must not keep a parallel nodeFsPost dial"); }); test("index.js /files/rename dials probe (60000) + rename (120000) through relayFsJson and renders variant panel", () => { // Note: this window (next app. anchor) also spans the adjacent // streamPanelUploadToNode/runDeferredServerImport helpers, whose OWN // nodeFsPost dials are out of scope this wave — so the "no parallel dial" // assertions below pin the former probe/rename dial SHAPES, not the whole // window. const w = routeWindow('app.post("/api/servers/:name/files/rename"', "files rename"); assert.match(w, /const probe = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/list"[\s\S]{0,400}?,\s*60_?000\s*[,)]/, "the rename probe must keep the 60000 list-timeout parity"); // The probe's daemon-facing body is deliberately NOT buildFsListPayload's // panel shape: it has always carried depth: 1 in this key order. assert.match(w, /\{ path: path\.posix\.dirname\(dest\), depth: 1, server: ctx\.serverName \}/, "the probe payload must stay byte-identical"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/rename"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the rename relay must keep the 120000 timeout parity"); assert.match(w, /renderFsRenameOutcome\(outcome, \{ variant: "panel" \}\)/); assert.ok(!w.includes('await nodeFsPost(ctx.node, "/v1/fs/list"'), "the rename route must not keep a parallel nodeFsPost probe dial"); assert.ok(!w.includes('await nodeFsPost(ctx.node, "/v1/fs/rename"'), "the rename route must not keep a parallel nodeFsPost rename dial"); }); test("index.js /extract dials through relayFsJson (630000 parity) and renders variant panel", () => { const w = routeWindow('app.post("/extract"', "extract"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/extract"[\s\S]{0,400}?,\s*630_?000\s*[,)]/, "the extract relay must keep the 630000 timeout parity (daemon's 10m budget + 30s relay slack)"); assert.match(w, /overwrite: canOverwrite/, "overwrite stays permission-derived in the route (adpanel:extract-no-clobber)"); assert.match(w, /method: nodeNoClobberMethod\(!canOverwrite\)/, "restricted extraction cannot use the legacy method"); assert.match(w, /renderFsExtractOutcome\(outcome, \{ variant: "panel", noClobber: !canOverwrite \}\)/); assert.ok(!w.includes("nodeFsPost("), "the extract route must not keep a parallel nodeFsPost dial"); }); test("index.js /archive dials through relayFsJson (330000 parity) and keeps its canonical URL segment", () => { const w = routeWindow('app.post("/archive"', "archive"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /\/v1\/servers\/\$\{botSeg\}\/files\/archive[\s\S]{0,400}?,\s*330_?000\s*[,)]/, "the archive relay must keep the 330000 timeout parity (daemon's 5m budget + 30s relay slack)"); assert.match(w, /const botSeg = encodeURIComponent\(ctx\.serverName\);/, "the canonical URL segment stays panel-shaped (spec D23)"); assert.match(w, /renderFsArchiveOutcome\(outcome, \{ variant: "panel" \}\)/); assert.ok(!w.includes("nodeFsPost("), "the archive route must not keep a parallel nodeFsPost dial"); }); test("index.js legacy /create dials through relayFsJson (120000 parity) and keeps its text-vs-JSON dispatch", () => { const w = routeWindow('app.post("/create"', "legacy create"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/write"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the legacy create relay must keep the 120000 write-timeout parity"); assert.match(w, /renderFsCreateLegacyOutcome\(outcome, relativePosix\)/); assert.match(w, /if \("json" in out\) return res\.status\(out\.status\)\.json\(out\.json\);/, "the legacy route keeps its text-vs-JSON dispatch"); assert.ok(!w.includes("nodeFsPost("), "the legacy create route must not keep a parallel nodeFsPost dial"); }); test("index.js legacy /rename dials probe (60000) + rename (120000) through relayFsJson with text dispatch", () => { const w = routeWindow('app.post("/rename"', "legacy rename"); assert.match(w, /const probe = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/list"[\s\S]{0,400}?,\s*60_?000\s*[,)]/, "the legacy rename probe must keep the 60000 list-timeout parity"); assert.match(w, /\{ path: path\.posix\.dirname\(dest\), depth: 1, server: ctx\.serverName \}/, "the probe payload must stay byte-identical"); assert.match(w, /"\/v1\/fs\/rename"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the legacy rename relay must keep the 120000 timeout parity"); assert.match(w, /renderFsRenameLegacyOutcome\(outcome, relative\)/); assert.match(w, /if \("json" in out\) return res\.status\(out\.status\)\.json\(out\.json\);/, "the legacy route keeps its text-vs-JSON dispatch"); assert.ok(!w.includes("nodeFsPost("), "the legacy rename route must not keep a parallel nodeFsPost dial"); }); // --------------------------------------------------------------------------- // Structural (Wave 2 Step B3): nodes.js's nine server-scoped fs relays ride // the shared core; their per-route guards stayed put // --------------------------------------------------------------------------- const NODES_SRC = fs.readFileSync(NODES_JS, "utf8"); function nodesRouteWindow(regPrefix, label) { const start = NODES_SRC.indexOf(regPrefix); assert.notStrictEqual(start, -1, `${label}: route anchor not found: ${regPrefix}`); const re = /^app\.(?:get|post|put|delete|patch|all|use)\s*\(/gm; re.lastIndex = start + 1; let end = NODES_SRC.length; let m; while ((m = re.exec(NODES_SRC)) !== null) { end = m.index; break; } return NODES_SRC.slice(start, end); } // The nodes-side dial-deps binding: byte-identical to nodeUrl's + nodeHeaders' // outputs, dialed through the shared hardened httpRequestJson (relayFsJson's // default dial — the SSRF pre-flight/guarded lookup/aborted-listener/hard-timer // posture lives in that core's node branch). test("nodes.js binds NODES_FS_RELAY_DEPS to its exact nodeUrl/nodeHeaders flavors", () => { const at = NODES_SRC.indexOf("const NODES_FS_RELAY_DEPS = {"); assert.notStrictEqual(at, -1, "expected the NODES_FS_RELAY_DEPS binding"); // Window bounded to the deps object literal itself (not a fixed 900-char // spill into whatever follows): the assertions below are exact-match / // negative pins on the binding, and a future comment that merely MENTIONS // a pinned identifier must not trip them. const close = NODES_SRC.indexOf("};", at); assert.notStrictEqual(close, -1, "expected the NODES_FS_RELAY_DEPS closing brace"); const w = NODES_SRC.slice(at, close + 2); assert.match( w, /buildNodeBaseUrl: \(node\) => buildNodeBaseUrl\(node\.address, node\.api_port, node\.ssl_enabled, nodeUnderCloudflare\(node\)\)/, "the base-URL flavor must stay byte-identical to nodeUrl's (clampPort, plain-http default, toString-minus-trailing-slash form)" ); assert.match( w, /buildNodeAuthHeaders: \(node\) => Object\.assign\(\{ "Content-Type": "application\/json" \}, nodeHeaders\(node\)\)/, "the header shape must stay Content-Type + nodeHeaders (X-Node-Token-Id always present, possibly empty)" ); // The former dials' D1/D2 hardening comes from the shared core — never from // a local reimplementation. assert.ok(!/res\.on\("aborted"\)/.test(w), "nodes.js must not grow a private relay dialer; the listeners live in services/node-http.js"); // Regression-hole closure (relay dial arity): relayFsJson dials POSITIONALLY // with SIX args through `deps.httpRequestJson || httpRequestJson` — // (url, "POST", headers, payload, timeoutMs, maxBytes) — while nodes.js's // LOCAL httpRequestJson GET-probe shim is a FOUR-arg wrapper // (fullUrl, method, headers, timeoutMs). A future regression adding // `httpRequestJson: httpRequestJson` to this deps object would pass every // test in this file while breaking every relay dial: the payload would land // in the shim's timeoutMs slot and the real timeout would be dropped. The // fallback to the hardened services/node-http.js core is load-bearing, so // pin the binding's absence: assert.ok(!/httpRequestJson:/.test(w), "NODES_FS_RELAY_DEPS must NOT bind httpRequestJson — the local 4-arg GET-probe shim is arity-incompatible with relayFsJson's positional 6-arg core dial (payload lands in the timeout slot); the hardened core fallback is load-bearing"); }); test("nodes.js /entries dials through relayFsJson (60000 parity) and renders variant relay with mapFsEntries", () => { const w = nodesRouteWindow('app.get("/api/nodes/server/:name/entries"', "entries"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /buildFsListPayload\(full, ctx\.nodeServerName, "relay"\)/, "the relay list body keeps depth:1 via buildFsListPayload (spec D3)"); assert.match(w, /"\/v1\/fs\/list"[\s\S]{0,400}?,\s*60_?000\s*[,)]/, "the list relay must keep the 60000 timeout parity"); assert.match(w, /renderFsListOutcome\(outcome, rel, \{ variant: "relay", entryMapper: mapFsEntries \}\)/, "entries keep the nodes.js shape via the injected mapper (spec D4)"); assert.ok(!w.includes("httpJson("), "the entries relay must not keep a parallel httpJson dial"); }); test("nodes.js /file GET dials through relayFsJson (120000 parity) and renders variant relay", () => { const w = nodesRouteWindow('app.get("/api/nodes/server/:name/file"', "file GET"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/read"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the read relay must keep the 120000 timeout parity"); assert.match(w, /encoding: "base64"/); assert.match(w, /renderFsReadOutcome\(outcome, rel, \{ variant: "relay" \}\)/, "the relay read has no 404 branch and no ok:true (spec §3)"); assert.ok(!w.includes("httpJson("), "the file GET relay must not keep a parallel httpJson dial"); }); test("nodes.js /file POST dials through relayFsJson (120000 parity), renders variant relay, keeps recordActivity", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/file"', "file POST"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/write"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the write relay must keep the 120000 timeout parity"); assert.match(w, /renderFsWriteOutcome\(outcome, \{ variant: "relay", base64: !!contentBase64, editorGuard: !!writePayload\.editorBaseSha256 \}\)/, "permission and guarded-save refusals use the shared renderer"); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_edit"/, "the file_edit activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the file POST relay must not keep a parallel httpJson dial"); assert.match(w, /if \(!attachEditorWriteHash\(writePayload, req\.body\?\.expectedSha256\)\) \{\s*return res\.status\(400\)/); assert.ok(w.indexOf("attachEditorWriteHash(writePayload") < w.indexOf('"/v1/fs/write"'), "the hash is included in the same write the daemon bounds"); assert.doesNotMatch(w, /verifyNodeFileUnchanged|"\/v1\/fs\/read"/, "the write itself carries the precondition"); }); test("nodes.js /delete dials through relayFsJson (120000 parity), keeps body-only input + root refusal", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/delete"', "delete"); assert.match(w, /const rel = String\(req\.body\.path \|\| ""\);/, "the body-only input contract stays (spec D8)"); assert.match(w, /const isDir = !!req\.body\.isDir;/, "isDir stays a strict boolean (spec D8)"); assert.match(w, /isServerRootResolvedPath\(ctx\.baseDir, full\)/, "the root refusal stays per-route"); assert.match(w, /"\/v1\/fs\/delete"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the delete relay must keep the 120000 timeout parity"); assert.match(w, /renderFsDeleteOutcome\(outcome, \{ variant: "relay" \}\)/); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_delete"/, "the file_delete activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the delete relay must not keep a parallel httpJson dial"); }); test("nodes.js /delete-batch dials through relayFsJson (120000 parity), keeps the ≤500 + root-refusal-aborts-batch guards", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/delete-batch"', "delete-batch"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/delete-batch"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the delete-batch relay must keep the 120000 timeout parity"); assert.match(w, /items\.length > 500/, "the ≤500 guard stays route-side (spec D29)"); assert.match(w, /fullItems\.some\(item => isServerRootResolvedPath\(ctx\.baseDir, item\.path\)\)/, "a root-resolving entry aborts the whole batch (spec D29)"); assert.match(w, /renderFsDeleteBatchOutcome\(outcome, \{ variant: "relay" \}\)/, "the relay-only renderer is consumed with the relay variant"); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_delete_batch"/, "the file_delete_batch activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the delete-batch relay must not keep a parallel httpJson dial"); }); test("nodes.js /rename dials probe (60000) + rename (120000) through relayFsJson and keeps the D9 fallback sanitizer verbatim", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/rename"', "rename"); assert.match(w, /const probe = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/list"[\s\S]{0,400}?,\s*60_?000\s*[,)]/, "the rename probe must keep the 60000 list-timeout parity"); assert.match(w, /\{ path: path\.posix\.dirname\(dest\), depth: 1, server: ctx\.nodeServerName \}/, "the probe payload must stay byte-identical"); assert.match(w, /"\/v1\/fs\/rename"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the rename relay must keep the 120000 timeout parity"); assert.match(w, /renderFsRenameOutcome\(outcome, \{ variant: "relay" \}\)/); // FLAGGED DIVERGENCE (spec D9): the newName derivation with its // sanitizeUploadFilename-then-strict-sanitizer fallback stays VERBATIM — // it must not be "fixed" to the canonical sanitizer in this step. // adpanel:sanitizer-lockstep — the fallback slot now binds the // utils/server-name.js storage mirror: the drifted nodes.js-local 100-cap // sanitizeName was the AGENTS.md-forbidden third server-name copy and is // deleted; the fallback remains a strict local sanitizer distinct from the // canonical file-name hook, which wins whenever injected. assert.match( w, /const newName = _sanitizeUploadFilename \? \(_sanitizeUploadFilename\(rawNewName\) \|\| ""\) : sanitizeNodeStorageName\(rawNewName\);/, "the D9 fallback-sanitizer derivation must stay verbatim (fallback = storage mirror, not the canonical hook)" ); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_rename"/, "the file_rename activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the rename relay must not keep a parallel httpJson dial"); }); test("nodes.js /extract dials through relayFsJson (630000 parity), keeps canOverwrite route-side", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/extract"', "extract"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/extract"[\s\S]{0,400}?,\s*630_?000\s*[,)]/, "the extract relay must keep the 630000 timeout parity (daemon's 10m budget + 30s relay slack)"); assert.match(w, /overwrite: canOverwrite/, "overwrite stays permission-derived in the route (adpanel:extract-no-clobber, spec D21)"); assert.match(w, /method: nodeNoClobberMethod\(!canOverwrite\)/, "restricted extraction cannot use the legacy method"); assert.match(w, /renderFsExtractOutcome\(outcome, \{ variant: "relay", noClobber: !canOverwrite \}\)/, "the skipped===0 msg stays json.msg || 'Extracted' (spec D20)"); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_extract"/, "the file_extract activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the extract relay must not keep a parallel httpJson dial"); }); test("nodes.js /archive dials through relayFsJson (330000 parity) and keeps its canonical URL segment", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/archive"', "archive"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /\/v1\/servers\/\$\{encodeURIComponent\(canonicalArchiveName\)\}\/files\/archive[\s\S]{0,400}?,\s*330_?000\s*[,)]/, "the archive relay must keep the 330000 timeout parity (daemon's 5m budget + 30s relay slack)"); assert.match( w, /const canonicalArchiveName = getCanonicalServerName\(ctx\.server, req\.params\.name\) \|\| req\.params\.name;/, "the canonical URL segment stays route-side (spec D23)" ); assert.match(w, /renderFsArchiveOutcome\(outcome, \{ variant: "relay" \}\)/); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), "file_archive"/, "the file_archive activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the archive relay must not keep a parallel httpJson dial"); }); test("nodes.js /create dials through relayFsJson (120000 parity) and keeps the D11 name sanitizer", () => { const w = nodesRouteWindow('app.post("/api/nodes/server/:name/create"', "create"); assert.match(w, /const outcome = await relayFsJson\(/); assert.match(w, /"\/v1\/fs\/write"[\s\S]{0,400}?,\s*120_?000\s*[,)]/, "the create relay must keep the 120000 write-timeout parity"); assert.match( w, /buildFsCreatePayload\(target, ctx\.nodeServerName, \{ directory: typeRaw === "folder" \}\)/, "the relay shares mkdir's directory payload and only uses it for folders" ); assert.strictEqual(JSON.stringify(buildFsCreatePayload("/vols/srv/file", "srv")), '{"path":"/vols/srv/file","server":"srv","content":"","encoding":"utf8","mode":"create"}'); // adpanel:sanitizer-lockstep — the route-side file-name sanitizer binds the // canonical file-name mirror (utils/upload-filename.js): leading dots (.env) // and valid non-ASCII stay, matching the panel POST /create route and the // daemon's upload naming. The drifted local sanitizeName it replaced was // the AGENTS.md-forbidden third server-name copy (it happened to keep // dots, but mangled spaces/unicode and capped at 100). Route-side // placement — the D11 divergence — is unchanged. assert.match(w, /const safeName = sanitizeUploadFilename\(nameRaw\);/, "the D11 file-name sanitizer stays route-side (flagged divergence)"); assert.match(w, /renderFsCreateOutcome\(outcome, relativePosix, \{ variant: "relay", type: typeRaw \}\)/); assert.match(w, /recordActivity\(getCanonicalServerName\(ctx\.server, req\.params\.name\), actionType/, "the folder_create/file_create activity entry stays (spec D30)"); assert.ok(!w.includes("httpJson("), "the create relay must not keep a parallel httpJson dial"); }); test("nodes.js defines no local sanitizeName copy (adpanel:sanitizer-lockstep) — storage derivations bind the utils/server-name.js mirror", () => { // The drift this pin forbids: nodes.js once carried its own sanitizeName // (100-char cap, no "-_." two-end trim, no leading non-alphanumeric strip) // — a third copy of the Go sanitizeName server-name sanitizer beside // utils/server-name.js sanitizeNodeStorageName (the AGENTS.md one-true-home // and C7-verified lockstep twin). For a 101-120-char legacy name it // truncated ctx.nodeServerName and every dial/baseDir derived from it at // 100 while the daemon's actual storage name is the 120-form, so the file // manager and backups broke for exactly those rows. The local copy is // deleted and must not return. assert.doesNotMatch(NODES_SRC, /function\s+sanitizeName\s*\(/, "nodes.js must not define its own sanitizeName (the drift cannot return)"); assert.match( NODES_SRC, /const nodeServerName = sanitizeNodeStorageName\(srv\.name \|\| serverName\);/, "remoteContext derives ctx.nodeServerName through the mirror (dial/baseDir parity with the daemon's Go form)" ); assert.match(NODES_SRC, /require\("\.\/utils\/server-name"\)/, "the mirror import stays"); // Behavioral: a 110-char fixed-point name (alnum start, only [\w-.] inside, // no leading/trailing "-_.") derives the daemon's full 120-form — the // deleted 100-cap drift truncated it. const { sanitizeNodeStorageName } = require("../utils/server-name"); const longFixedPoint = "srv-" + "a".repeat(106); // 110 chars, fixed point of the mirror assert.strictEqual(sanitizeNodeStorageName(longFixedPoint), longFixedPoint, "a 110-char fixed-point name derives whole (120-cap mirror, not the deleted 100-cap drift)"); }); test("nodes.js keeps its per-surface helpers OFF the shared core where B3 deliberately did not migrate them", () => { const dl = nodesRouteWindow('app.get("/api/nodes/server/:name/download"', "download"); assert.ok(!dl.includes("relayFsJson"), "the download proxy is a raw stream, not a JSON relay — its migration is a later step"); const uploadUrlAt = NODES_SRC.indexOf('nodeUrl(ctx.node, "/v1/fs/uploadUrl")'); assert.notStrictEqual(uploadUrlAt, -1, "the upload-url relay stays per-surface this wave"); }); test("both multipart upload routes defer disk quota to the daemon's file-byte check", () => { const panelSource = fs.readFileSync(path.join(__dirname, "..", "index.js"), "utf8"); const panelStart = panelSource.indexOf('app.post("/upload",'); const panelEnd = panelSource.indexOf('app.post("/upload-url",', panelStart); assert.ok(panelStart >= 0 && panelEnd > panelStart); const panel = panelSource.slice(panelStart, panelEnd); const relay = nodesRouteWindow('app.post("/api/nodes/server/:name/upload"', "upload"); for (const route of [panel, relay]) { assert.doesNotMatch(route, /content-length|buildDiskLimitUploadError/); assert.match(route, /stream(?:Panel)?UploadToNode\(/); assert.match(route, /isNodeQuota507\(result.status, result.json\)[\s\S]*?respond\(507, result.json\)/); } }); // Wave 2 review: the delete-batch backstop's fixed generic 500 body (raw error // text stays in the server log) had no pin — lock it so it cannot drift // silently in either direction (a detail field would leak internals; dropping // the error key would break the client's error branch). test("nodes.js delete-batch backstop keeps the fixed generic 500 shape (no detail leak)", () => { const at = NODES_SRC.indexOf("batch_delete_error"); assert.notStrictEqual(at, -1, "expected the delete-batch backstop body in nodes.js"); const window = NODES_SRC.slice(Math.max(0, at - 200), at + 120); assert.match(window, /error:\s*"batch_delete_error"/, "the backstop must answer { error: \"batch_delete_error\" }"); assert.doesNotMatch(window, /detail:/, "the backstop must not leak raw error text into the response"); }); // adpanel:relay-error-mask pin — the panel/backup relay 500 catches // (action/eula/command/create/backups and their :id twins) answer the // bridge_failed contract with a GENERIC detail: the pre-flight chains unwrap // DB-backed legs, so a raw e.message in the body could surface mysql2 // topology text (host/port/user fragments) to any authenticated user. The // full error is logged server-side instead. Locks every copy in lockstep so // a new relay cannot reintroduce the raw-text variant (the 11 known copies // at the time of the mask). test("nodes.js bridge_failed relay 500s keep the generic detail (no raw exception text)", () => { const re = /error:\s*"bridge_failed",\s*detail:\s*([^}]+?)\s*\}/g; let m; let count = 0; while ((m = re.exec(NODES_SRC)) !== null) { count += 1; assert.strictEqual(m[1], '"internal error"', "bridge_failed detail must stay the generic constant — raw e.message discloses DB topology"); } assert.ok(count >= 11, `expected the 11 known bridge_failed relay catches, found ${count}`); }); // Final-review blocker regression pin: index.js called renderFsRenameLegacyOutcome // without importing it — a runtime ReferenceError on every local-mode rename // that NO behavioral test could catch (index.js cannot be required in-process, // so the route never executed under the suite). Every renderFs*Outcome // identifier called in a monolith must be bound from that monolith's // services/node-fs-relay destructure or defined locally. test("every renderFs*Outcome called in a monolith is bound from its shared-module destructure", () => { for (const [label, src] of [["index.js", INDEX_SRC], ["nodes.js", NODES_SRC]]) { const code = src.split("\n").filter((line) => !/^\s*\/\//.test(line)).join("\n"); const used = [...new Set(code.match(/\brenderFs[A-Za-z]+\(/g) || [])]; assert.ok(used.length > 0, `${label}: expected renderer call sites`); const requireAt = code.indexOf('require("./services/node-fs-relay")'); assert.notStrictEqual(requireAt, -1, `${label}: expected the shared relay require`); const destructureStart = code.lastIndexOf("const {", requireAt); assert.ok(destructureStart !== -1, `${label}: expected a destructure before the shared relay require`); const destructure = code.slice(destructureStart, requireAt); for (const call of used) { const ident = call.slice(0, -1); const bound = new RegExp(`\\b${ident}\\b`).test(destructure) || new RegExp(`(?:function\\s+|const\\s+)${ident}\\b`).test(code); assert.ok( bound, `${label}: ${ident} is called but neither imported from services/node-fs-relay nor locally defined — this is a runtime ReferenceError the suite cannot catch by requiring the file` ); } } });