"use strict"; // Unit tests for the shared node HTTP/relay helper modules extracted in Wave 2 // Step A of the relay consolidation campaign (adpanel:relay-helper-consolidation). // // index.js and nodes.js carried drifting twins of every helper below; the twins // are deleted from both monoliths and re-bound from services/node-http.js and // services/node-fs-relay.js under the same identifier names. These tests pin: // 1. the two FLAGGED HARDENINGS (credential-in-URL rejection in // buildNodeBaseUrl on BOTH surfaces; the stricter NUL/containment union in // safeJoinUnix that newly refuses NUL-bearing paths on the panel surface), // 2. byte-identical per-surface behavior everywhere else (URL forms, header // shapes, 413/507/suspension bodies, the two deliberately different // maskPathErrorMessage policies, the two safeJoinUnix output styles), // 3. the response-cap posture of the moved httpRequestJson (error AND // aborted listeners, Content-Length pre-check, streaming cap, hard timer). const test = require("node:test"); const assert = require("node:assert"); const http = require("node:http"); const https = require("node:https"); const { EventEmitter } = require("node:events"); process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1"; const { configureNodeHttp, httpRequestJson, createBuildNodeBaseUrl, buildNodeAuthHeaders, nodeHeaders, truthyFlag, stripExplicitHostPort, CLOUDFLARE_HTTPS_EDGE_PORTS, } = require("../services/node-http"); const { safeJoinUnix, safeJoinUnixRelay, isServerRootResolvedPath, maskPathErrorMessage, maskPathErrorMessageRelay, isNodeQuota507, parseNodeDiskSnapshot, NODE_FS_WRITE_BODY_LIMIT_BYTES, NODE_FS_WRITE_BODY_LIMIT_MB, FILE_WRITE_LIMIT_CLIENT_MESSAGE, NODE_FS_WRITE_TOO_LARGE_MARKER, NODE_FS_WRITE_BASE64_LIMIT_MB, FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE, nodeFsWritePayloadTooLarge, fileWriteTooLargePayload, decodeNodeFileReadContent, attachEditorWriteHash, renderEditorWriteRefusal, FS_WRITE_STALE_CONFLICT_ERROR, FS_WRITE_STALE_CONFLICT_MESSAGE, isServerSuspended, suspendedServerBody, sendSuspendedServerJson, } = require("../services/node-fs-relay"); // services/* must stay leaf modules: no require of the monoliths. const fs = require("node:fs"); const path = require("node:path"); for (const mod of ["services/node-http.js", "services/node-fs-relay.js", "services/server-create.js"]) { test(`${mod} requires only utils/* and node builtins`, () => { const src = fs.readFileSync(path.join(__dirname, "..", mod), "utf8"); const requires = [...src.matchAll(/require\(["']([^"']+)["']\)/g)].map((m) => m[1]); for (const req of requires) { assert.ok( // "crypto" joined for the adpanel:editor-save-occ sha256 computation // in node-fs-relay.js — still a bare node builtin, same leaf posture. req.startsWith("node:") || ["http", "https", "path", "crypto"].includes(req) || req.startsWith("../utils/") || req.startsWith("./"), `${mod} must not require ${req} — services require only node builtins and utils/*` ); assert.ok(!/index\.js|nodes\.js/.test(req), `${mod} must never require the monoliths`); } }); } // --------------------------------------------------------------------------- // safeJoinUnix — panel (index.js) style // --------------------------------------------------------------------------- test("safeJoinUnix panel style joins under the base dir", () => { assert.strictEqual(safeJoinUnix("/vols/srv01", "config/settings.yml"), "/vols/srv01/config/settings.yml"); // "./" segments collapse; interior ".." segments are REJECTED by the raw // segment check (the deleted panel twin refused them too). assert.strictEqual(safeJoinUnix("/vols/srv01", "a/./b.txt"), "/vols/srv01/a/b.txt"); assert.throws(() => safeJoinUnix("/vols/srv01", "a/b/../c.txt"), /Unix path traversal detected/); // A backslash is a legal Linux FILENAME character on the panel surface // (panel clients never send backslashes and the panel twin never converted // them). The RELAY twin DID convert — pinned in the relay section below. assert.strictEqual(safeJoinUnix("/vols/srv01", "weird\\name"), "/vols/srv01/weird\\name"); }); test("safeJoinUnix panel style maps degenerate rels back to the normalized base", () => { assert.strictEqual(safeJoinUnix("/vols/srv01", ""), "/vols/srv01"); assert.strictEqual(safeJoinUnix("/vols/srv01", "."), "/vols/srv01"); // posix.join preserves a trailing slash coming from the BASE (the deleted // panel twin normalized with posix.normalize, which keeps it) — identical // output to the pre-extraction implementation. assert.strictEqual(safeJoinUnix("/vols/srv01/", "./"), "/vols/srv01/"); // Root base stays joinable (posix.join("/", "x") = "/x") — the containment // assert must not newly reject a base that itself ends with a slash. assert.strictEqual(safeJoinUnix("/", "foo"), "/foo"); }); test("safeJoinUnix panel style rejects traversal/absolute/control input BEFORE any dial", () => { assert.throws(() => safeJoinUnix("/vols/srv01", "../etc/passwd"), /Unix path traversal detected/); assert.throws(() => safeJoinUnix("/vols/srv01", "a/../../b"), /Unix path traversal detected/); assert.throws(() => safeJoinUnix("/vols/srv01", "/etc/passwd"), /Absolute path not allowed/); assert.throws(() => safeJoinUnix("/vols/srv01", "a\nb"), /Unsafe characters in path/); assert.throws(() => safeJoinUnix("/vols/srv01", "a\tb"), /Unsafe characters in path/); }); // adpanel:relay-helper-consolidation — FLAGGED HARDENING: the shared // implementation is the stricter union of both former twins. index.js's twin // used to STRIP NUL bytes from base and rel and forward the remainder; the // union rejects NUL outright (nodes.js's twin always did). Pin the new panel // refusal so it cannot silently revert. test("safeJoinUnix panel style now rejects NUL bytes (flagged hardening)", () => { assert.throws(() => safeJoinUnix("/vols/srv01", "bad\0name"), /Unix path traversal detected/); assert.throws(() => safeJoinUnix("/vols/srv\0", "x"), /Unix path traversal detected/); }); // --------------------------------------------------------------------------- // safeJoinUnix — relay (nodes.js) style // --------------------------------------------------------------------------- test("safeJoinUnixRelay keeps the string-concat output shape of the deleted nodes.js twin", () => { assert.strictEqual(safeJoinUnixRelay("/vols/srv01", "config/settings.yml"), "/vols/srv01/config/settings.yml"); // Degenerate rels keep the trailing slash the relay twin emitted — the // root predicate and the upstream payload depend on that byte. assert.strictEqual(safeJoinUnixRelay("/vols/srv01", ""), "/vols/srv01/"); assert.strictEqual(safeJoinUnixRelay("/vols/srv01", "."), "/vols/srv01/"); assert.strictEqual(safeJoinUnixRelay("/vols/srv01/", "./"), "/vols/srv01/"); }); test("safeJoinUnixRelay keeps the relay message vocabulary and NUL refusal", () => { assert.throws(() => safeJoinUnixRelay("/vols/srv01", "../etc/passwd"), /path traversal/); assert.throws(() => safeJoinUnixRelay("/vols/srv01", "/etc/passwd"), /Absolute path not allowed/); assert.throws(() => safeJoinUnixRelay("/vols/srv01", "a\nb"), /Unsafe characters in path/); assert.throws(() => safeJoinUnixRelay("/vols/srv01", "bad\0name"), /path traversal/); assert.throws(() => safeJoinUnixRelay("/vols/srv\0", "x"), /path traversal/); }); test("safeJoinUnixRelay keeps literal Linux names without accepting separator traversal", () => { assert.strictEqual(safeJoinUnixRelay("/vols/srv01", "dir\\file.txt"), "/vols/srv01/dir\\file.txt"); assert.strictEqual(safeJoinUnixRelay("/vols/srv01", "sub\\name/file.txt "), "/vols/srv01/sub\\name/file.txt "); assert.throws(() => safeJoinUnixRelay("/vols/srv01", "a\\..\\..\\x"), /path traversal/); assert.throws(() => safeJoinUnixRelay("/vols/srv01", "..\\x"), /path traversal/); }); // --------------------------------------------------------------------------- // isServerRootResolvedPath — one predicate accepting both reachable joined // shapes (panel posix.join output and relay concat output) // --------------------------------------------------------------------------- test("isServerRootResolvedPath refuses exactly the degenerate rels on both shapes", () => { // Panel joiner output shape (no trailing slash, normalized base). assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01"), true); assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01/other.txt"), false); // Relay joiner output shape (trailing slash for degenerate rels). assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01/"), true); assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01/other.txt"), false); // Odd but legal filenames never classify as the root. assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01/."), false); assert.strictEqual(isServerRootResolvedPath("/vols/srv01", "/vols/srv01/.."), false); }); // --------------------------------------------------------------------------- // maskPathErrorMessage — the two deliberately different policies (spec D13) // --------------------------------------------------------------------------- test("maskPathErrorMessage (index.js policy) maps the exact throw set and MASKS every other message", () => { assert.strictEqual(maskPathErrorMessage(new Error("Unix path traversal detected"), "Invalid path", "Create failed"), "Invalid path"); assert.strictEqual(maskPathErrorMessage(new Error("Absolute path not allowed"), "invalid path", "invalid path"), "invalid path"); assert.strictEqual(maskPathErrorMessage(new Error("Unsafe characters in path"), "invalid path", "invalid path"), "invalid path"); // adpanel:path-error-mask — the former raw err.message fallback is gone: // unexpected error text (driver detail, internal throws from a catch that // also spans the relay dial) NEVER reaches the client; every non-traversal // error takes the masked default, exactly like /upload's isPathTraversalError // posture. Pinned with both the call-site shape and a distinct fallback so a // regression back to raw passthrough trips on the message itself. assert.strictEqual(maskPathErrorMessage(new Error("some internal detail 42"), "invalid path", "invalid path"), "invalid path"); assert.strictEqual(maskPathErrorMessage(new Error("SQLSTATE[HY000]: driver exploded"), "Invalid path", "Create failed"), "Create failed"); assert.strictEqual(maskPathErrorMessage(new Error(""), "invalid path", "fallback"), "fallback"); }); test("maskPathErrorMessageRelay (nodes.js policy) substring-matches and falls back to bad_path", () => { assert.strictEqual(maskPathErrorMessageRelay(new Error("path traversal")), "invalid path"); assert.strictEqual(maskPathErrorMessageRelay(new Error("Unix path traversal detected")), "invalid path"); assert.strictEqual(maskPathErrorMessageRelay(new Error("Absolute path not allowed")), "invalid path"); assert.strictEqual(maskPathErrorMessageRelay(new Error("Unsafe characters in path")), "invalid path"); assert.strictEqual(maskPathErrorMessageRelay(new Error("zzz")), "zzz"); assert.strictEqual(maskPathErrorMessageRelay(new Error("")), "bad_path"); assert.strictEqual(maskPathErrorMessageRelay(new Error(""), "custom"), "custom"); }); // --------------------------------------------------------------------------- // Quota 507 passthrough + disk snapshot helpers // --------------------------------------------------------------------------- test("isNodeQuota507 accepts both daemon quota codes and nothing else", () => { assert.strictEqual(isNodeQuota507(507, { error: "disk_limit_exceeded" }), true); assert.strictEqual(isNodeQuota507(507, { error: "disk_capacity_exceeded" }), true); assert.strictEqual(isNodeQuota507(507, { error: "other" }), false); assert.strictEqual(isNodeQuota507(502, { error: "disk_limit_exceeded" }), false); assert.strictEqual(isNodeQuota507(507, null), false); }); test("parseNodeDiskSnapshot normalizes Mb/Gb snapshot variants", () => { const parsed = parseNodeDiskSnapshot({ disk: { usedMb: 512, limitGb: 2 } }); assert.strictEqual(parsed.usedBytes, 512 * 1024 * 1024); assert.strictEqual(parsed.limitBytes, 2 * 1024 * 1024 * 1024); assert.strictEqual(parsed.remainingBytes, 2 * 1024 * 1024 * 1024 - 512 * 1024 * 1024); assert.strictEqual(parseNodeDiskSnapshot({}).limitBytes, 0); }); // --------------------------------------------------------------------------- // Write 413 machinery — the single source of truth for the constants nodes.js // previously duplicated as *_NODES copies // --------------------------------------------------------------------------- test("the 413 constants keep their consolidated values", () => { assert.strictEqual(NODE_FS_WRITE_BODY_LIMIT_BYTES, 10 * 1024 * 1024); assert.strictEqual(NODE_FS_WRITE_BODY_LIMIT_MB, 10); assert.strictEqual(NODE_FS_WRITE_TOO_LARGE_MARKER, "content too large"); assert.strictEqual(NODE_FS_WRITE_BASE64_LIMIT_MB, 7.4); assert.strictEqual( FILE_WRITE_LIMIT_CLIENT_MESSAGE, "File exceeds the 10 MB editor limit — upload the file instead." ); assert.strictEqual( FILE_WRITE_BASE64_LIMIT_CLIENT_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." ); }); test("nodeFsWritePayloadTooLarge mirrors the daemon's inclusive 10 MiB raw-body cap", () => { const envelope = JSON.stringify({ path: "a", server: "b", content: "", encoding: "utf8", mode: "create" }); const fits = NODE_FS_WRITE_BODY_LIMIT_BYTES - Buffer.byteLength(envelope, "utf8"); assert.strictEqual(nodeFsWritePayloadTooLarge(JSON.parse(JSON.stringify({ path: "a", server: "b", content: "x".repeat(fits), encoding: "utf8", mode: "create" }))), false, "exactly at the cap must pass (http.MaxBytesReader is inclusive)"); assert.strictEqual(nodeFsWritePayloadTooLarge({ content: "x".repeat(NODE_FS_WRITE_BODY_LIMIT_BYTES) }), true); }); test("fileWriteTooLargePayload keeps the 413 wire shape", () => { assert.deepStrictEqual(fileWriteTooLargePayload(), { error: FILE_WRITE_LIMIT_CLIENT_MESSAGE, message: FILE_WRITE_LIMIT_CLIENT_MESSAGE, code: "file_too_large", limit_mb: 10, }); const base64 = fileWriteTooLargePayload(FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE, NODE_FS_WRITE_BASE64_LIMIT_MB); assert.strictEqual(base64.limit_mb, 7.4); assert.strictEqual(base64.code, "file_too_large"); }); // --------------------------------------------------------------------------- // Read decoding — the fatal UTF-8 binary gate // --------------------------------------------------------------------------- test("decodeNodeFileReadContent flags binary bytes and passes text/BOM/empty through", () => { assert.deepStrictEqual(decodeNodeFileReadContent(Buffer.from("hello", "utf8").toString("base64")), { binary: false, text: "hello" }); assert.deepStrictEqual(decodeNodeFileReadContent(Buffer.from([0xff, 0xfe, 0x01]).toString("base64")), { binary: true }); assert.deepStrictEqual(decodeNodeFileReadContent(""), { binary: false, text: "" }); assert.deepStrictEqual(decodeNodeFileReadContent(null), { binary: false, text: "" }); const withBom = decodeNodeFileReadContent(Buffer.from("\uFEFFhello", "utf8").toString("base64")); assert.strictEqual(withBom.binary, false); assert.strictEqual(withBom.text, "\uFEFFhello", "ignoreBOM keeps a leading BOM so files round-trip byte-exactly"); }); // --------------------------------------------------------------------------- // Suspension gates — one factored body, both surfaces' shapes // --------------------------------------------------------------------------- test("suspension helpers keep the exact 423 body and no-store header", () => { const srv = { name: "srv01", suspended: 1, suspended_at: 1730000000, suspended_by: "admin@x" }; assert.strictEqual(isServerSuspended(srv), true); assert.strictEqual(isServerSuspended({ name: "srv01" }), false); assert.strictEqual(isServerSuspended(null), false); assert.deepStrictEqual(suspendedServerBody(srv), { error: "server suspended", code: "server-suspended", server: "srv01", suspendedAt: 1730000000, suspendedBy: "admin@x", }); assert.deepStrictEqual(suspendedServerBody(null), { error: "server suspended", code: "server-suspended", server: null, suspendedAt: null, suspendedBy: null, }); const res = { headers: {}, setHeader(k, v) { this.headers[k] = v; }, status(code) { this.statusCode = code; return this; }, json(body) { this.body = body; return body; }, }; const out = sendSuspendedServerJson(res, srv); assert.strictEqual(res.statusCode, 423); assert.strictEqual(res.headers["Cache-Control"], "no-store, no-cache, must-revalidate, private"); assert.strictEqual(out, res.body); }); test("attachEditorWriteHash sends a valid hash on the write without changing its ACL mode", () => { for (const mode of ["", "create", "update"]) { const payload = { mode, path: "/srv/config.yml" }; assert.ok(attachEditorWriteHash(payload, "A".repeat(64))); assert.deepStrictEqual(payload, { mode, path: "/srv/config.yml", editorBaseSha256: "a".repeat(64) }); } }); test("attachEditorWriteHash preserves legacy writes but rejects a malformed opt-in", () => { for (const [value, ok] of [[undefined, true], [null, true], ["", true], [12345, true], ["nope", false], ["a".repeat(65), false]]) { const payload = {}; assert.strictEqual(attachEditorWriteHash(payload, value), ok); assert.deepStrictEqual(payload, {}); } }); test("editor write refusals distinguish changed bytes and a node that cannot enforce the guard", () => { const changed = { status: 409, json: { code: "file_changed_on_disk" } }; const oldNode = { status: 400, json: { error: "invalid JSON body" } }; const conflict = renderEditorWriteRefusal(changed, true); assert.strictEqual(conflict.status, 409); assert.deepStrictEqual(conflict.json, { error: FS_WRITE_STALE_CONFLICT_ERROR, message: FS_WRITE_STALE_CONFLICT_MESSAGE }); assert.strictEqual(renderEditorWriteRefusal(oldNode, true).json.error, "node_editor_upgrade_required"); assert.strictEqual(renderEditorWriteRefusal(oldNode, true).status, 503); assert.strictEqual(renderEditorWriteRefusal(oldNode, false), null); assert.strictEqual(renderEditorWriteRefusal({ status: 409, json: { existed: true } }, true), null); }); // --------------------------------------------------------------------------- // buildNodeBaseUrl — panel (index.js) flavor // --------------------------------------------------------------------------- // Mirrors index.js's clampApiPort (integer in [1,65535], else 8080). const clampApiPortLike = (p) => { const n = Number(p); return Number.isInteger(n) && n >= 1 && n <= 65535 ? n : 8080; }; const panelBuildNodeBaseUrl = createBuildNodeBaseUrl({ clampEdgePort: clampApiPortLike, clampUrlPathPort: clampApiPortLike, clampBareHostPort: clampApiPortLike, returnOrigin: true, }); test("panel buildNodeBaseUrl keeps its exact outputs", () => { assert.strictEqual(panelBuildNodeBaseUrl("example.com", 8080, false, false), "http://example.com:8080"); assert.strictEqual(panelBuildNodeBaseUrl("example.com", 8080, true, false), "https://example.com:8080"); assert.strictEqual(panelBuildNodeBaseUrl("", 8080, false, false), null); // Explicit URL form: origin-style output, no path/query/hash. assert.strictEqual(panelBuildNodeBaseUrl("https://example.com:8443/some/path?x=1#frag", 8080, false, false), "https://example.com:8443"); // An explicit port in the URL wins; only a MISSING port gets the clamped // api_port (the panel twin clamped this branch). assert.strictEqual(panelBuildNodeBaseUrl("https://example.com", 70000, false, false), "https://example.com:8080"); assert.strictEqual(panelBuildNodeBaseUrl("https://example.com", 9001, false, false), "https://example.com:9001"); // Bare-host branch clamps too. assert.strictEqual(panelBuildNodeBaseUrl("example.com", 70000, false, false), "http://example.com:8080"); // A configured default applies to bare node addresses. const prev = process.env.NODE_DEFAULT_SCHEME; process.env.NODE_DEFAULT_SCHEME = "https"; try { assert.strictEqual(panelBuildNodeBaseUrl("example.com", 8080, false, false), "https://example.com:8080"); } finally { if (prev === undefined) delete process.env.NODE_DEFAULT_SCHEME; else process.env.NODE_DEFAULT_SCHEME = prev; } // Cloudflare edge handling: a port not in the edge set clamps to 443 (bare // host, no port appended), an explicit edge-set port is kept. assert.strictEqual(CLOUDFLARE_HTTPS_EDGE_PORTS.has(443), true); assert.strictEqual(panelBuildNodeBaseUrl("example.com", 8080, false, true), "https://example.com"); assert.strictEqual(panelBuildNodeBaseUrl("example.com:8443", 8080, false, true), "https://example.com:8443"); }); // --------------------------------------------------------------------------- // buildNodeBaseUrl — relay (nodes.js) flavor // --------------------------------------------------------------------------- // Mirrors nodes.js's clampPort (toInt + range → 8080). const clampPortLike = (p) => { const n = Number(p); const rounded = Number.isFinite(n) ? Math.round(n) : 8080; return rounded >= 1 && rounded <= 65535 ? rounded : 8080; }; const relayBuildNodeBaseUrl = createBuildNodeBaseUrl({ clampEdgePort: clampPortLike, clampUrlPathPort: (p) => p, clampBareHostPort: clampPortLike, returnOrigin: false, }); test("relay buildNodeBaseUrl keeps its exact outputs", () => { assert.strictEqual(relayBuildNodeBaseUrl("example.com", 8080, false, false), "http://example.com:8080"); assert.strictEqual(relayBuildNodeBaseUrl("example.com", 8080, true, false), "https://example.com:8080"); // toString-minus-trailing-slash form (vs the panel's u.origin). assert.strictEqual(relayBuildNodeBaseUrl("https://example.com:8443/some/path?x=1#frag", 8080, false, false), "https://example.com:8443"); // The relay twin did NOT clamp the URL-branch port — preserved (WHATWG URL // drops the out-of-range value entirely, exactly as the deleted twin's // output did). assert.strictEqual(relayBuildNodeBaseUrl("https://example.com", 70000, false, false), "https://example.com"); // The bare-host branch DID clamp — preserved. assert.strictEqual(relayBuildNodeBaseUrl("example.com", 70000, false, false), "http://example.com:8080"); // The relay must not silently downgrade the panel's HTTPS default. const prev = process.env.NODE_DEFAULT_SCHEME; process.env.NODE_DEFAULT_SCHEME = "https"; try { assert.strictEqual(relayBuildNodeBaseUrl("example.com", 8080, false, false), "https://example.com:8080"); } finally { if (prev === undefined) delete process.env.NODE_DEFAULT_SCHEME; else process.env.NODE_DEFAULT_SCHEME = prev; } assert.strictEqual(relayBuildNodeBaseUrl("example.com:8443", 8080, false, true), "https://example.com:8443"); }); test("node TLS cannot be downgraded by the saved address scheme", () => { for (const buildBaseUrl of [panelBuildNodeBaseUrl, relayBuildNodeBaseUrl]) { assert.strictEqual(buildBaseUrl("http://node.example:8443", 8080, true), "https://node.example:8443"); assert.strictEqual(buildBaseUrl("http://node.example:443", 8080, true), "https://node.example"); assert.strictEqual(buildBaseUrl("http://node.example", 80, true), "https://node.example:80"); assert.strictEqual(buildBaseUrl("http://node.example:443", 8443, true, true), "https://node.example"); assert.strictEqual(buildBaseUrl("http://node.example", 8080, false), "http://node.example:8080"); } }); test("direct node addresses support an explicit port and IPv6 literals", () => { for (const buildBaseUrl of [panelBuildNodeBaseUrl, relayBuildNodeBaseUrl]) { assert.strictEqual(buildBaseUrl("node.example:8443", 8080, true), "https://node.example:8443"); assert.strictEqual(buildBaseUrl("https://node.example:443", 8443, true), "https://node.example"); assert.strictEqual(buildBaseUrl("https://node.example:443", 8443, true, true), "https://node.example"); assert.strictEqual(buildBaseUrl("http://node.example:80", 8080, false), "http://node.example"); assert.strictEqual(buildBaseUrl("http://node.example:80", 8443, true), "https://node.example:80"); assert.strictEqual(buildBaseUrl("node.example/ignored-path", 8080, true), "https://node.example:8080"); assert.strictEqual(buildBaseUrl("2001:db8::10", 8080, true), "https://[2001:db8::10]:8080"); assert.strictEqual(buildBaseUrl("[2001:db8::10]", 8080, true), "https://[2001:db8::10]:8080"); assert.strictEqual(buildBaseUrl("[2001:db8::10]:8443", 8080, true), "https://[2001:db8::10]:8443"); assert.strictEqual(buildBaseUrl("https://[2001:db8::10]:443", 8443, true), "https://[2001:db8::10]"); } }); test("FLAGGED HARDENING: credential-in-URL node addresses are refused on BOTH flavors", () => { assert.strictEqual(panelBuildNodeBaseUrl("https://user:pass@example.com:8443", 8080, false, false), null); assert.strictEqual(relayBuildNodeBaseUrl("https://user:pass@example.com:8443", 8080, false, false), null); assert.strictEqual(panelBuildNodeBaseUrl("https://user@example.com", 8080, false, false), null); assert.strictEqual(relayBuildNodeBaseUrl("https://:pass@example.com", 8080, false, false), null); // Credentials without an http(s) prefix reach the bare-host branch, where // the credential check never applied on either surface — unchanged. assert.strictEqual(relayBuildNodeBaseUrl("user:pass@example.com", 8080, false, false), "http://user:pass@example.com:8080"); }); test("truthyFlag and stripExplicitHostPort keep their moved bodies", () => { assert.strictEqual(truthyFlag(true), true); assert.strictEqual(truthyFlag(1), true); assert.strictEqual(truthyFlag("ON"), true); assert.strictEqual(truthyFlag("no"), false); assert.strictEqual(truthyFlag(undefined), false); assert.strictEqual(stripExplicitHostPort("example.com:8080"), "example.com"); assert.strictEqual(stripExplicitHostPort("[2001:db8::1]:8080"), "[2001:db8::1]"); assert.strictEqual(stripExplicitHostPort("example.com"), "example.com"); }); // --------------------------------------------------------------------------- // Node auth headers — one core, two former twins behind parameters // --------------------------------------------------------------------------- test("nodeHeaders keeps the nodes.js relay shape (X-Node-Token-Id always present)", () => { assert.deepStrictEqual(nodeHeaders({ token: "tok", token_id: "7" }), { Authorization: "Bearer tok", "X-Node-Token": "tok", "X-Node-Token-Id": "7", }); assert.deepStrictEqual(nodeHeaders({ token: "", token_id: "7" }), { Authorization: "Bearer ", "X-Node-Token": "", "X-Node-Token-Id": "7", }); assert.deepStrictEqual(nodeHeaders({ token: "tok" }), { Authorization: "Bearer tok", "X-Node-Token": "tok", "X-Node-Token-Id": "", }); }); test("buildNodeAuthHeaders keeps the index.js shape (Content-Type, conditional token id, local branch)", () => { const node = { token: "tok", token_id: "7" }; assert.deepStrictEqual(buildNodeAuthHeaders(node, { isRemote: true }), { "Content-Type": "application/json", Authorization: "Bearer tok", "X-Node-Token": "tok", "X-Node-Token-Id": "7", }); // token_id falsy → header absent (index.js contract). const noId = buildNodeAuthHeaders({ token: "tok" }, { isRemote: true }); assert.strictEqual("X-Node-Token-Id" in noId, false); // token resolution order token → secret → api_key. assert.strictEqual(buildNodeAuthHeaders({ secret: "s", api_key: "k" }, { isRemote: true }).Authorization, "Bearer s"); // Local (non-remote) daemon dial: the injected LOCAL_NODE_TOKEN, no token id. assert.deepStrictEqual(buildNodeAuthHeaders(node, { isRemote: false, localNodeToken: "local-tok" }), { "Content-Type": "application/json", Authorization: "Bearer local-tok", "X-Node-Token": "local-tok", }); // Remote dial with no token at all: Content-Type only (index.js contract). assert.deepStrictEqual(buildNodeAuthHeaders({}, { isRemote: true }), { "Content-Type": "application/json" }); }); // --------------------------------------------------------------------------- // httpRequestJson — response cap / listener / single-settle posture of the // moved helper (the node branch: X-Node-Token header ⇒ SSRF guard + guarded // lookup, the posture three worker crashes motivated) // --------------------------------------------------------------------------- function startEchoServer(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 = { "X-Node-Token": "t", Authorization: "Bearer t" }; test("httpRequestJson parses node responses and returns { status, json }", async () => { const { server, port } = await startEchoServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify({ ok: true, entries: [1, 2] })); }); try { const result = await httpRequestJson(`http://127.0.0.1:${port}/v1/fs/list`, "POST", NODE_AUTH, { path: "x" }, 5000); assert.strictEqual(result.status, 200); assert.deepStrictEqual(result.json, { ok: true, entries: [1, 2] }); } finally { stopServer(server); } }); // adpanel:node-http-cap-error-listeners - a header-only rejection still // destroys an IncomingMessage that can emit late error and aborted events. test("httpRequestJson attaches response listeners before rejecting oversized headers", async () => { for (const [protocol, transport] of [["http", http], ["https", https]]) { for (const includeText of [false, true]) { const originalRequest = transport.request; const upstream = new EventEmitter(); upstream.statusCode = 200; upstream.headers = { "content-length": String(17 * 1024 * 1024) }; let escapedError; let listenerCounts; upstream.destroy = () => { listenerCounts = [upstream.listenerCount("error"), upstream.listenerCount("aborted")]; upstream.emit("aborted"); try { upstream.emit("error", new Error("upstream reset during rejection")); } catch (error) { escapedError = error; } }; transport.request = (url, options, callback) => { const request = new EventEmitter(); request.setTimeout = () => request; request.destroy = () => {}; request.end = () => process.nextTick(() => callback(upstream)); return request; }; try { const result = await httpRequestJson(`${protocol}://127.0.0.1/`, "GET", {}, null, 1000, null, { nodeDial: true, includeText }); assert.strictEqual(escapedError, undefined, "an over-cap rejection must not leave an unhandled response error"); assert.ok(listenerCounts.every((count) => count > 0), "both listeners must attach before destroy"); assert.strictEqual(upstream.listenerCount("data"), 0, "an oversized response must not be buffered"); assert.strictEqual(result.tooLarge, true, "late events must not replace the size-limit outcome"); assert.strictEqual(result.error, "response too large"); if (includeText) assert.strictEqual(result.text, null); } finally { transport.request = originalRequest; } } } }); test("httpRequestJson rejects an over-cap response before buffering (Content-Length pre-check)", async () => { const CAP = 16 * 1024 * 1024; const { server, port } = await startEchoServer((req, res) => { res.writeHead(200, { "Content-Length": String(2 * CAP) }); res.end("x"); }); try { const result = await httpRequestJson(`http://127.0.0.1:${port}/`, "GET", NODE_AUTH, null, 5000); assert.strictEqual(result.status, 0); assert.strictEqual(result.tooLarge, true); assert.strictEqual(result.error, "response too large"); assert.strictEqual(result.json, null); } finally { stopServer(server); } }); test("httpRequestJson enforces a per-call maxBytes override from the headers alone", async () => { // The Content-Length pre-check compares against byteCap (the per-call // maxBytes when finite and positive, else MAX_RESPONSE_BYTES) — deterministic // because it fires before any body byte is buffered. const { server, port } = await startEchoServer((req, res) => { res.writeHead(200, { "Content-Length": String(2 * 1024 * 1024) }); res.end("x"); }); try { const overOverride = await httpRequestJson(`http://127.0.0.1:${port}/`, "GET", NODE_AUTH, null, 15000, 1024 * 1024); assert.strictEqual(overOverride.tooLarge, true, "a body over the per-call maxBytes must be refused"); assert.strictEqual(overOverride.status, 0); assert.strictEqual(overOverride.json, null); } finally { stopServer(server); } }); test("httpRequestJson still parses a streamed body under the default cap", async () => { const chunk = Buffer.alloc(256 * 1024, 0x61); let total = 0; const { server, port } = await startEchoServer((req, res) => { res.writeHead(200, { "Content-Type": "application/json" }); const pump = setInterval(() => { if (total >= 2 * 1024 * 1024 || res.destroyed) { res.end(); clearInterval(pump); return; } total += chunk.length; res.write(chunk); }, 1); res.on("close", () => clearInterval(pump)); }); try { const result = await httpRequestJson(`http://127.0.0.1:${port}/`, "GET", NODE_AUTH, null, 15000); assert.strictEqual(result.status, 200, "2 MiB is under the default 16 MiB cap"); assert.strictEqual(result.tooLarge, undefined); assert.strictEqual(result.json, null, "a non-JSON body parses to null without failing the request"); } finally { stopServer(server); } }); test("httpRequestJson's hard timer settles the promise (single-settle, no hang)", async () => { const { server, port } = await startEchoServer(() => { /* never respond */ }); try { const result = await httpRequestJson(`http://127.0.0.1:${port}/`, "GET", NODE_AUTH, null, 250); assert.strictEqual(result.status, 0); assert.strictEqual(result.json, null); assert.strictEqual(result.tooLarge, undefined); } finally { stopServer(server); } }); test("httpRequestJson answers status 0 for a refused SSRF guard target or refused dial (no throw)", async () => { configureNodeHttp({ getNodeMtlsAgent: () => null, createSsrfSafeAgent: () => null, tlsServernameForHost: (h) => h }); // A non-node dial (no X-Node-Token/Authorization) takes the non-node branch: // the SSRF validator refuses private addresses → { status: 0 }. const result = await httpRequestJson("http://127.0.0.1:1/", "GET", {}, null, 1000); assert.strictEqual(result.status, 0); assert.strictEqual(result.json, null); }); // Wave-verification gap: AGENTS.md calls the missing response error/aborted // listener class the one that crashed workers three times. The behavioral cap // tests prove settle-not-hang, but nothing pinned the listeners themselves on // the core (the streamer/captcha/SSE sites carry their own pins). test("the shared dial core carries res error+aborted listeners (crash-class pin)", () => { const src = fs.readFileSync(path.join(__dirname, "..", "services", "node-http.js"), "utf8"); const errAt = src.indexOf('res.on("error"'); const abortedAt = src.indexOf('res.on("aborted"'); assert.notStrictEqual(errAt, -1, "response error listener missing from the shared dial core"); assert.notStrictEqual(abortedAt, -1, "response aborted listener missing from the shared dial core"); assert.ok(Math.abs(abortedAt - errAt) < 400, "the error and aborted listeners must sit together in the response handler (the class AGENTS.md mandates on every upstream response)"); });