Files
Kelx/services/node-fs-relay.js
T
2026-11-30 16:32:37 +00:00

1064 lines
57 KiB
JavaScript

"use strict";
// adpanel:relay-helper-consolidation — ONE shared implementation of the pure
// relay helpers (Wave 2 Step A of the relay consolidation campaign, see
// .campaign/spec-relay.md §5/§6). index.js and nodes.js carried drifting twins
// of every helper below; the twins are deleted from both monoliths and
// re-bound here under the SAME identifier names, so no call site changed.
// This module requires ONLY node builtins and services/node-http.js — it must
// NEVER require index.js or nodes.js (dependency direction is one-way: the
// monoliths require this module). The relay and disk-snapshot fetcher take
// their dialer and request builders through injected dependencies.
//
// relayFsJson (Wave 2 Step B1) is the one shared JSON file-relay DIAL
// (panel→node): it is transport-only — URL building, auth header shaping and
// the dialer all arrive through the injected deps so each surface keeps its
// exact posture (see the function comment), while the tooLarge/offline/404/ok
// classification and the per-op response RENDERING (byte-exact wire bodies per
// surface, spec §2 for the panel and §3 for the relay) live here so they can
// never drift again. The SSRF posture needs no parameter: the dialer is
// services/node-http.js's hardened httpRequestJson, whose node branch (the
// headers carry the node's bearer credential) applies the assertNodeUrlHostAllowed
// pre-flight + guardedNodeLookup connect-time re-validation to every dial.
//
// The per-op renderers cover the READ ops (list/read/stream, Step B1) and —
// Wave 2 Step B2 — the MUTATING ops (write/mkdir/delete/rename/extract/
// archive plus the two create contracts). The routes keep everything that is
// NOT the daemon outcome mapping: auth/token/access/suspension/perm gates in
// their exact order, input validation, safeJoinUnix confinement, root
// refusals, the pre-flight try/catch structure, the pre-dial write 413 check,
// the rename destination probe and the legacy routes' text-vs-JSON dispatch.
//
// Deliberately DIFFERENT per-surface policies stay behind named exports
// rather than being "unified" — error-body text is a client-facing contract
// (bot.js branches on it), and the two maskers deliberately differ (spec D13):
// maskPathErrorMessage(err, traversalFallback, defaultFallback)
// — index.js policy: exact-set match on the three safeJoinUnix throw
// messages → traversalFallback, otherwise defaultFallback. The former
// RAW err.message fallback is GONE (adpanel:path-error-mask): the
// panel FS catches span DB-backed pre-flight work and the relay dial,
// so unexpected error text is never echoed to the client — only the
// exact traversal set produces specific messages (the /upload
// isPathTraversalError posture, applied to every masked catch).
// maskPathErrorMessageRelay(err, fallback = "bad_path")
// — nodes.js policy: substring "traversal"/"path" → "invalid path",
// else msg || fallback. nodes.js binds this under its original
// local name maskPathErrorMessage.
// Similarly safeJoinUnix carries a style parameter: "panel" (index.js's
// normalize + posix.join output shape) and "relay" (nodes.js's string-concat
// output shape) — the two joiners emit byte-different strings for degenerate
// rels ("" / "." → panel "base" vs relay "base/"), and downstream predicates
// and upstream payloads depend on those shapes, so they are preserved.
//
// THE SECOND FLAGGED SAFETY HARDENING (spec D14): the shared safeJoinUnix is
// the STRICTER UNION of both former twins' check sets. nodes.js's twin
// rejected NUL bytes in base and rel and asserted trailing-prefix containment
// after the join; index.js's twin stripped NULs instead of rejecting and had
// no post-join assert. The union applies BOTH checks to BOTH surfaces:
// - index.js (panel) routes now NEWLY REJECT (400, masked through their
// existing maskPathErrorMessage policy to the same traversalFallback
// bodies as every other confined-path rejection) paths containing NUL or
// other control characters that were previously silently stripped and
// forwarded to the node daemon. This is path-confinement hardening — the
// exact guard class this campaign protects — and it is fail-closed: no
// legitimate panel-managed path contains NUL/control bytes.
// - nodes.js relay behavior is preserved: the backslash→slash conversion,
// NUL-in-base refusal, absolute/control rejections, traversal checks and
// the trailing-prefix containment were all part of the relay twin's
// lineage and are kept. (The backslash conversion was briefly lost in
// the extraction and restored by the Wave 2 review — without it a literal
// backslash filename was accepted where the relay always traversed.)
// Throw messages remain a superset of both twins' vocabularies, and each
// style keeps its own traversal message ("Unix path traversal detected" on
// the panel, "path traversal" on the relay), so each surface's masker maps
// every rejection to exactly the visible body it maps today.
const path = require("path");
const { httpRequestJson } = require("./node-http");
// ---------------------------------------------------------------------------
// safeJoinUnix — path confinement for every FS operation on both surfaces.
// Self-contained by design (only `path` is closed over) so structural tests
// can slice and evaluate the real implementation.
// ---------------------------------------------------------------------------
function safeJoinUnix(baseDir, rel, style) {
const relay = style === "relay";
const traversalError = relay ? "path traversal" : "Unix path traversal detected";
// UNION (hardening on the panel surface; unchanged on the relay): reject NUL
// bytes outright — they can truncate paths in some syscalls and must never
// reach the node. The panel twin used to strip them and forward the rest.
if (String(baseDir ?? "").includes("\0") || String(rel ?? "").includes("\0")) {
throw new Error(traversalError);
}
// Absolute paths are REJECTED, not silently stripped. The check runs on the
// raw value BEFORE any normalization so the predicate matches the reference
// implementation exactly (a leading "\" is a legal Linux filename character,
// not a root).
if (path.posix.isAbsolute(String(rel ?? ""))) {
throw new Error("Absolute path not allowed");
}
// Base derivation per surface (output shapes must stay byte-identical):
// panel: posix.normalize — the panel twin normalized the base dir.
// relay: strip ONE trailing slash only — the relay twin did not normalize.
let base;
if (relay) {
base = String(baseDir ?? "");
base = base.endsWith("/") ? base.slice(0, -1) : base;
} else {
base = path.posix.normalize(String(baseDir ?? ""));
}
// adpanel:fs-path-identity - never translate a literal Linux filename into a different path.
const raw = String(rel ?? "");
// Reject control characters (incl. \r \n \t / NUL remnants) outright: they
// are illegal in panel-managed FS paths and could be smuggled into
// downstream protocols (e.g. multipart boundaries when proxying uploads to
// nodes).
// eslint-disable-next-line no-control-regex
if (/[\u0000-\u001f\u007f]/.test(raw)) {
throw new Error("Unsafe characters in path");
}
// Reject traversal segments in the raw value before normalization collapses
// them, so we never depend solely on the post-join containment check.
if (raw.split(relay ? /[\\/]/ : "/").includes("..")) {
throw new Error(traversalError);
}
const normalized = path.posix.normalize("/" + raw).replace(/^\/+/, "");
if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) {
throw new Error(traversalError);
}
// Join per surface (output shapes must stay byte-identical):
// panel: posix.join(base, normalized) — no trailing slash for the
// degenerate rels; a rel that itself ends in "/" keeps it.
// relay: `${base}/${normalized}` — appends the slash even for "" / ".".
let joined;
if (relay) {
joined = `${base}/${normalized}`;
} else {
joined = path.posix.join(base, normalized);
}
// UNION (hardening on the panel surface; unchanged on the relay):
// trailing-prefix containment assert. For panel inputs that pass the checks
// above this is provably a no-op (a normalized base plus a normalized rel
// with no ".." segment cannot join outside the base), so the only newly
// rejected panel inputs are the pathological ones the union exists to stop.
// The prefix form tolerates a base that itself ends with "/" (both twins'
// joiners could emit that shape). An empty base is unreachable in practice
// (every caller passes a validated absolute baseDir); with it the prefix
// degenerates to "" so startsWith always passes and the containment check
// is a no-op — matching the relay twin's lineage, which also never threw
// on an empty base.
const prefix = base ? (base.endsWith("/") ? base : base + "/") : "";
if (!joined.startsWith(prefix) && joined !== base) {
throw new Error(traversalError);
}
return joined;
}
// The relay (nodes.js) style under its own export name; nodes.js re-binds it
// to its original local identifier so its call sites stay untouched.
function safeJoinUnixRelay(base, rel) {
return safeJoinUnix(base, rel, "relay");
}
// ---------------------------------------------------------------------------
// A delete whose relative path resolves to the server root itself ("" / "." /
// "./" — anything safeJoinUnix maps back to the base dir) would recursively
// destroy the whole server directory. Whole-server destruction is admin-only
// through the dedicated server-delete/reinstall flows, so every delete relay
// refuses it. The comparison runs against the safeJoinUnix result, so dotted
// or encoded variants are caught uniformly while legal odd filenames (which
// never resolve back to the base) stay deletable.
//
// ONE predicate for both surfaces, accepting both reachable joined shapes:
// the panel joiner emits posix.normalize(baseDir) for degenerate rels, the
// relay joiner emits baseDir-minus-trailing-slash + "/" — verified
// decision-equivalent for every path each surface's safeJoinUnix can produce
// (both surfaces classify exactly the degenerate rels as root, and no
// non-degenerate rel can match any accepted form). Accepting BOTH forms is
// fail-closed: it can only widen the root-refusal, never allow a delete that
// either twin would have refused.
// ---------------------------------------------------------------------------
function isServerRootResolvedPath(baseDir, joinedPath) {
const raw = String(baseDir ?? "");
const normalizedBase = path.posix.normalize(raw).replace(/\0/g, "");
const stripped = raw.endsWith("/") ? raw.slice(0, -1) : raw;
const joined = String(joinedPath ?? "");
return joined === normalizedBase || joined === stripped || joined === stripped + "/";
}
// ---------------------------------------------------------------------------
// Error masking — TWO deliberately different policies (spec D13), one module.
// ---------------------------------------------------------------------------
// adpanel:path-error-mask — the ONE definition of "traversal error" for both
// consumers below: isPathTraversalError (the /upload catch's gate) and
// maskPathErrorMessage (every other panel FS catch). Only this exact
// safeJoinUnix throw set may reach a client as a specific 400 message from a
// catch that also spans DB-backed pre-flight work or the relay dial; anything
// else must render as that catch's generic fallback.
const PATH_TRAVERSAL_ERRORS = new Set([
"Absolute path not allowed",
"Unix path traversal detected",
"Unsafe characters in path",
]);
function isPathTraversalError(err) {
return PATH_TRAVERSAL_ERRORS.has(String(err?.message || ""));
}
// index.js policy: exact-set match on the safeJoinUnix throw messages →
// traversalFallback; EVERY other error — including one carrying a non-empty
// message — gets the masked defaultFallback. Unexpected error text (a DB
// driver message, an internal throw, a daemon transport failure) is NEVER
// echoed to the client: the former raw err.message fallback leaked it on
// every route whose catch spans more than the path checks (e.g. /archive's,
// whose catch also wraps the relay dial). Each call site already passes its
// own per-route generic default ("invalid path", "archive failed",
// "Create failed", "Invalid path"), so no call site changed with this
// hardening — only the formerly raw outputs become those defaults.
function maskPathErrorMessage(err, traversalFallback, defaultFallback) {
if (isPathTraversalError(err)) return traversalFallback;
return defaultFallback;
}
// nodes.js policy: substring match, then the fixed fallback.
function maskPathErrorMessageRelay(err, fallback = "bad_path") {
const msg = err && err.message ? String(err.message) : "";
const lower = msg.toLowerCase();
if (lower.includes("traversal") || lower.includes("path")) return "invalid path";
return msg || fallback;
}
// ---------------------------------------------------------------------------
// Quota (507) passthrough predicate — byte-identical twins on both surfaces.
// ---------------------------------------------------------------------------
// The daemon answers 507 with either quota code: the per-server
// "disk_limit_exceeded" or the per-disk ceiling "disk_capacity_exceeded"
// (checkDiskCapacity / diskCapacityAllowanceForPath on the node). Relays must
// pass both through verbatim — whitelisting only one downgraded a full
// secondary disk to a generic 502 transport error.
function isNodeQuota507(status, json) {
return status === 507 && (json?.error === "disk_limit_exceeded" || json?.error === "disk_capacity_exceeded");
}
// ---------------------------------------------------------------------------
// Numeric and disk snapshot helpers for node status reporting.
// ---------------------------------------------------------------------------
function finiteNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function parseNodeDiskSnapshot(payload) {
const disk = payload?.disk || {};
const statsDisk = payload?.stats?.disk || {};
let usedBytes = finiteNumber(disk.usedBytes);
let limitBytes = finiteNumber(disk.limitBytes);
if (usedBytes == null) {
const usedMb = finiteNumber(disk.usedMb ?? statsDisk.usedMb);
const usedGb = finiteNumber(disk.usedGb ?? statsDisk.usedGb);
if (usedMb != null) usedBytes = usedMb * 1024 * 1024;
else if (usedGb != null) usedBytes = usedGb * 1024 * 1024 * 1024;
}
if (limitBytes == null) {
const limitMb = finiteNumber(disk.limitMb ?? statsDisk.limitMb);
const limitGb = finiteNumber(disk.limitGb ?? statsDisk.limitGb);
if (limitMb != null) limitBytes = limitMb * 1024 * 1024;
else if (limitGb != null) limitBytes = limitGb * 1024 * 1024 * 1024;
}
usedBytes = Math.max(0, Math.round(usedBytes || 0));
limitBytes = limitBytes && limitBytes > 0 ? Math.round(limitBytes) : 0;
const remainingBytes = limitBytes > 0 ? Math.max(0, limitBytes - usedBytes) : null;
return {
usedBytes,
limitBytes,
remainingBytes,
percentUsed: limitBytes > 0 ? Math.min(100, (usedBytes / limitBytes) * 100) : 0,
};
}
// GET /v1/servers/<name> for the node info route's disk usage display.
function createNodeDiskSnapshotFetcher(deps) {
const dial = deps.dial || httpRequestJson;
if (typeof dial !== "function") throw new Error("createNodeDiskSnapshotFetcher requires a deps.dial function");
if (typeof deps.buildRequest !== "function") throw new Error("createNodeDiskSnapshotFetcher requires deps.buildRequest");
return async function fetchNodeDiskSnapshot(target, serverName, timeoutMs = 5000) {
const req = deps.buildRequest(target, serverName);
// buildRequest returns null for every guard failure (unbuildable base
// URL, empty sanitized name, non-remote ctx) — the same null each twin
// returned before dialing.
if (!req) return null;
const result = await dial(req.url, "GET", req.headers, null, timeoutMs);
if (result.status !== 200 || !result.json) return null;
return parseNodeDiskSnapshot(result.json);
};
}
// ---------------------------------------------------------------------------
// Write 413 machinery — the single source of truth for the 413 constants that
// nodes.js previously duplicated as *_NODES copies (spec D25). The duplicated
// string/value set was verified byte-identical before consolidation; the 413
// wire bodies do not change on either surface.
// ---------------------------------------------------------------------------
// The node daemon caps the RAW JSON request body of /v1/fs/write at 10 MiB
// (readJSON(w, r, 10<<20) in handleFSWrite, main.go): the JSON envelope plus
// the JSON-string-escaped content must fit in that budget. The boundary is
// inclusive — http.MaxBytesReader accepts a body of exactly 10,485,760 bytes
// and rejects anything larger — and express's "10mb" parser limit fails at the
// same byte (raw-body errors only when received > limit), so the parser never
// accepts a body the daemon would bounce as 502 node_write_failed. Content
// currently goes out as plain UTF-8 ("encoding": "utf8"); a future base64
// variant inflates content by 4/3 INSIDE the same body budget, so always
// measure Buffer.byteLength(JSON.stringify(payload)) against
// NODE_FS_WRITE_BODY_LIMIT_BYTES regardless of encoding.
const NODE_FS_WRITE_BODY_LIMIT_BYTES = 10 * 1024 * 1024;
const NODE_FS_WRITE_BODY_LIMIT_MB = NODE_FS_WRITE_BODY_LIMIT_BYTES / (1024 * 1024);
const FILE_WRITE_LIMIT_CLIENT_MESSAGE = `File exceeds the ${NODE_FS_WRITE_BODY_LIMIT_MB} MB editor limit — upload the file instead.`;
// handleFSWrite (main.go) answers an over-limit body with HTTP 400 and the
// error text "content too large (max 10MB)" (readJSON's MaxBytesReader trips
// before the content is decoded; malformed JSON answers "invalid JSON body"
// instead and must not map here); matched by substring
// so a minor daemon rewording still maps to 413 instead of 502.
const NODE_FS_WRITE_TOO_LARGE_MARKER = "content too large";
function nodeFsWritePayloadTooLarge(payload) {
return Buffer.byteLength(JSON.stringify(payload), "utf8") > NODE_FS_WRITE_BODY_LIMIT_BYTES;
}
function fileWriteTooLargePayload(message = FILE_WRITE_LIMIT_CLIENT_MESSAGE, limitMb = NODE_FS_WRITE_BODY_LIMIT_MB) {
return {
error: message,
message,
code: "file_too_large",
limit_mb: limitMb,
};
}
// A base64 write inflates content 4/3 INSIDE the same 10 MiB daemon raw-body
// cap (readJSON(w, r, 10<<20) counts the whole JSON envelope), so the decoded
// binary ceiling is (10,485,760 - envelope) * 3/4 — ~7.5 MB for a ~200-byte
// envelope. 7.4 MB is stated conservatively so the 413 stays accurate for
// longer paths. The daemon read cap (10 MB) is higher; that asymmetry is
// inherent to the daemon's raw-body cap and not something the panel can lift.
const NODE_FS_WRITE_BASE64_LIMIT_MB = 7.4;
const FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE = `Binary file exceeds the ~${NODE_FS_WRITE_BASE64_LIMIT_MB} MB editor save limit (base64 content must fit the node's ${NODE_FS_WRITE_BODY_LIMIT_MB} MB request body) — upload the file instead.`;
// ---------------------------------------------------------------------------
// Editor-facing read decoding — index.js's decodeNodeFileReadContent and
// nodes.js's decodeNodeFileReadContentNodes were byte-identical twins (same
// fatal decoder config, same { binary } / { binary: false, text } shape);
// ONE implementation now serves both (nodes.js re-binds it under its original
// local name).
//
// Editor-facing reads request the daemon's base64 encoding — its "utf8" mode
// lossily replaces non-UTF-8 bytes with U+FFFD before the panel ever sees
// them — then validate the bytes strictly, so a binary file is flagged
// instead of being served as mangled text the editor could save back over
// the original. ignoreBOM keeps a leading BOM in the decoded text so a
// BOM-prefixed file round-trips byte-exactly; empty files decode to "" and
// stay editable.
// ---------------------------------------------------------------------------
const NODE_FILE_READ_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
// Strict text reads also reject malformed payloads and NUL bytes.
function decodeNodeFileReadContent(base64Content, { strictText = false } = {}) {
if (strictText && typeof base64Content !== "string") return { invalid: true };
const bytes = Buffer.from(String(base64Content || ""), "base64");
if (strictText && bytes.toString("base64") !== base64Content) return { invalid: true };
try {
const text = NODE_FILE_READ_UTF8_DECODER.decode(bytes);
return strictText && text.includes("\0") ? { binary: true } : { binary: false, text };
} catch (e) {
return { binary: true };
}
}
// ---------------------------------------------------------------------------
// createNodeFsPost (Wave 3 HTTP-helper convergence) — the ONE shared POST
// relay to the node daemon's /v1/fs/* (and /v1/servers/...) endpoints, the
// re-home of index.js's nodeFsPost. It is relayFsJson's transport twin minus
// the classification: it returns the RAW dial result { status, json[, ...] }
// because its ~16 remaining index.js callers each do their own outcome
// mapping (socket handlers, deferred import, scheduler, AI tools, the disk
// snapshot/replacement fetchers). Never rejects; an unbuildable base URL
// (malformed node address, credential-in-URL rejection) resolves
// { status: 0, json: null } — the offline answer every caller already maps.
//
// deps (the panel builders nodeFsPost closed over — index.js binds them once
// as FS_RELAY_DEPS and both nodeFsPost and the Wave 2 relayFsJson routes dial
// through the same object):
// deps.buildNodeBaseUrl (node) → base URL string or null. index.js binds
// its panel flavor: buildNodeBaseUrl(node.address,
// node.api_port || 8080, node.ssl_enabled,
// nodeUnderCloudflare(node)).
// deps.buildNodeAuthHeaders (node) → header object. index.js binds
// nodeAuthHeadersFor(node, true) — Content-Type +
// Bearer/X-Node-Token + conditional X-Node-Token-Id.
// No cookies or user-derived data ever go upstream
// (spec §1.3).
// deps.httpRequestJson the dialer; defaults to the hardened core. The
// node branch (headers carry the node's bearer
// credential) applies the assertNodeUrlHostAllowed
// pre-flight and the guardedNodeLookup connect-time
// re-validation — the exact posture nodeFsPost
// always had.
// `payload` is sent verbatim as the JSON body — the factory never reshapes it.
// ---------------------------------------------------------------------------
function createNodeFsPost(deps) {
const dial = deps.httpRequestJson || httpRequestJson;
const buildBase = deps.buildNodeBaseUrl;
const buildHeaders = deps.buildNodeAuthHeaders;
if (typeof buildBase !== "function" || typeof buildHeaders !== "function") {
throw new Error("createNodeFsPost requires deps.buildNodeBaseUrl and deps.buildNodeAuthHeaders");
}
return async function nodeFsPost(node, endpoint, payload, timeoutMs = 20000, { maxBytes } = {}) {
const baseUrl = buildBase(node);
if (!baseUrl) return { status: 0, json: null };
return dial(`${baseUrl}${endpoint}`, "POST", buildHeaders(node), payload, timeoutMs, maxBytes);
};
}
// ---------------------------------------------------------------------------
// relayFsJson — the ONE shared panel→node JSON file-relay dial (Wave 2 Step
// B1, .campaign/spec-relay.md §4 step 12). Transport-only: the outcome is a
// transport-neutral classification (no message strings — those are the
// renderers' per-surface contract below). Everything caller-specific arrives
// through deps so each surface keeps its exact current posture:
// deps.httpRequestJson the dialer. Default: services/node-http.js's
// hardened httpRequestJson (response error AND
// aborted listeners, 16 MiB cap, hard total-duration
// timer + inactivity timeout, single-settle). Its
// node branch — triggered because the auth headers
// carry the node's bearer credential — applies the
// SSRF pre-flight (assertNodeUrlHostAllowed) and the
// guardedNodeLookup connect-time re-validation to
// every dial; there is no separate pre-flight step
// to reproduce.
// deps.buildNodeBaseUrl (node) → base URL string or null. Each caller
// binds its own createBuildNodeBaseUrl flavor (the
// panel: clampApiPort/NODE_DEFAULT_SCHEME/origin
// form; the relay: its unclamped-URL/toString form)
// plus its nodeUnderCloudflare policy — byte-identical
// to what index.js nodeFsPost / nodes.js nodeUrl
// computed before consolidation. null ⇒ offline.
// deps.buildNodeAuthHeaders (node) → header object. Each caller binds its
// own shape (panel: nodeAuthHeadersFor(node, true)
// — Content-Type + conditional X-Node-Token-Id;
// relay: Content-Type + nodeHeaders — X-Node-Token-Id
// always present). No cookies or user-derived data
// ever go upstream (spec §1.3).
// `payload` is caller-built (the joined path, the canonical server scope, op
// fields) and is sent verbatim as the JSON body — the core never reshapes it.
// ---------------------------------------------------------------------------
async function relayFsJson(deps, node, endpoint, payload, timeoutMs = 20000, { maxBytes, method = "POST" } = {}) {
const dial = deps.httpRequestJson || httpRequestJson;
const buildBase = deps.buildNodeBaseUrl;
const buildHeaders = deps.buildNodeAuthHeaders;
if (typeof buildBase !== "function" || typeof buildHeaders !== "function") {
throw new Error("relayFsJson requires deps.buildNodeBaseUrl and deps.buildNodeAuthHeaders");
}
// Mirror of the former nodeFsPost guard: an unbuildable base URL (malformed
// node address, credential-in-URL rejection) is a transport-level failure,
// reported exactly like an unreachable node.
const baseUrl = buildBase(node);
if (!baseUrl) return { kind: "offline", status: 0, json: null };
const result = await dial(`${baseUrl}${endpoint}`, method, buildHeaders(node), payload, timeoutMs, maxBytes);
return classifyNodeJsonResult(result);
}
// The classification the three GET file routes performed inline (and nodes.js
// relays perform inline): a status-0 dial resolves into tooLarge vs offline so
// "the node IS online, its listing is just too big to buffer" is never
// misreported as node_offline; a daemon 404 is its own kind so a renderer can
// choose per surface whether a missing file is a 404 or a generic failure; ok
// requires the daemon's ok flag, matching every route's
// `status !== 200 || !json || !json.ok` guard byte-for-byte.
function classifyNodeJsonResult(result) {
const status = (result && result.status) || 0;
const json = (result && result.json) || null;
if (status === 0 && result && result.tooLarge) return { kind: "too_large", status: 0, json: null };
if (status === 0) return { kind: "offline", status: 0, json: null };
if (status === 404) return { kind: "not_found", status, json };
if (status === 200 && json && json.ok) return { kind: "ok", status, json };
return { kind: "failed", status, json };
}
// ---------------------------------------------------------------------------
// Per-op response renderers — the byte-exact wire contract per surface
// (spec §2 = "panel" = index.js routes, spec §3 = "relay" = nodes.js routes).
// Each returns { status, json } (JSON ops) or { status, text } (the stream op,
// whose success/failure bodies are plain text); the caller applies them with
// res.status(...).json(...)/.end(...). Message strings live HERE so the two
// surfaces' deliberately different bodies (spec D4/D5) cannot drift.
// ---------------------------------------------------------------------------
// Spec §2 line 235: the panel's over-cap listing body (shared verbatim with
// the relay's entries route — nodes.js adopted index.js's wording for this one).
const FS_LIST_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.";
// Spec D5: ONLY the panel tells the user the node may be offline; the relay
// answers its plain node_list_failed body with no detail.
const FS_LIST_OFFLINE_MESSAGE = "Cannot connect to server node. The node may be offline.";
// Spec §2 line 236: the panel's over-cap read body (shared verbatim with the
// relay's file route).
const FS_READ_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.";
// Spec §2 line 219: the /files/stream over-cap body — a plain-text end(), not JSON.
const FS_STREAM_TOO_LARGE_MESSAGE = "This file is too large to stream: the node's response exceeded the panel's response size limit.";
// Spec D3: the panel list payload omits depth (the daemon's listing is flat
// either way); the relay sends depth: 1. Key order matches both former call
// sites so the JSON body bytes are unchanged.
function buildFsListPayload(dir, serverName, variant = "panel") {
return variant === "relay" ? { path: dir, server: serverName, depth: 1 } : { path: dir, server: serverName };
}
// list — panel success: { ok:true, path: rel, entries: <daemon entries
// verbatim>, truncated: json.truncated === true } (spec §2 line 235; the
// adpanel:listing-truncated contract — bot.js reads data.truncated for its
// truncation notice). Relay success: { path, entries: entryMapper(json.entries
// || []), truncated } — no ok:true, entries reshaped by the caller's mapper
// (spec D4; nodes.js passes its mapFsEntries). Relay offline/failed collapse
// into plain node_list_failed (spec D5).
function renderFsListOutcome(outcome, rel, opts = {}) {
const relay = opts.variant === "relay";
if (relay && typeof opts.entryMapper !== "function") {
throw new Error("renderFsListOutcome variant 'relay' requires an entryMapper function");
}
switch (outcome && outcome.kind) {
case "too_large":
return { status: 502, json: { error: "node_response_too_large", message: FS_LIST_TOO_LARGE_MESSAGE } };
case "offline":
return relay
? { status: 502, json: { error: "node_list_failed" } }
: { status: 502, json: { error: "node_offline", message: FS_LIST_OFFLINE_MESSAGE } };
case "ok":
return relay
? { status: 200, json: { path: rel, entries: opts.entryMapper(outcome.json.entries || []), truncated: outcome.json.truncated === true } }
: { status: 200, json: { ok: true, path: rel, entries: Array.isArray(outcome.json.entries) ? outcome.json.entries : [], truncated: outcome.json.truncated === true } };
// "failed" and "not_found": the list surfaces have no 404 branch — a
// daemon 404 is a listing failure like any other (both former routes
// mapped it through `status !== 200 || !json || !json.ok`).
default:
return relay
? { status: 502, json: { error: "node_list_failed" } }
: { status: 502, json: { error: "node_list_failed", detail: (outcome && outcome.json && outcome.json.error) || `status ${(outcome && outcome.status) || 0}` } };
}
}
// read — the editor read (daemon base64 + strict UTF-8 validation via
// decodeNodeFileReadContent). Panel success: { ok:true, path, content } /
// { ok:true, path, binary:true }; relay success: { path, content } /
// { path, binary:true } (spec D4). The PANEL route answers a daemon 404 with
// 404 { error: "file not found" }; the relay route has NO 404 branch — a
// missing file is node_read_failed there (spec §3 parity bodies). The over-cap
// body is shared verbatim by both surfaces.
function renderFsReadOutcome(outcome, rel, opts = {}) {
const relay = opts.variant === "relay";
switch (outcome && outcome.kind) {
case "not_found":
return relay
? { status: 502, json: { error: "node_read_failed" } }
: { status: 404, json: { error: "file not found" } };
case "too_large":
return { status: 502, json: { error: "node_response_too_large", message: FS_READ_TOO_LARGE_MESSAGE } };
case "ok": {
const decoded = decodeNodeFileReadContent(typeof outcome.json.content === "string" ? outcome.json.content : null, opts);
if (decoded.invalid) return { status: 502, json: { error: "node_read_failed" } };
if (decoded.binary) {
return relay
? { status: 200, json: { path: rel, binary: true } }
: { status: 200, json: { ok: true, path: rel, binary: true } };
}
return relay
? { status: 200, json: { path: rel, content: decoded.text } }
: { status: 200, json: { ok: true, path: rel, content: decoded.text } };
}
default:
return { status: 502, json: { error: "node_read_failed" } };
}
}
// stream — the panel's /files/stream external/API surface (spec §2 line 219,
// no frontend consumer): failures are plain-text end() bodies, success is the
// daemon's utf8 content served as text/plain; the Content-Type header is set
// by the route on the 200 path only, exactly as before. There is NO relay
// variant: spec §3 has no stream relay (the relay's download is a separate raw
// stream proxy) — a "relay" request here is a programming error, not a body
// this module may invent.
function renderFsStreamOutcome(outcome, opts = {}) {
if ((opts.variant || "panel") !== "panel") {
throw new Error("renderFsStreamOutcome: no relay-variant stream contract exists (spec §3) — panel only");
}
switch (outcome && outcome.kind) {
case "not_found":
return { status: 404, text: "file not found" };
case "too_large":
return { status: 502, text: FS_STREAM_TOO_LARGE_MESSAGE };
case "ok":
return { status: 200, text: typeof outcome.json.content === "string" ? outcome.json.content : "" };
// "failed" AND "offline": the former route had no node_offline branch —
// a status-0 dial fell through `status !== 200` to the generic body.
default:
return { status: 502, text: "node-read-failed" };
}
}
// ---------------------------------------------------------------------------
// Mutating-op renderers (Wave 2 Step B2) — same contract as the GET renderers
// above: a transport-neutral classification in, a byte-exact wire body out,
// per surface (spec §2 = "panel" = index.js routes, §3 = "relay" = nodes.js
// relays). Each renderer mirrors its former route bodies' branch ORDER exactly
// (507 quota → per-op status specials → generic 502 → success), because the
// first matching branch decided the response, and reproduces their trigger
// predicates verbatim (e.g. rename maps a daemon 404 OR a source_not_found
// error text at any status — not just the status code). What deliberately
// does NOT move here: auth/perm/suspension gates, input validation, path
// confinement, root refusals, pre-dial payload checks, the rename probe, the
// canonical archive URL segment (spec D23) and the create name sanitizer
// (spec D11) — those stay in the routes; the renderers own ONLY the daemon
// outcome → response mapping.
// ---------------------------------------------------------------------------
// write — the panel PUT /files/write and the relay POST file share the daemon
// /v1/fs/write outcome set. Per-surface differences (spec D6): the mapped 403
// permission bodies say "not authorized" on the panel, "permission denied" on
// the relay — same permission/detail fields, both pinned by tests. opts.base64
// selects the 413 message/limit variant (a base64 body's decoded ceiling is
// ~7.4 MB — the same rule on both surfaces, shared constants below). The 507
// quota passthrough relays the daemon's body verbatim.
function buildFsCreatePayload(target, server, { directory = false, content = "" } = {}) {
return { path: directory ? safeJoinUnix(target, ".keep") : target, server, content, encoding: "utf8", mode: "create" };
}
function reviewedFsRefusal(outcome, opts) {
if (!opts.reviewed || !outcome) return null;
const { status, json } = outcome;
if (status === 409 && json?.code === FS_WRITE_STALE_CONFLICT_ERROR) return staleFileWriteConflict();
if (opts.versionChecked && status === 400 && ["invalid JSON body", "bad json", "bad json or content too large (max 10MB)"].includes(json?.error)) {
return { status: 409, json: { error: "node_review_update_required" } };
}
if (status === 409 && json?.existed === true) return { status, json: { error: "review_path_exists" } };
if (status === 400 || status === 403 || status === 404 || status === 409 || status === 423) {
return { status, json: { error: status === 404 ? "review_path_missing" : "review_file_rejected" } };
}
return null;
}
function renderFsWriteOutcome(outcome, opts = {}) {
const relay = opts.variant === "relay";
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (isNodeQuota507(status, json)) return { status: 507, json };
const editorRefusal = renderEditorWriteRefusal(outcome, opts.editorGuard);
if (editorRefusal) return editorRefusal;
const refusal = reviewedFsRefusal(outcome, opts);
if (refusal) return refusal;
// Belt-and-suspenders (former route comment): a write that slipped past the
// route's pre-dial payload check (e.g. an operator raised the parser limit)
// comes back as the daemon's 400 "content too large (max 10MB)" — mapped to
// the same 413 shape instead of 502 node_write_failed.
if (status === 400 && typeof json?.error === "string" && json.error.includes(NODE_FS_WRITE_TOO_LARGE_MARKER)) {
const base64 = !!opts.base64;
return {
status: 413,
json: fileWriteTooLargePayload(
base64 ? FILE_WRITE_BASE64_LIMIT_CLIENT_MESSAGE : FILE_WRITE_LIMIT_CLIENT_MESSAGE,
base64 ? NODE_FS_WRITE_BASE64_LIMIT_MB : NODE_FS_WRITE_BODY_LIMIT_MB
),
};
}
// The node enforces create-vs-overwrite atomically; both surfaces surface
// those as a 403 so the user sees a permission boundary, not a 502.
if (status === 409) {
return {
status: 403,
json: {
error: relay ? "permission denied" : "not authorized",
permission: "files_write",
detail: "overwriting existing files requires the files_write permission",
},
};
}
if (status === 404 && json && json.existed === false) {
return {
status: 403,
json: {
error: relay ? "permission denied" : "not authorized",
permission: "files_create",
detail: "creating new files requires the files_create permission",
},
};
}
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true } };
return { status: 502, json: { error: "node_write_failed" } };
}
// mkdir — the panel's POST /files/mkdir creates the folder through the daemon's
// .keep-marker write (the daemon has no /v1/fs/mkdir). Panel-only: the relay
// surface has no mkdir route — its folder creation is POST /create
// (renderFsCreateOutcome), so a "relay" request here is a programming error,
// not an inventable contract (same posture as renderFsStreamOutcome). A daemon
// 404 on the marker write is a generic failure here — the write renderer's
// 403 files_create mapping belongs to the editor write contract, not mkdir.
function renderFsMkdirOutcome(outcome, opts = {}) {
if ((opts.variant || "panel") !== "panel") {
throw new Error("renderFsMkdirOutcome: no relay-variant mkdir contract exists (spec §3) — the relay's folder creation is POST /create");
}
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (isNodeQuota507(status, json)) return { status: 507, json };
const refusal = reviewedFsRefusal(outcome, opts);
if (refusal) return refusal;
if (status === 409) return { status: 400, json: { error: "already_exists" } };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true } };
return { status: 502, json: { error: "node_mkdir_failed" } };
}
// delete — the daemon /v1/fs/delete outcome mapping is byte-identical on both
// surfaces (panel /files/delete, relay .../delete): any non-ok outcome → 502
// node_delete_failed, success → { ok: true }. Deliberately NO 507 branch (the
// daemon does not quota a delete; neither former route mapped one) and NO 404
// branch — a missing path is a delete failure like any other. opts.variant is
// accepted for call-site symmetry only; the bodies were verified identical.
function renderFsDeleteOutcome(outcome, opts = {}) {
const refusal = reviewedFsRefusal(outcome, opts);
if (refusal) return refusal;
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true } };
return { status: 502, json: { error: "node_delete_failed" } };
}
// delete-batch — RELAY-ONLY op (spec D29: the daemon's /v1/fs/delete-batch is
// consumed only by nodes.js; the panel's counterpart is the socket single-delete
// loop). The former route's mapping is unusual and deliberate: it required only
// `status === 200 && json` — NOT the daemon's ok flag — because the daemon's
// 200 body is a per-item results envelope ({ ok: failCount === 0, results,
// success, failed }) whose top-level ok:false is a PARTIAL-SUCCESS answer the
// client must still receive verbatim. It is therefore keyed on status/json
// directly, not on the classifyNodeJsonResult "ok" kind (a 200 envelope with
// ok:false classifies as "failed" but must still relay). Every non-200 (and
// offline/too-large) outcome is 502 node_batch_delete_failed. Panel-only
// callers are a programming error: there is no panel route to preserve, so a
// "panel" request throws rather than inventing a body.
function renderFsDeleteBatchOutcome(outcome, opts = {}) {
if ((opts.variant || "relay") !== "relay") {
throw new Error("renderFsDeleteBatchOutcome: delete-batch is a relay-only op (spec D29) — the panel has no such route");
}
if (outcome && outcome.status === 200 && outcome.json) return { status: 200, json: outcome.json };
return { status: 502, json: { error: "node_batch_delete_failed" } };
}
// rename — the daemon /v1/fs/rename outcome mapping is byte-identical on both
// surfaces (panel /files/rename, relay .../rename): 409 or a
// destination_exists error text → 409; 404 or a source_not_found error text →
// 404; 400 → "invalid path"; everything else (incl. offline/too-large dials)
// → 502 node_rename_failed. The status-code OR error-text predicates match the
// former routes exactly, including their precedence over the ok branch. The
// destination pre-check probe and the input derivation stay in the routes: the
// probe's list body and its 409 rendering differ per surface (JSON vs the
// legacy text routes), and the rename input contracts differ (spec D9).
// opts.variant is accepted for call-site symmetry only.
function renderFsRenameOutcome(outcome, opts = {}) {
void opts;
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (status === 409 || json?.error === "destination_exists") return { status: 409, json: { error: "destination_exists" } };
if (status === 404 || json?.error === "source_not_found") return { status: 404, json: { error: "source_not_found" } };
if (status === 400) return { status: 400, json: { error: "invalid path" } };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true } };
return { status: 502, json: { error: "node_rename_failed" } };
}
// extract — success msg (spec D20): the skipped>0 wording is shared verbatim;
// the skipped===0 wording differs ("Extracted successfully" on the panel vs
// the daemon's own msg || "Extracted" on the relay). 507 passthrough on both
// surfaces (a clamped extraction budget is a quota answer).
function renderFsExtractOutcome(outcome, opts = {}) {
const relay = opts.variant === "relay";
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (opts.noClobber && (status === 405 || (status === 404 && json?.error === "not found"))) {
return { status: 503, json: { error: "node_extract_upgrade_required", message: "Update the node to extract archives without overwriting existing files." } };
}
if (isNodeQuota507(status, json)) return { status: 507, json };
if (outcome && outcome.kind === "ok") {
const skipped = Number(json.skipped || 0);
const msg = skipped > 0
? `Extracted with ${skipped} existing file(s) skipped`
: (relay ? (json.msg || "Extracted") : "Extracted successfully");
return { status: 200, json: { ok: true, msg, skipped } };
}
return { status: 502, json: { error: "node_extract_failed" } };
}
// archive — the per-server archive endpoint's outcome mapping is byte-identical
// on both surfaces (panel /archive, relay .../archive): failure relays the
// daemon's own error text ({ error: json?.error || "archive failed" }), success
// relays { ok, path, name } from the daemon body. The missing-input 400s and
// the canonical URL segment differ per surface (spec D22/D23) and stay in the
// routes. opts.variant is accepted for call-site symmetry only.
function renderFsArchiveOutcome(outcome, opts = {}) {
void opts;
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (isNodeQuota507(status, json)) return { status: 507, json };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true, path: json.path, name: json.name } };
return { status: 502, json: { error: json?.error || "archive failed" } };
}
// Legacy create (panel POST /create) — the TEXT error contract (spec D10/D13):
// 409 → 400 text "already_exists"; a generic daemon failure used to throw
// Error("node-create-failed") into the route's masked catch, whose former
// raw-message fallback put that literal text on the wire. The masker no longer
// echoes raw error text (adpanel:path-error-mask), so this generic failure now
// answers the route's masked default "Create failed" — still THROUGH the
// shared masker, not re-typed, so it cannot drift from the route's own catch
// (index.js: same masker, same fallback pair). Success stays JSON
// ({ ok, path }). Panel-only: the relay's create answers JSON.
function renderFsCreateLegacyOutcome(outcome, relativePosix, opts = {}) {
if ((opts.variant || "panel") !== "panel") {
throw new Error("renderFsCreateLegacyOutcome: the legacy create text contract is panel-only (spec §2/D10) — the relay's JSON create is renderFsCreateOutcome");
}
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (isNodeQuota507(status, json)) return { status: 507, json };
if (status === 409) return { status: 400, text: "already_exists" };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true, path: relativePosix } };
return { status: 400, text: maskPathErrorMessage(new Error("node-create-failed"), "Invalid path", "Create failed") };
}
// Legacy rename (panel POST /rename) — the TEXT error contract (spec D10):
// 409 or a destination_exists error text → 409 text "A file with that name
// already exists"; 404 or a source_not_found error text → 404 text "Source
// not found"; 400 → text "Invalid path"; everything else non-ok → 500 text
// "Rename failed" (note: 500, not 502 — the legacy route's own body). Success
// stays JSON ({ ok, path }). Panel-only: the relay's rename answers JSON
// (renderFsRenameOutcome).
function renderFsRenameLegacyOutcome(outcome, relative, opts = {}) {
if ((opts.variant || "panel") !== "panel") {
throw new Error("renderFsRenameLegacyOutcome: the legacy rename text contract is panel-only (spec §2/D10) — the relay's rename is renderFsRenameOutcome");
}
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (status === 409 || json?.error === "destination_exists") return { status: 409, text: "A file with that name already exists" };
if (status === 404 || json?.error === "source_not_found") return { status: 404, text: "Source not found" };
if (status === 400) return { status: 400, text: "Invalid path" };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true, path: relative } };
return { status: 500, text: "Rename failed" };
}
// Relay create (nodes.js POST /api/nodes/server/:name/create) — the JSON
// create contract (spec §3): the daemon's existence failures (error text
// containing "exist"/"EEXIST") map to 400 { error: "already_exists", message }
// with the type-bearing message; anything else non-ok is 502
// { error: "node_create_failed", message }; success relays
// { ok: true, path }. Note there is deliberately NO 409 special case — the
// former relay route ran only the error-text check. The input 400s
// (invalid_type / invalid_name) and the file-name sanitizer (spec D11) stay in
// the route; opts.type only feeds the failure messages.
function renderFsCreateOutcome(outcome, relativePosix, opts = {}) {
if ((opts.variant || "relay") !== "relay") {
throw new Error("renderFsCreateOutcome: the JSON create contract is the relay's (spec §3) — the panel's legacy create answers text (renderFsCreateLegacyOutcome)");
}
const type = String(opts.type || "");
const status = (outcome && outcome.status) || 0;
const json = (outcome && outcome.json) || null;
if (isNodeQuota507(status, json)) return { status: 507, json };
if (outcome && outcome.kind === "ok") return { status: 200, json: { ok: true, path: relativePosix } };
const errMsg = json?.error || "";
if (errMsg.includes("exist") || errMsg.includes("EEXIST")) {
return { status: 400, json: { error: "already_exists", message: `A ${type} with that name already exists` } };
}
return { status: 502, json: { error: "node_create_failed", message: `Failed to create ${type}. It may already exist.` } };
}
// ---------------------------------------------------------------------------
// Editor save optimistic-concurrency guard (adpanel:editor-save-occ) — ONE
// shared pre-write verification for BOTH panel write entry points (the
// PUT /api/servers/:name/files/write route and the socket "writeFile" twin,
// which is a documented carve-out duplicate of the write outcome mapping).
// adpanel:editor-save-occ - carry the loaded hash into the serialized daemon write.
// The machine-readable error code (client branches on it) and the user-facing
// message — both live here so the route and the socket twin cannot drift.
const FS_WRITE_STALE_CONFLICT_ERROR = "file_changed_on_disk";
const FS_WRITE_STALE_CONFLICT_MESSAGE = "Save blocked: this file changed on disk after you opened it, so saving would overwrite the newer version. Reload the file and re-apply your changes.";
function staleFileWriteConflict() {
return {
ok: false,
status: 409,
json: { error: FS_WRITE_STALE_CONFLICT_ERROR, message: FS_WRITE_STALE_CONFLICT_MESSAGE },
};
}
function attachEditorWriteHash(payload, expectedSha256) {
if (typeof expectedSha256 !== "string" || !expectedSha256) return true;
if (!/^[0-9a-fA-F]{64}$/.test(expectedSha256)) return false;
payload.editorBaseSha256 = expectedSha256.toLowerCase();
return true;
}
function renderEditorWriteRefusal(outcome, editorGuard) {
if (!editorGuard || !outcome) return null;
if (outcome.status === 409 && outcome.json?.code === FS_WRITE_STALE_CONFLICT_ERROR) return staleFileWriteConflict();
if (outcome.status === 400 && ["invalid JSON body", "bad json", "bad json or content too large (max 10MB)"].includes(outcome.json?.error)) {
return { status: 503, json: { error: "node_editor_upgrade_required", message: "Update the node before saving this file. Your edits have not been saved." } };
}
return null;
}
// ---------------------------------------------------------------------------
// Suspension gates — index.js's sendSuspendedServerJson inlined the 423 body;
// nodes.js factored it into suspendedServerBody. Bodies verified identical
// field-by-field, so ONE factored implementation serves both (nodes.js also
// re-uses suspendedServerBody for its performer 423 results).
// ---------------------------------------------------------------------------
function isServerSuspended(entry) {
return !!(entry && entry.suspended);
}
function suspendedServerBody(srv = null) {
return {
error: "server suspended",
code: "server-suspended",
server: srv?.name || null,
suspendedAt: srv?.suspended_at || null,
suspendedBy: srv?.suspended_by || null,
};
}
function sendSuspendedServerJson(res, entry = null) {
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private");
return res.status(423).json(suspendedServerBody(entry));
}
// adpanel:upload-multipart-setup — parser construction can throw before an error listener exists.
function createUploadMultipartParser(busboy, request, respond, logError) {
if (request.destroyed && !request.complete) return null;
let failed = false;
const onError = (err) => {
if (failed) return;
failed = true;
logError(err);
respond(400, { error: "bad_multipart", detail: "invalid multipart form data" });
};
let parser;
try {
parser = busboy({ headers: request.headers, defParamCharset: "utf8", limits: { files: 1, fields: 8, fieldSize: 64 * 1024 } });
} catch (err) {
onError(err);
return null;
}
const fields = Object.create(null);
parser.on("field", (name, value) => {
if (!Object.isFrozen(fields) && (name === "bot" || name === "path" || name === "filename")) fields[name] = value;
});
// adpanel:upload-target-binding - bind metadata and handle part errors before route awaits.
parser.on("file", (_name, fileStream, info) => {
if (!Object.isFrozen(fields)) {
fields.filename ??= info?.filename || "upload";
Object.freeze(fields);
}
fileStream.on("error", onError);
});
parser.on("error", onError);
// adpanel:upload-request-close - piping does not terminate an active file part when the client disconnects.
const onRequestClose = () => {
if (!request.complete) parser.destroy(new Error("Upload request closed before completion"));
};
request.once("close", onRequestClose);
parser.once("close", () => request.removeListener("close", onRequestClose));
return { parser, fields };
}
function buildNodeUploadMultipart(boundary, serverName, directory, filename) {
const server = String(serverName || "").replace(/[\u0000-\u001f"]/g, "_");
const dir = String(directory || "");
const name = String(filename || "upload.bin").replace(/[\u0000-\u001f\u007f]/g, "_").replace(/["\\]/g, "\\$&");
// adpanel:fs-path-identity - a field body can contain quotes; never remap the selected directory.
if (/[\u0000-\u001f\u007f]/.test(dir)) throw new Error("Unsafe characters in path");
const serverPart = server
? `--${boundary}\r\nContent-Disposition: form-data; name="server"\r\n\r\n${server}\r\n`
: "";
return {
preamble: Buffer.from(serverPart +
`--${boundary}\r\nContent-Disposition: form-data; name="dir"\r\n\r\n${dir}\r\n` +
`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\n` +
"Content-Type: application/octet-stream\r\n\r\n", "utf8"),
epilogue: Buffer.from(`\r\n--${boundary}--\r\n`, "utf8"),
};
}
// adpanel:fs-no-clobber - old daemons reject PUT rather than ignoring the restriction.
function nodeNoClobberMethod(createOnly) {
return createOnly ? "PUT" : "POST";
}
function renderCreateOnlyUploadFailure(result, createOnly) {
if (!createOnly) return null;
if (result.status === 409 && result.json?.error === "destination_exists") {
return { status: 409, json: { error: "destination_exists", message: "A file with this name already exists. Choose a different name." } };
}
if (result.status === 404 || result.status === 405) {
return { status: 503, json: { error: "node_upload_upgrade_required", message: "The node must support protected uploads before this file can be uploaded." } };
}
return null;
}
module.exports = {
safeJoinUnix,
safeJoinUnixRelay,
isServerRootResolvedPath,
maskPathErrorMessage,
isPathTraversalError,
maskPathErrorMessageRelay,
isNodeQuota507,
finiteNumber,
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,
createUploadMultipartParser,
buildNodeUploadMultipart,
nodeNoClobberMethod,
renderCreateOnlyUploadFailure,
createNodeFsPost,
createNodeDiskSnapshotFetcher,
relayFsJson,
classifyNodeJsonResult,
buildFsListPayload,
buildFsCreatePayload,
renderFsListOutcome,
renderFsReadOutcome,
renderFsStreamOutcome,
renderFsWriteOutcome,
renderFsMkdirOutcome,
renderFsDeleteOutcome,
renderFsDeleteBatchOutcome,
renderFsRenameOutcome,
renderFsExtractOutcome,
renderFsArchiveOutcome,
renderFsCreateLegacyOutcome,
renderFsCreateOutcome,
renderFsRenameLegacyOutcome,
FS_LIST_TOO_LARGE_MESSAGE,
FS_LIST_OFFLINE_MESSAGE,
FS_READ_TOO_LARGE_MESSAGE,
FS_STREAM_TOO_LARGE_MESSAGE,
isServerSuspended,
suspendedServerBody,
sendSuspendedServerJson,
FS_WRITE_STALE_CONFLICT_ERROR,
FS_WRITE_STALE_CONFLICT_MESSAGE,
attachEditorWriteHash,
renderEditorWriteRefusal,
};