const express = require("express"); const fs = require("fs"); const fsp = require("fs/promises"); const path = require("path"); const crypto = require("crypto"); const net = require("net"); const dns = require("dns").promises; const http = require("http"); const https = require("https"); const ipRangeCheck = require("ip-range-check"); const nodeSsrfGuard = require("./utils/node-ssrf-guard"); const { rejectCrossSiteRead } = require("./utils/cross-site-read-guard"); const remoteUrlGuard = require("./utils/remote-url-guard"); const { isNodeApiPath } = require("./utils/node-api-path"); const { withKeyedLock, tryWithKeyedLock } = require("./utils/keyed-async-lock"); const { validateDiskMountPathPanel } = require("./utils/disk-mount-validation"); const { NODE_SERVER_ASSIGNMENT_WHERE, nodeServerAssignmentParams, assignedServerPortUses } = require("./utils/server-host-ports"); // adpanel:sanitizer-lockstep — sanitizeNodeStorageName is the ONE JS mirror of // the daemon's Go sanitizeName (main.go); every server-storage derivation in // this module (remoteContext, baseDir validation/resolution, daemon dials) // and the node-name normalizers bind it. The former local sanitizeName copy // (100-char cap, no "-_." two-end trim, no leading non-alphanumeric strip) // diverged from Go for 101-120-char legacy names and is deleted below. const { sanitizeServerToken, sanitizeDisplayNameToken, sanitizeNodeStorageName, getCanonicalServerName } = require("./utils/server-name"); const { getReinstallPowerConflict, withServerPowerStart } = require("./utils/server-op-guard"); // adpanel:sanitizer-lockstep — file/folder names are a DIFFERENT namespace // from server storage names: the canonical file-name mirror (Go // sanitizeUploadFilename) keeps leading dots (.env) and valid non-ASCII that // the panel /create route passes through and the daemon preserves on upload. // The /create relay binds it directly (utils/upload-filename.js requires only // node:path — no import cycle). const { sanitizeUploadFilename } = require("./utils/upload-filename"); const { activityLogFileKey, legacyActivityLogFileKey } = require("./utils/activity-log-name"); const { setPinnedDownloadHeaders } = require("./utils/download-headers"); const { resolveMcFork, resolveMcVersion, SUPPORTED_MC_FORKS, } = require("./utils/minecraft-versions"); // adpanel:server-create-consolidation — the node-proxy create path runs its // shared steps (name guards, in-lock duplicate check, same-node // storage-collision scan, guarded index commit + ownership-guarded // compensation) through the ONE shared server-creation service. This module // requires the service directly (services requires only utils/* — no cycle: // index.js → nodes.js → services → utils); the index-owned capabilities the // service needs on this path (findServer, normalizeTemplateId) arrive through // setServerCreateHelpers below. const { serverNameGuardOutcome, duplicateServerNameOutcome, scanNodeStorageCollisions, commitCreatedServer, resolveServerCreateBindAddress, renderServerCreateOutcome, } = require("./services/server-create"); // adpanel:relay-helper-consolidation — the node HTTP/relay helpers are // re-homed into services/ (ONE implementation for index.js and nodes.js; the // drifting twins were deleted from this file in the same commit). Identifiers // are bound under the SAME names they had when defined here (relay-flavored // exports are renamed into their original local names in the destructure), so // no call site changed. The buildNodeBaseUrl binding keeps this surface's // exact outputs (clampPort clamping, the // toString-without-trailing-slash URL form, unclamped explicit-URL-branch // port, always-present X-Node-Token-Id) while inheriting the shared module's // ONE unconditional hardening: credential-in-URL rejection on a node address // embedding user:pass (previously this relay forwarded such URLs verbatim). const { truthyFlag, CLOUDFLARE_HTTPS_EDGE_PORTS, stripExplicitHostPort, createBuildNodeBaseUrl, nodeTlsAgent, nodeHeaders, nodeUnderCloudflare, nodeConnectionState, openNodeConsoleLogStream, // adpanel:relay-helper-consolidation (Wave 3) — the hardened buffered-dial // core. This surface's httpJson and GET-probe httpRequestJson are now thin // wrappers over it (bound under their original names below); the alias // keeps the wrapper identifier distinct from the wrapped contract. httpRequestJson: httpRequestJsonCore, } = require("./services/node-http"); const buildNodeBaseUrl = createBuildNodeBaseUrl({ clampEdgePort: clampPort, clampUrlPathPort: (p) => p, clampBareHostPort: clampPort, returnOrigin: false, }); const { safeJoinUnixRelay: safeJoinUnix, isServerRootResolvedPath, maskPathErrorMessageRelay: maskPathErrorMessage, isNodeQuota507, finiteNumber, isServerSuspended, suspendedServerBody, sendSuspendedServerJson, // Wave 2 Step B3 (adpanel:relay-helper-consolidation): the shared JSON-relay // DIAL + per-op renderers. The relay-variant rows are the byte-contract of // spec .campaign/spec-relay.md §3 — the "relay" bodies below are the ones // this surface's routes put on the wire before the dial/mapping moved here. relayFsJson, buildFsListPayload, buildFsCreatePayload, renderFsListOutcome, renderFsReadOutcome, renderFsWriteOutcome, // adpanel:node-file-write-scoped-parser — the shared 413 body (ONE home for // the wire string, byte-identical to what the panel-side write route // answers) mapped from body-parser's bare 413 on this surface's scoped // write parser below. fileWriteTooLargePayload, renderFsDeleteOutcome, renderFsDeleteBatchOutcome, renderFsRenameOutcome, renderFsExtractOutcome, renderFsArchiveOutcome, renderFsCreateOutcome, attachEditorWriteHash, createNodeDiskSnapshotFetcher, createUploadMultipartParser, buildNodeUploadMultipart, nodeNoClobberMethod, renderCreateOnlyUploadFailure, } = require("./services/node-fs-relay"); const db = require("./db"); const nodeTokenCrypto = require("./utils/node-token-crypto"); const { deriveNodeHmacSecret, signPanelProbeRequest, verifyNodeProbeResponse } = require("./utils/node-hmac"); const { createNonceCache, createSharedHeartbeatNonceStore, verifyHeartbeatEnvelope } = require("./utils/heartbeat-auth"); const panelHmacSecret = require("./utils/panel-hmac-secret"); const { createNodeBootstrapStore, createNodeBootstrapRateLimiter, createBootstrapScriptHandler, createBootstrapConfigHandler, clientIpFromReqDefault, isEnrollId, } = require("./utils/node-bootstrap"); // Trusted-proxy-aware client-IP extraction shared with index.js. index.js // keeps an equivalent PRIVATE copy of these helpers (it cannot be required // from here: index.js requires this module, so a require back would be // circular) — keep utils/trusted-proxy-ip.js and the index.js copy in sync. const { getTrustedForwardedFor, getDirectRemoteIp, } = require("./utils/trusted-proxy-ip"); const ACTIVITY_LOGS_DIR = path.join(__dirname, ".activity-logs"); const ACTIVITY_LOG_BATCH_INTERVAL = parseInt(process.env.ACTIVITY_LOG_BATCH_INTERVAL || "", 10) || 1000; const ACTIVITY_LOG_MAX_SIZE = parseInt(process.env.ACTIVITY_LOG_MAX_SIZE || "", 10) || 5 * 1024 * 1024; const ACTIVITY_LOG_MAX_FILES = parseInt(process.env.ACTIVITY_LOG_MAX_FILES || "", 10) || 10; const ACTIVITY_LOG_MAX_BUFFER_SIZE = 100; const ACTIVITY_LOG_MAX_SERVERS = parseInt(process.env.ACTIVITY_LOG_MAX_SERVERS || "", 10) || 5000; // Ceiling for the failed-write retry backoff (doubles per consecutive // failure, see armActivityLogRetryTimer): a persistent ENOSPC must not // hot-loop disk writes. const ACTIVITY_LOG_MAX_WRITE_RETRY_INTERVAL_MS = 30 * 1000; // adpanel:activity-log-mode — the activity store holds full actor emails, IPs // and verbatim console_command payloads, so it gets the same at-rest posture // as the session store (SESSION_DIR is mkdir'd 0o700) and the secret configs // (atomic writes at 0o600): the directory is 0o700 and every log file 0o600. // mkdir's mode applies only to freshly created directories and appendFile's // mode only to freshly created files, so EXISTING installs are repaired // best-effort below: chmod the directory and every *.log inside it that this // process owns. A chmod failure (EPERM on odd deployments) is warned and // never fatal — fresh files still converge to 0o600 on every append. const ACTIVITY_LOG_DIR_MODE = 0o700; const ACTIVITY_LOG_FILE_MODE = 0o600; try { fs.mkdirSync(ACTIVITY_LOGS_DIR, { recursive: true, mode: ACTIVITY_LOG_DIR_MODE }); } catch { } // Boot repair for files created before the modes existed (they landed at the // umask default, world-readable). Only *.log files inside ACTIVITY_LOGS_DIR // are touched, every per-file failure is tolerated with a warn, and the // whole repair never throws — module init must not crash over permissions. try { fs.chmodSync(ACTIVITY_LOGS_DIR, ACTIVITY_LOG_DIR_MODE); } catch (dirChmodErr) { console.warn("[activity-log] Could not tighten permissions on the activity log directory:", dirChmodErr?.message || dirChmodErr); } try { for (const entry of fs.readdirSync(ACTIVITY_LOGS_DIR)) { if (!entry.endsWith(".log")) continue; try { fs.chmodSync(path.join(ACTIVITY_LOGS_DIR, entry), ACTIVITY_LOG_FILE_MODE); } catch (fileChmodErr) { console.warn(`[activity-log] Could not tighten permissions on activity log file ${entry}:`, fileChmodErr?.message || fileChmodErr); } } } catch (readdirErr) { console.warn("[activity-log] Could not repair activity log file permissions:", readdirErr?.message || readdirErr); } const activityLogBuffers = new Map(); const activityLogWriteTimers = new Map(); // Concurrency/backoff state per server: the in-flight flush promise (so // overlapping flushActivityLogs calls serialize instead of double-writing or // losing entries) and the consecutive write-failure count (drives the retry // backoff; reset on success). const activityLogInFlightFlushes = new Map(); const activityLogWriteFailures = new Map(); function getActivityLogPath(serverName) { // Cross-tenant fix: the filename key MUST be the injective encoding from // utils/activity-log-name.js, not the old non-injective collapse (every // character outside [A-Za-z0-9_-] rewritten to an underscore). Server names // legally contain dots (sanitizeServerToken keeps [A-Za-z0-9\-_.]), so the // old collapse mapped "shop.bot" and "shop_bot" onto ONE shared file while // the access check authorized the raw requested name — either tenant could // read the other's full audit trail. The new key keeps the same // [A-Za-z0-9_-] charset but never merges two distinct names. return path.join(ACTIVITY_LOGS_DIR, `${activityLogFileKey(serverName)}.log`); } function validatePortInput(value) { if (value === undefined || value === null) return null; const str = String(value).trim(); if (!/^[1-9]\d{0,4}$/.test(str)) return null; const port = Number(str); if (!Number.isInteger(port) || port < 1 || port > 65535) return null; return port; } async function rotateActivityLogIfNeeded(serverName) { const logPath = getActivityLogPath(serverName); try { const stats = await fsp.stat(logPath).catch(() => null); if (!stats || stats.size < ACTIVITY_LOG_MAX_SIZE) return; // The rotated-file prefix and the pruning filter below MUST use the SAME // key getActivityLogPath wrote the live file under, otherwise pruning // would either starve (never matching the new-style rotated files) or // over-match (deleting another server's history). legacyKey additionally // covers files written before the injective-key fix, which were named // `${legacyKey}.${ts}.log` with the old collapsing transform. const key = activityLogFileKey(serverName); const legacyKey = legacyActivityLogFileKey(serverName); const rotatedPath = logPath.replace(/\.log$/, `.${Date.now()}.log`); await fsp.rename(logPath, rotatedPath); setImmediate(async () => { try { const files = await fsp.readdir(ACTIVITY_LOGS_DIR); // Prune BOTH prefixes: `${key}.` matches this server's post-fix // rotated files, `${legacyKey}.` matches pre-fix ones (and the live // pre-fix file, excluded explicitly below). When key === legacyKey // (all-ASCII name) the two prefixes are identical, so nothing changes // for names that never contained a character outside [A-Za-z0-9_-]. // Pre-fix legacy prefixes can be shared by two servers (that is the // collision this fix removes); such files are dead history — the // reader skips ambiguous legacy files — so pruning them from either // side loses nothing readable. const isRotated = (fname, prefix) => fname.startsWith(prefix + ".") && fname.endsWith(".log"); const serverFiles = files .filter(f => (isRotated(f, key) || (legacyKey && legacyKey !== key && isRotated(f, legacyKey))) && f !== `${key}.log` && f !== `${legacyKey}.log`) .sort() .reverse(); for (let i = ACTIVITY_LOG_MAX_FILES; i < serverFiles.length; i++) { await fsp.unlink(path.join(ACTIVITY_LOGS_DIR, serverFiles[i])).catch(() => { }); } } catch { } }); } catch (err) { // Rotation failure is logged but deliberately NOT propagated: the current // log file is often still writable, so flushActivityLogs must go on and // attempt the append anyway. The fire-and-forget pruning of old rotated // files above is untouched. console.error(`[activity-log] Rotation failed for ${serverName}:`, err?.message || err); } } function requeueFailedActivityLogEntries(serverName, failedEntries) { // recordActivity may have pushed newer entries into a fresh buffer while // the failed write was in progress; those newer entries sit at the front of // the live buffer, so the failed (older) batch is PREPENDED to keep the // chronological ordering intact. const current = activityLogBuffers.get(serverName); let merged = failedEntries.concat(Array.isArray(current) ? current : []); if (merged.length > ACTIVITY_LOG_MAX_BUFFER_SIZE) { const dropped = merged.length - ACTIVITY_LOG_MAX_BUFFER_SIZE; // Drop the OLDEST overflow entries (head of the merged list) so repeated // failures can never grow the buffer unboundedly. merged = merged.slice(dropped); console.error(`[activity-log] Dropped ${dropped} oldest buffered activity entries for ${serverName} (retry buffer exceeded ${ACTIVITY_LOG_MAX_BUFFER_SIZE} entries)`); } activityLogBuffers.set(serverName, merged); } function armActivityLogRetryTimer(serverName) { const failures = (activityLogWriteFailures.get(serverName) || 0) + 1; activityLogWriteFailures.set(serverName, failures); // Modest backoff: double the batch interval per consecutive failure, capped // at ACTIVITY_LOG_MAX_WRITE_RETRY_INTERVAL_MS, reset on success (the write // path deletes the counter). A persistent ENOSPC therefore retries at 2x, // 4x, 8x ... the batch interval instead of hot-looping disk writes. const delay = Math.min( ACTIVITY_LOG_BATCH_INTERVAL * Math.pow(2, failures), ACTIVITY_LOG_MAX_WRITE_RETRY_INTERVAL_MS ); const previousTimer = activityLogWriteTimers.get(serverName); if (previousTimer) clearTimeout(previousTimer); activityLogWriteTimers.set(serverName, setTimeout(() => flushActivityLogs(serverName), delay)); } // Append everything buffered for one server to its log file. Awaitable and // safe to call concurrently. Overlapping calls for the same server are // serialized: each call first SYNCHRONOUSLY claims (detaches) whatever is // buffered — so two flushes can never take the same batch, and entries // recordActivity pushes during a write land in a fresh buffer for the next // flush — then AWAITS any in-flight write before writing its own claimed // batch. The await (rather than a no-op) is deliberate: index.js's activity // reader calls flushActivityLogs right before reading the log, and a no-op // would let the reader observe the file WITHOUT the batch currently being // appended. On a write failure the claimed batch is re-buffered (prepended, // capped) and a backed-off retry timer is armed; flush never throws. async function flushActivityLogs(serverName) { if (!serverName) return; // 1. Synchronously claim the buffered batch (no await before this point). const buffer = activityLogBuffers.get(serverName); const hasBatch = !!(buffer && buffer.length > 0); if (hasBatch) { activityLogBuffers.set(serverName, []); const pendingTimer = activityLogWriteTimers.get(serverName); if (pendingTimer) clearTimeout(pendingTimer); activityLogWriteTimers.delete(serverName); } // 2. Serialize behind an in-flight write for this server, if any. The loop // also covers a flush that chained onto the write we just awaited. while (true) { const inFlight = activityLogInFlightFlushes.get(serverName); if (!inFlight) break; try { await inFlight; } catch { /* the write never rejects; defensive */ } } if (!hasBatch) return; // 3. Write the claimed batch. The in-flight slot is set synchronously with // the claim (the IIFE below runs synchronously up to its first real await), // so no other flush can slip in between claiming and registering. const logPath = getActivityLogPath(serverName); const write = (async () => { let lines; try { // Rotation failure must NOT prevent the append attempt: rotate // activityLogIfNeeded logs its own failure and never throws, and the // local catch below is a structural guarantee the append is attempted. try { await rotateActivityLogIfNeeded(serverName); } catch (rotateErr) { console.error(`[activity-log] Rotation error for ${serverName}:`, rotateErr?.message || rotateErr); } lines = buffer.map(entry => JSON.stringify(entry)).join("\n") + "\n"; // adpanel:activity-log-mode — the mode applies when the file is CREATED; // appends to an existing file never loosen it, and the boot repair at // the top of this module converges pre-existing files to the same mode. await fsp.appendFile(logPath, lines, { encoding: "utf8", mode: ACTIVITY_LOG_FILE_MODE }); activityLogWriteFailures.delete(serverName); // success resets the backoff } catch (err) { console.error(`[activity-log] Write error for ${serverName}:`, err?.message || err); if (lines === undefined) { // Serialization itself failed (e.g. a circular `details` object): // retrying cannot succeed, so the batch is dropped instead of // looping on poison entries. Nothing is re-queued and no retry timer // is armed. console.error(`[activity-log] Dropped ${buffer.length} unserializable activity entries for ${serverName}`); return; } // Re-buffer the failed batch (prepended, capped — see helper) and // schedule a backed-off retry. requeueFailedActivityLogEntries(serverName, buffer); armActivityLogRetryTimer(serverName); } })(); activityLogInFlightFlushes.set(serverName, write); try { await write; } finally { if (activityLogInFlightFlushes.get(serverName) === write) { activityLogInFlightFlushes.delete(serverName); } } } let _webhookDispatcher = null; function setWebhookDispatcher(fn) { _webhookDispatcher = fn; } // Audit-log contract: `serverName` MUST be the canonical server name // (servers row `name`, e.g. ctx.server.name from remoteContext), NOT a raw // URL parameter — relay resolution is case-insensitive and alias-aware across // name/legacy_id/bot/id, so logging the raw requested token would split the // entry into a log file the activity scene (keyed on the canonical name) // never shows. Call sites should pass getCanonicalServerName(ctx.server, // rawFallback). This function is sync and DB-free, so it cannot normalize // the name itself. function recordActivity(serverName, action, details, userEmail, userIp) { if (!serverName) return; const entry = { ts: Date.now(), action: String(action || "unknown"), details: details || null, user: String(userEmail || "unknown"), ip: String(userIp || "unknown"), }; if (!activityLogBuffers.has(serverName)) { if (activityLogBuffers.size >= ACTIVITY_LOG_MAX_SERVERS) { const oldest = activityLogBuffers.keys().next().value; if (oldest) { flushActivityLogs(oldest); activityLogBuffers.delete(oldest); if (activityLogWriteTimers.has(oldest)) { clearTimeout(activityLogWriteTimers.get(oldest)); activityLogWriteTimers.delete(oldest); } // Map hygiene: drop the evicted server's backoff state too (a still // in-flight or retried flush is unaffected; a later failure simply // restarts the backoff at 2x the batch interval). activityLogWriteFailures.delete(oldest); } } activityLogBuffers.set(serverName, []); } const buffer = activityLogBuffers.get(serverName); buffer.push(entry); if (_webhookDispatcher) { try { _webhookDispatcher(entry.action, entry.details, entry.user, serverName); } catch (e) { } } if (buffer.length >= ACTIVITY_LOG_MAX_BUFFER_SIZE) { if (activityLogWriteTimers.has(serverName)) { clearTimeout(activityLogWriteTimers.get(serverName)); activityLogWriteTimers.delete(serverName); } setImmediate(() => flushActivityLogs(serverName)); return; } if (!activityLogWriteTimers.has(serverName)) { const timerId = setTimeout(() => flushActivityLogs(serverName), ACTIVITY_LOG_BATCH_INTERVAL); activityLogWriteTimers.set(serverName, timerId); } } // Trusted-proxy-aware client IP, mirroring index.js's getRequestIp exactly // (shared implementation in utils/trusted-proxy-ip.js — index.js keeps an // equivalent private copy that must be kept in sync; it cannot be required // from here because index.js requires this module). The previous version // trusted the LEFTMOST X-Forwarded-For value unconditionally, letting any // client forge the IP recorded in audit entries and webhooks. Semantics now: // XFF is honored only when the DIRECT socket peer is a trusted proxy // (loopback or TRUSTED_PROXY_IPS); the hop chain is then walked // right-to-left to the first untrusted address; otherwise the direct socket // address wins; with no socket address (e.g. a UNIX socket) the result is // "unknown". Note req.ip is deliberately NOT used: it can itself be // XFF-derived under Express trust-proxy settings. function getRequestIp(req) { const forwarded = getTrustedForwardedFor(req); const direct = getDirectRemoteIp(req); return forwarded || direct || "unknown"; } const MAX_CONSOLE_COMMAND_LENGTH = parseInt(process.env.MAX_CONSOLE_COMMAND_LENGTH || "", 10) || 512; function sanitizeConsoleCommand(rawValue) { const raw = String(rawValue || "").replace(/\0/g, "").trim(); if (!raw) { return { ok: false, error: "empty_command" }; } if (raw.length > MAX_CONSOLE_COMMAND_LENGTH) { return { ok: false, error: "command_too_long", detail: `Console commands must be ${MAX_CONSOLE_COMMAND_LENGTH} characters or fewer.`, }; } if (/[\r\n]/.test(raw)) { return { ok: false, error: "multiline_command_not_allowed", detail: "Only one console command can be sent at a time.", }; } if (/[\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(raw)) { return { ok: false, error: "invalid_command_characters", detail: "Console commands cannot include control characters.", }; } return { ok: true, command: raw }; } let _getEffectivePermsForUserOnServer = null; let _isAdmin = null; let _userHasAccessToServer = null; let _consoleLogSessionChecks = null; let _serverActionObserver = null; function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn, consoleLogSessionChecks = null) { _getEffectivePermsForUserOnServer = getPerms; _isAdmin = isAdminFn; _userHasAccessToServer = hasAccessFn || null; _consoleLogSessionChecks = consoleLogSessionChecks; } function setServerActionObserver(fn) { _serverActionObserver = typeof fn === "function" ? fn : null; } // M3: the node-proxy create path must commit a panel index row after the // daemon create succeeds (the row drives ACLs, port-ownership checks and the // dashboard). The writer lives in index.js, which cannot be required from // here (circular import — this module is loaded BY index.js), so index.js // injects it at startup next to setPermissionCheckers. The create commit uses // the GUARDED variant (index.js insertServerIndexEntryGuarded): an insert-only // writer (a create must never repoint an existing row) that additionally // re-checks the template under the "templates-write" key the template DELETE // route holds. // Fail-closed: without the guarded injection the proxy create route refuses // to commit a server at all instead of leaving it unmanageable. // // adpanel:proxy-create-race (MEDIUM #2a): the same setter also injects the // cross-process per-name create lock acquirer (index.js // acquireServerCreateLock). Injecting the very same function is what makes // exclusion hold across paths AND workers: the lock files are named from the // same lowercased name (server-create-.lock) and live in the same // registry, so a proxy create, the main route POST /api/servers/create and // the assistant create_server tool serialize against each other across all // pm2 cluster workers. Without it the proxy's duplicate check and commit are // not serialized against the other create paths, and the ER_DUP_ENTRY loser's // compensating delete can destroy the winner's server. Fail-closed: without // this injection the proxy create route refuses to create at all instead of // running unserialized. // The upserting writer (index.js upsertServerIndexEntry) is deliberately NOT // captured: no create path may upsert — the proxy commits only through the // guarded insert-only writer above, and an upsert here would silently // repoint another server's row. (index.js insertServerIndexEntry is the // plain insert-only writer; the proxy has no use for it either — its commit // is always the guarded one.) let _insertServerIndexEntryGuarded = null; let _acquireServerCreateLock = null; function setServerIndexWriters(writers = {}) { _insertServerIndexEntryGuarded = typeof writers.insertServerIndexEntryGuarded === "function" ? writers.insertServerIndexEntryGuarded : null; _acquireServerCreateLock = typeof writers.acquireServerCreateLock === "function" ? writers.acquireServerCreateLock : null; } // adpanel:server-create-consolidation — the proxy create path's shared steps // run through services/server-create.js, which needs two index.js-owned // implementations this module cannot reach (circular import — this module is // loaded BY index.js, see setServerIndexWriters above): // - findServer (index.js, case-insensitive name/legacy_id/bot match): the // in-lock duplicate pre-check via the service's duplicateServerNameOutcome. // Detection is equivalent to this module's former local // panelServerNameConflict (same three LOWER(alias) legs); findServer's row // ranking only picks WHICH row is reported, never whether one is. // - normalizeTemplateId (index.js): decides whether the Minecraft-specific // mcFork/mcVersion validation applies — replaces this module's former // hand mirror, which was byte-equivalent but a drift risk. // Fail closed: without either injection the proxy create throws inside its // locked continuation and the route wrapper answers 500 node_create_failed — // the create is refused rather than run unverified (the duplicate check is a // pre-check; the UNIQUE servers.name key and the guarded writer remain the // arbiters, but an unwired module must not silently skip a guard). let _findServer = null; let _normalizeTemplateId = null; function setServerCreateHelpers(helpers = {}) { _findServer = typeof helpers.findServer === "function" ? helpers.findServer : null; _normalizeTemplateId = typeof helpers.normalizeTemplateId === "function" ? helpers.normalizeTemplateId : null; } // deps for the shared server-create service steps on the proxy path, per // request (plain object of module references — cannot throw): // - dbQuery: the rows-only db.query (this module reads row arrays directly // everywhere). // - deleteServerOnNode: the compensating-delete leg the canonical // deleteOwnOrphanServerOnNodeForCreate requires — this module's own // callNodeApi DELETE with its historical 30s budget (the proxy's // compensating delete has always gone straight to the node daemon, not // through the panel's 120s deleteServerOnNode). // - insertServerIndexEntryGuarded: the injected guarded writer (null when // index.js has not wired it — the service's commit then fails closed with // its index_commit_failed contract). // - findServer: the injected duplicate-check reader. // No withTimeout: the proxy's duplicate check and storage-collision scan have // never been timeout-wrapped (a slow DB rejects into the route wrapper's 500 // node_create_failed) — injecting index.js's withTimeout here would ADD a // bound this path never had. function serverCreateDeps() { return { findServer: _findServer, dbQuery: (sql, params) => db.query(sql, params), deleteServerOnNode: (targetNode, serverName) => callNodeApi(targetNode, `/v1/servers/${encodeURIComponent(serverName)}`, "DELETE", null, 30_000), insertServerIndexEntryGuarded: _insertServerIndexEntryGuarded, }; } // The proxy's compensation log strings for commitCreatedServer: console.error // (the proxy logs post-provisioning failures at error level, the panel at // warn) with this module's own wording — kept byte-faithful from the former // inline blocks. const PROXY_COMMIT_LOG = { tag: "[node-proxy-create]", level: "error", notWiredWithheld: (name) => `index writer missing and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server may belong to another worker's live create; it was left intact`, notWiredError: (name) => `index writer missing and ownership-guarded compensating delete of "${name}" failed — server may be orphaned on the node:`, templateDeletedWithheld: (name) => `template deleted during create and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server may belong to another worker's live create; it was left intact`, templateDeletedError: (name) => `template deleted during create and compensating delete of "${name}" failed — server is orphaned on the node:`, commitWithheld: (name) => `index commit failed and compensating delete of "${name}" was WITHHELD — the committed index row claims this name on this node, so the daemon server belongs to another writer's live create; winner left intact`, commitError: (name) => `index commit failed and ownership-guarded compensating delete of "${name}" failed — server may be orphaned on the node:`, }; // Upload-policy parity for the node-proxy upload route (POST // /api/nodes/server/:name/upload). The panel's POST /upload (index.js) enforces // the operator's upload extension allow/block list, a filename sanitizer, a // session-bound action token and a per-user rate limiter; the relay route must // enforce the exact same policy or remote-mode uploads become a bypass for all // of it. This module cannot require index.js for any of those (circular import // — see setServerIndexWriters above), so index.js injects the very same // implementations it uses for POST /upload at startup. Everything fails closed // when not injected: no sanitizer/policy hook → every upload is rejected, no // token hook → the standard 403 action-token shape, no limiter hook → every // upload is rejected with the limiter's own 429 shape (no hook ever leaves the // relay unthrottled or unauthenticated). // adpanel:backups-list-brake — the same setter also carries the ALWAYS-ON read // brake for GET /api/nodes/server/:name/backups (index.js // nodeBackupsListRateLimiter): that relay dials the daemon with a 15s budget // and triggers the daemon's orphan-backup sweep per dial, so its brake is // injected through the one shared hook surface and fails closed identically // (no hook ever leaves the list route unbraked either). let _isUploadExtensionAllowed = null; let _sanitizeUploadFilename = null; let _requireActionTokenOr403 = null; let _uploadRateLimiter = null; let _fsReadRateLimiter = null; let _fsMutateRateLimiter = null; let _backupsListRateLimiter = null; function setUploadPolicyHooks(hooks = {}) { _isUploadExtensionAllowed = typeof hooks.isUploadExtensionAllowed === "function" ? hooks.isUploadExtensionAllowed : null; _sanitizeUploadFilename = typeof hooks.sanitizeUploadFilename === "function" ? hooks.sanitizeUploadFilename : null; _requireActionTokenOr403 = typeof hooks.requireActionTokenOr403 === "function" ? hooks.requireActionTokenOr403 : null; _uploadRateLimiter = typeof hooks.uploadRateLimiter === "function" ? hooks.uploadRateLimiter : null; _fsReadRateLimiter = typeof hooks.fsReadRateLimiter === "function" ? hooks.fsReadRateLimiter : null; _fsMutateRateLimiter = typeof hooks.fsMutateRateLimiter === "function" ? hooks.fsMutateRateLimiter : null; _backupsListRateLimiter = typeof hooks.backupsListRateLimiter === "function" ? hooks.backupsListRateLimiter : null; } // Self-defending admin check for the node-fleet handlers that used to rely // solely on the panel-side /api/nodes admin gate. Belt-and-suspenders: even // if a gate layer ever regresses (the gate bypassed via case-variant URLs // once, see utils/node-api-path.js), these endpoints still refuse non-admins. // Same rule as the ports/in-use route: index.js-computed req.isAdmin with the // injected _isAdmin checker as fallback. Sends the 403 itself and returns // false when denied. // Fail-closed: if the _isAdmin checker throws, access is denied. async function requireNodeAdmin(req, res) { if (!req.isAdmin) { let checkerAllows = false; try { checkerAllows = !!(_isAdmin && (await _isAdmin(req))); } catch (err) { console.error("[SECURITY] requireNodeAdmin: admin check failed - denying access", err && err.message); checkerAllows = false; } if (!checkerAllows) { res.status(403).json({ error: "admin required" }); return false; } } return true; } async function checkUserPerm(req, serverName, permKey) { if (!_getEffectivePermsForUserOnServer || !_isAdmin) { console.error("[SECURITY] Permission checkers not configured - denying access"); return false; } const userEmail = req.session?.user; if (!userEmail) return false; if (await _isAdmin(req)) return true; const perms = await _getEffectivePermsForUserOnServer(userEmail, serverName); return !!(perms && perms[permKey]); } // resolveFsWriteMode decides which write operations a user may perform and the // constraint to hand the node so it can enforce create-vs-overwrite atomically // (no panel-side TOCTOU). Returns: // { ok:true, mode:"" } -> may create new AND overwrite existing (admin / both perms) // { ok:true, mode:"create" } -> may only create new files (node 409s if it exists) // { ok:true, mode:"update" } -> may only overwrite existing files (node 404s if missing) // { ok:false, permission } -> no write capability at all // Back-compat: an existing files_create grant continues to allow creating files; // files_write is the new, separate capability for overwriting existing files. async function resolveFsWriteMode(req, serverName) { if (!_getEffectivePermsForUserOnServer || !_isAdmin) { return { ok: false, permission: "files_create" }; } const userEmail = req.session?.user; if (!userEmail) return { ok: false, permission: "files_create" }; if (await _isAdmin(req)) return { ok: true, mode: "" }; const perms = await _getEffectivePermsForUserOnServer(userEmail, serverName); const canCreate = !!(perms && perms.files_create); const canWrite = !!(perms && perms.files_write); if (canCreate && canWrite) return { ok: true, mode: "" }; if (canCreate) return { ok: true, mode: "create" }; if (canWrite) return { ok: true, mode: "update" }; return { ok: false, permission: "files_create" }; } // Server-scoped access gate. The access list grants are plain strings // (server names, legacy ids, bot aliases, or "all"), so the gate must be // evaluated against the RESOLVED row's own identifiers — not the raw URL // key. Checking the raw key lets a request authorize on one row while // remoteContext resolves a different one (alias collision: a server named // "123" vs the row whose auto-increment id/legacy_id is 123), yielding // cross-user file access; checking the resolved row's identifiers makes // authorization and operation target the same row by construction, since // both go through findServerByNameOrId's deterministic (M9) ranking. async function checkServerAccess(req, serverName) { const userEmail = req.session?.user; if (!userEmail) return { ok: false, status: 401, error: "not authenticated" }; if (_isAdmin && await _isAdmin(req)) return { ok: true }; if (_userHasAccessToServer) { // Resolve first; a resolver error must fail closed (a lookup error is // not a grant). Identifiers are tried in stored-name → legacy_id → bot // order so the common name-grant case costs one injected call; each call // re-checks the admin bypass and the fail-closed access-list timeout in // index.js's userHasAccessToServer. let srv = null; try { srv = await findServerByNameOrId(serverName); } catch (err) { console.error("[SECURITY] Server row lookup failed while checking access; denying:", err?.message || err); return { ok: false, status: 403, error: "no access to server" }; } if (srv) { for (const ident of [srv.name, srv.legacy_id, srv.bot]) { const candidate = String(ident || "").trim(); if (!candidate) continue; if (await _userHasAccessToServer(userEmail, candidate)) { return { ok: true, server: srv }; } } return { ok: false, status: 403, error: "no access to server" }; } // No row resolved (deleted mid-flight / stale grant): fall back to the // legacy raw-key compare so today's observable flow for nonexistent // servers is preserved (a stale grant still reaches the route's 404). // Safe: with no row, remoteContext can never resolve a baseDir to // operate on. const hasAccess = await _userHasAccessToServer(userEmail, serverName); if (!hasAccess) return { ok: false, status: 403, error: "no access to server" }; } else { console.error("[SECURITY] userHasAccessToServer not configured - denying non-admin access"); return { ok: false, status: 403, error: "access checker not configured" }; } return { ok: true }; } const PORT = process.env.NODES_PORT ? Number(process.env.NODES_PORT) : 3550; const HEARTBEAT_TTL_MS = 120_000; const UPLOAD_TIMEOUT_MS = 3600_000; const NODE_BOOTSTRAP_TOKEN = (process.env.NODE_BOOTSTRAP_TOKEN || "").trim(); const PANEL_PUBLIC_URL = (process.env.PANEL_PUBLIC_URL || "").trim(); const ALLOW_INSECURE_NODE_BOOTSTRAP = truthyFlag(process.env.ALLOW_INSECURE_NODE_BOOTSTRAP); let nodeBootstrapTransport = { secure: (req) => !!req?.socket?.encrypted, trustedHost: () => "", }; function setNodeBootstrapTransport(transport) { nodeBootstrapTransport = transport; } // Same resolver as index.js: env > persisted > auto-generated, so both panel // processes always agree on one fleet master (see utils/panel-hmac-secret.js). const PANEL_HMAC_SECRET = panelHmacSecret.resolvePanelHmacSecret().secret; // Single-use nonce store backing the signed heartbeat envelope (see // utils/heartbeat-auth.js). In-memory on purpose: it only has to cover the // ±5 minute drift window, so panel restarts may flush it without risk. // // adpanel:heartbeat-nonce-shared — this per-process cache is the DEGRADED // FALLBACK ONLY. Under PM2 cluster (INSTANCES = cores - 2, // utils/db-proxy.js) a per-process ledger is 1/N effective: a captured // heartbeat is replayable once per worker. The shared Redis arbiter below // (SET NX PX, key includes the node id, TTL > drift window) is the // authoritative replay check once index.js wires the session client via // setHeartbeatSharedNonceDeps({ clientOf, readyOf }); this cache stays as // the write-through companion and the Redis-outage fallback, because // heartbeat availability outranks replay strictness while the envelope // itself still authenticates the sender (see the module header of // utils/heartbeat-auth.js for the full trade-off). const heartbeatNonceCache = createNonceCache(); // Injected access to index.js's session Redis client (circular import — the // setter mirrors setServerIndexWriters/setUploadPolicyHooks). Unwired → the // shared store is never consulted and the per-process cache above remains // the sole replay ledger (single-process installs are unaffected; clustered // installs need the wiring in index.js). let _heartbeatRedisDeps = null; let _heartbeatSharedNonceStore = null; function setHeartbeatSharedNonceDeps(deps = {}) { _heartbeatRedisDeps = { clientOf: typeof deps.clientOf === "function" ? deps.clientOf : null, readyOf: typeof deps.readyOf === "function" ? deps.readyOf : null, }; // Recreate so a re-wire (tests) picks up the new accessors. _heartbeatSharedNonceStore = null; } function heartbeatSharedNonceStore() { if (!_heartbeatRedisDeps || !_heartbeatRedisDeps.clientOf) return null; if (!_heartbeatSharedNonceStore) { _heartbeatSharedNonceStore = createSharedHeartbeatNonceStore({ clientOf: _heartbeatRedisDeps.clientOf, readyOf: _heartbeatRedisDeps.readyOf || (() => false), logger: console, }); } return _heartbeatSharedNonceStore; } // Single-use enrollment store behind the secret-free one-time setup command // (see utils/node-bootstrap.js). One entry pair per revealed command; entries // expire in minutes and die with the first download or a panel restart, so // in-memory storage is sufficient. The 30/min per-IP cap only has to absorb // scanner noise on the two unauthenticated bootstrap GETs. const NODE_ENROLL_TTL_MS = parseInt(process.env.NODE_ENROLL_TTL_MS || "", 10) || 10 * 60 * 1000; const nodeEnrollStore = createNodeBootstrapStore({ ttlMs: NODE_ENROLL_TTL_MS, filePath: path.join(__dirname, "data", "node-bootstrap-enrollments.json") }); const nodeEnrollLimiter = createNodeBootstrapRateLimiter({ windowMs: 60 * 1000, max: parseInt(process.env.NODE_ENROLL_RATE_MAX || "", 10) || 30, }); // Heartbeat limiter (same fixed-window per-IP pattern as the enrollment // limiter above). Sized for NAT'd daemon fleets: daemons heartbeat on an // interval and many can share one egress IP, so the ceiling is generous // (300/min/IP default). It counts every attempt — including unauthenticated // ones rejected with 401 — as a cheap DoS guard for that path. const NODE_HEARTBEAT_RATE_MAX = parseInt(process.env.NODE_HEARTBEAT_RATE_MAX || "", 10) || 300; const heartbeatLimiter = createNodeBootstrapRateLimiter({ windowMs: 60 * 1000, max: NODE_HEARTBEAT_RATE_MAX, }); // M2: the pre-auth GET /api/nodes/:id/config.yml gate does a node lookup // (MySQL) on EVERY request before it can answer 401, so flooding it is a // cheap DB-exhaustion lever. Always-on fixed-window per-IP cap, independent // of security.json's global limiter toggle — pre-auth surfaces must never // depend on an operator having flipped that switch. 60/min/IP leaves ample // headroom for daemon config re-fetches while capping lookup floods. const NODE_CONFIG_RATE_MAX = parseInt(process.env.NODE_CONFIG_RATE_MAX || "", 10) || 60; const nodeConfigPreAuthLimiter = createNodeBootstrapRateLimiter({ windowMs: 60 * 1000, max: NODE_CONFIG_RATE_MAX, }); (async () => { try { await db.query("ALTER TABLE nodes ADD COLUMN max_upload_mb INT NOT NULL DEFAULT 10240"); console.log("[nodes] Migration: added max_upload_mb column to nodes table"); } catch (e) { if (e && e.code !== "ER_DUP_FIELDNAME" && !String(e.message || "").includes("Duplicate column")) { console.warn("[nodes] Migration warning (max_upload_mb):", e.message); } } })(); (async () => { try { await db.query("ALTER TABLE nodes ADD COLUMN sftp_port INT NOT NULL DEFAULT 2022 AFTER api_port"); console.log("[nodes] Migration: added sftp_port column to nodes table"); } catch (e) { if (e && e.code !== "ER_DUP_FIELDNAME" && !String(e.message || "").includes("Duplicate column")) { console.warn("[nodes] Migration warning (sftp_port):", e.message); } } })(); (async () => { try { await db.query("ALTER TABLE nodes ADD COLUMN token_status VARCHAR(32) NULL AFTER token"); console.log("[nodes] Migration: added token_status column to nodes table"); } catch (e) { if (e && e.code !== "ER_DUP_FIELDNAME" && !String(e.message || "").includes("Duplicate column")) { console.warn("[nodes] Migration warning (token_status):", e.message); } } })(); function safeCompare(a, b) { if (typeof a !== "string" || typeof b !== "string") return false; // adpanel:safecompare-length-cap-nodes — sibling of the index.js cap // (adpanel:safecompare-length-cap): every legitimate compared value here is a // fixed-size token (census of all call sites: panel probe nonce 32 hex, // heartbeat token_id "tok_" + 16 hex, node/daemon bearer + bootstrap tokens // server-generated ~55 b64url chars or operator env config) and the largest // attacker-shaped inputs are header-bounded by Node's default // max-http-header-size (16384) or body-bounded by the heartbeat JSON parser // limit — 16384 is strictly above every genuine value, so the cap can never // reject a real comparison. An overlong input (either side) returns false // immediately: that early-false path leaks only that the ATTACKER-SUPPLIED // length exceeded the cap — attacker-known metadata, never secret-derived — // while sub-cap comparisons keep the full length-mismatch equalization below. // Consolidating this copy with index.js's into one shared module is a // campaign-level task: the index.js body is source-pinned by ~10 test files // via marker extraction, so neither function moves in this change. if (a.length > 16384 || b.length > 16384) return false; const bufA = Buffer.from(a); const bufB = Buffer.from(b); if (bufA.length !== bufB.length) { crypto.timingSafeEqual(bufA, bufA); return false; } return crypto.timingSafeEqual(bufA, bufB); } function safeDecodeURIComponent(value) { try { return decodeURIComponent(String(value || "")); } catch { return String(value || ""); } } function parseDbJson(value, fallback) { if (value === undefined || value === null || value === "") return fallback; if (typeof value === "object") return value; try { return JSON.parse(value); } catch { return fallback; } } function toDbJson(value, fallback) { if (value === undefined || value === null) return fallback; return JSON.stringify(value); } function uid() { return crypto.randomUUID(); } function randTokenId() { return "tok_" + crypto.randomBytes(8).toString("hex"); } function randSecret() { const ts = Buffer.alloc(8); const now = BigInt(Date.now()); ts.writeBigUInt64BE(now); const rand = crypto.randomBytes(32); const combined = Buffer.concat([ts, rand]); return combined .toString("base64") .replace(/\+/g, "-") .replace(/\//g, "_") .replace(/=+$/, ""); } // adpanel:sanitizer-lockstep — nodes.js no longer carries a drifted sanitizeName copy: every storage-name derivation uses the utils/server-name.js mirror (the AGENTS.md one-true-home); the local 100-cap variant diverged from Go for 101-120-char legacy names. function isInt(n) { return Number.isInteger(n); } function toInt(n, def = 0) { const x = Number(n); return Number.isFinite(x) ? Math.round(x) : def; } const MIN_NODE_PORT = 1024; const MAX_NODE_PORT = 65535; // Matches the create/edit UI cap ("Port Count ≤ 1000"); enforced server-side so // a direct API call cannot balloon a node's allocation JSON. const MAX_NODE_PORT_ALLOCATION_COUNT = 1000; function validateNodePortsInput(input) { if (input == null) return { ok: true }; const tooMany = () => ({ ok: false, error: "At most 1000 ports can be allocated per node." }); const invalidPool = { ok: false, error: "Invalid port allocation pool." }; const checkPort = (p) => { const num = Number(p); if (!Number.isInteger(num) || !["number", "string"].includes(typeof p)) return { ok: false, error: "Invalid port number." }; if (num < MIN_NODE_PORT) { return { ok: false, error: "Ports below 1024 cannot be allocated." }; } if (num > MAX_NODE_PORT) { return { ok: false, error: "Ports cannot exceed 65535." }; } return { ok: true }; }; if (Array.isArray(input)) { if (input.length > MAX_NODE_PORT_ALLOCATION_COUNT) return tooMany(); for (const item of input) { if (typeof item === "object" && item !== null) { const res = checkPort(item.port); if (!res.ok) return res; } else if (typeof item === "string" && item.includes(":")) { const parts = item.split(":"); const res = checkPort(parts[parts.length - 1]); if (!res.ok) return res; } else { const res = checkPort(item); if (!res.ok) return res; } } return { ok: true }; } if (typeof input === "object") { if (input.allocations !== undefined && !Array.isArray(input.allocations)) return invalidPool; if (input.ports !== undefined && !Array.isArray(input.ports)) return invalidPool; if (Array.isArray(input.allocations)) { if (input.allocations.length > MAX_NODE_PORT_ALLOCATION_COUNT) return tooMany(); for (const item of input.allocations) { if (typeof item === "object" && item !== null) { const res = checkPort(item.port); if (!res.ok) return res; } else if (typeof item === "string" && item.includes(":")) { const parts = item.split(":"); const res = checkPort(parts[parts.length - 1]); if (!res.ok) return res; } else { const res = checkPort(item); if (!res.ok) return res; } } } if (Array.isArray(input.ports)) { if (input.ports.length > MAX_NODE_PORT_ALLOCATION_COUNT) return tooMany(); for (const p of input.ports) { const res = checkPort(p); if (!res.ok) return res; } } if (Array.isArray(input.allocations) || (input.mode === "list" && Array.isArray(input.ports))) return { ok: true }; if (input.mode === "range") { const count = Number(input.count ?? 10); if (count > MAX_NODE_PORT_ALLOCATION_COUNT) return tooMany(); if (!Number.isInteger(count) || count < 1) return invalidPool; const startCheck = checkPort(input.start); if (!startCheck.ok) return startCheck; if (Number(input.start) + count - 1 > MAX_NODE_PORT) return { ok: false, error: "Port range exceeds 65535." }; return { ok: true }; } } if (typeof input === "string") { const parts = input.split(",").map(s => s.trim()).filter(Boolean); if (parts.length > MAX_NODE_PORT_ALLOCATION_COUNT) return tooMany(); for (const part of parts) { const res = checkPort(part); if (!res.ok) return res; } return { ok: true }; } return invalidPool; } function clampPort(p) { const n = toInt(p, 8080); if (n < 1 || n > 65535) return 8080; return n; } function normalizePorts(input, defaultIp = "") { if (Array.isArray(input)) { const allocations = []; const portsSet = new Set(); for (const item of input) { if (typeof item === "object" && item !== null) { const p = toInt(item.port); const ip = String(item.ip || defaultIp || "").trim(); if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) { allocations.push({ ip, port: p }); portsSet.add(p); } } else { const separator = typeof item === "string" ? item.lastIndexOf(":") : -1; const p = toInt(separator < 0 ? item : item.slice(separator + 1)); if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) { const ip = (separator < 0 ? "" : item.slice(0, separator).trim()) || defaultIp; allocations.push({ ip, port: p }); portsSet.add(p); } } } const uniqueMap = new Map(); for (const a of allocations) { const key = `${a.ip || defaultIp}:${a.port}`; if (!uniqueMap.has(key)) uniqueMap.set(key, a); } const uniqueAllocations = Array.from(uniqueMap.values()); uniqueAllocations.sort((a, b) => a.port - b.port); return { mode: "list", allocations: uniqueAllocations, ports: Array.from(portsSet).sort((a, b) => a - b) }; } if (input && typeof input === "object") { const targetIp = String(input.ip || defaultIp || "").trim() || defaultIp; if (Array.isArray(input.allocations) && !input.allocations.length && Array.isArray(input.ports)) { return normalizePorts({ mode: "list", ip: targetIp, ports: input.ports }, defaultIp); } if (Array.isArray(input.allocations)) { const allocations = []; const portsSet = new Set(); for (const item of input.allocations) { if (typeof item === "object" && item !== null) { const p = toInt(item.port); const ip = String(item.ip || targetIp || defaultIp || "").trim(); if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) { allocations.push({ ip, port: p }); portsSet.add(p); } } else if (typeof item === "string" && item.includes(":")) { const parts = item.split(":"); const p = toInt(parts[parts.length - 1]); const ip = parts.slice(0, -1).join(":").trim(); if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) { allocations.push({ ip: ip || targetIp || defaultIp || "", port: p }); portsSet.add(p); } } else { const p = toInt(item); if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) { allocations.push({ ip: targetIp || defaultIp || "", port: p }); portsSet.add(p); } } } const uniqueMap = new Map(); for (const a of allocations) { const key = `${a.ip || defaultIp}:${a.port}`; if (!uniqueMap.has(key)) uniqueMap.set(key, a); } const uniqueAllocations = Array.from(uniqueMap.values()); uniqueAllocations.sort((a, b) => a.port - b.port); if (!uniqueAllocations.length) return { mode: "list", allocations: [], ports: [] }; return { mode: input.mode || "list", allocations: uniqueAllocations, ports: Array.from(portsSet).sort((a, b) => a - b), start: toInt(input.start, 25565), count: toInt(input.count, 10) }; } if (input.mode === "range") { const start = Number(input.start); const requestedCount = Number(input.count ?? 10); if (!Number.isInteger(start) || start < MIN_NODE_PORT || start > MAX_NODE_PORT || !Number.isInteger(requestedCount) || requestedCount < 1) { return { mode: "list", ports: [], allocations: [] }; } const count = Math.min(requestedCount, MAX_NODE_PORT - start + 1); const allocations = []; const ports = []; for (let i = 0; i < count; i++) { const p = start + i; allocations.push({ ip: targetIp || defaultIp || "", port: p }); ports.push(p); } return { mode: "range", start, count, allocations, ports }; } if (input.mode === "list") { const ports = Array.from(new Set((Array.isArray(input.ports) ? input.ports : []) .map(p => toInt(p)) .filter(p => p >= MIN_NODE_PORT && p <= MAX_NODE_PORT))); const allocations = ports.map(p => ({ ip: targetIp || defaultIp || "", port: p })); return { mode: "list", ports, allocations }; } } if (typeof input === "string") { // "3000,3001" style lists: parse exactly like the list mode so a payload // that already passed validateNodePortsInput persists as exactly those // ports instead of silently falling through to the default range below. // Same last-defense clamping as the array/object branches: out-of-bounds // ports are dropped, duplicates collapse, and the count cap matches // MAX_NODE_PORT_ALLOCATION_COUNT. const portsSet = new Set(); for (const part of input.split(",")) { const p = toInt(part.trim()); if (p < MIN_NODE_PORT || p > MAX_NODE_PORT) continue; portsSet.add(p); if (portsSet.size >= MAX_NODE_PORT_ALLOCATION_COUNT) break; } const ports = Array.from(portsSet).sort((a, b) => a - b); const allocations = ports.map(p => ({ ip: defaultIp || "", port: p })); return { mode: "list", ports, allocations }; } return { mode: "list", allocations: [], ports: [] }; } function ambiguousPortAllocation(ports, previous = []) { const existing = new Set(previous.map(({ ip, port }) => `${ip}:${port}`)); const seen = new Set(); const duplicates = new Set(); for (const { port } of ports.allocations) { if (seen.has(port)) duplicates.add(port); seen.add(port); } const invalid = ports.allocations.find(({ ip, port }) => duplicates.has(port) && !existing.has(`${ip}:${port}`)); return invalid ? `Port ${invalid.port} can only be allocated once per node. Remove its existing allocation before using another address.` : null; } function isPortInNodeAllocation(node, port) { const p = Number(port); if (!Number.isFinite(p) || p < MIN_NODE_PORT || p > MAX_NODE_PORT) return false; const alloc = node && node.ports; // Fail closed in every degenerate state: an unknown or empty allocation // must mean "nothing is assignable", never "everything is assignable". // The Ports pane's own Select All → Delete persists exactly // {mode:"list", allocations:[], ports:[]}; treating that empty pool as an // allow-all would let server creation bind any free host port on the node, // including ports the admin reserved for node services (the daemon's live // bind test only rejects ports that are already bound). if (!alloc || typeof alloc !== "object") return false; if (Array.isArray(alloc.allocations) && alloc.allocations.length > 0) { return alloc.allocations.some(a => Number(a.port) === p); } if (alloc.mode === "range") { const start = Number(alloc.start || 0); const count = Number(alloc.count || 0); if (start <= 0 || count <= 0) return false; return p >= start && p < start + count; } if (alloc.mode === "list" && Array.isArray(alloc.ports)) { if (alloc.ports.length === 0) return false; return alloc.ports.includes(p); } return false; } function getNodeAllocatedPortsList(node) { const alloc = (node && node.ports) ? node.ports : node; if (!alloc) return []; if (Array.isArray(alloc.allocations) && alloc.allocations.length > 0) { return Array.from(new Set(alloc.allocations.map(a => Number(a.port)).filter(p => Number.isFinite(p) && p >= MIN_NODE_PORT && p <= MAX_NODE_PORT))).sort((a, b) => a - b); } if (Array.isArray(alloc.ports) && alloc.ports.length > 0) { return Array.from(new Set(alloc.ports.map(Number).filter(p => Number.isFinite(p) && p >= MIN_NODE_PORT && p <= MAX_NODE_PORT))).sort((a, b) => a - b); } if (alloc.mode === "range") { const start = Number(alloc.start || 0); const count = Number(alloc.count || 0); if (start >= MIN_NODE_PORT && count > 0) { const list = []; for (let i = 0; i < count; i++) { const p = start + i; if (p <= MAX_NODE_PORT) list.push(p); } return list; } } return []; } function getNodeAllocations(node) { const alloc = node && node.ports; const defaultIp = (node && node.address) ? node.address : "0.0.0.0"; if (!alloc) return []; if (Array.isArray(alloc.allocations) && alloc.allocations.length > 0) { return alloc.allocations.map(a => ({ ip: String(a.ip || defaultIp || "").trim() || defaultIp, port: Number(a.port) })).filter(a => Number.isInteger(a.port) && a.port >= MIN_NODE_PORT && a.port <= MAX_NODE_PORT); } if (alloc.mode === "range") { const start = Number(alloc.start || 25565); const count = Number(alloc.count || 10); if (start < MIN_NODE_PORT) return []; const list = []; for (let i = 0; i < count; i++) { const p = start + i; if (p >= MIN_NODE_PORT && p <= MAX_NODE_PORT) list.push({ ip: defaultIp, port: p }); } return list; } if (alloc.mode === "list" && Array.isArray(alloc.ports)) { return alloc.ports.map(p => ({ ip: defaultIp, port: Number(p) })).filter(a => Number.isInteger(a.port) && a.port >= MIN_NODE_PORT && a.port <= MAX_NODE_PORT); } return []; } async function getServersUsingPortsOnNode(node) { if (!node) return new Map(); const rows = await db.query( `SELECT id, name, display_name, legacy_id, node_id, ip, port, status, resources, runtime, (SELECT host_port FROM server_reinstall_dispatch WHERE server_id = servers.id) AS reinstall_pending_port FROM servers WHERE ${NODE_SERVER_ASSIGNMENT_WHERE}`, nodeServerAssignmentParams(node) ); const usedMap = new Map(); if (Array.isArray(rows)) { for (const row of rows) { const serverName = row.display_name || row.name || row.legacy_id || `Server #${row.id}`; const status = String(row.status || "").toLowerCase(); for (const { port, portType, ip } of assignedServerPortUses({ port: row.port, ip: row.ip, reinstallPendingPort: row.reinstall_pending_port, runtime: parseDbJson(row.runtime, null), resources: parseDbJson(row.resources, null), })) { if (!usedMap.has(port)) usedMap.set(port, []); usedMap.get(port).push({ name: row.name, serverName, serverId: row.id, portType, ip, status }); } } } return usedMap; } // adpanel:relay-helper-consolidation — truthyFlag and // CLOUDFLARE_HTTPS_EDGE_PORTS moved to services/node-http.js (byte-identical // twins with index.js; closure set of the shared buildNodeBaseUrl) and are // re-bound from that module above. const CLOUDFLARE_IPS_V4_URL = "https://www.cloudflare.com/ips-v4"; const CLOUDFLARE_IPS_V6_URL = "https://www.cloudflare.com/ips-v6"; const CLOUDFLARE_IP_CACHE_TTL_MS = 6 * 60 * 60 * 1000; const CLOUDFLARE_IP_RANGES_FALLBACK = Object.freeze([ "173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18", "108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17", "162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22", "2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32", "2a06:98c0::/29", "2c0f:f248::/32", ]); const cloudflareDnsResolver = new dns.Resolver(); cloudflareDnsResolver.setServers(["1.1.1.1", "1.0.0.1"]); let cloudflareIpRangesCache = { expiresAt: 0, ranges: CLOUDFLARE_IP_RANGES_FALLBACK }; let cloudflareIpRangesInFlight = null; // adpanel:relay-helper-consolidation — cloudflareHttpsEdgePort (edge-port // lookup, parameterized by clamp in the shared module), hasExplicitHostPort, // explicitHostPort and stripExplicitHostPort moved to services/node-http.js // and are re-bound from there above (stripExplicitHostPort keeps one caller // below at the node address validation). function isCloudflareHttpsPort(port) { return CLOUDFLARE_HTTPS_EDGE_PORTS.has(clampPort(port || 0)); } // adpanel:http-straggler — deliberate raw https.get (NOT // services/node-http.js's core): the targets are the two hardcoded // www.cloudflare.com IP-range lists (never user input, no SSRF surface), the // result feeds a cache with a bundled fallback, and the payload is // Cloudflare's own bounded text list — no body cap needed. Posture otherwise // matches the core: response error listener, request timeout + error. function httpsGetText(url, timeoutMs = 5000) { return new Promise((resolve, reject) => { const req = https.get(url, { timeout: timeoutMs, headers: { "User-Agent": "ADPanel/Cloudflare-Proxy-Check" } }, (res) => { if (res.statusCode !== 200) { res.resume(); reject(new Error(`Cloudflare IP list returned ${res.statusCode}`)); return; } const chunks = []; res.on("data", chunk => chunks.push(chunk)); res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); // Without a listener a mid-body failure is swallowed (IncomingMessage // emits 'error' only when one is attached) and the promise never // settles — mirror the req error handler below. res.on("error", reject); }); req.on("timeout", () => req.destroy(new Error("Cloudflare IP list timeout"))); req.on("error", reject); }); } function parseCloudflareIpList(text) { return String(text || "") .split(/\r?\n/) .map(line => line.trim()) .filter(line => line && !line.startsWith("#")); } async function getCloudflareIpRanges() { const now = Date.now(); if (cloudflareIpRangesCache.expiresAt > now && cloudflareIpRangesCache.ranges.length) { return cloudflareIpRangesCache.ranges; } if (cloudflareIpRangesInFlight) return cloudflareIpRangesInFlight; cloudflareIpRangesInFlight = (async () => { try { const [v4, v6] = await Promise.all([ httpsGetText(CLOUDFLARE_IPS_V4_URL), httpsGetText(CLOUDFLARE_IPS_V6_URL), ]); const ranges = [...parseCloudflareIpList(v4), ...parseCloudflareIpList(v6)]; if (!ranges.length) throw new Error("empty Cloudflare IP list"); cloudflareIpRangesCache = { expiresAt: now + CLOUDFLARE_IP_CACHE_TTL_MS, ranges }; return ranges; } catch (err) { console.warn("[cloudflare-check] Falling back to bundled Cloudflare IP ranges:", err?.message || err); cloudflareIpRangesCache = { expiresAt: now + 15 * 60 * 1000, ranges: CLOUDFLARE_IP_RANGES_FALLBACK }; return cloudflareIpRangesCache.ranges; } finally { cloudflareIpRangesInFlight = null; } })(); return cloudflareIpRangesInFlight; } async function resolvePublicHostnameIps(hostname) { const resolvers = [ { name: "Cloudflare DNS", resolver: cloudflareDnsResolver }, { name: "system DNS", resolver: dns }, ]; const errors = []; for (const entry of resolvers) { const [v4, v6] = await Promise.all([ entry.resolver.resolve4(hostname).catch(err => { errors.push(`${entry.name} A: ${err?.code || err?.message || "failed"}`); return []; }), entry.resolver.resolve6(hostname).catch(err => { errors.push(`${entry.name} AAAA: ${err?.code || err?.message || "failed"}`); return []; }), ]); const ips = [...v4, ...v6].filter(Boolean); if (ips.length) return { ips, resolver: entry.name }; } return { ips: [], resolver: "", error: errors.join("; ") }; } async function verifyCloudflareProxiedAddress(address, allocations = [], previousNode = null, portUsage) { // adpanel:node-proxy-address - validate the complete address before verifying its DNS name. const extracted = nodeSsrfGuard.extractNodeAddressHost(address); if (!extracted.ok) return extracted; const hostname = extracted.host; if (hostname === "localhost" || net.isIP(hostname) || !/^[a-z0-9.-]+$/.test(hostname)) { return { ok: false, error: "Under Cloudflare requires a public hostname, not an IP address or localhost.", }; } // adpanel:node-proxy-allocation - a Cloudflare management address is not a game socket bind address. const retained = new Set(getNodeAllocations(previousNode).map(({ ip, port }) => `${ip}:${port}`)); for (const { ip, port } of allocations) { const bind = resolveServerCreateBindAddress({ address: ip || address, under_cloudflare: true }, port); if (!bind.error) continue; if (retained.has(`${ip}:${port}`)) { if (nodeUnderCloudflare(previousNode)) continue; portUsage ??= await getServersUsingPortsOnNode(previousNode); if (portUsage.has(port)) continue; } return { ok: false, error: renderServerCreateOutcome(bind.error, "panel").body.error }; } const [{ ips, resolver, error }, ranges] = await Promise.all([ resolvePublicHostnameIps(hostname), getCloudflareIpRanges(), ]); if (!ips.length) { // adpanel:relay-error-mask — generic detail (null; the curated error above // already names the hostname); the per-resolver DNS error text is logged // server-side only. console.warn("[nodes] Cloudflare proxy verification could not resolve", hostname, "-", error || "no resolver answered"); return { ok: false, error: `Could not resolve ${hostname} in public DNS for Cloudflare proxy verification.`, detail: null, }; } const nonCloudflareIps = ips.filter(ip => !ipRangeCheck(ip, ranges)); if (nonCloudflareIps.length) { return { ok: false, error: `${hostname} is not proxied by Cloudflare. Turn on the orange-cloud proxy in Cloudflare DNS, then try again.`, detail: `Resolved via ${resolver}: ${ips.join(", ")}. Non-Cloudflare IPs: ${nonCloudflareIps.join(", ")}`, }; } return { ok: true, hostname, ips, resolver }; } // nodeUnderCloudflare (byte-identical twin with index.js) is hoisted to // services/node-http.js and re-bound from the destructure above. function hardenNode(n) { const clone = Object.assign({ id: uid(), uuid: "", name: "node", address: "", ram_mb: 0, disk_gb: 0, token_id: randTokenId(), token: randSecret(), createdAt: Date.now(), api_port: 8080, sftp_port: 2022, port_ok: null, last_seen: null, last_check: null, online: null, buildConfig: {}, under_cloudflare: false, max_upload_mb: 10240 }, n || {}); if (!clone.id) clone.id = uid(); if (!clone.uuid) clone.uuid = clone.id; if (!isInt(clone.ram_mb)) clone.ram_mb = toInt(clone.ram_mb, 0); if (!isInt(clone.disk_gb)) clone.disk_gb = toInt(clone.disk_gb, 0); clone.name = sanitizeNodeStorageName(clone.name || "node"); clone.address = String(clone.address || "").trim(); clone.ports = normalizePorts(clone.ports, clone.address); if (!clone.token_id) clone.token_id = randTokenId(); // token_status === "rotate_required" means the previous credential was // invalidated (pre-migration plaintext value, or ciphertext that failed GCM // verification). Deliberately do NOT auto-mint a replacement here: the // daemon is still running the old token, so a fresh panel-side secret would // silently desync the pair and brick the node with no badge explaining why. // Rotation must go through rotateNodeToken()/the rotate-token endpoint, // which pairs the new credential with admin guidance to re-deploy config. if (!clone.token) { if (clone.token_status === nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED) { clone.token = ""; } else { clone.token = randSecret(); } } if (clone.token_status === nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED) { clone.token_status = nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED; } else if (!clone.token) { clone.token_status = nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED; } else { clone.token_status = nodeTokenCrypto.TOKEN_STATUS_OK; } if (!clone.createdAt) clone.createdAt = Date.now(); clone.api_port = clampPort(clone.api_port || 8080); clone.sftp_port = clampPort(clone.sftp_port || 2022); clone.max_upload_mb = Math.max(1, Math.min(100000, toInt(clone.max_upload_mb, 10240))); clone.buildConfig = (clone.buildConfig && typeof clone.buildConfig === "object") ? clone.buildConfig : {}; let rawAdditional = []; if (Array.isArray(n?.additional_ips)) rawAdditional = n.additional_ips; else if (Array.isArray(clone.buildConfig.ips)) rawAdditional = clone.buildConfig.ips; else if (Array.isArray(n?.ips)) rawAdditional = n.ips; const cleanAdditional = Array.from(new Set(rawAdditional.map(ip => String(ip || "").trim()).filter(ip => ip && ip !== clone.address))); clone.buildConfig.ips = cleanAdditional; clone.additional_ips = cleanAdditional; clone.ips = [clone.address, ...cleanAdditional].filter(Boolean); clone.under_cloudflare = nodeUnderCloudflare(clone); clone.buildConfig.under_cloudflare = !!clone.under_cloudflare; // Collapse the legacy cloudflare_proxy alias into under_cloudflare and strip // the residual key: nodeUnderCloudflare() ORs the alias back in, so a stale // cloudflare_proxy:true would keep HTTPS-dial semantics alive after an admin // turned under_cloudflare off, bypassing the Cloudflare port check and // verifyCloudflareProxiedAddress() on every later update. nodeUnderCloudflare() // above already folded the alias into clone.under_cloudflare, so deleting it // is semantics-preserving. delete clone.buildConfig.cloudflare_proxy; if (typeof clone.port_ok !== "boolean") clone.port_ok = null; if (clone.last_seen != null) clone.last_seen = Number(clone.last_seen); if (clone.last_check != null) clone.last_check = Number(clone.last_check); return clone; } function mapNodeRow(row) { const bc = parseDbJson(row.build_config, {}); return hardenNode({ id: row.id, uuid: row.uuid, name: row.name, address: row.address, ram_mb: row.ram_mb, disk_gb: row.disk_gb, ports: parseDbJson(row.ports, null), token_id: row.token_id, token: nodeTokenCrypto.decryptNodeToken(row.token), token_status: row.token_status || null, createdAt: row.created_at ? Number(row.created_at) : null, api_port: row.api_port, sftp_port: row.sftp_port != null ? Number(row.sftp_port) : 2022, port_ok: row.port_ok === null ? null : !!row.port_ok, last_seen: row.last_seen, last_check: row.last_check, online: row.online === null ? null : !!row.online, buildConfig: bc, ssl_enabled: !!bc.ssl_enabled, under_cloudflare: nodeUnderCloudflare({ buildConfig: bc }), max_upload_mb: row.max_upload_mb != null ? Number(row.max_upload_mb) : 10240, additional_ips: Array.isArray(bc.ips) ? bc.ips : [], ips: [row.address, ...(Array.isArray(bc.ips) ? bc.ips : [])].filter(Boolean) }); } async function loadNodes() { const rows = await db.query("SELECT * FROM nodes"); return rows.map(mapNodeRow); } async function loadNodesPaginated(page, limit, search) { page = Math.max(1, parseInt(page, 10) || 1); limit = Math.max(1, Math.min(100, parseInt(limit, 10) || 50)); let countSql = "SELECT COUNT(*) AS total FROM nodes"; let dataSql = "SELECT * FROM nodes"; const params = []; const countParams = []; if (search && typeof search === "string" && search.trim()) { const pattern = `%${search.trim()}%`; const where = " WHERE LOWER(name) LIKE ? OR LOWER(address) LIKE ? OR LOWER(id) LIKE ? OR LOWER(uuid) LIKE ?"; countSql += where; dataSql += where; countParams.push(pattern, pattern, pattern, pattern); params.push(pattern, pattern, pattern, pattern); } // The requested page is clamped into range before slicing: a list that // shrank under a parked client must serve the last real page, not an empty // past-the-end slice (same contract as the templates/servers endpoints). // The clamp needs the total first, so the data query runs after the count // instead of in parallel with it. const countRows = await db.query(countSql, countParams); const total = Number(countRows[0]?.total || 0); const totalPages = Math.ceil(total / limit) || 1; page = Math.min(page, totalPages); const offset = (page - 1) * limit; // MariaDB on this project rejects prepared placeholders inside LIMIT/OFFSET. const dataRows = await db.query(`${dataSql} ORDER BY name ASC LIMIT ${limit} OFFSET ${offset}`, params); return { nodes: dataRows.map(mapNodeRow), total, page, limit, totalPages }; } async function findNodeByIdOrName(idOrName) { const key = String(idOrName || "").trim().toLowerCase(); if (!key) return null; // Deterministic resolution: the create/rename guards below historically // blocked only name-vs-name collisions, so a node's name can still equal // another node's id or uuid and this OR can match several distinct rows. // With a bare LIMIT 1 the row MariaDB returns is then unspecified, so a // PATCH/DELETE on that identifier (or a step-up grant minted from this // lookup) could land on a different node than the caller addressed. Rank // the matches by specificity — exact id beats uuid beats name — so the // winning row is stable for databases that already contain such rows. // What matches is unchanged; only which matching row wins. Bound // placeholders inside ORDER BY CASE are fine: the MariaDB restriction // noted above covers LIMIT/OFFSET only, and LIMIT 1 here is a literal. const rows = await db.query( "SELECT * FROM nodes WHERE id = ? OR uuid = ? OR LOWER(name) = ? ORDER BY CASE WHEN id = ? THEN 0 WHEN uuid = ? THEN 1 ELSE 2 END LIMIT 1", [key, key, key, key, key] ); return rows.length ? mapNodeRow(rows[0]) : null; } // adpanel:node-step-up-target - a verified identifier cannot fall back to another row's alias. async function findNodeForMutation(req) { const verifiedId = req.verifiedNodeMutationId; const node = await findNodeByIdOrName(verifiedId ?? req.params.id); return verifiedId == null || String(node?.id) === verifiedId ? node : null; } async function insertNode(node) { const payload = hardenNode(node); const online = computeOnline(payload); await db.query( `INSERT INTO nodes (id, uuid, name, address, ram_mb, disk_gb, ports, token_id, token, token_status, created_at, api_port, sftp_port, port_ok, last_seen, last_check, online, build_config, max_upload_mb) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [ payload.id, payload.uuid || payload.id, payload.name, payload.address, payload.ram_mb, payload.disk_gb, toDbJson(payload.ports, "{}"), payload.token_id, nodeTokenCrypto.encryptNodeToken(payload.token), payload.token_status || nodeTokenCrypto.TOKEN_STATUS_OK, payload.createdAt || Date.now(), payload.api_port || 8080, payload.sftp_port || 2022, payload.port_ok === null ? null : payload.port_ok ? 1 : 0, payload.last_seen ?? null, payload.last_check ?? null, online ? 1 : 0, toDbJson(payload.buildConfig || {}, "{}"), payload.max_upload_mb, ] ); return payload; } async function saveNode(node, previousConnectionState) { const payload = hardenNode(node); if (previousConnectionState !== undefined && nodeConnectionState(payload) !== previousConnectionState) { payload.port_ok = null; payload.last_seen = null; payload.last_check = null; payload.online = false; } const online = computeOnline(payload); await db.query( `UPDATE nodes SET uuid = ?, name = ?, address = ?, ram_mb = ?, disk_gb = ?, ports = ?, token_id = ?, token = ?, token_status = ?, created_at = ?, api_port = ?, sftp_port = ?, port_ok = ?, last_seen = ?, last_check = ?, online = ?, build_config = ?, max_upload_mb = ? WHERE id = ?`, [ payload.uuid || payload.id, payload.name, payload.address, payload.ram_mb, payload.disk_gb, toDbJson(payload.ports, "{}"), payload.token_id, nodeTokenCrypto.encryptNodeToken(payload.token), payload.token_status || nodeTokenCrypto.TOKEN_STATUS_OK, payload.createdAt || Date.now(), payload.api_port || 8080, payload.sftp_port || 2022, payload.port_ok === null ? null : payload.port_ok ? 1 : 0, payload.last_seen ?? null, payload.last_check ?? null, online ? 1 : 0, toDbJson(payload.buildConfig || {}, "{}"), payload.max_upload_mb, payload.id, ] ); return payload; } // adpanel:node-health-ownership - Only admin configuration owns the dial port. // Targeted health-only persistence for the background check loop, the // "check now" endpoint. These writers hold a node snapshot // across seconds of network probing; writing the full row back would let a // stale snapshot silently revert a concurrent token rotation or the startup // integrity gate's rotate_required flag, so only the health telemetry columns // are ever touched here. Credential columns (token/token_id/token_status) are // owned by rotateNodeToken()/the rotate-token endpoint and by the startup // gate — never by health writers. async function saveNodeHealth(node) { return tryWithKeyedLock(`node-ports:${node.id}`, async () => { const current = await findNodeByIdOrName(node.id); if (!current || current.id !== node.id) return null; // adpanel:node-health-ownership - only the connection and credential that answered may establish reachability. if (current.last_check > node.last_check || nodeConnectionState(current) !== nodeConnectionState(node) || current.token !== node.token || current.token_id !== node.token_id) return null; current.port_ok = node.port_ok; current.last_seen = Math.max(current.last_seen || 0, node.last_seen || 0) || null; current.last_check = node.last_check; current.online = computeOnline({ ...current, online: true }); await db.query("UPDATE nodes SET port_ok = ?, last_seen = NULLIF(GREATEST(COALESCE(last_seen, 0), ?), 0), last_check = ?, online = ? WHERE id = ?", [ current.port_ok === null || current.port_ok === undefined ? null : current.port_ok ? 1 : 0, current.last_seen ?? 0, current.last_check ?? null, current.online ? 1 : 0, current.id, ]); return current; }); } async function deleteNode(nodeId) { await db.query("DELETE FROM nodes WHERE id = ?", [nodeId]); } // Generates a fresh bearer token for a node and persists it (encrypted at // rest by saveNode). The caller is responsible for installing the same token // on the node daemon before the old one is invalidated. async function rotateNodeToken(nodeId, newToken) { const node = await findNodeByIdOrName(nodeId); if (!node) return null; // saveNode persists the FULL row, so this read-modify-write must be // serialized under the same per-node lock every other full-row writer uses // (PATCH, the build route, the pending-disk applier, delete) — otherwise a // PATCH stalled for seconds on DNS/Cloudflare verification can commit its // own snapshot after the rotation and resurrect the old credential, // silently defeating a leak-eviction rotation (or bricking a daemon that // already adopted the new token once its grace expires); the reverse race — // this stale snapshot reverting a rename the PATCH just committed — dies // with the same lock. The fresh re-read inside the lock applies the // rotation onto the row as it exists after any queued operation, never onto // a seconds-stale snapshot. The lock is NOT reentrant (see // utils/keyed-async-lock.js), so nothing in this callback may take the same // lock — findNodeByIdOrName and saveNode are plain db calls. return withKeyedLock(`node-ports:${node.id}`, () => rotateNodeTokenPrelocked(node.id, newToken)); } // The persist half of rotateNodeToken() for callers that must hold // withKeyedLock(`node-ports:`) across MORE than the persist — today // the rotate-token endpoint, which serializes the whole credential swap // (fresh read -> daemon push -> persist) under one acquisition so two // concurrent rotations cannot invert daemon-push order against persist order // and leave the panel holding a credential the daemon only serves from its // 10-minute old-token grace. The lock is not reentrant, so that endpoint // cannot call rotateNodeToken() while holding it. MUST be called while // already holding withKeyedLock(`node-ports:`): without the lock the // full-row read-modify-write below races every other full-row writer exactly // the way rotateNodeToken()'s lock exists to prevent. async function rotateNodeTokenPrelocked(nodeId, newToken) { const token = String(newToken || "").trim() || randSecret(); const fresh = await findNodeByIdOrName(nodeId); if (!fresh) return null; return saveNode({ ...fresh, token, token_status: nodeTokenCrypto.TOKEN_STATUS_OK }); } function sanitizeUpdatePayload(body) { const out = {}; if (typeof body.name !== "undefined") out.name = sanitizeNodeStorageName(body.name); if (typeof body.address !== "undefined") out.address = String(body.address || "").trim(); if (typeof body.additional_ips !== "undefined") { out.additional_ips = Array.isArray(body.additional_ips) ? body.additional_ips.map(ip => String(ip || "").trim()).filter(Boolean) : []; } else if (typeof body.ips !== "undefined") { out.additional_ips = Array.isArray(body.ips) ? body.ips.map(ip => String(ip || "").trim()).filter(Boolean) : []; } if (typeof body.cpu_cores !== "undefined") out.cpu_cores = toInt(body.cpu_cores, 0); if (typeof body.ram_mb !== "undefined") out.ram_mb = toInt(body.ram_mb, 0); else if (typeof body.ramMB !== "undefined") out.ram_mb = toInt(body.ramMB, 0); else if (typeof body.ram_gb !== "undefined") out.ram_mb = toInt(body.ram_gb, 0) * 1024; if (typeof body.disk_gb !== "undefined") out.disk_gb = toInt(body.disk_gb, 0); else if (typeof body.storage_gb !== "undefined") out.disk_gb = toInt(body.storage_gb, 0); else if (typeof body.storageGB !== "undefined") out.disk_gb = toInt(body.storageGB, 0); if (typeof body.ports !== "undefined" || typeof body.port_list !== "undefined" || typeof body.ports_list !== "undefined" || typeof body.mode !== "undefined") { const candidate = body.ports ?? body.ports_list ?? body.port_list; // Only an explicit alias (ports / ports_list / port_list) may touch the // pool: the previous `?? body` fallback let a bare {"mode":"anything"} // body normalize the ENTIRE payload object and wipe the allocation back // to the default range. Scattered {mode,start,count} fields without an // alias are ignored (no dashboard surface sends them). if (typeof candidate !== "undefined") out.ports = candidate; } if (typeof body.api_port !== "undefined") out.api_port = clampPort(body.api_port); if (typeof body.sftp_port !== "undefined") out.sftp_port = clampPort(body.sftp_port); if (typeof body.max_upload_mb !== "undefined") { out.max_upload_mb = Math.max(1, Math.min(100000, toInt(body.max_upload_mb, 10240))); } if (typeof body.ssl_enabled !== "undefined") out.ssl_enabled = truthyFlag(body.ssl_enabled); if (typeof body.under_cloudflare !== "undefined") out.under_cloudflare = truthyFlag(body.under_cloudflare); else if (typeof body.cloudflare_proxy !== "undefined") out.under_cloudflare = truthyFlag(body.cloudflare_proxy); return out; } function computeOnline(n) { if (!n) return false; const fresh = !!(n.last_seen && (Date.now() - Number(n.last_seen)) < HEARTBEAT_TTL_MS); const portOk = n.port_ok === true || n.port_ok === 1; const onlineFlag = typeof n.online === 'undefined' ? true : (n.online === true || n.online === 1); return !!(fresh && portOk && onlineFlag); } function nodePortsRevision(node) { const allocations = getNodeAllocations(node).sort((first, second) => first.port - second.port); return crypto.createHash("sha256").update(JSON.stringify([node.id, node.address, allocations])).digest("hex"); } // Public node serialization. token_id/token are the node daemon's bearer // credentials and must NEVER appear in an API response: any admin session // (or an XSS on one) could read them straight from the JSON. The browser // obtains the full config.yml / setup command only through the step-up // verified reveal endpoints registered in index.js (POST, password or 2FA). function toPublic(n) { const bc = n.buildConfig || {}; const additionalIps = Array.isArray(bc.ips) ? bc.ips : (Array.isArray(n.additional_ips) ? n.additional_ips : []); const allIps = [n.address, ...additionalIps].filter(Boolean); const out = { id: n.id, uuid: n.uuid, name: n.name, address: n.address, ips: allIps, additional_ips: additionalIps, cpu_cores: bc.cpu_cores || 0, ram_mb: n.ram_mb, disk_gb: n.disk_gb, ports: n.ports, ports_revision: nodePortsRevision(n), createdAt: n.createdAt, api_port: n.api_port, sftp_port: n.sftp_port || 2022, max_upload_mb: n.max_upload_mb || 10240, ssl_enabled: !!bc.ssl_enabled, under_cloudflare: nodeUnderCloudflare(n), // Credential hygiene flags for the admin UI ("rotate required" badge). // Deliberately booleans: token_status/token_id/token never leak here. token_rotate_required: n.token_status === nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED, token_invalidated: n.token_status === nodeTokenCrypto.TOKEN_STATUS_ROTATE_REQUIRED && !n.token, port_ok: n.port_ok, last_seen: n.last_seen, online: computeOnline(n), buildConfig: bc }; return out; } // adpanel:relay-helper-consolidation — buildNodeBaseUrl moved to // services/node-http.js and is re-bound from there at the top of this file, // parameterized to keep this surface's exact outputs (clampPort clamping, // u.toString() minus trailing slash, unclamped // explicit-URL-branch port). The one intentional behavior change is the // shared credential-in-URL rejection: a node address like // https://user:pass@host previously reached the URL branch here and its // credentials leaked into every relayed upstream URL; it is now refused // (null → the routes' existing !base fallback) on this surface too. // Panel-side cap for buffered node responses — mirrors index.js's // MAX_RESPONSE_BYTES. Since the Wave 3 convergence the 16 MiB cap itself is // enforced ONCE, inside services/node-http.js's core (MAX_RESPONSE_BYTES) // for every helper that buffers there (httpJson, the GET-probe // httpRequestJson); this local constant remains ONLY for callNodeApiOnce, // which still buffers inline. Same sizing rationale as the core's comment: // the daemon serves file reads up to 10 MiB (maxEditorRead = 10 << 20, // handleFSRead in main.go) and puts no size cap on /v1/fs/list output, so // 16 MiB fits every daemon-legal response with headroom; a body beyond it // fails as { error: "response too large", tooLarge: true } so routes can // answer node_response_too_large instead of a generic node failure — and a // misbehaving or compromised daemon cannot exhaust the worker's memory by // streaming an unbounded response at any of these helpers. const MAX_NODE_RESPONSE_BYTES = 16 * 1024 * 1024; const nodeResponseTooLarge = () => ({ status: 0, json: null, text: null, error: "response too large", tooLarge: true }); // adpanel:relay-helper-consolidation (Wave 3) — this GET-probe helper is now // a thin wrapper over services/node-http.js's hardened httpRequestJson core // (its former inline implementation — assertNodeUrlHostAllowed pre-flight + // guardedNodeLookup, 16 MiB cap via MAX_NODE_RESPONSE_BYTES, inactivity // req.setTimeout, response error listener — converged onto the one core that // had the superset posture). The wrapper preserves this helper's EXACT // external contract so its three callers (fetchNodeInfoVerified's signed and // unsigned probes, activeCheckNode's /health check) are unchanged: // signature (fullUrl, method = "GET", headers = {}, timeoutMs = 2500) — // GET-only, no body, the 2.5s default kept as the signature fallback; // result shape { status, json }, never rejects: every transport failure // (guard error, timeout, request/response error, setup throw) resolves // { status: 0, json: null } exactly as before. // opts.nodeDial keeps the core on this surface's historical guard branch: the // former helper applied the node guard chain UNCONDITIONALLY, including the // /health probe that sends NO auth headers — without the flag those dials // would fall into the core's external-URL branch, whose 80/443 port allowlist // rejects every node's custom api_port. // Flagged hardening deltas that ride with the core (the old helper lacked // them): res.on("aborted") alongside res.on("error") — the worker-crash class // AGENTS.md calls out — a hard total-duration timer on top of the inactivity // timeout, single-settle finish(), and the panel-injected node mTLS agent on // https dials when one is configured (the same posture the relayFsJson dials // adopted in Wave 2; without mTLS configured the default agent is used, as // before). The too-large result loses its former (unread) `text: null` key — // the status/json/error/tooLarge fields the probes consume are unchanged. function httpRequestJson(fullUrl, method = "GET", headers = {}, timeoutMs = 2500) { return httpRequestJsonCore(fullUrl, method, headers, null, timeoutMs, null, { nodeDial: true }); } const DEFAULT_NODE_TIMEOUT_MS = 10000; const LONG_NODE_TIMEOUT_MS = 120000; function isRecoverableNodeCreateStatus(status) { return status === 0 || status === 520 || status === 522 || status === 523 || status === 524; } // adpanel:http-straggler — deliberate raw dial (NOT services/node-http.js's // core): its contract attaches an error STRING on every failure path // ({status, json, error}) — guard, timeout, request/response error, too-large // — while the core resolves {status, json} with no error key except // tooLarge. The 80+ core call sites consume the core shape, so // parameterizing the string contract in would risk the converged helpers for // no hardening gain: this dial already carries the SSRF guard chain, the // 16 MiB Content-Length + streaming cap, a single-settle promise, and // response error + request error/timeout listeners. It also carries the two // core hardenings it formerly lacked: an explicit 'aborted' listener (a // mid-body abort previously left the promise unsettled until the socket died) // and a hard total-duration timer — req.setTimeout is an INACTIVITY timeout // that every trickling byte resets, so a never-settling dial could hold a // proxy create lock (or any caller) open indefinitely. Every settle path // clears the timer (single-settle): an uncleared timer would later destroy() // a finished request whose keep-alive socket the agent may already have // reassigned to another dial, and unref() keeps it from holding the event // loop in the window before settle. function callNodeApiOnce(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = DEFAULT_NODE_TIMEOUT_MS) { return new Promise((resolve) => { let hardTimer = null; const settle = (out) => { if (hardTimer) { clearTimeout(hardTimer); hardTimer = null; } resolve(out); }; try { // SSRF guard (finding 3.3) — pre-flight for literal-IP hosts; the guarded // lookup below re-validates resolved IPs for hostnames. Every dial to a // node goes through this guard: no caller may bypass it, because the // request headers carry the node's bearer credential. const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl); if (guardError) return settle({ status: 0, json: null, error: guardError.message }); const isHttps = fullUrl.startsWith("https:"); const lib = isHttps ? https : http; const requestOpts = { method, headers, lookup: nodeSsrfGuard.guardedNodeLookup, agent: nodeTlsAgent(fullUrl) }; const req = lib.request(fullUrl, requestOpts, (res) => { // adpanel:node-http-cap-error-listeners - header-only refusals still // destroy responses that can emit late error and aborted events. res.on("error", (err) => settle({ status: 0, json: null, error: err?.message || "response error" })); res.on("aborted", () => settle({ status: 0, json: null, error: "response aborted" })); // Content-Length pre-check: reject an over-cap body before buffering // any of it (mirrors index.js httpGetRaw). Settle BEFORE destroying — // destroy() on a mid-message response emits 'aborted' synchronously, // and the aborted listener below would win the race and misreport an // over-cap dial as a generic transport failure. const contentLength = parseInt(res.headers["content-length"], 10); if (Number.isFinite(contentLength) && contentLength > MAX_NODE_RESPONSE_BYTES) { settle(nodeResponseTooLarge()); try { res.destroy(); } catch { } return; } const chunks = []; let totalBytes = 0; res.on("data", (d) => { totalBytes += d.length; if (totalBytes > MAX_NODE_RESPONSE_BYTES) { // Settle BEFORE destroying, for the same aborted-listener race as // the Content-Length pre-check: the over-cap shape must win. // Destroying still stops the drain (the remainder is never // buffered) and the later 'end'/'error' events are no-ops. settle(nodeResponseTooLarge()); try { res.destroy(); } catch { } return; } chunks.push(d); }); res.on("end", () => { const bodyStr = Buffer.concat(chunks).toString("utf8"); try { const json = bodyStr ? JSON.parse(bodyStr) : null; settle({ status: res.statusCode, json, error: null }); } catch { settle({ status: res.statusCode, json: null, error: null }); } }); }); req.on("timeout", () => { try { req.destroy(new Error("timeout")); } catch { } settle({ status: 0, json: null, error: "timeout" }); }); req.on("error", (err) => settle({ status: 0, json: null, error: err?.message || "request error" })); req.setTimeout(timeoutMs); // Hard total-duration bound, mirroring the hardened core's posture: the // inactivity timeout above resets on every socket tick, so a dial that // never settles could hold a proxy create lock until the socket died. // settle() clears this timer, so an early-completing dial leaves no // pending destroy() behind. hardTimer = setTimeout(() => { try { req.destroy(new Error("timeout")); } catch { } settle({ status: 0, json: null, error: "timeout" }); }, timeoutMs); hardTimer.unref(); if (body) req.write(JSON.stringify(body)); req.end(); } catch { settle({ status: 0, json: null, error: "request setup failed" }); } }); } // (The former resolveLoopbackNodeBase hairpin fallback was removed. It probed // loopback /health for the node's UUID and then re-sent the node's full bearer // credentials to whichever local listener had answered — but the daemon's // /health never returns a UUID, so the real daemon could never be matched and // the only responder that could pass the check was an impostor farming the // token (the UUID is public via the node API). A loopback probe that // authenticates the daemon without exposing the token would require a signed // challenge protocol on the daemon side; until then, no fallback is safer // than a fallback that can only feed credentials to a squatter.) async function callNodeApi(node, pathSuffix, method = "GET", body = null, timeoutMs = DEFAULT_NODE_TIMEOUT_MS) { const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); if (!base) return { status: 0, json: null, error: "invalid node base url" }; const safeSuffix = String(pathSuffix || "").startsWith("/") ? String(pathSuffix) : `/${String(pathSuffix || "")}`; const headers = { "Authorization": `Bearer ${node.token}`, "X-Node-Token": node.token || "", "X-Node-Token-Id": node.token_id || "", "Content-Type": "application/json", }; return callNodeApiOnce(`${base}${safeSuffix}`, method, headers, body, timeoutMs); } async function waitForNodeServerReady(node, name, { timeoutMs = 30_000, intervalMs = 2000 } = {}) { const safeName = encodeURIComponent(String(name || "")); const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const result = await callNodeApi(node, `/v1/servers/${safeName}`, "GET", null, Math.min(intervalMs, 10_000)); if (result.status === 200 && result.json && (result.json.ok === true || result.json.name || result.json.status)) { return true; } await new Promise(resolve => setTimeout(resolve, intervalMs)); } return false; } function extractHostnameForNodeTls(address) { const raw = String(address || "").trim(); if (!raw) return ""; let host = ""; if (/^https?:\/\//i.test(raw)) { try { host = new URL(raw).hostname; } catch { return ""; } } else { const withoutPath = raw.split(/[/?#]/)[0]; if (withoutPath.startsWith("[")) { const end = withoutPath.indexOf("]"); host = end > 0 ? withoutPath.slice(1, end) : withoutPath; } else { const colonCount = (withoutPath.match(/:/g) || []).length; host = colonCount === 1 ? withoutPath.split(":")[0] : withoutPath; } } host = String(host || "").trim().toLowerCase(); if (!host || host === "localhost" || net.isIP(host)) return ""; if (!/^[a-z0-9.-]+$/i.test(host)) return ""; return host; } function defaultNodeTlsPaths(node) { if (!node || !node.ssl_enabled) return { cert: "", key: "" }; const host = extractHostnameForNodeTls(node.address); if (!host) return { cert: "", key: "" }; return { cert: `/etc/letsencrypt/live/${host}/fullchain.pem`, key: `/etc/letsencrypt/live/${host}/privkey.pem`, }; } function yamlDoubleQuote(value) { return `"${String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } function shellSingleQuote(value) { return `'${String(value == null ? "" : value).replace(/'/g, `'\\''`)}'`; } function buildPanelPublicUrl(req) { const host = nodeBootstrapTransport.trustedHost(req) || req?.get?.("host"); const scheme = nodeBootstrapTransport.secure(req) ? "https" : "http"; try { const url = new URL(PANEL_PUBLIC_URL || (host ? `${scheme}://${host}` : "")); if ((url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password && url.pathname === "/" && !url.search && !url.hash) return url.origin; } catch { } throw new Error("Cannot determine the panel origin. Configure PANEL_PUBLIC_URL."); } // adpanel:bootstrap-transport - credential routes require HTTPS independently of the panel's pre-auth middleware. function requireNodeBootstrapTransport(req, res, next) { const browserWrite = req.method === "POST"; if (browserWrite) res.set("Cache-Control", "no-store"); if (ALLOW_INSECURE_NODE_BOOTSTRAP || nodeBootstrapTransport.secure(req)) return next(); if (browserWrite) return res.status(403).json({ error: "HTTPS required for node credentials." }); return res.status(403).set("Cache-Control", "no-store").type("text/plain").send("HTTPS required"); } // (The legacy buildNodeConfigRestartCommand heredoc — which embedded the full // config.yml, bearer token and hmac_secret included, into the pasted setup // command — was removed: pasting writes it verbatim into shell history and // scrollback on the node host. oneTimeCommand() below now returns a secret- // free one-liner backed by the single-use enrollment endpoints.) // // (The legacy /api/nodes/:id/install-daemon.sh route and its signed installer // token machinery were removed with it: issueNodeInstallerToken had no caller, // so no valid token could ever exist and the endpoint could only ever answer // 401 — a pre-auth-reachable, TLS-gate-skipping surface that existed purely to // leak node existence (404 vs 401) and embed the full config.yml base64. The // supported install path is the single-use /api/node-bootstrap one-time // command.) async function resolveNodeForServer(serverName) { const name = String(serverName || "").trim(); if (!name) return { server: null, node: null, nodeId: null }; const srv = await findServerByNameOrId(name); if (!srv) return { server: null, node: null, nodeId: null }; const rawNodeId = (srv.node || srv.nodeId || srv.node_id || ""); const key = String(rawNodeId || "").trim(); if (!key) return { server: srv, node: null, nodeId: null }; const node = await findNodeByIdOrName(key); return { server: srv, node, nodeId: node ? node.uuid : null }; } // (The former httpRequestJsonWithBody was deleted in the Wave 3 HTTP-helper // convergence: it had ZERO callers — verified by grep across nodes.js, // index.js, utils/ and services/ — and was pinned only by // tests/node-response-cap.test.js, whose pin was consciously re-pointed at // the helpers that exist. Any future body-carrying dial to a node goes // through httpJson or callNodeApi, both wrappers over the hardened core.) async function httpJson(fullUrl, { method = "GET", headers = {}, body = null, timeoutMs = 5000 } = {}) { // adpanel:relay-helper-consolidation (Wave 3) — thin wrapper over // services/node-http.js's hardened httpRequestJson core, preserving this // helper's EXACT external contract: // signature (fullUrl, { method = "GET", headers = {}, body = null, // timeoutMs = 5000 }) — the 5s default stays (pinned by // tests/node-relay-timeout-parity.test.js, which also pins that every // relay call passes an explicit timeoutMs); // result shape { status, json, text }, never rejects — text carries the // raw response body on the end path and null on the guard-error / // response-error / too-large paths, exactly as this helper always // resolved them (the timeout / request-error / setup-failure paths // resolve WITHOUT the text key, as before — the backup performers' // `String(json?.error || text || "no body")` logging is shape-exact); // too-large resolves { status: 0, json: null, text: null, // error: "response too large", tooLarge: true } (the 16 MiB cap itself // now lives once, in the core); // request body wire: Content-Type: application/json defaulted when the // caller did not pass one, plus an explicit Content-Length — byte-for-byte // the headers the former inline implementation set via req.setHeader // (the core alone would send the body chunked; this surface's relays keep // the declared-length form they always sent). // opts.nodeDial keeps the core on this surface's historical guard branch: // the former helper applied the node guard chain (assertNodeUrlHostAllowed // pre-flight + guardedNodeLookup) UNCONDITIONALLY; every current caller // sends node auth headers so the core's header-sniffing branch would agree, // but the flag pins the posture rather than trusting the coincidence. // Flagged hardening deltas that ride with the core (the old inline helper // lacked them): res.on("aborted") alongside res.on("error") — the // worker-crash class — a hard total-duration timer on top of the inactivity // req.setTimeout, single-settle finish(), and the panel-injected node mTLS // agent on https dials when one is configured (the same posture the // relayFsJson dials adopted in Wave 2). let dialHeaders = headers; let dialBody = body; if (body != null) { let data; try { data = typeof body === "string" ? body : JSON.stringify(body); } catch { // The former inline implementation stringified inside its promise // executor's try, so an unserializable body resolved // { status: 0, json: null } instead of rejecting — keep that. return { status: 0, json: null }; } dialHeaders = { ...headers }; if (!dialHeaders["Content-Type"]) dialHeaders["Content-Type"] = "application/json"; dialHeaders["Content-Length"] = Buffer.byteLength(data); dialBody = data; } return httpRequestJsonCore(fullUrl, method, dialHeaders, dialBody, timeoutMs, null, { includeText: true, nodeDial: true }); } function tcpCheck(host, port, timeoutMs = 2000) { return new Promise((resolve) => { let finished = false; const done = (ok) => { if (finished) return; finished = true; try { socket.destroy(); } catch { } resolve(!!ok); }; let socket; try { // Resolve through the SSRF guard first so this primitive can never // become an unguarded internal port scanner (finding 3.3). nodeSsrfGuard.guardedNodeLookup(String(host || ""), { family: 0 }, (err, address) => { if (err || !address) return done(false); socket = new net.Socket(); socket.setTimeout(timeoutMs); socket.once("connect", () => done(true)); socket.once("timeout", () => done(false)); socket.once("error", () => done(false)); socket.connect(clampPort(port || 8080), address); }); } catch { done(false); } }); } // Probe mode memo for the signed /v1/info check: once a node is known to // reject the signed envelope (401 on every secret), skip signing for a while // so the batch health loop does not burn a 3-request chain on it every cycle. const _nodeInfoProbeMode = new Map(); // nodeId -> { signedOk: bool, expires: ts } const NODE_PROBE_MODE_TTL_MS = 10 * 60 * 1000; const _unverifiedProbeWarnedAt = new Map(); // nodeId -> last warn ts function rememberNodeInfoProbeMode(nodeId, signedOk) { if (!nodeId) return; _nodeInfoProbeMode.set(nodeId, { signedOk: !!signedOk, expires: Date.now() + NODE_PROBE_MODE_TTL_MS }); } function cachedNodeInfoProbeMode(nodeId) { const memo = _nodeInfoProbeMode.get(nodeId); if (!memo) return null; if (Date.now() > memo.expires) { _nodeInfoProbeMode.delete(nodeId); return null; } return memo.signedOk; } // Fetches /v1/info, preferring the probe with a signed response. Returns // { res, verified }. Nodes that answer 200 without proof are legacy // binaries — accepted with verified:false, exactly the pre-hardening trust // level, but distinguishable to callers. async function fetchNodeInfoVerified(node, baseUrl, checkTimeout) { const url = `${baseUrl}/v1/info`; const baseHeaders = { "Authorization": `Bearer ${node.token}` }; const nodeId = node.uuid || node.id; const secrets = []; const derived = deriveNodeHmacSecret(PANEL_HMAC_SECRET, nodeId); if (derived) secrets.push(derived); if (PANEL_HMAC_SECRET && PANEL_HMAC_SECRET !== derived) secrets.push(PANEL_HMAC_SECRET); if (secrets.length > 0 && cachedNodeInfoProbeMode(nodeId) !== false) { for (const secret of secrets) { const probe = signPanelProbeRequest(secret, nodeId, "info"); if (!probe) continue; const res = await httpRequestJson(url, "GET", Object.assign({}, baseHeaders, probe.headers), checkTimeout); if (res && res.status === 200 && res.json) { rememberNodeInfoProbeMode(nodeId, true); return { res, verified: verifyNodeProbeResponse(secret, nodeId, "info", probe, res.json), }; } if (res && res.status === 401) continue; // try next secret return { res, verified: false }; } // All secrets rejected — remember to go straight unsigned next cycles. rememberNodeInfoProbeMode(nodeId, false); } const res = await httpRequestJson(url, "GET", baseHeaders, checkTimeout); return { res, verified: false }; } async function activeCheckNode(node, opts = { force: false }) { const now = Date.now(); if (!opts.force && node.last_check && (now - Number(node.last_check)) < 5000) return; node.last_check = now; let ok = false; let verified = false; const baseUrl = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); if (baseUrl) { const checkTimeout = 1500; try { const [infoProbe, healthRes] = await Promise.all([ fetchNodeInfoVerified(node, baseUrl, checkTimeout), httpRequestJson(`${baseUrl}/health`, "GET", {}, checkTimeout) ]); const infoRes = infoProbe.res; verified = !!infoProbe.verified; if (infoRes.status === 200 && infoRes.json && infoRes.json.ok && infoRes.json.node) { const uuid = String(infoRes.json.node.uuid || ""); if (uuid && (uuid === node.uuid || uuid === node.id)) ok = true; if (infoRes.json.node.volumesDir) { node.volumesDir = String(infoRes.json.node.volumesDir); const cacheKey = String(node.uuid || node.id || ""); if (cacheKey) _nodeVolumeDirCache.set(cacheKey, node.volumesDir); } } // adpanel:node-health-auth - liveness alone cannot establish an operational daemon connection. if (!ok && healthRes.status === 200 && infoRes.status === 401) { console.warn(`[node-check] Node ${node.name} (${node.address}) is reachable but auth FAILED. Token mismatch — re-deploy config.yml.`); } if (ok && !verified && PANEL_HMAC_SECRET) { // Accepted on the legacy UUID check alone: the daemon is either an // older binary or (worse) the responder is not the real daemon. Not // fatal for monitoring, but worth surfacing — at most hourly per // node so a legacy fleet cannot flood the log. const warnKey = String(node.uuid || node.id || ""); const lastWarn = _unverifiedProbeWarnedAt.get(warnKey) || 0; if (Date.now() - lastWarn > 60 * 60 * 1000) { _unverifiedProbeWarnedAt.set(warnKey, Date.now()); console.warn(`[node-check] Node ${node.name} (${node.address}) online but identity NOT verified by signed probe — daemon may need an update.`); } } } catch { ok = false; } } node.port_ok = !!ok; if (ok) { node.last_seen = now; } } // The node agent's API listener defaults to the panel-reachable interface — // the node's own address — instead of 0.0.0.0, so a daemon running without // TLS is not additionally exposed on every interface of the host. Precedence: // 1. NODE_API_BIND_MODE=wildcard — fleet-wide escape hatch for deployments // that genuinely need the listener on all interfaces (checked first) // 2. buildConfig.api_host — explicit per-node override ("0.0.0.0" restores // the wildcard bind; settable via the node build endpoint) // 3. node.address when it is a literal IP (v4/v6) — the interface the panel // (and any client) is expected to reach // 4. 0.0.0.0 — hostnames (and Cloudflare-proxied nodes, whose origin IP // cannot be derived from the proxied name) give no bindable address, so // the wildcard stays and the caller is expected to warn. function resolveNodeApiBindHost(node) { if (String(process.env.NODE_API_BIND_MODE || "").trim().toLowerCase() === "wildcard") { return "0.0.0.0"; } const explicit = String(node?.buildConfig?.api_host || "").trim(); if (explicit) { // Operator-chosen, but must stay a bare host token — never YAML structure, // whitespace, or a URL. if (/^[A-Za-z0-9._:-]{1,64}$/.test(explicit)) return explicit; console.warn(`[nodes] Ignoring invalid buildConfig.api_host for node ${node?.name || node?.id || "?"}: ${JSON.stringify(explicit.slice(0, 64))}`); } const rawAddress = stripExplicitHostPort( String(node?.address || "").trim().replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").split(/[/?#]/)[0] ); const address = rawAddress.replace(/^\[|\]$/g, ""); if (nodeUnderCloudflare(node)) return "0.0.0.0"; if (address && net.isIP(address)) return address; return "0.0.0.0"; } function buildConfigYml(node, req) { if (!String(node?.token || "").trim()) { // An invalidated/empty credential would render as an empty `token:` line — // deploying that config bricks the daemon. Refuse to build it; the admin // must rotate/re-issue the token (rotate-token endpoint) first. throw new Error("node token is invalidated or empty — rotate the node token before building config.yml"); } const panelUrl = buildPanelPublicUrl(req); const sslEnabled = !!node.ssl_enabled; const tlsPaths = defaultNodeTlsPaths(node); const bindHost = resolveNodeApiBindHost(node); const apiPort = clampPort(node.api_port || 8080); const lines = [ `debug: false`, `uuid: ${node.uuid}`, `token_id: ${node.token_id}`, `token: ${node.token}`, `auth:`, ` token_id: ${node.token_id}`, ` token: ${node.token}`, `api:`, ` # Bound to ${bindHost} (the panel-reachable interface). Override per node via buildConfig.api_host,`, ` # or set NODE_API_BIND_MODE=wildcard on the panel to restore 0.0.0.0 everywhere.`, ]; if (!sslEnabled) { // Loud, persistent warnings in the artifact itself: this config is what // the operator deploys, so this is the one place they cannot miss it. lines.push( ` # ================================ SECURITY WARNING ================================`, ` # ssl.enabled is FALSE: the node API below serves PLAINTEXT HTTP, bearer token`, ` # included. Anyone on path to ${bindHost}:${apiPort} can read the credential and any`, ` # traffic (file transfers, console, backups). Enable SSL for this node in the panel`, ` # (node settings), or firewall ${apiPort} down to the panel's IP, before deploying.`, ` # ==================================================================================` ); console.warn( `[security] config.yml for node "${node.name || node.id}" (${node.address}): daemon API ` + `will serve PLAINTEXT HTTP (ssl.enabled=false) on ${bindHost}:${apiPort}. The node bearer ` + `token crosses the wire unencrypted — enable TLS for the node or restrict its firewall.` ); if (bindHost === "0.0.0.0") { console.warn( `[security] config.yml for node "${node.name || node.id}" (${node.address}): plaintext ` + `daemon API is bound to ALL interfaces (0.0.0.0) because "${node.address}" is not a ` + `literal IP. Set buildConfig.api_host to the panel-reachable IP to limit exposure.` ); } } lines.push( ` host: ${yamlDoubleQuote(bindHost)}`, ` port: ${apiPort}`, ` ssl:`, ` enabled: ${sslEnabled}`, ` cert: "${tlsPaths.cert}"`, ` key: "${tlsPaths.key}"`, ` upload_limit: ${node.max_upload_mb || 10240}`, `system:`, ` data: /var/lib/node`, `allowed_mounts: []`, `panel:`, ` url: ${panelUrl}`, ` node_id: ${node.uuid}` ); // The node receives only its own per-node derived signing secret — never // the fleet master (PANEL_HMAC_SECRET). A stolen config.yml is then useless // for forging admin signatures against other nodes or the panel. const nodeHmacSecret = deriveNodeHmacSecret(PANEL_HMAC_SECRET, node.uuid); if (nodeHmacSecret) { lines.push(` hmac_secret: ${yamlDoubleQuote(nodeHmacSecret)}`); } return lines.join("\n") + "\n"; } // Builds the one-time setup command as a secret-free one-liner. Nothing about // the node's credentials is pasted into a terminal any more: the command only // carries a single-use bootstrap link, and the node fetches config.yml (token // and hmac_secret included) over TLS from the panel exactly once. A fresh // enrollment pair is minted on every reveal; each link is consumed by its // first download and expires after NODE_ENROLL_TTL_MS. async function oneTimeCommand(node, req) { const base = buildPanelPublicUrl(req); if (!ALLOW_INSECURE_NODE_BOOTSTRAP && !base.startsWith("https://")) { throw Object.assign(new Error("Node setup requires an HTTPS panel URL."), { status: 403 }); } const enroll = await nodeEnrollStore.issue(node); const url = `${base}/api/node-bootstrap/${encodeURIComponent(enroll.scriptId)}`; return `curl -fsSL ${shellSingleQuote(url)} | bash`; } // Route matcher + validator for the unauthenticated bootstrap endpoints, // called from index.js's isOpenNodeRoute() so the panel-wide pre-auth and CSRF // middlewares treat them like the other node-daemon routes. Fail-closed: any // request that is not a well-formed bootstrap GET is reported as not-open and // falls through to the ordinary auth chain. The TLS transport gate is applied // by index.js right next to this classification — via its trusted-proxy-aware // isRequestSecure() and the ALLOW_INSECURE_NODE_BOOTSTRAP override, the exact // policy the /api/nodes/:id/config.yml bootstrap endpoint uses (x-forwarded- // proto is only honored from configured trusted proxies there). const NODE_BOOTSTRAP_ROUTE_RE = /^\/api\/node-bootstrap\/([A-Za-z0-9_-]+)(\/config\.yml)?$/; function isOpenNodeBootstrapRoute(req) { if (String(req?.method || "GET").toUpperCase() !== "GET") return false; const match = NODE_BOOTSTRAP_ROUTE_RE.exec(String(req?.path || "")); if (!match) return false; // Without a literal enrollment ID shape there is nothing a legitimate // client could send, so do not even classify it as a bootstrap route. return isEnrollId(match[1]); } const app = express(); app.disable("x-powered-by"); // adpanel:node-file-write-scoped-parser — the remote-mode editor save relay // (POST /api/nodes/server/:name/file) rides the same scoped large-body JSON // parser as the panel's PUT /api/servers/:name/files/write. The daemon caps // the RAW /v1/fs/write request body at 10 MiB inclusive (readJSON(w, r, // 10<<20) in handleFSWrite, main.go), so the serialized JSON envelope must be // accepted up to that same byte: the constant below mirrors index.js's // FILE_WRITE_JSON_LIMIT exactly (same env override, same "10mb" default — // derivation in services/node-fs-relay.js NODE_FS_WRITE_BODY_LIMIT_BYTES; // this file cannot import index.js, so the mirror is deliberate and pinned by // name). Without it, the global 2mb parser below bounced 2-10 MB editor saves // with a bare 413 before the route ran. Order: the dispatch sits ahead of the // global parser (an already-parsed body skips every later body-parser via the // req._body sentinel) and pre-auth, matching index.js's write route, where // jsonParserFileWrite also runs pre-auth at its large-body dispatch, in front // of session auth and the route's own action-token check. In integrated mode // index.js's own pre-auth dispatch — fronted by its always-on large-body rate // limiter — parses this exact path first and this parser then skips; in // standalone mode (`node nodes.js`) the surface keeps the pre-auth JSON-parse // posture the 2mb global parser already gave every route, raised to this // route's real body budget. body-parser's own 413 would surface as an HTML // error page, so it maps to the shared fileWriteTooLargePayload() JSON — the // exact shape the client's 413 branch reads (j.message = // FILE_WRITE_LIMIT_CLIENT_MESSAGE). const FILE_WRITE_JSON_LIMIT = process.env.FILE_WRITE_JSON_LIMIT || "10mb"; const jsonParserFileWrite = express.json({ limit: FILE_WRITE_JSON_LIMIT }); // The heartbeat-path matcher for the raw-body capture below (this router sees // the full path: index.js mounts it at "/" and standalone mode serves it // directly). Kept in lockstep with the gate middleware's literal of the same // regex — that one stays inline because // tests/node-api-gate-case-bypass.test.js extracts and runs it in isolation. const HEARTBEAT_ROUTE_RE = /^\/api\/nodes\/[^/]+\/heartbeat$/; // adpanel:heartbeat-body-binding — capture the heartbeat's EXACT raw body // bytes BEFORE JSON parsing. The v2 envelope's body hash is sha256 over the // wire bytes; verifying it against a re-serialized req.body would accept // bodies the daemon never sent (JSON stringification is not byte-stable // across writers), so the verifier hashes what this capture stored. The // buffer is kept only for the one heartbeat path (zero overhead elsewhere) // and dies with the request. If the parser does not run (no/wrong // content-type, bodyless request) nothing is captured and a v2 sender fails // closed — v2 daemons send a JSON body; legacy v1 senders are unaffected. // adpanel:heartbeat-capture-integrated — the capture must live on the parser // that ACTUALLY parses the heartbeat in each deployment topology. Standalone // (`node nodes.js`) keeps it on the 2mb parser below. In integrated mode // (index.js + app.use(nodesRouter)) index.js's pre-auth JSON dispatch parses // this route FIRST, and body-parser then skips every later parser via the // req._body sentinel — checked before verify is ever invoked // (node_modules/body-parser/lib/types/json.js) — so a verify only on THIS // parser silently never fires there and every v2 heartbeat failed closed // (body-unavailable → uniform 401). index.js therefore binds this same ONE // implementation (exported below) onto a heartbeat-scoped parser ahead of its // catch-all jsonParserDefault; no second capture implementation may exist. const HEARTBEAT_RAW_BODY_PROP = "heartbeatRawBody"; function captureHeartbeatRawBody(req, _res, buf) { if (HEARTBEAT_ROUTE_RE.test(String(req.path || ""))) { try { req[HEARTBEAT_RAW_BODY_PROP] = Buffer.isBuffer(buf) ? Buffer.from(buf) : Buffer.alloc(0); } catch (_) { // Never throw from verify: a capture failure must degrade to the v2 // fail-closed verdict in the verifier, not to a parser 4xx. } } } app.use((req, res, next) => { if (req.method === "POST" && /^\/api\/nodes\/server\/[^/]+\/file$/.test(req.path || "")) { return jsonParserFileWrite(req, res, (parseErr) => { if (parseErr && (parseErr.type === "entity.too.large" || parseErr.statusCode === 413 || parseErr.status === 413)) { return res.status(413).json(fileWriteTooLargePayload()); } return next(parseErr); }); } return next(); }); app.use(express.json({ limit: "2mb", verify: captureHeartbeatRawBody })); app.use(express.urlencoded({ extended: true })); // Fail-closed, allowlist-only CORS: an Origin receives a credentialed grant // (exact ACAO echo + credentials, never a wildcard) ONLY when the operator // lists it in NODES_CORS_ORIGINS. There is deliberately NO default same-origin // echo: same-origin requests never consult CORS, the panel's own frontend // calls these routes with relative paths, and a dynamic reflection branch — // however tight — is one careless widening of its origin computation (e.g. // trusting X-Forwarded-Host, or suffix matching) away from becoming a // credentialed cross-origin grant. Zero reflection leaves nothing to widen; // an empty allowlist therefore emits no CORS header at all. const CORS_ALLOWED_ORIGINS = new Set( (process.env.NODES_CORS_ORIGINS || "") .split(",") .map(s => s.trim()) .filter(Boolean) ); function applyCors(req, res) { // Whether Access-Control-Allow-Origin is echoed depends on the request's // Origin header, so every response through this router must tell caches it // varies by that header — without this, a shared cache could serve a // response minted for one origin (with that origin's ACAO) to another. res.vary("Origin"); const origin = req.get("origin"); if (!origin) return; if (!CORS_ALLOWED_ORIGINS.has(origin)) return; res.header("Access-Control-Allow-Origin", origin); res.header("Access-Control-Allow-Credentials", "true"); res.header("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,OPTIONS"); res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Node-Token-Id, x-action-token"); } app.use((req, res, next) => { applyCors(req, res); if (req.method === "OPTIONS") return res.sendStatus(204); next(); }); const NODES_PUBLIC_ROUTES = new Set([ "/health", "/api/nodes/:id/heartbeat", "/api/nodes/:id/config.yml", ]); const NODES_SERVER_ROUTES_PATTERN = /^\/api\/nodes\/server\/[^/]+\/(info|entries|file|logs|stats|action|command|delete|delete-batch|rename|upload|upload-url|create|download|extract|archive|backups(\/[^/]+)?(\/restore)?|eula(\/accept)?)$/; app.use(async (req, res, next) => { try { const path = req.path || ""; if (path === "/health") return next(); // Kept as the literal (not the HEARTBEAT_ROUTE_RE const): this gate is // extracted and run in isolation by tests/node-api-gate-case-bypass.test.js, // whose sandbox injects only NODES_SERVER_ROUTES_PATTERN. It must stay in // lockstep with HEARTBEAT_ROUTE_RE — the pre-auth raw-body capture below // matches the exact same one route. if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next(); if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next(); // Same exemption for case-variant spellings: index.js classifies // case-variant paths as node routes, so this layer must exempt the same // set — the server handlers below enforce per-server access themselves. if (NODES_SERVER_ROUTES_PATTERN.test(path.toLowerCase())) return next(); // Must mirror Express's case-insensitive dispatch: a case-sensitive // prefix check here let /API/NODES skip the admin requirement and reach // the node fleet routes (utils/node-api-path.js). if (isNodeApiPath(path)) { if (!req.isAdmin) { return res.status(403).json({ error: "admin required" }); } } return next(); } catch (err) { return next(err); } }); // --- Secret-free node bootstrap (single-use enrollment endpoints) ----------- // Unauthenticated by design: the only capability a request carries is the // 256-bit single-use enrollment ID itself, and each download consumes it // before any node data is touched. Reachability for sessionless callers is // granted by index.js isOpenNodeRoute() via isOpenNodeBootstrapRoute() below; // both endpoints are GET-only, rate limited per IP and marked no-store. app.get("/api/node-bootstrap/:id", requireNodeBootstrapTransport, createBootstrapScriptHandler({ store: nodeEnrollStore, limiter: nodeEnrollLimiter, findNode: findNodeByIdOrName, buildPanelBaseUrl: buildPanelPublicUrl, log: (msg) => console.log(`[node-bootstrap] ${msg}`), })); app.get("/api/node-bootstrap/:id/config.yml", requireNodeBootstrapTransport, createBootstrapConfigHandler({ store: nodeEnrollStore, limiter: nodeEnrollLimiter, findNode: findNodeByIdOrName, buildConfig: buildConfigYml, log: (msg) => console.log(`[node-bootstrap] ${msg}`), })); app.get("/health", (_req, res) => res.json({ ok: true })); app.get("/api/nodes", async (req, res) => { // Pre-flight guard: the admin gate and both node-index reads are DB-backed // and previously had no catch beneath them — Express 4 does not catch // async-handler rejections, so any DB rejection here hung the request and // only fed the process-level unhandledRejection log. The handler had no body // catch, so the whole body is wrapped: the client gets a generic 500 and the // full error stays in the server log. try { if (!(await requireNodeAdmin(req, res))) return; const wantPaginated = req.query.page || req.query.limit || req.query.search; if (wantPaginated) { const result = await loadNodesPaginated(req.query.page, req.query.limit, req.query.search); return res.json({ nodes: result.nodes.map((n) => toPublic(n)), total: result.total, page: result.page, limit: result.limit, totalPages: result.totalPages }); } const list = await loadNodes(); res.json({ nodes: list.map((n) => toPublic(n)) }); } catch (err) { console.error("[/api/nodes] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); app.get("/api/nodes/:id", async (req, res) => { // Pre-flight guard: the admin gate and the node lookup are DB-backed and // previously had no catch beneath them — Express 4 does not catch // async-handler rejections, so any DB rejection here hung the request. The // handler had no body catch, so the whole body is wrapped: the client gets a // generic 500 and the full error stays in the server log. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "not found" }); res.json(toPublic(node)); } catch (err) { console.error("[/api/nodes/:id] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); app.post("/api/nodes/:id/check", async (req, res) => { // Pre-flight guard: the admin gate, the node lookup and the health check // writes are DB-backed and previously had no catch beneath them — Express 4 // does not catch async-handler rejections, so any DB rejection here hung the // request. The handler had no body catch, so the whole body is wrapped: the // client gets a generic 500 and the full error stays in the server log. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "not found" }); await activeCheckNode(node, { force: true }); const current = await saveNodeHealth(node) || await findNodeByIdOrName(node.id); if (!current || current.id !== node.id) return res.status(404).json({ error: "not found" }); res.json({ ok: computeOnline(current), node: toPublic(current) }); } catch (err) { console.error("[/api/nodes/:id/check] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); app.get("/api/nodes/:id/ports/check", async (req, res) => { // Pre-flight guard: the admin gate, the node lookup and the daemon port // probe are DB/network-backed and previously had no catch beneath them — // Express 4 does not catch async-handler rejections, so any rejection here // hung the request. The handler had no body catch, so the whole body is // wrapped: the client gets a generic 500 and the full error stays in the // server log. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ ok: false, error: "node_not_found" }); const port = validatePortInput(req.query?.port); if (!port) return res.status(400).json({ ok: false, error: "invalid_port" }); if (!isPortInNodeAllocation(node, port)) { const alloc = node.ports || {}; let allocDesc = "none"; if (alloc.mode === "range") allocDesc = `range ${alloc.start}\u2013${alloc.start + alloc.count - 1}`; else if (alloc.mode === "list" && Array.isArray(alloc.ports)) allocDesc = `list [${alloc.ports.slice(0, 10).join(", ")}${alloc.ports.length > 10 ? "\u2026" : ""}]`; return res.json({ ok: true, port, available: false, reason: "outside-allocation", detail: `Port ${port} is not in this node's allocated ports (${allocDesc}).` }); } const reservations = await getServersUsingPortsOnNode(node); if (reservations.has(port)) { return res.json({ ok: true, port, available: false, reason: "assigned-to-server", detail: `Port ${port} is already reserved by a server on this node.` }); } const result = await callNodeApi(node, `/v1/ports/check?port=${encodeURIComponent(String(port))}`, "GET", null, 10_000); if (result.status === 200 && result.json && result.json.ok) { return res.json(result.json); } return res.json({ ok: true, port, available: null, verified: false, status: result.status || 0 }); } catch (err) { console.error("[/api/nodes/:id/ports/check] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); app.get("/api/nodes/:id/ports/in-use", async (req, res) => { // Pre-flight guard: the admin gate, the node lookup and the port-usage // query are DB-backed and previously had no catch beneath them — Express 4 // does not catch async-handler rejections, so any DB rejection here hung the // request. The handler had no body catch, so the whole body is wrapped: the // client gets a generic 500 and the full error stays in the server log. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "not found" }); const serverPortUsage = await getServersUsingPortsOnNode(node); const inUse = {}; for (const [port, srvList] of serverPortUsage.entries()) { inUse[port] = srvList.map(s => s.serverName); } res.json({ inUse }); } catch (err) { console.error("[/api/nodes/:id/ports/in-use] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); // adpanel:server-create-consolidation — the proxy create path's former local // twins were folded into services/server-create.js (the one true home): // - panelServerNameConflict (M4 duplicate pre-check) → the service's // duplicateServerNameOutcome (same three LOWER(name/legacy_id/bot) legs, // detection-equivalent; its M4 rationale — answer the conflict with a clean // 409 before any daemon provisioning instead of after the container exists // — lives on the shared helper). // - deleteOwnOrphanServerOnNode (adpanel:proxy-create-race MEDIUM #2b, // ownership-aware compensating delete) → the canonical // deleteOwnOrphanServerOnNodeForCreate: verified equivalent before the // fold — same SELECT, same withhold predicates (rows claiming the name on // this node via id/uuid/name or the address, compared lowercased on both // sides; rows with neither node_id nor ip withheld fail-closed), same // never-throw contract, and the delete goes through the // serverCreateDeps().deleteServerOnNode dep wrapping THIS module's // callNodeApi DELETE with its 30s budget. // - normalizeTemplateIdForCreate (mirror of index.js) → the injected real // normalizeTemplateId via setServerCreateHelpers (verified equivalent // before the fold). // M3: the main create route (index.js POST /api/servers/create) sanitizes the // name, validates mcFork/mcVersion against the strict allowlist (both are // interpolated by the daemon into the PaperMC/Purpur API URL path) and // commits a servers-index row after the daemon create. This proxy used to // forward the raw body and return the daemon response — leaving the server // absent from ACLs, invisible to getServersUsingPortsOnNode (a second create // could be granted the same port on panel records) and unmanageable. All // three gaps are closed here, with the same validations and the same // entry-shape the main route commits. async function nodeProxyCreateHandler(req, res) { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "node_not_found" }); const rawName = String(req.body?.name || "").trim(); const name = sanitizeServerToken(rawName); // adpanel:node-storage-name — the shared guard (ONE home with the panel // route) refuses the three fatal shapes in the same order: empty token // form, no node-storable form, storage form ≠ token form. The daemon keys // its filesystem on the Go sanitizeName form and the panel's baseDir // validation requires the token form, so the two must be equal (and the // storage form non-empty) or the server's Files tab breaks. The proxy // renders its own tokens — missing_name / invalid_name — where the panel // renders "invalid name"; same outcome codes, per-variant strings. const nameGuard = serverNameGuardOutcome(name); if (nameGuard) { const rendered = renderServerCreateOutcome(nameGuard, "proxy"); return res.status(rendered.status).json(rendered.body); } // adpanel:proxy-create-race (MEDIUM #2a) — cross-process per-name create // lock, shared with the main create route (index.js acquireServerCreateLock, // injected into this module next to the index writers): the pm2 ecosystem // runs several worker processes, and without it two same-name creates // landing on DIFFERENT workers both passed the duplicate check inside the // node-ports keyed lock, both provisioned on the node (the daemon's // stale-dir branch wipes and recreates a meta-less directory), and the // loser's ER_DUP_ENTRY commit backstop compensated away the WINNER's // container and directory. tryAcquire is synchronous and fail-fast, so // contention answers the route's 429 "action-in-progress" shape instead of // queueing. Acquired BEFORE the shared duplicate check (services/ // server-create.js duplicateServerNameOutcome) so the check runs inside the // lock, and held across daemon provisioning, readiness polling, index // commit and compensation; it stays OUTSIDE the // node-ports keyed lock with the same lock order as the main create route // (create lock -> node-ports), so the two paths can never deadlock against // each other. Fail-closed when index.js did not wire the acquirer (same // discipline as the missing-guarded-writer refusal below): the proxy // refuses to create at all rather than running unserialized. if (typeof _acquireServerCreateLock !== "function") { return res.status(500).json({ error: "server_create_lock_unavailable", detail: "server create lock not wired" }); } const releaseServerCreateLock = _acquireServerCreateLock(name); if (!releaseServerCreateLock) { return res.status(429).json({ error: "action-in-progress", code: "action_in_progress", message: `Server "${name}" is already being created. Please choose a different name or wait.` }); } try { return await nodeProxyCreateLocked(req, res, node, name); } finally { // adpanel:proxy-create-race — release() is idempotent and token-checked // (see acquireServerCreateLock in index.js): it only unlinks the lock // file while this holder still owns it, so a lock stolen after a // prolonged event-loop stall is left to its new owner. Runs on every // early-return and throw path of the locked continuation below. releaseServerCreateLock(); } } // The create continuation, run with the cross-process per-name create lock // already held (see nodeProxyCreateHandler above). The name guard in the // caller has validated that `name`'s sanitizeNodeStorageName form is non-empty // and equal to `name` — the shared storage-collision scan below derives that // storage form from `name` itself. async function nodeProxyCreateLocked(req, res, node, name) { // Mirrors the wrapper's rawName (kept local: it feeds only the displayName // fallback below; `name` is already the sanitized form). const rawName = String(req.body?.name || "").trim(); const templateId = String(req.body?.templateId || "minecraft"); // Injected index.js normalizeTemplateId (setServerCreateHelpers) — decides // whether the Minecraft-specific mcFork/mcVersion validation below applies. const tpl = _normalizeTemplateId(templateId); const displayName = sanitizeDisplayNameToken(req.body?.displayName || rawName) || name; // adpanel:F8 - strict allowlist validation, not sanitization; mirrors the // main create route so both create paths answer identically. const mcFork = resolveMcFork(req.body?.mcFork); const mcVersion = resolveMcVersion(req.body?.mcVersion); if (tpl === "minecraft") { if (mcFork === null) { return res.status(400).json({ error: `Invalid mcFork (supported: ${SUPPORTED_MC_FORKS.join(", ")})` }); } if (mcVersion === null) { return res.status(400).json({ error: "Invalid mcVersion (expected e.g. 1.21.8, 1.21.8-pre1, 24w14a)" }); } } const safeMcFork = mcFork === null ? resolveMcFork("") : mcFork; const safeMcVersion = mcVersion === null ? resolveMcVersion("") : mcVersion; const requestedHostPort = req.body?.hostPort; const hostPort = requestedHostPort == null || String(requestedHostPort).trim() === "" ? 25565 : validatePortInput(requestedHostPort); const autoStart = !!req.body?.autoStart; if (!hostPort) return res.status(400).json({ error: "invalid_host_port" }); // adpanel:multidisk - resolve and verify the requested target disk belongs to // this node before forwarding. Empty/"primary" => default primary disk. let diskId = String(req.body?.diskId || "").trim(); if (diskId && diskId !== "primary") { const diskRes = await callNodeApi(node, "/v1/disks", "GET", null, 8000); const disks = (diskRes.status === 200 && diskRes.json?.ok && Array.isArray(diskRes.json.disks)) ? diskRes.json.disks : []; if (!disks.some((d) => String(d.id) === diskId)) { return res.status(400).json({ error: "invalid_disk", detail: "Target disk does not belong to this node." }); } } else { diskId = ""; } // Same per-node serialization as the port-update PATCH and the index.js // POST /api/servers path: allocation check, daemon port check and create // commit run atomically against port removals. const createOutcome = await withKeyedLock(`node-ports:${node.id}`, async () => { // Re-read under the lock: a concurrent port update may have re-pointed the // allocation while this request was queued behind it. const freshNode = await findNodeByIdOrName(node.id); if (!freshNode) return { ok: false, status: 404, body: { error: "node_not_found" } }; // M4: refuse a duplicate server name before the daemon call — the shared // check (services/server-create.js duplicateServerNameOutcome, ONE home // with the panel route's findServer pre-check): same name/legacy_id/bot // case-insensitive match, so technical-name collisions are refused too, // and the conflict is answered with a clean 409 before any daemon // provisioning instead of surfacing as ER_DUP_ENTRY after the container // already exists. Not timeout-wrapped on this path (never has been): a // slow DB rejects into the route wrapper's 500 node_create_failed. const duplicateOutcome = await duplicateServerNameOutcome(serverCreateDeps(), name); if (duplicateOutcome) { // Proxy contract: the plain 409 — the renderer drops // duplicateServerNameOutcome's panel-only "(on node X)" suffix. const rendered = renderServerCreateOutcome(duplicateOutcome, "proxy"); return { ok: false, status: rendered.status, body: rendered.body }; } // adpanel:node-storage-collision (MEDIUM #2c) — same-node // storage-collision scan through the shared scanNodeStorageCollisions // (ONE home with the panel route; full rationale on the helper). The // proxy's node identity is 4-way — node id/uuid/name OR the node address, // the same identity test as the port checks below — where the panel scans // 3-way without the ip leg; uuidFallbackId keeps this path's historical // `uuid || id` fallback. The caller's name guard validated that // sanitizeNodeStorageName(name) is non-empty and equal to `name`, so the // helper's internal sanitizeNodeStorageName(name) is that exact form and // its requestedStorageName guard is vacuous here (as the former inline // scan's comment noted). const collisionOutcome = await scanNodeStorageCollisions(serverCreateDeps(), freshNode, name, { includeIpLeg: true, uuidFallbackId: true }); if (collisionOutcome) { const rendered = renderServerCreateOutcome(collisionOutcome, "proxy"); return { ok: false, status: rendered.status, body: rendered.body }; } if (hostPort > 0 && !isPortInNodeAllocation(freshNode, hostPort)) { const alloc = freshNode.ports || {}; let allocDesc = "none"; if (alloc.mode === "range") allocDesc = `range ${alloc.start}\u2013${alloc.start + alloc.count - 1}`; else if (alloc.mode === "list" && Array.isArray(alloc.ports)) allocDesc = `list [${alloc.ports.slice(0, 10).join(", ")}${alloc.ports.length > 10 ? "\u2026" : ""}]`; return { ok: false, status: 400, body: { error: `Port ${hostPort} is not in this node's allocated ports (${allocDesc}).` } }; } const bind = resolveServerCreateBindAddress(freshNode, hostPort, { preserveLegacyRangeBind: true }); if (bind.error) { const rendered = renderServerCreateOutcome(bind.error, "proxy"); return { ok: false, status: rendered.status, body: rendered.body }; } const nodeBindIP = bind.address; if (hostPort > 0) { // Panel-side ownership checks, matching the main create path in index.js // (findServerUsingNodePort): the daemon's live bind test alone can be // won by a server row another create commits concurrently. const serverPortUsage = await getServersUsingPortsOnNode(freshNode); const portUsers = serverPortUsage.get(hostPort) || []; const activeUser = portUsers.find(u => u.status !== "deleting"); if (activeUser) { return { ok: false, status: 409, body: { error: `Port ${hostPort} is already assigned to server "${activeUser.serverName}" on this node.`, code: "port_in_use" } }; } // adpanel:port-teardown - keep every host binding reserved until the row is gone. const pendingTeardown = portUsers.find(u => u.status === "deleting"); if (pendingTeardown) { return { ok: false, status: 409, body: { error: `Port ${hostPort} is being released by server "${pendingTeardown.name}" on this node; retry in a moment.`, code: "port_in_use" } }; } const portCheck = await callNodeApi(freshNode, `/v1/ports/check?port=${encodeURIComponent(String(hostPort))}`, "GET", null, 10_000); if (portCheck.status === 200 && portCheck.json?.ok && portCheck.json.available === false) { const owner = portCheck.json.owner ? ` by ${portCheck.json.owner}` : ""; return { ok: false, status: 409, body: { error: `Port ${hostPort} is already in use on this node${owner}.`, code: "port_in_use" } }; } } // Mirror the main create flow (index.js POST /api/servers/create) and send // asyncSetup: true: the daemon then answers right after its synchronous // prepare phase (preflight + docker image pulls in // prepareMinecraftCreateSetup/prepareCustomCreateSetup — cache hits once // the node holds the image) and runs the jar download (30-minute context), // archive import and container start in the background. Without it all of // that precedes the first response byte and LONG_NODE_TIMEOUT_MS (120s) // could never carry it — the daemon completed the create while this relay // reported a failure and a retry collided with it. 120s stays ample for the // respond point (a cold first pull is bounded by the daemon's own 120s // server WriteTimeout, and the recoverable-status poll below covers a // response the daemon dropped); the handling below already parses // json.asyncSetup, so the committed row and forwarded response carry the // main flow's async shape. const created = await callNodeApi( freshNode, "/v1/servers/create", "POST", { name, templateId, mcFork: safeMcFork, mcVersion: safeMcVersion, hostPort, autoStart, asyncSetup: true, bind_ip: nodeBindIP || undefined, host_ip: nodeBindIP || undefined, // adpanel:backup-cap-daemon-enforced — the panel-side count-then-create // checks (this relay's 409, the scheduler's skip) are a TOCTOU // fast-fail; the daemon's backupsMax (checked under the per-server op // lock over an untruncated ReadDir of ALL backup subdirs) is the // authoritative bound, so every creator transmits the panel cap here // (MAX_BACKUPS_PER_SERVER — the same constant this relay refuses at) // and both layers agree. The daemon treats a MISSING or non-positive // backupsMax as "no cap" (`if backupsMax > 0`), so the transmitted // value is always the resolved positive integer. resources: { backupsMax: MAX_BACKUPS_PER_SERVER }, ...(diskId ? { diskId } : {}), }, LONG_NODE_TIMEOUT_MS ); const { status, json } = created; const daemonOk = status === 200 && json && json.ok; if (!daemonOk && !isRecoverableNodeCreateStatus(status)) { return { ok: false, status: 500, body: { error: "node_create_failed", status, detail: json && json.error } }; } let recovered = false; if (!daemonOk) { recovered = await waitForNodeServerReady(freshNode, name, { timeoutMs: nodeUnderCloudflare(freshNode) ? 180_000 : 30_000, intervalMs: 3000, }); if (!recovered) { return { ok: false, status: 500, body: { error: "node_create_failed", status, detail: json && json.error } }; } } // M3: commit the panel index row while still inside the node-ports lock — // the same discipline as the main create route — so concurrent port // allocation checks see the new owner immediately. const setupStatusRaw = json && json.meta ? String(json.meta.setupStatus || "").trim() : ""; const setupStatusLower = setupStatusRaw.toLowerCase(); const serverEntry = { name, displayName, template: templateId, mcFork: tpl === "minecraft" ? safeMcFork : undefined, mcVersion: tpl === "minecraft" ? safeMcVersion : undefined, start: tpl === "minecraft" ? "server.jar" : (tpl === "nodejs" || tpl === "discord-bot" ? "index.js" : (tpl === "python" ? "main.py" : null)), nodeId: freshNode.uuid || freshNode.id || freshNode.name, ip: nodeBindIP || freshNode.address || null, bind_ip: nodeBindIP || undefined, host_ip: nodeBindIP || undefined, port: hostPort, status: json && json.asyncSetup ? (setupStatusLower === "failed" ? "error" : "installing") : undefined, setupStatus: setupStatusRaw || undefined, setupMessage: (json && json.meta && json.meta.setupMessage) || undefined, // adpanel:backup-cap-daemon-enforced — the committed entry mirrors the // resources this create transmitted to the daemon (the payload above), // exactly like the panel route's entry (services/server-create.js) and // the assistant tool's entry: the settings resources editor prefills // from the entry and the transfer flows re-apply entry.resources, so // the panel index and the daemon meta must agree on the cap. resources: { backupsMax: MAX_BACKUPS_PER_SERVER }, }; // M3/M4: commit the panel index row while still inside the node-ports // lock — the same discipline as the main create route — through the ONE // shared guarded-commit choreography (services/server-create.js // commitCreatedServer): insert-only commit (never upserts) through the // guarded writer, which re-checks the template under the same // "templates-write" key the template DELETE route holds, so a template // deleted while the daemon create was in flight fails here instead of // committing a row that points at a deleted custom template; and on // EVERY failure the just-created daemon server is best-effort removed // through the ownership-guarded compensating delete // (adpanel:proxy-create-race — a committed row claiming this name on // this node belongs to another writer's live create and must never be // deleted by name alone; ER_DUP_ENTRY maps to the plain 409). Proxy // wiring: a missing guarded writer fails closed with detail "server // index writer not wired" after the ownership-guarded compensating // delete, and non-dup commit failures render as index_commit_failed // (the panel variant rethrows into its route's 500 "create failed" // catch instead). This module's compensation log strings (console.error) // ride along in PROXY_COMMIT_LOG. const commitOutcome = await commitCreatedServer(serverCreateDeps(), { entry: serverEntry, name, node: freshNode, templateName: templateId, notWiredDetail: "server index writer not wired", rethrowNonDup: false, log: PROXY_COMMIT_LOG, }); if (commitOutcome) { const rendered = renderServerCreateOutcome(commitOutcome, "proxy"); return { ok: false, status: rendered.status, body: rendered.body }; } return { ok: true, json: daemonOk ? json : { ok: true, name, recovered: true }, serverName: name, serverEntry, savedPort: hostPort, freshNode, }; }); if (!createOutcome.ok) return res.status(createOutcome.status).json(createOutcome.body); try { const { serverName, serverEntry, savedPort, freshNode } = createOutcome; recordActivity(serverName, "server_create", { template: serverEntry.template, node: freshNode.name || freshNode.uuid || freshNode.id, port: savedPort || "auto", displayName: serverEntry.displayName && serverEntry.displayName !== serverName ? serverEntry.displayName : undefined }, req.session?.user, getRequestIp(req)); recordActivity("_system", "server_create", { server: serverName, template: serverEntry.template, node: freshNode.name || freshNode.uuid || freshNode.id, port: savedPort || "auto" }, req.session?.user, getRequestIp(req)); } catch (actErr) { console.warn("[node-proxy-create] Failed to record activity:", actErr?.message || actErr); } return res.json(createOutcome.json); } // Express 4 does not catch async handler throws and there is no // unhandledRejection handler — an escaping rejection here (e.g. a transient // MySQL failure inside the keyed lock) would kill the worker for every user. // Same wrapper discipline as POST /api/nodes above. app.post("/api/nodes/:id/servers/create", async (req, res) => { try { return await nodeProxyCreateHandler(req, res); } catch (err) { console.error("[nodes] POST /api/nodes/:id/servers/create failed:", (err && (err.code || err.message)) || err); if (!res.headersSent) { // adpanel:relay-error-mask — generic detail; raw error stays in the log above. return res.status(500).json({ error: "node_create_failed", detail: "internal error" }); } } }); // Wizard/API "disks" entries for node create/update. The daemon is usually // installed after registration, so requests are validated here, stored on the // node as buildConfig.requestedDisks, and provisioned by the panel-side // applier in index.js once the daemon is reachable. Undefined means "not // provided" (leave any stored pending list untouched); an empty array clears it. const MAX_NODE_REQUESTED_DISKS = 16; function parseNodeDisksRequest(rawDisks) { if (typeof rawDisks === "undefined") return { ok: true, disks: undefined }; if (!Array.isArray(rawDisks)) return { ok: false, error: "disks must be an array of { mount, limit }." }; if (rawDisks.length > MAX_NODE_REQUESTED_DISKS) { return { ok: false, error: `At most ${MAX_NODE_REQUESTED_DISKS} disks can be requested per node.` }; } const out = []; const seenMounts = new Set(); for (const entry of rawDisks) { const mountCheck = validateDiskMountPathPanel(entry?.mount ?? entry?.mountPath); if (!mountCheck.ok) return { ok: false, error: mountCheck.error }; const limitGb = Number(entry?.limit ?? entry?.limitGb); if (!Number.isFinite(limitGb) || limitGb <= 0 || !Number.isInteger(limitGb)) { return { ok: false, error: `Disk limit for ${mountCheck.value} must be a positive whole number of GB.` }; } if (seenMounts.has(mountCheck.value)) continue; seenMounts.add(mountCheck.value); out.push({ mount: mountCheck.value, limitGb }); } return { ok: true, disks: out }; } // nodes.ram_mb / nodes.disk_gb are signed INT columns (mysql-schema.sql). A // value beyond 2147483647 makes MySQL reject the write as out-of-range — and // because Express 4 does not catch async handler throws and the process has // no unhandledRejection handler, that rejection would crash the worker for // every user. The cap is the column limit, not a product opinion, so genuine // high-capacity hosts keep working; the create/edit wizard mirrors it with // max= attributes (2097151 GB = the same limit after the GB→MB x1024). const MAX_NODE_RAM_MB = 2147483647; const MAX_NODE_DISK_GB = 2147483647; async function createNodeHandler(req, res) { if (!(await requireNodeAdmin(req, res))) return; const body = req.body || {}; const name = sanitizeNodeStorageName(body.name || body.node || body.id); const address = String(body.address || body.ip || body.fqdn || "").trim(); if (!name) return res.status(400).json({ error: "invalid name" }); if (!address) return res.status(400).json({ error: "invalid address" }); const nameKey = name.toLowerCase(); // Identifier collision guard: sanitizeNodeStorageName passes id/uuid-shaped // names through untouched, and findNodeByIdOrName() resolves a node by name AS // WELL AS by id and uuid — so a name equal to an existing node's id or // uuid would let this node hijack that identifier at resolution time. // Reject all three collision kinds, not just name-vs-name. (Databases // created before this guard may already hold such rows; the resolver // orders them deterministically.) const exists = await db.query( "SELECT id FROM nodes WHERE LOWER(name) = ? OR LOWER(id) = ? OR LOWER(uuid) = ? LIMIT 1", [nameKey, nameKey, nameKey] ); if (exists.length) { return res.status(400).json({ error: "node already exists" }); } const cpu_cores = toInt(body.cpu_cores, 0); const ram_mb = (typeof body.ram_mb !== "undefined") ? toInt(body.ram_mb, 0) : (typeof body.ramMB !== "undefined") ? toInt(body.ramMB, 0) : (typeof body.ram_gb !== "undefined") ? toInt(body.ram_gb, 0) * 1024 : 0; const disk_gb = (typeof body.disk_gb !== "undefined") ? toInt(body.disk_gb, 0) : (typeof body.storage_gb !== "undefined") ? toInt(body.storage_gb, 0) : (typeof body.storageGB !== "undefined") ? toInt(body.storageGB, 0) : 0; // Audit fix: a stored capacity of 0 is rendered as an empty field by the UI // and disables every panel-enforced ceiling for servers created later, so // capacities below the UI minimums are rejected outright instead. if (!Number.isInteger(cpu_cores) || cpu_cores < 1) { return res.status(400).json({ error: "cpu_cores must be a whole number of at least 1." }); } if (!Number.isInteger(ram_mb) || ram_mb < 1024) { return res.status(400).json({ error: "ram_mb must be a whole number of at least 1024 (1 GB)." }); } if (ram_mb > MAX_NODE_RAM_MB) return res.status(400).json({ error: "ram_mb must not exceed 2147483647." }); if (!Number.isInteger(disk_gb) || disk_gb < 10) { return res.status(400).json({ error: "disk_gb must be a whole number of at least 10." }); } if (disk_gb > MAX_NODE_DISK_GB) return res.status(400).json({ error: "disk_gb must not exceed 2147483647." }); const disksRequest = parseNodeDisksRequest(body.disks); if (!disksRequest.ok) return res.status(400).json({ error: disksRequest.error }); const rawAdditionalIps = Array.isArray(body.additional_ips) ? body.additional_ips : (Array.isArray(body.ips) ? body.ips : []); const additional_ips = Array.from(new Set(rawAdditionalIps.map(ip => String(ip || "").trim()).filter(ip => ip && ip !== address))); const rawPorts = body.ports ?? body.ports_list ?? body.port_list; if (typeof rawPorts !== "undefined") { const portCheck = validateNodePortsInput(rawPorts); if (!portCheck.ok) return res.status(400).json({ error: portCheck.error }); } const ports = normalizePorts(rawPorts, address); const ambiguousPort = ambiguousPortAllocation(ports); if (ambiguousPort) return res.status(400).json({ error: ambiguousPort }); const api_port = clampPort(body.api_port || 8080); const sftp_port = clampPort(body.sftp_port || 2022); const max_upload_mb = Math.max(1, Math.min(100000, toInt(body.max_upload_mb, 10240))); const ssl_enabled = truthyFlag(body.ssl_enabled); const under_cloudflare = !!(ssl_enabled && truthyFlag(body.under_cloudflare)); if (under_cloudflare && !isCloudflareHttpsPort(api_port)) { return res.status(400).json({ error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." }); } // The Cloudflare branch skips validateNodeAddressInput() (the SSRF private- // range filter does not apply to names that resolve only to Cloudflare's // public edges), so it would otherwise never bound the stored string: a // multi-hundred-kilobyte address passes the proxy check and overflows the // address VARCHAR(255) column at INSERT. Bound it before any DNS work. if (address.length > nodeSsrfGuard.MAX_ADDRESS_LENGTH) { return res.status(400).json({ error: `Node address exceeds ${nodeSsrfGuard.MAX_ADDRESS_LENGTH} characters.` }); } if (under_cloudflare) { const cloudflareCheck = await verifyCloudflareProxiedAddress(address, getNodeAllocations({ address, ports })); if (!cloudflareCheck.ok) { return res.status(400).json({ error: cloudflareCheck.error, detail: cloudflareCheck.detail || undefined, }); } } else { // SSRF guard (finding 3.3): the panel dials this address for every // health check and API call, so loopback/link-local/private/metadata // targets are rejected unless ADPANEL_ALLOW_PRIVATE_NODES=1. Cloudflare- // proxied nodes are exempt: verifyCloudflareProxiedAddress() above // already proves the name resolves only to Cloudflare's public edges. const addressCheck = await nodeSsrfGuard.validateNodeAddressInput(address); if (!addressCheck.ok) return res.status(400).json({ error: addressCheck.error }); } // Additional IPs are bind/bookkeeping metadata (never dialed by the // panel), so they get a syntax check rather than the full SSRF filter. const additionalIpsCheck = nodeSsrfGuard.validateNodeAddressListInput(additional_ips); if (!additionalIpsCheck.ok) return res.status(400).json({ error: additionalIpsCheck.error }); let node; try { node = await insertNode({ id: uid(), uuid: undefined, name, address, ram_mb, disk_gb, ports, token_id: randTokenId(), token: randSecret(), createdAt: Date.now(), api_port, sftp_port, max_upload_mb, port_ok: null, last_seen: null, last_check: null, buildConfig: { cpu_cores, ssl_enabled, under_cloudflare, ips: additional_ips, ...(disksRequest.disks && disksRequest.disks.length ? { requestedDisks: disksRequest.disks } : {}) } }); } catch (err) { // A UNIQUE index on nodes.name backs the pre-check above: if another // create commits the same name between the SELECT and this INSERT, the // duplicate key surfaces here — answer gracefully instead of a 500. if (err && err.code === "ER_DUP_ENTRY") { return res.status(409).json({ error: "node already exists" }); } throw err; } try { recordActivity("_system", "node.create", { node: node.name, nodeId: node.id, address: node.address }, req.session?.user, getRequestIp(req)); } catch (actErr) { console.warn("[nodes] Failed to record node.create activity:", actErr?.message || actErr); } res.json(toPublic(node)); } app.post("/api/nodes", async (req, res) => { try { return await createNodeHandler(req, res); } catch (err) { // Express 4 does not catch async throws and there is no // unhandledRejection handler: an escaping rejection here would kill the // worker for every user. Answer 500 instead; the ER_DUP_ENTRY -> 409 // mapping inside the handler is unaffected (it returns, never throws). console.error("[nodes] POST /api/nodes failed:", (err && (err.code || err.message)) || err); if (!res.headersSent) return res.status(500).json({ error: "node_create_failed" }); } }); async function updateNodeHandler(req, res) { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeForMutation(req); if (!node) return res.status(404).json({ error: "not found" }); const body = req.body || {}; const upd = sanitizeUpdatePayload(body); // Port-allocation updates race with concurrent server creation: the // removed-port in-use check and the final save are serialized per node // against the creation paths (index.js POST /api/servers and the // /api/nodes/:id/servers/create proxy), which take the same lock around // their allocation check + create, so a server can never claim a port this // request is removing (or the removal commit a claim) between check and // commit. ALL mutation work runs inside that lock: saveNode persists the // FULL row, so applying it to the snapshot taken before the lock would let // a concurrent token rotation (token/token_id/token_status) or heartbeat // (last_seen/last_check/online/port_ok) that committed while this request // was queued be reverted with seconds-stale values. const outcome = await withKeyedLock(`node-ports:${node.id}`, async () => { // Fresh re-read under the lock (same pattern as the build route below). const fresh = await findNodeByIdOrName(node.id); if (!fresh || fresh.id !== node.id) return { ok: false, status: 404, body: { error: "not found" } }; // adpanel:node-step-up-state - a grace-verified save must still leave the locked connection unchanged. if (req.nodeMutationUsedGrace && nodeConnectionState(fresh, body) !== nodeConnectionState(fresh)) { return { ok: false, status: 409, body: { error: "Node connection settings changed. Reopen this node and verify again." } }; } const current = hardenNode({ ...fresh, buildConfig: { ...fresh.buildConfig } }); const portsRevision = req.body?.ports_revision; if (typeof upd.ports !== "undefined" && typeof portsRevision !== "undefined" && portsRevision !== nodePortsRevision(current)) { return { ok: false, status: 409, body: { error: "Port allocations changed. Reopen this node and retry." } }; } const oldAddress = String(current.address || "").trim(); const addressProvided = typeof upd.address !== "undefined"; const newAddress = addressProvided ? String(upd.address || "").trim() : oldAddress; const addressChanged = addressProvided && newAddress !== oldAddress; if (addressProvided) current.address = newAddress; if (typeof upd.additional_ips !== "undefined") { current.buildConfig = current.buildConfig || {}; current.buildConfig.ips = Array.from(new Set(upd.additional_ips.filter(ip => ip && ip !== current.address))); current.additional_ips = current.buildConfig.ips; current.ips = [current.address, ...current.additional_ips]; // Syntax check only — bind/bookkeeping metadata, not a panel-dialed target. const additionalIpsCheck = nodeSsrfGuard.validateNodeAddressListInput(current.additional_ips); if (!additionalIpsCheck.ok) return { ok: false, status: 400, body: { error: additionalIpsCheck.error } }; } if (typeof upd.name !== "undefined" && upd.name) { // Rename collision guard (backed by the DB's UNIQUE index on // nodes.name): reject the rename instead of silently merging two nodes // into one findNodeByIdOrName() target. That resolver also matches id // and uuid, so the new name must not collide with ANOTHER node's id or // uuid either — otherwise the renamed node could hijack that node's // identifier at resolution time. const newKey = upd.name.toLowerCase(); const nameConflict = await db.query( "SELECT id FROM nodes WHERE (LOWER(name) = ? OR LOWER(id) = ? OR LOWER(uuid) = ?) AND id <> ? LIMIT 1", [newKey, newKey, newKey, current.id] ); if (nameConflict.length) { return { ok: false, status: 409, body: { error: "node name already in use" } }; } current.name = upd.name; } if (typeof upd.cpu_cores !== "undefined") { if (!Number.isInteger(upd.cpu_cores) || upd.cpu_cores < 1) { return { ok: false, status: 400, body: { error: "cpu_cores must be a whole number of at least 1." } }; } current.buildConfig = current.buildConfig || {}; current.buildConfig.cpu_cores = upd.cpu_cores; } if (typeof upd.ssl_enabled !== "undefined") { current.buildConfig = current.buildConfig || {}; current.buildConfig.ssl_enabled = !!upd.ssl_enabled; if (!current.buildConfig.ssl_enabled) current.buildConfig.under_cloudflare = false; } if (typeof upd.under_cloudflare !== "undefined") { current.buildConfig = current.buildConfig || {}; current.buildConfig.under_cloudflare = !!(upd.under_cloudflare && current.buildConfig.ssl_enabled); } if (typeof upd.ram_mb !== "undefined") { if (!Number.isInteger(upd.ram_mb) || upd.ram_mb < 1024) { return { ok: false, status: 400, body: { error: "ram_mb must be a whole number of at least 1024 (1 GB)." } }; } if (upd.ram_mb > MAX_NODE_RAM_MB) { return { ok: false, status: 400, body: { error: "ram_mb must not exceed 2147483647." } }; } current.ram_mb = upd.ram_mb; } if (typeof upd.disk_gb !== "undefined") { if (!Number.isInteger(upd.disk_gb) || upd.disk_gb < 10) { return { ok: false, status: 400, body: { error: "disk_gb must be a whole number of at least 10." } }; } if (upd.disk_gb > MAX_NODE_DISK_GB) { return { ok: false, status: 400, body: { error: "disk_gb must not exceed 2147483647." } }; } current.disk_gb = upd.disk_gb; } const disksRequest = parseNodeDisksRequest(req.body?.disks); if (!disksRequest.ok) { return { ok: false, status: 400, body: { error: disksRequest.error } }; } if (disksRequest.disks) { current.buildConfig = current.buildConfig || {}; if (disksRequest.disks.length) current.buildConfig.requestedDisks = disksRequest.disks; else delete current.buildConfig.requestedDisks; } const underCloudflare = !!(current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare); let serverPortUsage; if (addressChanged && !underCloudflare && typeof upd.ports === "undefined" && current.ports) { const serverPortUsage = await getServersUsingPortsOnNode(fresh); const existingAllocations = getNodeAllocations(fresh); if (existingAllocations.length > 0) { current.ports.allocations = existingAllocations.map(allocation => (!allocation.ip || allocation.ip === oldAddress) && !serverPortUsage.has(allocation.port) ? { ...allocation, ip: newAddress } : allocation ); } } if (typeof upd.ports !== "undefined") { const rawPorts = upd.ports; const portCheck = validateNodePortsInput(rawPorts); if (!portCheck.ok) return { ok: false, status: 400, body: { error: portCheck.error } }; const nextPorts = normalizePorts(rawPorts, current.address); const ambiguousPort = ambiguousPortAllocation(nextPorts, getNodeAllocations(fresh)); if (ambiguousPort) return { ok: false, status: 400, body: { error: ambiguousPort } }; const oldAllocations = getNodeAllocatedPortsList(current); const newAllocations = getNodeAllocatedPortsList({ ports: nextPorts }); const newPortSet = new Set(newAllocations); serverPortUsage = await getServersUsingPortsOnNode(fresh); const removedPorts = oldAllocations.filter(p => !newPortSet.has(p)); if (removedPorts.length > 0) { const conflicts = []; for (const p of removedPorts) { if (serverPortUsage.has(p)) { const srvList = serverPortUsage.get(p); const srvNames = srvList.map(s => `"${s.serverName}"`).join(", "); conflicts.push(`Port ${p} (in use by ${srvNames})`); } } if (conflicts.length > 0) { return { ok: false, status: 409, body: { error: `Cannot delete port(s) from node: ${conflicts.join("; ")}. This port is currently used by a server on ADPanel.` } }; } } if (Array.isArray(nextPorts.allocations)) { nextPorts.allocations = nextPorts.allocations.map(a => { const p = Number(a.port); if (serverPortUsage.has(p)) { const srvList = serverPortUsage.get(p); const occupiedIp = (srvList[0] && srvList[0].ip) ? srvList[0].ip : (a.ip || current.address); return { ip: occupiedIp, port: p }; } return { ip: a.ip || current.address, port: p }; }); } current.ports = nextPorts; } if (typeof upd.api_port !== "undefined") current.api_port = clampPort(upd.api_port); if (typeof upd.sftp_port !== "undefined") current.sftp_port = clampPort(upd.sftp_port); if (typeof upd.max_upload_mb !== "undefined") current.max_upload_mb = upd.max_upload_mb; if (addressChanged) { // The Cloudflare branch below skips validateNodeAddressInput, so bound the stored-form length here. if (newAddress.length > nodeSsrfGuard.MAX_ADDRESS_LENGTH) { return { ok: false, status: 400, body: { error: `Node address exceeds ${nodeSsrfGuard.MAX_ADDRESS_LENGTH} characters.` } }; } // SSRF guard (finding 3.3) on every address change. Under Cloudflare the // verifyCloudflareProxiedAddress() check below is the stronger gate // (name must resolve only to Cloudflare's public edges), so the private- // range filter would be redundant there. if (!underCloudflare) { const addressCheck = await nodeSsrfGuard.validateNodeAddressInput(newAddress); if (!addressCheck.ok) return { ok: false, status: 400, body: { error: addressCheck.error } }; } } if (underCloudflare && !isCloudflareHttpsPort(current.api_port)) { return { ok: false, status: 400, body: { error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." } }; } if (underCloudflare) { const cloudflareCheck = await verifyCloudflareProxiedAddress(current.address, getNodeAllocations(current), fresh, serverPortUsage); if (!cloudflareCheck.ok) { return { ok: false, status: 400, body: { error: cloudflareCheck.error, detail: cloudflareCheck.detail || undefined } }; } } if (addressChanged || current.name !== fresh.name) { const previousAssignment = nodeServerAssignmentParams(fresh); const nextAssignment = nodeServerAssignmentParams(current); const [nodeId, nodeUuid, previousName] = previousAssignment; const [, , nextName] = nextAssignment; const detached = await db.query( `SELECT 1 FROM servers WHERE (${NODE_SERVER_ASSIGNMENT_WHERE}) AND ((${NODE_SERVER_ASSIGNMENT_WHERE}) IS NOT TRUE OR (LOWER(servers.node_id) = ? AND LOWER(servers.node_id) <> ? AND servers.node_id NOT IN (?, ?))) LIMIT 1`, [...previousAssignment, ...nextAssignment, previousName, nextName, nodeId, nodeUuid] ); if (detached.length) { return { ok: false, status: 409, body: { error: "Cannot change the node name or address while servers are assigned by the previous name or address. Update those server assignments first." } }; } } current.last_check = null; let saved; try { saved = await saveNode(current, nodeConnectionState(fresh)); } catch (err) { // The uniq_nodes_name index is the DB backstop for the in-lock rename // pre-check: a create that committed the same name between check and // save lands here as ER_DUP_ENTRY. Answer 409 instead of letting the // rejection escape the handler (Express 4 does not catch async throws). if (err && err.code === "ER_DUP_ENTRY") { return { ok: false, status: 409, body: { error: "node name already in use" } }; } throw err; } return { ok: true, saved }; }); if (!outcome.ok) return res.status(outcome.status).json(outcome.body); res.json(toPublic(outcome.saved)); } app.patch("/api/nodes/:id", async (req, res) => { try { return await updateNodeHandler(req, res); } catch (err) { // Same Express-4 async-throw containment rationale as POST /api/nodes above. console.error("[nodes] PATCH /api/nodes/:id failed:", (err && (err.code || err.message)) || err); if (!res.headersSent) return res.status(500).json({ error: "node_update_failed" }); } }); app.delete("/api/nodes/:id", async (req, res) => { // Express 4 does not forward async handler rejections, so the whole handler // body is contained here (same rationale as POST/PATCH above) — a DB or // lock failure must answer 500, not crash the process. The admin self-check // sits inside the try for the same containment: requireNodeAdmin never // throws, but if its 403-send ever did, the wrapper answers 500 behind its // headersSent guard instead of escaping the async handler uncaught. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeForMutation(req); if (!node) return res.status(404).json({ error: "not found" }); // The COUNT guard and the delete run under the same per-node lock the // server-create paths (index.js POST /api/servers and the // /api/nodes/:id/servers/create proxy) hold around their allocation check + // create commit — otherwise a create queued between the COUNT and the // delete could commit a row onto a node that has just vanished. const outcome = await withKeyedLock(`node-ports:${node.id}`, async () => { // Re-resolve under the lock: the node may already be gone while this // request was queued behind another node operation. const fresh = await findNodeByIdOrName(node.id); if (!fresh || fresh.id !== node.id) return { ok: false, status: 404, body: { error: "not found" } }; const assignedServers = await db.query( `SELECT COUNT(*) AS cnt FROM servers WHERE ${NODE_SERVER_ASSIGNMENT_WHERE}`, nodeServerAssignmentParams(fresh) ); const serverCount = Number(assignedServers[0]?.cnt || 0); if (serverCount > 0) { return { ok: false, status: 409, body: { error: `Cannot delete node — ${serverCount} server${serverCount === 1 ? " is" : "s are"} still assigned to it. Reassign or delete them first.` } }; } await deleteNode(fresh.id); return { ok: true, deleted: fresh.id, name: fresh.name }; }); if (!outcome.ok) return res.status(outcome.status).json(outcome.body); try { recordActivity("_system", "node.delete", { node: outcome.name, nodeId: outcome.deleted }, req.session?.user, getRequestIp(req)); } catch (actErr) { console.warn("[nodes] Failed to record node.delete activity:", actErr?.message || actErr); } res.json({ ok: true, deleted: outcome.deleted }); } catch (err) { console.error("[nodes] DELETE /api/nodes/:id failed:", (err && (err.code || err.message)) || err); if (!res.headersSent) return res.status(500).json({ error: "node_delete_failed" }); } }); app.get("/api/nodes/:id/build", async (req, res) => { // Pre-flight guard: the admin gate and the node lookup are DB-backed and // previously had no catch beneath them — Express 4 does not catch // async-handler rejections, so any DB rejection here hung the request. The // handler had no body catch, so the whole body is wrapped: the client gets a // generic 500 and the full error stays in the server log. try { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "not found" }); res.json({ build: node.buildConfig || {} }); } catch (err) { console.error("[/api/nodes/:id/build] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); async function updateNodeBuildHandler(req, res) { if (!(await requireNodeAdmin(req, res))) return; const node = await findNodeForMutation(req); if (!node) return res.status(404).json({ error: "not found" }); const incoming = (req.body && typeof req.body === "object") ? req.body : {}; const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); if (hasOwn(incoming, "cpu_cores")) { const n = Number(incoming.cpu_cores); if (!Number.isInteger(n) || n < 1) { return res.status(400).json({ error: "cpu_cores must be a whole number of at least 1." }); } } if (hasOwn(incoming, "ram_mb")) { const n = Number(incoming.ram_mb); if (!Number.isInteger(n) || n < 1024) { return res.status(400).json({ error: "ram_mb must be a whole number of at least 1024 (1 GB)." }); } if (n > MAX_NODE_RAM_MB) { return res.status(400).json({ error: "ram_mb must not exceed 2147483647." }); } } if (hasOwn(incoming, "disk_gb")) { const n = Number(incoming.disk_gb); if (!Number.isInteger(n) || n < 10) { return res.status(400).json({ error: "disk_gb must be a whole number of at least 10." }); } if (n > MAX_NODE_DISK_GB) { return res.status(400).json({ error: "disk_gb must not exceed 2147483647." }); } } // Step-up for this trust-config write is enforced by the guard registered // in index.js ahead of this router's mount (same gate class as PATCH). // The merge below is a strict allowlist — arbitrary body keys must never // reach build_config, and the merge runs on a FRESH re-read under the node // lock so a concurrent token rotation that committed while this request was // in flight is never overwritten with this request's stale snapshot. const outcome = await withKeyedLock(`node-ports:${node.id}`, async () => { const fresh = await findNodeByIdOrName(node.id); if (!fresh || fresh.id !== node.id) return { ok: false, status: 404, body: { error: "not found" } }; if (req.nodeMutationUsedGrace && nodeConnectionState(fresh, incoming, true) !== nodeConnectionState(fresh)) { return { ok: false, status: 409, body: { error: "Node connection settings changed. Reopen this node and verify again." } }; } const previousConnectionState = nodeConnectionState(fresh); const current = hardenNode(fresh); const nextBuild = Object.assign({}, current.buildConfig || {}); if (hasOwn(incoming, "cpu_cores")) nextBuild.cpu_cores = Number(incoming.cpu_cores); if (hasOwn(incoming, "ram_mb")) nextBuild.ram_mb = Number(incoming.ram_mb); if (hasOwn(incoming, "disk_gb")) nextBuild.disk_gb = Number(incoming.disk_gb); if (hasOwn(incoming, "ssl_enabled")) { nextBuild.ssl_enabled = truthyFlag(incoming.ssl_enabled); if (!nextBuild.ssl_enabled) nextBuild.under_cloudflare = false; } if (hasOwn(incoming, "under_cloudflare") || hasOwn(incoming, "cloudflare_proxy")) { nextBuild.under_cloudflare = !!(nextBuild.ssl_enabled && truthyFlag(incoming.under_cloudflare ?? incoming.cloudflare_proxy)); } if (hasOwn(incoming, "api_host")) { const apiHost = String(incoming.api_host || "").trim(); // Same shape resolveNodeApiBindHost() enforces at read time — reject at // write time instead of silently ignoring. if (apiHost && !/^[A-Za-z0-9._:-]{1,64}$/.test(apiHost)) { return { ok: false, status: 400, body: { error: "api_host must be a bare host token (letters, digits, dot, underscore, colon, hyphen; max 64 chars)." } }; } if (apiHost) nextBuild.api_host = apiHost; else delete nextBuild.api_host; } // The legacy cloudflare_proxy alias is collapsed into under_cloudflare // above and must never persist as a residual key: nodeUnderCloudflare() // ORs it back in, which would keep HTTPS-dial semantics alive after an // admin turned the proxy off, bypassing both checks below. delete nextBuild.cloudflare_proxy; current.buildConfig = nextBuild; current.under_cloudflare = nodeUnderCloudflare(current); if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare && !isCloudflareHttpsPort(current.api_port)) { return { ok: false, status: 400, body: { error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." } }; } if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare) { const cloudflareCheck = await verifyCloudflareProxiedAddress(current.address, getNodeAllocations(current), fresh); if (!cloudflareCheck.ok) { return { ok: false, status: 400, body: { error: cloudflareCheck.error, detail: cloudflareCheck.detail || undefined } }; } } const saved = await saveNode(current, previousConnectionState); return { ok: true, saved }; }); if (!outcome.ok) return res.status(outcome.status).json(outcome.body); res.json({ ok: true }); } app.post("/api/nodes/:id/build", async (req, res) => { try { return await updateNodeBuildHandler(req, res); } catch (err) { // Same Express-4 async-throw containment rationale as POST /api/nodes above. console.error("[nodes] POST /api/nodes/:id/build failed:", (err && (err.code || err.message)) || err); if (!res.headersSent) return res.status(500).json({ error: "node_build_failed" }); } }); app.get("/api/nodes/:id/config.yml", requireNodeBootstrapTransport, async (req, res) => { // M2: per-IP cap counted BEFORE the node lookup so the pre-auth 401 path // cannot be flooded into a MySQL exhaustion. Always-on (not gated on the // global security.json toggle) for the same reason as the heartbeat cap. const configRequestIp = clientIpFromReqDefault(req); if (!nodeConfigPreAuthLimiter.allow(configRequestIp)) { res.setHeader("RateLimit-Limit", String(NODE_CONFIG_RATE_MAX)); res.setHeader("RateLimit-Remaining", "0"); res.setHeader("RateLimit-Reset", "60"); res.setHeader("Retry-After", "60"); return res.status(429).send("too many requests"); } // Pre-flight guard: the node lookup is DB-backed and previously had no catch // beneath it (the per-IP limiter above is synchronous) — Express 4 does not // catch async-handler rejections, so a DB rejection here hung the request. // The auth checks and 401s stay inside the guard in their original order; // node is hoisted so the config build below (with its own 409 catch) reads // it, and the client gets a generic 500 text on a pre-flight failure. let node = null; try { const bootstrapHeader = req.get("X-Node-Bootstrap") || ""; const bearerToken = (req.get("authorization") || "").replace(/^Bearer\s+/i, ""); node = await findNodeByIdOrName(req.params.id); // This GET serves ONLY the node daemon itself (bootstrap header or its own // bearer token). Browser admins must never fetch the raw config over a // plain authenticated GET — the config embeds the daemon's bearer token, so // the admin path is the step-up verified POST reveal in index.js. if (NODE_BOOTSTRAP_TOKEN && bootstrapHeader && safeCompare(bootstrapHeader, NODE_BOOTSTRAP_TOKEN)) { } else if (bearerToken && node && safeCompare(bearerToken, node.token)) { } else { return res.status(401).send("authentication required"); } // Unknown node: answered with the same 401 as a bad credential (never 404) // so credentialed callers cannot enumerate node ids/names by status code. if (!node) return res.status(401).send("authentication required"); } catch (err) { console.error("[/api/nodes/:id/config.yml] pre-flight failed:", err); if (!res.headersSent) return res.status(500).send("Internal error"); return; } let yml; try { yml = buildConfigYml(node, req); } catch (err) { return res.status(409).send("node token is invalidated or empty — rotate the node token before downloading config.yml"); } res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); res.setHeader("Pragma", "no-cache"); res.setHeader("Content-Type", "text/yaml; charset=utf-8"); res.send(yml); }); // (The legacy /api/nodes/:id/install-daemon.sh route was removed: it served a // script embedding the node's full config.yml — bearer token included — gated // by an installer token that no code path ever issued, so it could only ever // answer 401 while remaining a pre-auth-reachable, TLS-gate-skipping surface. // The supported install path is the single-use /api/node-bootstrap one-time // command.) // adpanel:heartbeat-fallback-scoped — one-time warn so the broken-install // condition is loud: with the fleet master unresolvable every heartbeat is // rejected (no bearer fallback, no state mutation), and without this warning // the rejections would be indistinguishable from ordinary bad credentials // while an operator wonders why a healthy-configured node shows offline. let heartbeatFallbackRejectWarned = false; function warnHeartbeatFallbackRejectedOnce() { if (heartbeatFallbackRejectWarned) return; heartbeatFallbackRejectWarned = true; console.warn( "[heartbeat] PANEL_HMAC_SECRET is unresolvable (see the [panel-hmac] boot warning): " + "unsigned/bearer heartbeats are REJECTED and nodes will show OFFLINE until the fleet " + "master is restored — set PANEL_HMAC_SECRET or repair data/panel-hmac-secret.json, then " + "restart the panel. Node configs carrying a secret derived from a lost master must be re-deployed." ); } // adpanel:heartbeat-body-binding — one-time warn for the transitional v1 // acceptance: the v1 envelope's signature covers only id/ts/nonce, so this // heartbeat was accepted with an UNBOUND body — a captured (ts, nonce, sign) // triple is valid for any body inside the drift window and could repoint // api_port or refresh last_seen. The v2 envelope (x-node-body-hash over the // exact raw bytes, signed into the base) removes that; it ships in the // node-daemon binaries (no sender in this repo), so v1 acceptance is a // documented transitional state that must be retired — v1 rejected — once // the fleet signs v2. Loud exactly once per process so operators learn the // fleet still has v1 daemons without spamming every heartbeat. let heartbeatLegacyEnvelopeWarned = false; function warnHeartbeatLegacyEnvelopeOnce() { if (heartbeatLegacyEnvelopeWarned) return; heartbeatLegacyEnvelopeWarned = true; console.warn( "[heartbeat] Accepted a heartbeat signed with the legacy v1 envelope (no x-node-body-hash): " + "the signature does not bind the request body. Upgrade the node daemon to the body-bound v2 " + "envelope. v1 acceptance is transitional." ); } // adpanel:heartbeat-nonce-shared — one-time warn when the shared nonce store // WAS wired but Redis was unavailable on this heartbeat: replay protection // fell back to the per-process cache, which is 1/N effective under PM2 // cluster. Heartbeats keep flowing (the envelope still authenticates the // sender — only the replay ledger degrades to the pre-fix posture), but the // operator should know the cluster-wide replay bound is not active. let heartbeatNonceFallbackWarned = false; function warnHeartbeatNonceLocalFallbackOnce() { if (heartbeatNonceFallbackWarned) return; heartbeatNonceFallbackWarned = true; console.warn( "[heartbeat] Shared Redis nonce store unavailable: heartbeat nonce replay protection fell " + "back to the per-process cache (1/N effective under PM2 cluster — a captured heartbeat is " + "replayable once per worker while Redis is down). Heartbeats remain authenticated by the " + "HMAC envelope; the shared ledger resumes automatically when Redis is restored." ); } // The one-time setup command embeds config.yml (daemon bearer token) and is // therefore only served via the step-up verified POST reveal registered in // index.js, before this router is mounted. A plain authenticated GET here // would hand the credential to any admin session without re-verification. app.post("/api/nodes/:id/heartbeat", async (req, res) => { try { // Per-IP fixed-window cap, counted on EVERY attempt (before any lookup // or auth decision) so flooding the unauthenticated 401 path is capped // too. Standard rate-limit headers advertise the ceiling; on 429 the // client also gets Retry-After for the remainder of the window. const heartbeatIp = clientIpFromReqDefault(req); if (!heartbeatLimiter.allow(heartbeatIp)) { res.setHeader("RateLimit-Limit", String(NODE_HEARTBEAT_RATE_MAX)); res.setHeader("RateLimit-Remaining", "0"); res.setHeader("RateLimit-Reset", "60"); res.setHeader("Retry-After", "60"); return res.status(429).json({ error: "too many requests" }); } res.setHeader("RateLimit-Limit", String(NODE_HEARTBEAT_RATE_MAX)); const node = await findNodeByIdOrName(req.params.id); // Unknown node: answered with the same 401 as a bad credential (never // 404), so a credentialed caller cannot distinguish "node exists but is // unauthorized" from "no such node" and enumerate node names. if (!node) return res.status(401).json({ error: "authentication required" }); const current = hardenNode(node); const authHeader = req.get("authorization") || ""; const bearer = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null; const body = req.body || {}; const bodyToken = body.token || null; const bodyTokenId = body.token_id || null; // The heartbeat is reachable without an admin session (bootstrap by // design) and a successful call flips the node online for a full TTL, so // a long-lived bearer token alone is insufficient: a captured heartbeat // could be replayed forever. When a per-node signing secret exists (the // daemon already persists it as panel.hmac_secret), require the // x-node-ts/x-node-sign/x-node-nonce envelope — timestamp-bounded and // single-use, so neither a sniffed heartbeat nor a stolen token keeps a // fake node alive. Signed senders prove possession of the *derived* // secret, which never crosses this endpoint. const heartbeatSecret = deriveNodeHmacSecret(PANEL_HMAC_SECRET, current.uuid || current.id); if (heartbeatSecret) { const verdict = await verifyHeartbeatEnvelope(req.headers, { secret: heartbeatSecret, nodeId: current.uuid || current.id, nonceCache: heartbeatNonceCache, // adpanel:heartbeat-nonce-shared — the cluster-shared replay arbiter: // null until index.js injects the session client via // setHeartbeatSharedNonceDeps (then the per-process cache is the sole // ledger, scope "local"); injected but Redis-unavailable yields scope // "local-fallback" and the one-time warn below. sharedNonceStore: heartbeatSharedNonceStore(), // adpanel:heartbeat-body-binding — the pre-parse raw bytes of THIS // request; v2 verifies its body hash against these and fails closed // when they were not captured (never against a re-serialization). rawBody: req[HEARTBEAT_RAW_BODY_PROP], }); if (!verdict.ok) { console.warn(`[heartbeat] Rejected unsigned/replayed heartbeat for node ${current.uuid || current.id}: ${verdict.reason}`); // The specific reason stays server-side only: a uniform 401 body keeps // a credentialed caller from telling "node exists" from "no such node". return res.status(401).json({ error: "authentication required" }); } // Operational (never blocking) one-time warns for the two documented // degraded postures: a legacy v1 envelope (body unbound — daemon needs // the v2 upgrade) and a shared nonce ledger unavailable (Redis down — // replay check degraded to per-process). Both fire at most once per // process; neither changes the verdict. if (verdict.envelope === "v1") warnHeartbeatLegacyEnvelopeOnce(); if (verdict.nonceScope === "local-fallback") warnHeartbeatNonceLocalFallbackOnce(); // Defense in depth: when a bearer/body credential is presented it must // still match; the signature alone is authoritative for senders that // omit it. if (bearer && !safeCompare(bearer, current.token)) { return res.status(401).json({ error: "authentication required" }); } if (!bearer && bodyToken && !safeCompare(bodyToken, current.token)) { return res.status(401).json({ error: "authentication required" }); } } else { // adpanel:heartbeat-fallback-scoped — the legacy bearer-token fallback // that used to live here ("PANEL_HMAC_SECRET not configured") is dead // on any healthy install: utils/panel-hmac-secret.js resolves — or // auto-generates and persists — the fleet master at boot, so "" only // ever means a BROKEN install (unwritable data dir, or a corrupt // data/panel-hmac-secret.json that must not be silently regenerated). // In that state a single captured daemon bearer token could still flip // any known node online for a full TTL and repoint its api_port (where // the panel later sends admin and server traffic) with no replay bound // at all — ops deception bought by a broken install. Fail closed // instead: a heartbeat that cannot be HMAC-verified never mutates node // state, and nodes honestly show offline until the master is restored // (see the [panel-hmac] boot warning). The 401 body stays identical to // this endpoint's other rejections: the node lookup has already // happened, so a distinguishable status would leak node-name validity // to unauthenticated callers. warnHeartbeatFallbackRejectedOnce(); return res.status(401).json({ error: "authentication required" }); } if (bodyTokenId && !safeCompare(bodyTokenId, current.token_id)) { return res.status(401).json({ error: "authentication required" }); } // adpanel:node-heartbeat-direction - inbound liveness does not prove the panel can reach the daemon. current.last_seen = Date.now(); await db.query("UPDATE nodes SET last_seen = GREATEST(COALESCE(last_seen, 0), ?) WHERE id = ?", [current.last_seen, current.id]); return res.json({ ok: true, now: current.last_seen, port_ok: current.port_ok, online: computeOnline(current) }); } catch (e) { console.error("[heartbeat] failed:", e && e.message); return res.status(500).json({ error: "heartbeat failed" }); } }); const HC_BATCH_SIZE = parseInt(process.env.HC_BATCH_SIZE || "10", 10) || 10; const HC_INTERVAL_MS = parseInt(process.env.HC_INTERVAL_MS || "5000", 10) || 5000; let _hcOffset = 0; let _healthLoopTimer = null; // Started explicitly by index.js AFTER the startup token-encryption migration // and integrity gate have settled the credential columns. The loop itself only // ever writes health telemetry (saveNodeHealth), so even a tick racing an // admin token rotation can no longer write a stale credential back. function startNodeHealthLoop() { if (_healthLoopTimer) return _healthLoopTimer; _healthLoopTimer = setInterval(async () => { try { const countRows = await db.query("SELECT COUNT(*) AS total FROM nodes"); const total = Number(countRows[0]?.total || 0); if (total === 0) { _hcOffset = 0; return; } if (_hcOffset >= total) _hcOffset = 0; const batch = await db.query( `SELECT * FROM nodes ORDER BY id ASC LIMIT ${HC_BATCH_SIZE} OFFSET ${_hcOffset}` ); _hcOffset += HC_BATCH_SIZE; const nodes = batch.map(mapNodeRow); for (const n of nodes) { try { await activeCheckNode(n, { force: true }); await saveNodeHealth(n); } catch (_) { } } } catch (_) { } }, HC_INTERVAL_MS); return _healthLoopTimer; } const NODE_VOLUME_ROOT = "/var/lib/node/servers"; const _nodeVolumeDirCache = new Map(); function getNodeVolumesDir(node) { const key = String(node.uuid || node.id || ""); return (key && _nodeVolumeDirCache.get(key)) || node.volumesDir || NODE_VOLUME_ROOT; } function mapServerRow(row) { return { id: row.id, name: row.name, legacy_id: row.legacy_id, bot: row.bot, template: row.template, start: row.start, node_id: row.node_id, nodeId: row.node_id, node: row.node_id, ip: row.ip, port: row.port, status: row.status, suspended: !!row.suspended, suspended_at: row.suspended_at === null || row.suspended_at === undefined ? null : Number(row.suspended_at), suspended_by: row.suspended_by || null, runtime: parseDbJson(row.runtime, null), docker: parseDbJson(row.docker, null), acl: parseDbJson(row.acl, null), resources: parseDbJson(row.resources, null), }; } async function findServerByNameOrId(name) { const key = String(name || "").trim(); if (!key) return null; const lower = key.toLowerCase(); const numericId = /^\d+$/.test(key) ? Number(key) : null; // M9 parity with index.js findServer: the OR match can hit several rows // (a server literally named "123" collides with whichever row later gets // auto-increment id 123, whose legacy_id is the id-as-string — and only // `name` is UNIQUE), and MySQL gives no ordering guarantee for a bare // LIMIT 1, so which row wins could flip between queries. Every consumer of // this row — access checks, suspension gates, remoteContext's baseDir — // must agree on WHICH row a URL key denotes: an unordered match can // authorize on one row and read/write/delete another user's directory. // Rank exact-name matches first, then legacy_id, then bot, then the // numeric-id match (kept last for old/imported rows whose legacy_id is // NULL), with id as the final tiebreaker. const rows = await db.query( `SELECT * FROM servers WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ? OR id = ? ORDER BY CASE WHEN LOWER(name) = ? THEN 0 WHEN LOWER(legacy_id) = ? THEN 1 WHEN LOWER(bot) = ? THEN 2 WHEN id = ? THEN 3 ELSE 4 END, id ASC LIMIT 1`, [lower, lower, lower, numericId, lower, lower, lower, numericId] ); return rows.length ? mapServerRow(rows[0]) : null; } // --------------------------------------------------------------------------- // Server suspension policy (REST bridge). // // The socket path in index.js refuses every interaction with a suspended // server — join, power actions, console commands, file read/write/delete and // resource subscriptions — for ALL callers (admins included; unsuspend // first). This REST bridge historically skipped that check, so a user with a // live session could keep controlling a suspended server over HTTP: remote // power actions and the HTTP command fallback target these routes first, // and remote file editing uses them exclusively. The helpers below mirror // index.js (isServerSuspended / sendSuspendedServerJson) — same 423 + code, // same no-admin-exemption policy — and every server-scoped route and // performer here runs the check after the access check and before // permission checks, so the body (which names the suspending admin) never // reaches a caller that could not open the server in the first place. // --------------------------------------------------------------------------- // adpanel:relay-helper-consolidation — isServerSuspended/suspendedServerBody/ // sendSuspendedServerJson moved to services/node-fs-relay.js (index.js's // twins inlined the same body; field sets verified identical) and are // re-bound from that module above. // Performers return { status, body } for the route handlers (and for the // index.js AI tools) to relay verbatim; this is their 423 shape. function suspendedServerResult(srv = null) { return { status: 423, body: suspendedServerBody(srv) }; } // Gate for routes that validate access before resolving the server row: // resolves the row itself and answers the 423. True = request already // answered, caller must return. async function rejectIfServerSuspended(res, serverName) { const srv = await findServerByNameOrId(serverName); if (isServerSuspended(srv)) { sendSuspendedServerJson(res, srv); return true; } return false; } // Gate for performers, which relay { status, body } instead of writing to // res: resolves the row and returns the 423 result, or null when the server // is not suspended. async function resolveIfServerSuspended(serverName) { const srv = await findServerByNameOrId(serverName); return isServerSuspended(srv) ? suspendedServerResult(srv) : null; } function serverNodeRef(srv) { return (srv && (srv.node || srv.nodeId || srv.node_id)) || null; } function buildServerInfo(srv) { if (!srv) return {}; const ip = srv.ip || srv.host || srv.address || srv.hostname || null; const port = srv.port || srv.server_port || srv.bind_port || null; const start = srv.start || srv.startFile || srv.entry || null; return { ip, port, start }; } // adpanel:relay-helper-consolidation — nodeHeaders moved to // services/node-http.js (one core buildNodeAuthHeaders behind parameters: // this surface keeps its exact shape — no Content-Type, token from node.token // only, X-Node-Token-Id always present, possibly empty) and is re-bound above. function nodeUrl(node, suffix) { const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); return `${base}${suffix}`; } // adpanel:relay-helper-consolidation — finiteNumber moved to // services/node-fs-relay.js (byte-identical with index.js's finiteUploadNumber; // one implementation, both names exported) and is re-bound above. function nodeUploadLimitMb(node) { const configured = finiteNumber(node?.max_upload_mb); return configured && configured > 0 ? configured : 10240; } const fetchServerDiskSnapshot = createNodeDiskSnapshotFetcher({ // Dial through this surface's own dialer — now the hardened-core wrapper // above — so the GET wire request (nodeHeaders, no body, per-call timeout) // is byte-identical to the former inline implementation. dial: (url, method, headers, body, timeoutMs) => httpJson(url, { method, headers, body, timeoutMs }), buildRequest: (ctx, serverName) => { if (!ctx?.remote || !ctx.node) return null; const nodeServerName = ctx.nodeServerName || sanitizeNodeStorageName(ctx.server?.name || serverName); if (!nodeServerName) return null; return { url: nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(nodeServerName)}`), headers: nodeHeaders(ctx.node), }; }, }); function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb, serverName, createOnly) { return new Promise((resolve) => { let settled = false; let nodeReq = null; const done = (result) => { if (settled) return; settled = true; require("./utils/stream-lifecycle").releaseFailedUpload(result, sourceStream, nodeReq); resolve(result); }; try { const fullUrl = nodeUrl(node, "/v1/fs/upload"); const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(fullUrl); // SSRF guard (finding 3.3) if (guardError) return done({ status: 0, json: { error: "upload_network_error" } }); const lib = fullUrl.startsWith("https:") ? https : http; const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`; const { preamble, epilogue } = buildNodeUploadMultipart(boundary, serverName, destDir, originalName); const headers = { ...nodeHeaders(node), "Content-Type": `multipart/form-data; boundary=${boundary}`, }; nodeReq = lib.request(fullUrl, { method: nodeNoClobberMethod(createOnly), headers, lookup: nodeSsrfGuard.guardedNodeLookup, agent: nodeTlsAgent(fullUrl) }, (res) => { const chunks = []; let total = 0; res.on("data", (d) => { if (total < 64 * 1024) { chunks.push(d); total += d.length; } }); res.on("end", () => { if (settled) return; const bodyStr = Buffer.concat(chunks).toString("utf8"); let json = null; try { json = bodyStr ? JSON.parse(bodyStr) : null; } catch { } done({ status: res.statusCode, json }); }); // adpanel:upload-response-error — Without an 'error' listener a // mid-response failure is swallowed (IncomingMessage emits 'error' // only when one is attached) and this promise never settles — the // relay upload request would hang open forever. Mirror the nodeReq // error handler below. 'aborted' (node closed the response // prematurely) can arrive without a paired 'error' event and tears // down the same way. res.on("error", (err) => { if (settled) return; try { nodeReq.destroy(); } catch { } // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.warn("[node-upload-relay] node response stream error:", err); done({ status: 0, json: { error: "upload_network_error", detail: "node connection failed" } }); }); res.on("aborted", () => { if (settled) return; try { nodeReq.destroy(); } catch { } done({ status: 0, json: { error: "upload_network_error", detail: "response stream aborted" } }); }); }); nodeReq.setTimeout(UPLOAD_TIMEOUT_MS); nodeReq.on("timeout", () => { try { nodeReq.destroy(); } catch { } done({ status: 0, json: { error: "upload_timeout" } }); }); nodeReq.on("error", (err) => { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.warn("[node-upload-relay] node request error:", err); done({ status: 0, json: { error: "upload_network_error", detail: "node connection failed" } }); }); nodeReq.write(preamble); let written = 0; sourceStream.on("data", (chunk) => { if (settled) return; written += chunk.length; if (maxBytes > 0 && written > maxBytes) { try { sourceStream.destroy(); } catch { } try { nodeReq.destroy(); } catch { } done({ status: 413, json: { error: "file_too_large", message: `File exceeds this node's upload limit of ${maxMb || Math.round(maxBytes / 1024 / 1024)} MB`, limit_mb: maxMb || Math.round(maxBytes / 1024 / 1024), }, }); return; } if (!nodeReq.write(chunk)) { sourceStream.pause(); nodeReq.once("drain", () => { if (!settled) sourceStream.resume(); }); } }); sourceStream.on("end", () => { if (settled) return; nodeReq.write(epilogue); nodeReq.end(); }); const sourceFailure = (err) => { if (settled) return; try { nodeReq.destroy(); } catch { } // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.warn("[node-upload-relay] source stream error:", err); done({ status: 0, json: { error: "upload_stream_error", detail: "upload stream failed" } }); }; sourceStream.on("error", sourceFailure); require("./utils/stream-lifecycle").onPrematureClose(sourceStream, sourceFailure); } catch (err) { try { if (nodeReq) nodeReq.destroy(); } catch { } // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[node-upload-relay] upload failed:", err); done({ status: 0, json: { error: "stream_error", detail: "upload failed" } }); } }); } // adpanel:relay-helper-consolidation — safeJoinUnix, isServerRootResolvedPath // and maskPathErrorMessage moved to services/node-fs-relay.js and are // re-bound above under their original local names (safeJoinUnixRelay and // maskPathErrorMessageRelay renamed in the destructure). The shared // safeJoinUnix is the STRICTER UNION of this file's checks and index.js's // (this surface's NUL-in-base rejection and trailing-prefix containment assert // now apply on the panel surface too — flagged hardening there, unchanged // here); the relay style preserves this surface's exact string-concat join // output and throw messages, so maskPathErrorMessage's substring policy maps // every rejection to the same "invalid path" bodies as before. function mapFsEntries(entries) { const out = []; (entries || []).forEach(e => { if (!e || !e.name) return; const entry = { name: e.name, isDir: !!(e.type === "dir" || e.isDir) }; if (typeof e.size === "number") entry.size = e.size; // Forward the node-reported last-modified time (Unix seconds) so the UI can // render when the file was created/changed. Only accept a sane numeric value. if (typeof e.mtime === "number" && isFinite(e.mtime) && e.mtime > 0) entry.mtime = e.mtime; out.push(entry); }); return out; } // adpanel:multidisk - per-server base-dir cache (server may be on a secondary disk). const _nodeServerBaseDirCache = new Map(); // key `${nodeKey}:${name}` -> { baseDir, at } const NODE_SERVER_BASEDIR_TTL_MS = 5 * 60 * 1000; // validateResolvedBaseDir hardens the node-reported base dir before the panel uses // it as a prefix for safeJoinUnix. The node already enforces disk-root containment, // but the panel independently rejects anything that is not a clean, absolute path // whose final segment is exactly the sanitized server name. This prevents a // compromised/spoofed node response from steering FS operations elsewhere and // blocks traversal/NUL injection at the panel boundary. function validateResolvedBaseDir(baseDir, expectedName) { if (typeof baseDir !== "string" || !baseDir) return null; if (baseDir.includes("\0")) return null; // Reject traversal in the raw value *before* normalization collapses it. if (baseDir.split("/").includes("..")) return null; // POSIX-normalize; the node filesystem is always Unix. const normalized = require("path").posix.normalize(baseDir).replace(/\/+$/, ""); if (!normalized.startsWith("/")) return null; if (normalized === "/" || normalized === "") return null; if (normalized.split("/").includes("..")) return null; const safeName = sanitizeNodeStorageName(expectedName); if (!safeName) return null; // The directory that holds the server files must be named exactly after the // sanitized server name (…//). No suffix tricks, no parent. const segments = normalized.split("/"); if (segments[segments.length - 1] !== safeName) return null; return normalized; } async function resolveNodeServerBaseDir(node, nodeServerName) { const nodeKey = String(node.uuid || node.id || node.name || ""); const safeName = sanitizeNodeStorageName(nodeServerName); if (!nodeKey || !safeName) return null; const cacheKey = `${nodeKey}:${safeName}`; const cached = _nodeServerBaseDirCache.get(cacheKey); if (cached && Date.now() - cached.at < NODE_SERVER_BASEDIR_TTL_MS) { return cached.baseDir; } const { status, json } = await httpJson( nodeUrl(node, `/v1/servers/${encodeURIComponent(safeName)}`), { method: "GET", headers: nodeHeaders(node), timeoutMs: 5000 } ); if (status !== 200 || !json || json.ok !== true) return null; const validated = validateResolvedBaseDir(json.baseDir, safeName); if (!validated) return null; _nodeServerBaseDirCache.set(cacheKey, { baseDir: validated, at: Date.now() }); return validated; } async function remoteContext(serverName, expectedServerId = null) { const srv = await findServerByNameOrId(serverName); if (!srv || (expectedServerId != null && String(srv.legacy_id || srv.id) !== String(expectedServerId))) return { exists: false }; const ref = serverNodeRef(srv); // `server` is exposed on every exists:true shape (also the non-remote // ones) so the suspension gate can run off ctx.server uniformly. if (!ref) return { exists: true, remote: false, server: srv, info: buildServerInfo(srv) }; const node = await findNodeByIdOrName(ref); if (!node) return { exists: true, remote: false, server: srv, info: buildServerInfo(srv) }; const volRoot = getNodeVolumesDir(node); const nodeServerName = sanitizeNodeStorageName(srv.name || serverName); // adpanel:multidisk - the server may live on a secondary disk. Resolve its real // base directory from the node (disk-aware) and fall back to the primary volumes // root for older/unreachable nodes. The node remains the source of truth and // re-validates every path, so this only affects which root the panel prefixes. let baseDir = `${volRoot}/${nodeServerName}`; try { const resolved = await resolveNodeServerBaseDir(node, nodeServerName); if (resolved) baseDir = resolved; } catch (_) { /* fall back to primary path */ } return { exists: true, remote: true, server: srv, node, nodeId: node.uuid, nodeServerName, baseDir, info: buildServerInfo(srv) }; } // Same cross-site read guard as the file relays below (shared implementation // in utils/cross-site-read-guard.js): /info serves baseDir, disk snapshots // and node metadata to session-authenticated browsers, so it rejects // exactly what the file relays reject. app.get("/api/nodes/server/:name/info", rejectCrossSiteRead, async (req, res) => { // Pre-flight guard: the access check, suspension gate and remote-context // resolution are DB-backed and previously had no catch beneath them — // Express 4 does not catch async-handler rejections, so any DB rejection // here hung the request and only fed the process-level unhandledRejection // log. The handler had no body catch, so the whole body is wrapped: the // client gets a generic 500 and the full error stays in the server log. The // guarded probes below (activeCheckNode, the disk snapshot .catch) are // untouched inside. try { res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); const serverName = req.params.name; const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } if (await rejectIfServerSuspended(res, serverName)) return; const ctx = await remoteContext(serverName); if (!ctx.exists) { console.log(`[node-info] Server ${serverName} not found`); return res.json({ ok: false, remote: false, info: null, nodeOnline: false }); } if (ctx.remote && ctx.node) { try { await activeCheckNode(ctx.node, { force: true }); } catch (e) { console.log(`[node-info] activeCheckNode error for ${req.params.name}:`, e.message); } const nodeOnline = computeOnline(ctx.node); const maxUploadMb = nodeUploadLimitMb(ctx.node); const disk = await fetchServerDiskSnapshot(ctx, serverName, 5000).catch(() => null); console.log(`[node-info] Server ${req.params.name} - remote: true, port_ok: ${ctx.node.port_ok}, last_seen: ${ctx.node.last_seen}, nodeOnline: ${nodeOnline}`); return res.json({ ok: true, remote: true, nodeId: ctx.node.uuid, info: ctx.info || {}, baseDir: ctx.baseDir, maxUploadMb, maxUploadBytes: Math.round(maxUploadMb * 1024 * 1024), disk, nodeOnline }); } console.log(`[node-info] Server ${req.params.name} - remote: false (no nodeId), returning nodeOnline: true`); return res.json({ ok: true, remote: false, nodeId: null, info: ctx.info || {}, nodeOnline: true }); } catch (err) { console.error("[/api/nodes/server/:name/info] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } }); // adpanel:relay-helper-consolidation (Wave 2 Step B3) — the relay-side dial // posture for the server-scoped fs relays, byte-identical to nodeUrl's + // nodeHeaders' outputs (this surface's buildNodeBaseUrl flavor: clampPort // clamping, plain-http default scheme, the toString-minus-trailing-slash URL // form; the relay header shape: Content-Type added per dial, token from // node.token only, X-Node-Token-Id always present). The dial itself is // services/node-http.js's hardened httpRequestJson — the core relayFsJson // defaults to — because the auth headers carry the node's bearer credential, // which switches that core into its node branch: assertNodeUrlHostAllowed // pre-flight + guardedNodeLookup connect-time re-validation + 16 MiB cap + // single-settle finish. // // adpanel:relay-crash-hardening — DELIBERATE hardening delta vs the former // httpJson dials these routes used (spec D1/D2, the crash class that took the // worker down three times): the shared core attaches res.on("aborted") in // addition to res.on("error") on every upstream response and runs a hard // total-duration timer (req.setTimeout alone was an inactivity timer, so a // stalled-but-open socket dial hung the relay promise forever). No // wire-visible change: same status/json shapes, same 16 MiB tooLarge // classification, same per-op timeouts — the failure now SETTLES instead of // hanging or crashing. const NODES_FS_RELAY_DEPS = { buildNodeBaseUrl: (node) => buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)), buildNodeAuthHeaders: (node) => Object.assign({ "Content-Type": "application/json" }, nodeHeaders(node)), }; // Same cross-site read guard as the panel's own file routes (index.js // /api/servers/:name/files/*, shared implementation in // utils/cross-site-read-guard.js): a forged cross-site GET must not be able // to read node files through an authenticated browser, and the relay must // reject exactly what the panel-side twin rejects. // adpanel:fs-relay-brake — both HTTP layouts must draw from the same Files budgets. function nodeFsRateLimiterGate(req, res, next) { const limiter = req.method === "GET" || req.method === "HEAD" ? _fsReadRateLimiter : _fsMutateRateLimiter; if (!limiter) return res.status(503).json({ error: "File rate limiter unavailable" }); return limiter(req, res, next); } app.get("/api/nodes/server/:name/entries", rejectCrossSiteRead, nodeFsRateLimiterGate, async (req, res) => { const serverName = req.params.name; // Pre-flight guard: the access check, suspension gate, files_read permission // and remote-context resolution are DB-backed and previously had no catch // beneath them — Express 4 does not catch async-handler rejections, so any // DB rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // ctx is hoisted so the body try below (which keeps its own catch) reads it. let ctx = null; try { const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } if (!(await checkUserPerm(req, serverName, "files_read"))) { return res.status(403).json({ error: "permission denied", permission: "files_read" }); } // adpanel:fs-perms-before-suspension — parity with the panel fs routes // (index.js): authorization (403) before state (423). A caller without the // fine-grained perm must not learn the server's suspension state, so every // relay fs route answers the perm denial before the suspension body. if (await rejectIfServerSuspended(res, serverName)) return; ctx = await remoteContext(serverName); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); } catch (err) { console.error("[/api/nodes/server/:name/entries] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.query.path || ""); try { const full = safeJoinUnix(ctx.baseDir, rel); // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsListOutcome, spec §3 "relay" bodies). // buildFsListPayload keeps this surface's exact list body ({path, server, // depth: 1} — spec D3) and mapFsEntries stays injected as the entryMapper // (spec D4); offline/failed collapse into the plain node_list_failed body // with no detail (spec D5). 60000 is the list-timeout parity with // index.js's fs-relay dial: a shorter cutoff aborted the relay on large // directories while the node was still producing the listing, surfacing a // false node_list_failed. const outcome = await relayFsJson( NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/list", buildFsListPayload(full, ctx.nodeServerName, "relay"), 60000 ); // adpanel:listing-truncated — the renderer relays the daemon's // bounded-listing flag (maxDirListEntries): the client reads // data.truncated to show its truncation notice, so dropping the field // left that notice dead code. An over-cap listing renders the shared // node_response_too_large body (the node IS online — never report it as // node_list_failed). const out = renderFsListOutcome(outcome, rel, { variant: "relay", entryMapper: mapFsEntries }); return res.status(out.status).json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); app.get("/api/nodes/server/:name/file", rejectCrossSiteRead, nodeFsRateLimiterGate, async (req, res) => { const serverName = req.params.name; // Pre-flight guard: the access check, suspension gate, files_read permission // and remote-context resolution are DB-backed and previously had no catch // beneath them — Express 4 does not catch async-handler rejections, so any // DB rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // ctx is hoisted so the body try below (which keeps its own catch) reads it. let ctx = null; try { const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } if (!(await checkUserPerm(req, serverName, "files_read"))) { return res.status(403).json({ error: "permission denied", permission: "files_read" }); } if (await rejectIfServerSuspended(res, serverName)) return; ctx = await remoteContext(serverName); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); } catch (err) { console.error("[/api/nodes/server/:name/file] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.query.path || ""); try { const full = safeJoinUnix(ctx.baseDir, rel); // Base64 read (parity with the panel's /files/read route): the daemon's // utf8 mode lossily replaces non-UTF-8 bytes with U+FFFD, so this relay // fetches base64 and validates the bytes strictly — a binary file answers // { path, binary: true } with NO content field instead of mangled text // a client could save back over the original. The dial + response mapping // moved into services/node-fs-relay.js (relayFsJson + // renderFsReadOutcome, spec §3 "relay" bodies — deliberately NO 404 // branch and no ok:true on success). 120000 is the read-timeout parity // with index.js's fs-relay dial: a short cutoff aborted the relay while // the daemon completed the read anyway, so the user saw node_read_failed // and a retry re-executed the operation. const outcome = await relayFsJson( NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/read", { path: full, server: ctx.nodeServerName, encoding: "base64" }, 120000 ); const out = renderFsReadOutcome(outcome, rel, { variant: "relay" }); return res.status(out.status).json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); app.get("/api/nodes/server/:name/download", rejectCrossSiteRead, nodeFsRateLimiterGate, async (req, res) => { const serverName = req.params.name; // Pre-flight guard: the access check, suspension gate, files_read permission // and remote-context resolution are DB-backed and previously had no catch // beneath them — Express 4 does not catch async-handler rejections, so any // DB rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // ctx is hoisted so the body try below (which keeps its own catch) reads it; // the piped download stream inside keeps its own error listeners. let ctx = null; try { const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } if (!(await checkUserPerm(req, serverName, "files_read"))) { return res.status(403).json({ error: "permission denied", permission: "files_read" }); } if (await rejectIfServerSuspended(res, serverName)) return; ctx = await remoteContext(serverName); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); } catch (err) { console.error("[/api/nodes/server/:name/download] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.query.path || ""); try { const full = safeJoinUnix(ctx.baseDir, rel); const downloadUrl = nodeUrl(ctx.node, "/v1/fs/download"); const guardError = nodeSsrfGuard.assertNodeUrlHostAllowed(downloadUrl); // SSRF guard (finding 3.3) if (guardError) return res.status(502).json({ error: "node connection failed" }); const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http"); const postData = JSON.stringify({ path: full, server: ctx.nodeServerName }); const url = new URL(downloadUrl); const reqOpts = { hostname: url.hostname, port: url.port, path: url.pathname, method: "POST", headers: Object.assign({ "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }, nodeHeaders(ctx.node)), timeout: 300000, agent: nodeTlsAgent(downloadUrl), lookup: nodeSsrfGuard.guardedNodeLookup // connect-time SSRF re-validation (finding 3.3) }; const proxyReq = lib.request(reqOpts, (proxyRes) => { // adpanel:http-straggler — deliberate per-surface streaming dial (AGENTS.md: // download stream proxies stay per-surface until a streaming-shaped shared // contract exists); the buffered core would buffer whole archives in RAM. // Full crash-class posture below: response error listeners on every // branch, client-close teardown, request error handler, 300s timeout. if (res.destroyed) { // The client went away before the upstream response arrived; stop // pulling the body from the node daemon. The 'error' listener is // defense-in-depth: destroying proxyReq mid-response can surface a // premature-close error on proxyRes, and an unhandled one would // take down the worker (mirrors the 200-path listener below). proxyRes.resume(); proxyRes.on("error", () => { try { res.destroy(); } catch { } }); try { proxyReq.destroy(); } catch { } return; } if (proxyRes.statusCode !== 200) { // Drain the error body so the node connection is released instead of // idling until timeout, and give the stream an 'error' listener — // IncomingMessage only emits 'error' when one is attached, and an // unhandled one would take down the worker (same hardening as the // panel's files download proxy in index.js). proxyRes.on("error", () => { try { res.destroy(); } catch { } }); proxyRes.resume(); return res.status(proxyRes.statusCode || 502).json({ error: "download failed" }); } // adpanel:download-headers-pinning - node-supplied Content-Type / // Content-Disposition are never trusted (same rationale as the panel's // files download proxy in index.js); headers are pinned via the shared // helper and the filename comes from the requested path. setPinnedDownloadHeaders(res, path.posix.basename(rel || "")); if (proxyRes.headers["content-length"]) res.setHeader("Content-Length", proxyRes.headers["content-length"]); // An 'error' on the upstream response (node daemon reset mid-body) has // no listener via pipe() alone; without one the failure is swallowed and // the client response hangs open forever with a leaked socket. proxyRes.on("error", () => { try { res.destroy(); } catch { } }); // A client abort must stop pulling the body from the node; 'close' // also fires on normal completion, so only tear down when the body // never finished arriving. res.on("close", () => { if (!proxyRes.complete) { try { proxyReq.destroy(); } catch { } } }); proxyRes.pipe(res); }); proxyReq.on("error", () => { // Once the 200 headers are forwarded the 502 cannot be sent anymore: // res.status().json() here would append JSON to the binary body (or // emit an unhandled 'error' on an already-destroyed response) — kill // the response instead. if (res.headersSent) { try { res.destroy(); } catch { } return; } res.status(502).json({ error: "node connection failed" }); }); proxyReq.on("timeout", () => { proxyReq.destroy(); // After the 200 headers went out, appending JSON to the body would // silently corrupt the downloaded file — kill the response instead. if (res.headersSent) { try { res.destroy(); } catch { } return; } res.status(504).json({ error: "download timeout" }); }); proxyReq.write(postData); proxyReq.end(); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); // adpanel:relay-helper-consolidation — the duplicated *_NODES 413 constants // (byte-identical copies of index.js's, kept here only because this module // could not import index.js) and the decodeNodeFileReadContentNodes twin of // index.js's base64 read decoder live in services/node-fs-relay.js as the // single source of truth; the file write/read relays below consume them // THROUGH the shared renderers (renderFsWriteOutcome / renderFsReadOutcome), // so the 413/413-base64/404-existed wire bodies cannot drift from the panel's. app.post("/api/nodes/server/:name/file", nodeFsRateLimiterGate, requireNodeFileActionToken("PUT /api/servers/:name/files/write"), async (req, res) => { const serverName = req.params.name; // Pre-flight guard: the access check, suspension gate, fs write-mode // resolution and remote-context resolution are DB-backed and previously had // no catch beneath them — Express 4 does not catch async-handler rejections, // so any DB rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // ctx/writeMode are hoisted so the body try below (which keeps its own // catch) reads them. let ctx = null; let writeMode = null; try { const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } writeMode = await resolveFsWriteMode(req, serverName); if (!writeMode.ok) { return res.status(403).json({ error: "permission denied", permission: writeMode.permission }); } if (await rejectIfServerSuspended(res, serverName)) return; ctx = await remoteContext(serverName); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); } catch (err) { console.error("[/api/nodes/server/:name/file] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.body.path || ""); const content = String((req.body && req.body.content) || ""); // Optional base64 passthrough (parity with the panel's PUT /files/write and // the socket writeFile handler): a non-empty string contentBase64 is relayed // untouched with encoding "base64" and takes precedence over text content. // The shipped client never sends it — API symmetry only. The scoped 10mb // parser on this route caps the serialized request body (the // adpanel:node-file-write-scoped-parser dispatch ahead of the global 2mb // parser), which inherently covers base64's 4/3 inflation inside the // daemon's 10 MiB raw-body budget. const contentBase64 = typeof req.body?.contentBase64 === "string" && req.body.contentBase64 ? req.body.contentBase64 : ""; try { const full = safeJoinUnix(ctx.baseDir, rel); const writePayload = contentBase64 ? { path: full, server: ctx.nodeServerName, content: contentBase64, encoding: "base64", mode: writeMode.mode } : { path: full, server: ctx.nodeServerName, content, encoding: "utf8", mode: writeMode.mode }; if (!attachEditorWriteHash(writePayload, req.body?.expectedSha256)) { return res.status(400).json({ error: "invalid expectedSha256" }); } // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsWriteOutcome, spec §3 "relay" bodies): 507 quota // passthrough, the daemon-400 "content too large" → 413 backstop (shared // constants; base64 picked per encoding), the 409/404 permission mappings // ("permission denied" — spec D6) and the 502 all render there. 120000 is // the write-timeout parity with index.js's fs-relay dial: a short cutoff // aborted the relay while the daemon completed the write anyway, so the // user saw node_write_failed and a retry re-executed it. const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/write", writePayload, 120000); const out = renderFsWriteOutcome(outcome, { variant: "relay", base64: !!contentBase64, editorGuard: !!writePayload.editorBaseSha256 }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_edit", { path: rel, created: outcome.json.existed === false }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); app.post("/api/nodes/server/:name/delete", nodeFsRateLimiterGate, requireNodeFileActionToken("DELETE /api/servers/:name/files/delete"), async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_delete permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the body try below (which keeps its own catch) reads it. let ctx = null; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_delete"))) { return res.status(403).json({ error: "permission denied", permission: "files_delete" }); } if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/delete] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.body.path || ""); const isDir = !!req.body.isDir; try { const full = safeJoinUnix(ctx.baseDir, rel); if (isServerRootResolvedPath(ctx.baseDir, full)) { return res.status(400).json({ error: "refusing to delete server root" }); } // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsDeleteOutcome, spec §3 "relay" bodies): any // non-ok outcome renders 502 node_delete_failed — no 404 and no 507 // branch, matching this route's former mapping. 120000 is the // delete-timeout parity with index.js's fs-relay dial: a short cutoff // aborted the relay while the daemon completed the delete anyway, so the // user saw node_delete_failed and a retry re-executed it. const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/delete", { path: full, server: ctx.nodeServerName, isDir }, 120000); const out = renderFsDeleteOutcome(outcome, { variant: "relay" }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_delete", { path: rel, isDir }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); app.post("/api/nodes/server/:name/delete-batch", nodeFsRateLimiterGate, requireNodeFileActionToken("DELETE /api/servers/:name/files/delete"), async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_delete permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the body tries below (which keep their own catches) read it. let ctx = null; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_delete"))) { return res.status(403).json({ error: "permission denied", permission: "files_delete" }); } if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/delete-batch] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const items = req.body.items; if (!Array.isArray(items) || items.length === 0) { return res.status(400).json({ error: "items array required" }); } if (items.length > 500) { return res.status(400).json({ error: "too many items (max 500)" }); } // Path validation answers 400 with the same convention as the delete/rename // siblings — safeJoinUnix throws are client input errors, not server faults. // The node round-trip below reports connection and node-side failures as 502 // node_batch_delete_failed via the status check (the shared relay dial // resolves, never rejects); its catch is only a backstop for unexpected // internal errors and // answers a fixed generic shape — raw error text stays in the server log. let fullItems; try { fullItems = items.map(item => ({ path: safeJoinUnix(ctx.baseDir, String(item.path || "")), isDir: !!item.isDir })); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } try { // Refuse the ENTIRE request when any entry resolves to the server root: // forwarding a malformed batch would let the node perform a partial // recursive deletion before the offending entry is rejected, which is // worse than a single clear error for the whole request. if (fullItems.some(item => isServerRootResolvedPath(ctx.baseDir, item.path))) { return res.status(400).json({ error: "refusing to delete server root" }); } // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsDeleteBatchOutcome — the relay-only op, spec // D29). The renderer keys on status 200 + a parseable body (NOT the // daemon's ok flag): a 200 envelope with top-level ok:false is a // partial-success answer the client must receive verbatim. Every non-200 // (and offline/too-large) outcome renders 502 node_batch_delete_failed. // 120000 keeps the delete-timeout parity with the single-delete relay. const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/delete-batch", { items: fullItems, server: ctx.nodeServerName }, 120000); const out = renderFsDeleteBatchOutcome(outcome, { variant: "relay" }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_delete_batch", { count: items.length, success: out.json.success || 0, failed: out.json.failed || 0 }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { console.error("[delete-batch] Error:", e); return res.status(500).json({ error: "batch_delete_error" }); } }); app.post("/api/nodes/server/:name/rename", nodeFsRateLimiterGate, requireNodeFileActionToken("POST /api/servers/:name/files/rename"), async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_rename permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the body try below (which keeps its own catch) reads it. let ctx = null; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_rename"))) { return res.status(403).json({ error: "permission denied", permission: "files_rename" }); } if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/rename] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.body.path || ""); // Same sanitizer the panel rename routes and the daemon run, injected via // setUploadPolicyHooks; the strict local fallback only covers a standalone // nodes.js that user routes can't serve anyway (no session store). // adpanel:sanitizer-lockstep — the fallback 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 gone. Per spec D9 the // fallback stays a strict sanitizer distinct from the canonical file-name // hook, which wins whenever injected. const rawNewName = String(req.body.newName || ""); const newName = _sanitizeUploadFilename ? (_sanitizeUploadFilename(rawNewName) || "") : sanitizeNodeStorageName(rawNewName); if (!newName) return res.status(400).json({ error: "invalid newName" }); try { const full = safeJoinUnix(ctx.baseDir, rel); // Root and no-op refusals, mirroring the panel rename routes: renaming // (or over) the server root is reserved for the dedicated admin server // flows, exactly like deleting it. newName is sanitized to a bare name, // so the destination is newName in the source's directory (the daemon's // in-place rename contract). if (isServerRootResolvedPath(ctx.baseDir, full)) { return res.status(400).json({ error: "refusing to rename server root" }); } const dest = path.posix.join(path.posix.dirname(full), newName); if (isServerRootResolvedPath(ctx.baseDir, dest)) { return res.status(400).json({ error: "refusing to rename server root" }); } if (newName === path.posix.basename(full)) { return res.status(400).json({ error: "source and destination are the same" }); } // Destination pre-check via the daemon's depth-1 list (no single-path // stat endpoint; racy but cheap) - a failed probe never blocks, the // daemon's RENAME_NOREPLACE (409) is authoritative. Protects the // destination against older daemons that still rename with plain // overwrite semantics. The probe rides the shared relayFsJson dial // (classification first: kind "ok" ⇔ the former `list.status === 200 && // list.json?.ok` guard). Its request body is deliberately NOT // buildFsListPayload's shape — it has always carried depth: 1 in this // exact key order, and this daemon-facing body must stay byte-identical. // 60000 is the list-timeout parity with index.js's rename probe. try { const probe = await relayFsJson( NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/list", { path: path.posix.dirname(dest), depth: 1, server: ctx.nodeServerName }, 60000 ); if (probe.kind === "ok" && Array.isArray(probe.json.entries) && probe.json.entries.some((e) => e && e.name === newName)) { return res.status(409).json({ error: "destination_exists" }); } } catch { } // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsRenameOutcome, spec §3 "relay" bodies — verified // byte-identical to the panel's): 409/destination_exists → 409, // 404/source_not_found → 404, 400 → "invalid path", else 502. 120000 is // the rename-timeout parity with index.js's fs-relay dial: a short cutoff // aborted the relay while the daemon completed the rename anyway, so the // user saw a failure and a retry re-executed it. const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/rename", { path: full, server: ctx.nodeServerName, newName }, 120000); const out = renderFsRenameOutcome(outcome, { variant: "relay" }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_rename", { src: rel, dest: newName }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); // Same limiter gate as the upload relays: extract drives daemon-side 7z/unrar // pre-flight parsing plus a quota-clamped write budget, and the panel's own // POST /extract is throttled (serverFsMutateRateLimiter), so the node relay // must not be the unthrottled bypass. Rides the shared per-user upload budget // — the only limiter injected into this router (see setUploadPolicyHooks). // Issue 4: it now also verifies the same "POST /extract" token pair the panel // route checks (minted by GET /permissions as fileExtract), so the shipped // client attaches the same token in remote mode. app.post("/api/nodes/server/:name/extract", nodeUploadRateLimiterGate, requireNodeFileActionToken("POST /extract"), async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_create permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the body try below (which keeps its own catch) reads it. canOverwrite is // hoisted the same way. let ctx = null; let canOverwrite = false; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_create"))) { return res.status(403).json({ error: "permission denied", permission: "files_create" }); } // adpanel:extract-no-clobber - the daemon skips existing files unless the // request opts into overwrite, so overwrite is computed here from the // requester's permissions (files_write; admins pass checkUserPerm too), // never taken from the client body — same files_create/files_write split // as the panel's POST /extract and PUT /files/write. canOverwrite = await checkUserPerm(req, req.params.name, "files_write"); if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/extract] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const rel = String(req.body.path || ""); try { const full = safeJoinUnix(ctx.baseDir, rel); // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsExtractOutcome, spec §3 "relay" bodies): 507 // quota passthrough, 502 node_extract_failed, and the success msg with // this surface's own skipped===0 wording (json.msg || "Extracted" — spec // D20). 630000 = the daemon's 10-minute extract budget // (extractCallerWaitBudget) + 30s relay slack, the same slack doctrine // the backup relays keep: a copy completing just past the daemon's // boundary still receives its success response instead of being reported // as a panel-side failure. (A short cutoff aborted the relay mid-archive // while the daemon completed the extraction anyway, so the user saw // node_extract_failed and a retry re-executed the whole extraction.) const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/extract", { path: full, server: ctx.nodeServerName, overwrite: canOverwrite }, 630000, { method: nodeNoClobberMethod(!canOverwrite) }); const out = renderFsExtractOutcome(outcome, { variant: "relay", noClobber: !canOverwrite }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_extract", { path: rel }, userEmail, getRequestIp(req)); // The daemon answers 200 with ok:true even when it skipped existing files // (no-clobber mode), so this stays a 200 — the skipped count and the // surfaced msg are data for the client, not a failure. return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); // Same limiter gate as the upload relays (see the extract note above): the // panel's own POST /archive is throttled, so the node relay must not be the // unthrottled bypass. Issue 4: it also verifies the same "POST /archive" token // pair the panel route checks (minted as fileArchive). app.post("/api/nodes/server/:name/archive", nodeUploadRateLimiterGate, requireNodeFileActionToken("POST /archive"), async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_archive permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the validation and body tries below (which keep their own catches) read // it, and the sync paths/destDir checks keep their positions after the // guards. let ctx = null; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_archive"))) { return res.status(403).json({ error: "permission denied", permission: "files_archive" }); } if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/archive] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } const paths = req.body.paths; const destDir = String(req.body.destDir || ""); if (!Array.isArray(paths) || paths.length === 0) { return res.status(400).json({ error: "missing paths" }); } if (paths.length > 1000) { return res.status(400).json({ error: "too many paths (max 1000)" }); } // #4 belt-and-suspenders: the per-server node endpoint already re-confines // every path under the server root, but we also validate at the panel boundary // so traversal/NUL/absolute inputs are rejected here regardless of which node // endpoint they are ever routed to. We forward the original RELATIVE paths // (the node prefixes its own server root); we only use safeJoinUnix as a // throw-on-violation validator against the resolved baseDir. const cleanPaths = []; try { for (const p of paths) { const rel = String(p || ""); if (!rel) continue; safeJoinUnix(ctx.baseDir, rel); // throws on traversal / NUL / absolute cleanPaths.push(rel); } if (destDir) safeJoinUnix(ctx.baseDir, destDir); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } if (cleanPaths.length === 0) { return res.status(400).json({ error: "missing paths" }); } try { // adpanel:archive-relay-name — the node sanitizes the URL segment with its // own sanitizer, so the canonical panel form must be what travels (raw // req.params.name input must not): build the segment from the same // getCanonicalServerName value the activity log below records, falling // back to the raw param only if the canonical form came back empty. The // dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsArchiveOutcome, spec §3 "relay" bodies — verified // byte-identical to the panel's: the failure body relays the daemon's own // error text). 330000 = the daemon's 5-minute archive budget // (archiveCallerWaitBudget) + 30s relay slack, the same slack doctrine // the backup relays keep: a walk completing just past the daemon's // boundary still receives its success response instead of being reported // as a panel-side failure. const canonicalArchiveName = getCanonicalServerName(ctx.server, req.params.name) || req.params.name; const outcome = await relayFsJson( NODES_FS_RELAY_DEPS, ctx.node, `/v1/servers/${encodeURIComponent(canonicalArchiveName)}/files/archive`, { paths: cleanPaths, destDir }, 330000 ); const out = renderFsArchiveOutcome(outcome, { variant: "relay" }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_archive", { paths, destDir, archiveName: out.json.name }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); // Rate limiter gate for SEVEN node-proxy routes (see their route comments // and the mount pins in tests/node-relay-backups-action-token.test.js): the // extract and archive relays, POST /upload, POST /upload-url and the three // mutating backups relays (adpanel:backup-relay-brake). It resolves the // injected limiter (index.js serverFsUploadRateLimiter — the SAME instance // POST /upload uses, so all seven routes draw from one per-user budget) // per-request, because nodes.js routes are registered before index.js // finishes its startup injection. Like every injected hook on this module // the gate fails CLOSED: without the hook every upload is rejected with the // limiter's own 429 shape instead of proceeding unthrottled (see the // fail-closed note on setUploadPolicyHooks). function nodeUploadRateLimiterGate(req, res, next) { const limiter = _uploadRateLimiter; if (!limiter) { // Mirror the rejection handler of index.js serverFsUploadRateLimiter so // clients see one 429 shape whether the budget is exhausted or the hook // was never injected. return res.status(429).json({ error: "Too many upload attempts, slow down." }); } return limiter(req, res, next); } // adpanel:backups-list-brake — read brake for GET /api/nodes/server/:name/backups // ONLY (the three mutating backups relays keep their own nodeUploadRateLimiterGate // mount — their budgets are deliberately shared with the upload routes'). Every // list request dials the node daemon with a 15s budget and triggers the daemon's // orphan-backup sweep, and the global throttles are no-ops on the shipped // default (security.rate_limiting is false in security.json), so without this // brake a backups_view holder could stream unbounded panel→node list dials — // the same class the scheduler read brake (index.js // schedulerTasksReadRateLimiter) exists for. The limiter itself is ALWAYS-ON // and account-keyed in index.js (nodeBackupsListRateLimiter, own // "node-backups-list:" store instance + prefix); it rides the SAME injected // hook surface as the upload gate (setUploadPolicyHooks) because nodes.js // routes register before index.js finishes startup injection. Fails CLOSED // like every injected hook on this module: without the hook every list is // rejected with the limiter's own 429 shape instead of proceeding unbraked. function nodeBackupsListRateLimiterGate(req, res, next) { const limiter = _backupsListRateLimiter; if (!limiter) { // Mirror the rejection handler of index.js nodeBackupsListRateLimiter so // clients see one 429 shape whether the budget is exhausted or the hook // was never injected. return res.status(429).json({ error: "Too many backups list requests, slow down." }); } return limiter(req, res, next); } // Action-token gate for the node-proxy upload routes, bound to the exact same // action/resource pair the client already mints for POST /upload // ("POST /upload" + {serverName}) — GET /api/servers/:name/permissions hands // out one fileUpload token that covers both routes, so the shipped client only // needs to attach it in remote mode too (public/js/bot.js). This kills the // cookie-authenticated CSRF path: a forged cross-site POST cannot read the // token, and index.js's verifyActionToken additionally binds it to the // session id. The URL uploader reuses this same gate: the panel's own // POST /upload-url verifies the exact same pair. Delegates to index.js // requireActionTokenOr403, which sends the canonical // 403 { error, code: "ACTION_TOKEN_INVALID" } on failure; when the // hook is missing this gate fails closed with the same shape. async function requireNodeUploadActionToken(req, res, next) { const ok = typeof _requireActionTokenOr403 === "function" && await _requireActionTokenOr403(req, res, "POST /upload", { serverName: String(req.params.name || "").trim() }); if (ok) return next(); if (!res.headersSent) { return res.status(403).json({ error: "invalid or missing action token", code: "ACTION_TOKEN_INVALID" }); } } // Issue 4: same gate pattern as requireNodeUploadActionToken, parameterized by // the action pair the caller mints. Every file-mutation relay verifies the // exact mint/verify pair its panel-side twin uses, so the tokens GET // /api/servers/:name/permissions hands out cover both the local route and the // relay (the backups relays reuse this same gate with their own fresh-minted // pairs, see their route comments): // /delete + /delete-batch → fileDelete ("DELETE /api/servers/:name/files/delete") // /rename → fileRename ("POST /api/servers/:name/files/rename") // /extract → fileExtract ("POST /extract") // /archive → fileArchive ("POST /archive") // /file → fileWrite ("PUT /api/servers/:name/files/write") // /create → fileMkdir ("POST /api/servers/:name/files/mkdir", // the same pair the panel's legacy POST /create verifies) // /delete-batch consumes ONE token for the whole batch call; the shipped client // loops single deletes and mints per entry (its fileDelete mint is one-time), // so both callers draw from the same verified pair. Fails closed like the // upload gate when the hook is missing, with the identical rejection shape. function requireNodeFileActionToken(action) { return async function (req, res, next) { const ok = typeof _requireActionTokenOr403 === "function" && await _requireActionTokenOr403(req, res, action, { serverName: String(req.params.name || "").trim() }); if (ok) return next(); if (!res.headersSent) { return res.status(403).json({ error: "invalid or missing action token", code: "ACTION_TOKEN_INVALID" }); } }; } app.post("/api/nodes/server/:name/upload", nodeUploadRateLimiterGate, requireNodeUploadActionToken, async (req, res) => { // Pre-flight guard: the remote-context resolution, access check and // files_upload permission are DB-backed and previously had no catch beneath // them — Express 4 does not catch async-handler rejections, so any DB // rejection here hung the request and only fed the process-level // unhandledRejection log. Same per-route guard as the panel's /upload-url: // the client gets a generic 500 and the full error stays in the server log. // The original order (context before access) is preserved; ctx is hoisted so // the busboy callbacks read it, and the multipart stream section keeps its // own respond()/error handling, untouched outside this guard. let ctx = null; let createOnly = true; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_upload"))) { return res.status(403).json({ error: "permission denied", permission: "files_upload" }); } createOnly = !(await checkUserPerm(req, req.params.name, "files_write")); if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); } catch (err) { console.error("[/api/nodes/server/:name/upload] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } let fileSeen = false; let responded = false; let uploadPromise = null; const nodeMaxMb = nodeUploadLimitMb(ctx.node); const nodeMaxBytes = nodeMaxMb * 1024 * 1024; const respond = (status, payload) => { if (responded || res.headersSent) return; responded = true; res.status(status).json(payload); }; const multipart = createUploadMultipartParser(require("busboy"), req, respond, (err) => console.warn("[node-upload-relay] multipart parse error:", err)); if (!multipart) return; const { parser: bb, fields } = multipart; bb.on("file", (name, fileStream) => { if (responded) { fileStream.resume(); return; } if (name !== "file") { fileStream.resume(); return; } if (fileSeen) { fileStream.resume(); respond(400, { error: "too_many_files" }); return; } fileSeen = true; const rel = String(fields.path || ""); // Same upload policy as POST /upload (index.js): sanitize the client // filename first, then enforce the operator's extension allow/block list // on the sanitized name, and relay the sanitized name — exactly the chain // the panel-side route uses, so the policy cannot be dodged by sending the // upload through the node proxy instead. Busboy's files:1 limit plus the // fileSeen guard mean at most one file entry reaches here, and every file // entry is checked before any bytes are relayed. Fail closed when the // panel did not inject the hooks (see setUploadPolicyHooks). const safeFilename = _sanitizeUploadFilename ? _sanitizeUploadFilename(fields.filename) : null; if (!safeFilename) { fileStream.resume(); respond(400, { error: "Invalid filename" }); return; } if (!_isUploadExtensionAllowed || !_isUploadExtensionAllowed(safeFilename)) { fileStream.resume(); respond(400, { error: "file-type-not-allowed" }); return; } uploadPromise = (async () => { const full = safeJoinUnix(ctx.baseDir, rel ? rel : ""); // adpanel:upload-quota - only the daemon can check actual file bytes under the storage lock. if (responded || fileStream.destroyed) return null; return streamUploadToNode(ctx.node, fileStream, safeFilename, full, nodeMaxBytes, nodeMaxMb, ctx.nodeServerName, createOnly); })(); uploadPromise.then((result) => { if (responded || !result) return; const failure = renderCreateOnlyUploadFailure(result, createOnly); if (failure) return respond(failure.status, failure.json); if (isNodeQuota507(result.status, result.json)) { respond(507, result.json); return; } if (result.status === 413) { respond(413, result.json || { error: "file_too_large", message: `File exceeds this node's upload limit of ${nodeMaxMb} MB`, limit_mb: nodeMaxMb, }); return; } if (result.status !== 200 || !result.json || !result.json.ok) { respond(502, { error: "node_upload_failed", detail: result.json?.error }); return; } const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), "file_upload", { path: rel, filename: safeFilename }, userEmail, getRequestIp(req)); respond(200, { ok: true, msg: result.json.msg || "Uploaded" }); }).catch((e) => { respond(400, { error: maskPathErrorMessage(e) }); }); }); bb.on("finish", () => { if (!responded && !fileSeen) { respond(400, { error: "no_file" }); } }); req.pipe(bb); }); // ============= URL Uploader (remote node) ============= // URL validation for the upload-url relay below runs through the PANEL's own // SSRF validator (utils/remote-url-guard.js, required at the top of this // module) instead of a private copy. The node daemon independently // re-validates URL, ports and resolved IPs at connect time // (main.go uploadURLPortAllowed + its private-IP checks), but the pre-flight // here must agree with the panel's own validator — site-local fec0::/10, // multicast ff00::/8, NAT64 64:ff9b::/96, the TEST-NETs and the 80/443 port // allowlist (REMOTE_FETCH_ALLOW_ANY_PORT escape hatch honored identically) — // so a copy that lags the panel cannot come back. // The URL uploader rides the same two gates as the direct upload relay: the // shared per-user upload rate limiter and the session-bound action token (the // panel's own POST /upload-url verifies "POST /upload" + {serverName} — the // exact pair requireNodeUploadActionToken checks). Fail closed when the panel // did not inject the hooks (see setUploadPolicyHooks). app.post("/api/nodes/server/:name/upload-url", nodeUploadRateLimiterGate, requireNodeUploadActionToken, async (req, res) => { // Pre-flight guard: the remote-context resolution, access check, files_upload // permission and the SSRF url validation are DB/network-backed and // previously had no catch beneath them — Express 4 does not catch // async-handler rejections, so any rejection here hung the request and only // fed the process-level unhandledRejection log. Same shape as the panel's // own POST /upload-url: the client gets a generic 500 and the full error // stays in the server log. The sync url 400s stay inside the guard, in their // original positions after the auth checks; ctx/rel/urlFilename/validatedUrl // are hoisted so the body try below (which keeps its own catch) reads them. let ctx = null; let rel = ""; let urlFilename = null; let validatedUrl = null; let createOnly = true; try { ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_upload"))) { return res.status(403).json({ error: "permission denied", permission: "files_upload" }); } createOnly = !(await checkUserPerm(req, req.params.name, "files_write")); if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); const rawUrl = String(req.body?.url || "").trim(); rel = String(req.body?.path || ""); if (!rawUrl) return res.status(400).json({ error: "missing url" }); if (rawUrl.length > 2048) return res.status(400).json({ error: "url too long" }); // Same extension policy as the panel's POST /upload-url (index.js), in the // same order: parse + protocol check first, then derive the target filename // from the URL's last path segment, sanitize it, and run it through the // operator's allow/block lists — so a blocked file type cannot be pulled in // through the node proxy instead, and the decision happens before any DNS or // network work. The approved name is forwarded to the daemon as `filename` // so the stored spelling is exactly the one this policy saw — a hostile // origin cannot smuggle a blocked type past it via Content-Disposition. // The daemon re-sanitizes the field and only lets it override its own // Content-Disposition-derived name when it is non-empty. Fail closed // when the panel did not inject the hooks (see setUploadPolicyHooks). let parsedInputUrl; try { const normalizedUrl = /^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\//.test(rawUrl) ? rawUrl : `https://${rawUrl}`; parsedInputUrl = new URL(normalizedUrl); } catch (err) { return res.status(400).json({ error: "invalid_url", message: "Invalid URL" }); } if (parsedInputUrl.protocol !== "http:" && parsedInputUrl.protocol !== "https:") { return res.status(400).json({ error: "invalid_url", message: "Only http(s) URLs are allowed" }); } let rawName = String(parsedInputUrl.pathname || "").split("/").filter(Boolean).pop() || ""; try { rawName = decodeURIComponent(rawName); } catch { } urlFilename = _sanitizeUploadFilename ? (_sanitizeUploadFilename(rawName) || "download.bin") : null; if (!urlFilename) { return res.status(400).json({ error: "Invalid filename" }); } if (!_isUploadExtensionAllowed || !_isUploadExtensionAllowed(urlFilename)) { return res.status(400).json({ error: "file-type-not-allowed" }); } try { // The panel's own validator (assertSafeRemoteUrlWithResolvedIp, shared // via utils/remote-url-guard.js): parse + protocol + credentials + // localhost + 80/443 port allowlist + full private-address resolution // checks, including the site-local/multicast/NAT64 IPv6 ranges and the // reject-any-private-answer rule. The daemon re-validates URL, ports and // resolved IPs at connect time; this pre-flight agrees with the panel's // own gate instead of a weaker local copy. resolvedIp is intentionally // unused here — the daemon does its own resolution and pins it at // connect time, so the panel cannot pin for it. const validated = await remoteUrlGuard.assertSafeRemoteUrlWithResolvedIp(parsedInputUrl.toString()); validatedUrl = validated.url; } catch (err) { return res.status(400).json({ error: "invalid_url", message: err.message || "Invalid URL" }); } } catch (err) { console.error("[/api/nodes/server/:name/upload-url] pre-flight failed:", err); if (!res.headersSent) return res.status(500).json({ error: "internal error" }); return; } try { const full = safeJoinUnix(ctx.baseDir, rel); // This socket-inactivity timeout must stay ABOVE the daemon's response // schedule for /v1/fs/uploadUrl: 30m fetch budget (uploadURLFetchTimeout) // + 2m commit/response headroom (uploadURLResponseHeadroom), + 1m margin // here. If the relay gives up first, a download that finishes near the // budget line commits on the daemon and still reaches the user as a 502, // inviting a retry of an upload that already succeeded. const result = await httpJson( nodeUrl(ctx.node, "/v1/fs/uploadUrl"), { method: nodeNoClobberMethod(createOnly), headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { dir: full, server: ctx.nodeServerName, url: validatedUrl.toString(), filename: urlFilename }, timeoutMs: 33 * 60 * 1000 } ); const { status, json } = result; const failure = renderCreateOnlyUploadFailure(result, createOnly); if (failure) return res.status(failure.status).json(failure.json); if (isNodeQuota507(status, json)) { return res.status(507).json(json); } if (status === 413 && json) { return res.status(413).json(json); } if (status !== 200 || !json || json.ok !== true) { const msg = (json && (json.error || json.message)) || `node_upload_url_failed (HTTP ${status})`; return res.status(502).json({ error: "node_upload_url_failed", message: msg }); } const userEmail = req.session?.user || "unknown"; recordActivity( getCanonicalServerName(ctx.server, req.params.name), "file_upload_url", // Presigned URLs (S3/GCS/Azure/CDN) embed signature/token credentials in // the query string — persisting the full URL would leak live credentials // into the activity log. The audit trail needs origin+path only (this // also drops the fragment); the daemon still gets the full URL above to // perform the actual fetch. { path: rel, url: validatedUrl.origin + validatedUrl.pathname, filename: json.filename || null, size: json.bytes || null }, userEmail, getRequestIp(req) ); return res.json({ ok: true, msg: json.msg || "Uploaded from URL", filename: json.filename || null, bytes: json.bytes || null }); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } }); // ============= /URL Uploader ============= async function startPayloadFor(name, server = null) { const srv = server || await findServerByNameOrId(name); const conflict = getReinstallPowerConflict(srv); if (conflict) return { conflict }; const chosenPort = validatePortInput(srv?.hostPort ?? srv?.port ?? srv?.server_port); return { payload: chosenPort == null ? {} : { hostPort: chosenPort } }; } async function seedRuntimeOnNode(node, srv) { try { const tpl = String(srv?.template || "").toLowerCase(); const isMinecraft = tpl === "minecraft"; const isRuntimeTemplate = ["nodejs", "python", "discord-bot"].includes(tpl); if (srv && tpl && !isMinecraft && isRuntimeTemplate) { const runtimePayload = { runtime: srv.runtime || {}, template: tpl, start: srv.start || srv.startFile || srv.entry || null, port: srv.hostPort || srv.port || srv.server_port || null, nodeId: node?.uuid || node?.id || null, }; // adpanel:daemon-dial-canonical — dial the canonical storage name // (sanitizeNodeStorageName(srv.name), the exact derivation remoteContext uses for // ctx.nodeServerName), not the caller's alias: the daemon derives // identity from the URL key, so legacy_id/bot access would seed a // nonexistent server. await callNodeApi( node, `/v1/servers/${encodeURIComponent(sanitizeNodeStorageName(srv.name))}/runtime`, "POST", runtimePayload, LONG_NODE_TIMEOUT_MS ).catch(() => { }); } } catch (_) { } } async function performPanelServerAction(req, serverName, cmdRaw, expectedServerId) { const targetServer = String(serverName || "").trim(); const cmdValue = String(cmdRaw || "").toLowerCase(); const cmd = (cmdValue === "run") ? "start" : cmdValue; const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const ctx = await remoteContext(targetServer, expectedServerId); if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; if (isServerSuspended(ctx.server)) return suspendedServerResult(ctx.server); let requiredPerms = ["server_start"]; if (cmd === "start") requiredPerms = ["server_start"]; else if (cmd === "restart") requiredPerms = ["server_stop", "server_start"]; else if (cmd === "stop" || cmd === "kill") requiredPerms = ["server_stop"]; else if (cmd === "status") requiredPerms = []; else return { status: 400, body: { error: "invalid_cmd" } }; for (const requiredPerm of requiredPerms) { if (!(await checkUserPerm(req, targetServer, requiredPerm))) { return { status: 403, body: { error: "permission denied", permission: requiredPerm } }; } } if (cmd !== "status") { const conflict = getReinstallPowerConflict(await findServerByNameOrId(targetServer)); if (conflict) return conflict; } // adpanel:daemon-dial-canonical — the daemon derives identity from the URL // key (main.go dispatch: name := sanitizeName(parts[0]); the server dir and // the container are both built from it), so every server-scoped dial must // carry the resolved canonical storage name (ctx.nodeServerName), not the // request alias — legacy_id/bot (or legacy-row) access otherwise passes // every check above and then lands on a nonexistent container/dir: spurious // 404s/failures for exactly the users the backup relays were canonicalized // for (adpanel:backup-dial-canonical). The auth, suspension and permission // checks above stay on targetServer — they resolve canonically in the DB // already. Same constraint as the seedRuntimeOnNode /runtime dial on the // start path, the eula/eula-accept/command performers, the logs relay and // the settings resources save/fetch routes (index.js derives the same // storage-name form from the serverEntry it already resolved there), and // the socket action/command handlers (index.js derives it from the row // their findServer match resolved, for their action dials and the // watcher/tail seeds, while rooms and emits stay on the alias). const dialName = ctx.nodeServerName; let path = null; let method = "POST"; if (cmd === "start") { path = `/v1/servers/${encodeURIComponent(dialName)}/start?wait=false`; } else if (cmd === "stop") { path = `/v1/servers/${encodeURIComponent(dialName)}/stop`; } else if (cmd === "kill") { path = `/v1/servers/${encodeURIComponent(dialName)}/kill`; } else if (cmd === "restart") { path = `/v1/servers/${encodeURIComponent(dialName)}/restart`; } else if (cmd === "status") { method = "GET"; path = `/v1/servers/${encodeURIComponent(dialName)}`; } if (cmd !== "status") { const actionMap = { start: "server_start", stop: "server_stop", restart: "server_restart", kill: "server_kill" }; const actionName = actionMap[cmd] || `server_${cmd}`; const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, targetServer), actionName, null, userEmail, getRequestIp(req)); } const timeoutMs = cmd === "start" ? LONG_NODE_TIMEOUT_MS : DEFAULT_NODE_TIMEOUT_MS; const power = cmd === "start" || cmd === "restart" ? await withServerPowerStart({ findServer: findServerByNameOrId }, ctx.server, async (server) => { if (cmd !== "start") return callNodeApi(ctx.node, path, method, null, timeoutMs); await seedRuntimeOnNode(ctx.node, server); const { payload } = await startPayloadFor(targetServer, server); return callNodeApi(ctx.node, path, method, payload, timeoutMs); }) : { result: await callNodeApi(ctx.node, path, method, null, timeoutMs) }; if (power.conflict) return power.conflict; const { status, json, error } = power.result; if (status === 0 && cmd !== "status") { return { status: 502, body: { error: "server_action_result_unconfirmed", detail: "The node did not confirm the power action. Check the server state before retrying.", } }; } // Structured node rejections (e.g. the Minecraft EULA gate, or the op-lock's // backup_in_progress / reinstall_in_progress / runtime_seed_in_progress / // server_op_in_progress refusals) are passed through so the caller can react // (console popup / retry-after message) instead of being masked behind a // generic 502 node_action_failed. if (status === 409 && json && (json.code === "minecraft_eula_required" || json.code === "backup_in_progress" || json.code === "reinstall_in_progress" || json.code === "runtime_seed_in_progress" || json.code === "server_op_in_progress" || json.code === "server_stop_in_progress" || json.code === "server_already_running")) { return { status: 409, body: json }; } if ((status === 200 || status === 202) && json && (json.ok === true || json.ok === undefined)) { if (_serverActionObserver && cmd !== "status") { try { await _serverActionObserver({ req, serverName: targetServer, action: cmd, result: json || { ok: true } }); } catch (observerErr) { console.warn("[nodes-action] observer failed:", observerErr?.message || observerErr); } } return { status: 200, body: json || { ok: true } }; } const detail = (json && (json.detail || json.error || json.message)) || error || `HTTP ${status}`; console.warn(`[nodes-action] ${targetServer} ${cmd} failed: status=${status} detail=${String(detail)}`); return { status: 502, body: { error: "node_action_failed", status, detail, response: json || null, }, }; } // performPanelEulaAccept writes eula=true on the node for a Minecraft server. // The node endpoint only exists for servers it identifies as Minecraft (fixed // eula.txt path inside the server dir), and the panel restricts the call to // users that are allowed to write files on that server. // adpanel:eula-start-permission - consent must not start a server; the // regular power action owns server_start authorization and status updates. async function performPanelEulaAccept(req, serverName) { const targetServer = String(serverName || "").trim(); // Authenticate BEFORE resolving the server (same ordering rationale as // performPanelEulaStatus — no unauthenticated existence oracle). const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const ctx = await remoteContext(targetServer); if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; if (isServerSuspended(ctx.server)) return suspendedServerResult(ctx.server); // Accepting the EULA writes eula.txt into the server files, so it requires // the same capability as writing files (admins pass implicitly). const writeMode = await resolveFsWriteMode(req, targetServer); if (!writeMode.ok) { return { status: 403, body: { error: "permission denied", permission: "files_write" } }; } // adpanel:daemon-dial-canonical — dial ctx.nodeServerName, not the request // alias (see performPanelServerAction). const { status, json } = await callNodeApi( ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/eula-accept`, // adpanel:eula-write-mode - a legacy node ignoring mode must refuse the // method, not fall back to a write the caller was not granted. writeMode.mode ? "PUT" : "POST", writeMode.mode ? { autostart: false, mode: writeMode.mode } : { autostart: false } ); if (status === 200 && json && json.ok) { const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, targetServer), "minecraft_eula_accept", null, userEmail, getRequestIp(req)); return { status: 200, body: json }; } if (status === 400 && json && json.error === "not_minecraft") { return { status: 400, body: json }; } if (status === 409 && json?.error === "eula_file_exists") { return { status: 403, body: { error: "permission denied", permission: "files_write", detail: "Editing the existing EULA file requires file edit permission." } }; } if (status === 404 && json?.error === "eula_file_missing") { return { status: 403, body: { error: "permission denied", permission: "files_create", detail: "Creating the EULA file requires file create permission." } }; } if (isNodeQuota507(status, json)) return { status, body: json }; return { status: 502, body: { error: "node_eula_accept_failed", status, detail: (json && (json.detail || json.error)) || `status ${status}`, }, }; } // performPanelEulaStatus reports whether the server still needs Minecraft EULA // consent so the console can show the prompt without waiting for a blocked // start attempt. Read-only; requires plain server access. async function performPanelEulaStatus(req, serverName) { const targetServer = String(serverName || "").trim(); // Authenticate BEFORE resolving the server: resolving first let an // unauthenticated caller distinguish existing servers (401) from // nonexistent ones (404) — a server-name existence oracle. checkServerAccess // answers before any server lookup, collapsing the distinction. (Same order // as performPanelListBackups.) const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const ctx = await remoteContext(targetServer); if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; // adpanel:daemon-dial-canonical — dial ctx.nodeServerName, not the request // alias (see performPanelServerAction). const { status, json } = await callNodeApi( ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/eula`, "GET" ); if (status === 200 && json && json.ok) return { status: 200, body: json }; return { status: 502, body: { error: "node_eula_status_failed", status, detail: (json && (json.detail || json.error)) || `status ${status}`, }, }; } async function performPanelConsoleCommand(req, serverName, rawCommand, requestId = "", expectedServerId) { const targetServer = String(serverName || "").trim(); // Authenticate BEFORE resolving the server (same ordering rationale as // performPanelEulaStatus — no unauthenticated existence oracle). const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const ctx = await remoteContext(targetServer, expectedServerId); if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; if (isServerSuspended(ctx.server)) return suspendedServerResult(ctx.server); if (!(await checkUserPerm(req, targetServer, "console_write"))) { return { status: 403, body: { error: "permission denied", permission: "console_write" } }; } const commandCheck = sanitizeConsoleCommand(rawCommand); if (!commandCheck.ok) { return { status: 400, body: { error: commandCheck.error, detail: commandCheck.detail || null } }; } const command = commandCheck.command; const commandRequestId = String(requestId || "").trim(); const userEmail = req.session?.user || "unknown"; recordActivity(getCanonicalServerName(ctx.server, targetServer), "console_command", { command }, userEmail, getRequestIp(req)); // adpanel:daemon-dial-canonical — dial ctx.nodeServerName, not the request // alias (see performPanelServerAction). const { status, json } = await callNodeApi( ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/command`, "POST", commandRequestId ? { command, requestId: commandRequestId } : { command } ); if (status === 200 && json && json.ok) return { status: 200, body: json }; return { status: 502, body: { error: "node_command_failed", status, detail: (json && (json.detail || json.error)) || `status ${status}`, }, }; } async function performPanelListBackups(req, serverName) { const targetServer = String(serverName || "").trim(); const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const suspendedResult = await resolveIfServerSuspended(targetServer); if (suspendedResult) return suspendedResult; if (!(await checkUserPerm(req, targetServer, "backups_view"))) { return { status: 403, body: { error: "forbidden", detail: "You do not have permission to view backups" } }; } const ctx = await remoteContext(targetServer); if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; // adpanel:backup-dial-canonical — the daemon derives storage from the URL // key (sanitizeName), so the dial must use the resolved canonical storage // name, not the request alias (legacy_id/bot access otherwise lands on a // nonexistent storage name: empty list / spurious 404s). The auth, // suspension and permission checks above stay on targetServer — they // resolve canonically in the DB already. const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/backups`); const { status, json, text } = await httpJson(url, { method: "GET", headers: nodeHeaders(ctx.node), timeoutMs: 15000 }); if (status === 0) { return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; } if (status !== 200 || !json || !json.ok) { // Daemon error bodies stay out of the client response (same disclosure // concern as create/restore/delete below): log the full error server-side // only and return a generic, user-safe detail. The `error` key is unchanged. console.warn(`[backups] List failed on node: server=${targetServer} node=${ctx.node.name || ctx.node.uuid} status=${status} detail=${String(json?.error || text || "no body")}`); return { status: 502, body: { error: "node_backup_list_failed", detail: "Backup list failed on node" } }; } return { status: 200, body: { ok: true, backups: json.backups || [] } }; } async function performPanelCreateBackup(req, serverName, backupName, description, expectedServerId) { const targetServer = String(serverName || "").trim(); const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const suspendedResult = await resolveIfServerSuspended(targetServer); if (suspendedResult) return suspendedResult; if (!(await checkUserPerm(req, targetServer, "backups_create"))) { return { status: 403, body: { error: "forbidden", detail: "You do not have permission to create backups" } }; } const ctx = await remoteContext(targetServer, expectedServerId); if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; // adpanel:backup-count-cap - refuse the create at the same ceiling the // scheduler enforces (index.js SCHEDULER_MAX_BACKUPS_PER_SERVER, mirrored // in MAX_BACKUPS_PER_SERVER below): count the server's existing backups // BEFORE the create and return 409 once the total reaches the cap. WHY // refuse and not prune: this relay's actor proved only backups_create, and // a backups_create holder must never be able to destroy other users' (or // scheduled) backups — destroying backups is backups_delete's job — so the // interactive path must never delete anything; refusing also matches the // scheduler's pre-create check and the daemon's backupsMax semantics. The // listing goes through listServerBackupsForHygiene (direct node GET with // one retry on failure). The count check fails OPEN after that retry // (listing outage => warn + proceed), identical precedence to the // scheduler's count check — backup availability beats the cap, and the // daemon's disk-quota 507 bounds disk growth meanwhile. let existingBackupCount = null; try { // adpanel:backup-dial-canonical — count the storage the create below // dials (the canonical name), not the request alias. const listed = await listServerBackupsForHygiene(ctx.node, ctx.nodeServerName); if (listed.ok) { existingBackupCount = listed.backups.length; } else { console.warn(`[backups] Backup count check unavailable for ${targetServer} (${listed.error}); proceeding with create`); } } catch (listErr) { console.warn(`[backups] Backup count check failed for ${targetServer}: ${listErr?.message || listErr}; proceeding with create`); } if (existingBackupCount !== null && existingBackupCount >= MAX_BACKUPS_PER_SERVER) { return { status: 409, body: { error: "backup_cap_reached", detail: `Server already has ${existingBackupCount} backups (limit ${MAX_BACKUPS_PER_SERVER}). Delete backups to make room (requires the backups_delete permission).`, }, }; } // Clamp name/description at the relay: name to 120 (AI-path parity; the UI // caps names at 100), description to 500 (matching the UI textarea // maxlength; the AI path separately pre-clamps to 280 before calling). // The daemon accepts bodies up to 1 MB and only TrimSpaces, so oversized // values would otherwise be persisted verbatim. // adpanel:log-injection-backup-name - the name/description reach // console.log, recordActivity (→ the Discord webhook dispatcher) and the // daemon's backup storage verbatim, so interior newlines and control // characters could forge log/activity/webhook lines downstream. Strips // C0/C1 controls at the validation boundary and collapses the whitespace // runs the strip leaves behind; the length cap is applied AFTER the strip // so control-padded names cannot slip by. Mirrors // adpanel:log-injection-task-name (index.js). Per the one-true-home rule // BOTH clamp copies (this interactive relay and the scheduler fire path, // index.js case "backup" — plus the AI arg pre-clamp in index.js // sanitizeBotToolArgs) carry the identical strip in the same change. // Empty-after-strip keeps today's behavior — the daemon defaults the name // to "Backup ". const safeName = String(backupName || "").trim().replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 120); const safeDescription = String(description || "").trim().replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 500); // adpanel:backup-dial-canonical — dial the canonical storage name (see // performPanelListBackups), not the request alias. const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/backups`); const { status, json, text } = await httpJson(url, { method: "POST", // adpanel:backup-cap-fallback — the daemon's count gate enforces this cap // only when the server meta lacks a positive resources.backupsMax (meta // wins unchanged when present), closing the overshoot window for // pre-feature servers. Sent as a request HEADER, not a JSON body field: // the daemon's readJSON rejects unknown body fields, so a body field // would break the create on an older daemon (rolling upgrade), while // unknown headers are ignored — backward-compatible in both directions. headers: Object.assign( { "Content-Type": "application/json", "X-ADPanel-Backups-Max": String(MAX_BACKUPS_PER_SERVER) }, nodeHeaders(ctx.node) ), body: { name: safeName, description: safeDescription }, // A backup create is a full copyDir of the server dir, the same cost // profile as /v1/fs/extract: match the extract precedent (630000 in the // extract relay below; index.js's extract relays pass 630000 too) so // big-server copies no longer outlive the relay and surface // as spurious 502s while the daemon keeps copying. The relay budget must // EXCEED the daemon's own backupCreateCallerWaitBudget (10 * time.Minute): // a copy finishing just past that boundary completes on the node but // would report failure here and drift the panel's accounting — same // 630000 slack the scheduler's backup call uses. timeoutMs: 630000, }); if (status === 0) { return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; } if (isNodeQuota507(status, json)) { return { status: 507, body: json }; } // Daemon 409 = the per-server backup op lock is already held (create/ // restore/delete in flight). Pass the daemon status/body through instead of // masking it as a generic 502 so the UI can surface "backup operation // already in progress" for an overlapping retry. if (status === 409 && json) { return { status: 409, body: json }; } // Daemon 403 = backup_limit_reached ({error, message, current, max}) and // 404 = server not found — the only 403/404 the backup endpoints write // (auth failures are 401 upstream), both structured id/limit-only bodies // with no node paths. Pass them through instead of masking as a generic // 502 so the UI can surface "backup limit reached" / "not found" as-is. if ((status === 403 || status === 404) && json && json.error) { return { status, body: json }; } if (status !== 200 || !json || !json.ok) { // The daemon's remaining error bodies can embed absolute node paths // ("failed to copy server files: ..."): keep the full error in the // server log only and return a generic, user-safe detail so the node // layout is never disclosed to end users. The `error` key is unchanged. console.warn(`[backups] Create failed on node: server=${targetServer} node=${ctx.node.name || ctx.node.uuid} status=${status} detail=${String(json?.error || text || "no body")}`); return { status: 502, body: { error: "node_backup_create_failed", detail: "Backup create failed on node" } }; } const userEmail = req.session?.user || "unknown"; const userIp = getRequestIp(req); recordActivity(getCanonicalServerName(ctx.server, targetServer), "backup_create", { backupId: json.backup?.id, name: json.backup?.name }, userEmail, userIp); return { status: 200, body: { ok: true, backup: json.backup } }; } async function performPanelRestoreBackup(req, serverName, backupIdRaw, deleteOldFiles, expectedServerId) { const targetServer = String(serverName || "").trim(); const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const suspendedResult = await resolveIfServerSuspended(targetServer); if (suspendedResult) return suspendedResult; if (!(await checkUserPerm(req, targetServer, "backups_create"))) { return { status: 403, body: { error: "forbidden", detail: "You do not have permission to restore backups" } }; } const ctx = await remoteContext(targetServer, expectedServerId); if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; const backupId = String(backupIdRaw || "").trim(); if (!backupId) return { status: 400, body: { error: "missing backup id" } }; // adpanel:backup-dial-canonical — dial the canonical storage name (see // performPanelListBackups), not the request alias. const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/backups/${encodeURIComponent(backupId)}/restore`); const { status, json, text } = await httpJson(url, { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { deleteOldFiles: !!deleteOldFiles }, // A restore optionally wipes the server dir and copies the whole backup // back — the longest copy the panel relays. Match the largest generic // long-copy precedent (index.js transfer upload streaming, 30 * 60 * 1000). // The only larger node timeout is the upload-url relay's 33 min, which is // budget-derived for /v1/fs/uploadUrl's documented 30m fetch + headroom, // not a file-copy op. 1830000 = the daemon's own backupRestoreCallerWaitBudget // (30 * time.Minute) + the same 30s slack the create relay keeps over its // daemon budget, so a copy finishing just past the daemon's boundary // completes on the node but would report failure here and drift the // panel's accounting. timeoutMs: 1830000, }); if (status === 0) { return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; } if (isNodeQuota507(status, json)) { return { status: 507, body: json }; } // Daemon 409 = the per-server backup op lock is already held (create/ // restore/delete in flight). Pass the daemon status/body through instead of // masking it as a generic 502 so the UI can surface "backup operation // already in progress" for an overlapping retry. if (status === 409 && json) { return { status: 409, body: json }; } // Daemon 404 = backup not found (wrong or concurrently deleted id) — a // structured id-only body with no node paths; 403 is accepted symmetrically // (no backup endpoint writes a 403 with sensitive content today). Pass both // through instead of masking as a generic 502 so the UI can surface "backup // not found" as-is. if ((status === 403 || status === 404) && json && json.error) { return { status, body: json }; } if (status !== 200 || !json || !json.ok) { // The daemon's remaining error bodies can embed absolute node paths // ("failed to restore backup: ..."): keep the full error in the // server log only and return a generic, user-safe detail so the node // layout is never disclosed to end users. The `error` key is unchanged. console.warn(`[backups] Restore failed on node: server=${targetServer} node=${ctx.node.name || ctx.node.uuid} status=${status} detail=${String(json?.error || text || "no body")}`); return { status: 502, body: { error: "node_backup_restore_failed", detail: "Backup restore failed on node" } }; } const userEmail = req.session?.user || "unknown"; const userIp = getRequestIp(req); recordActivity(getCanonicalServerName(ctx.server, targetServer), "backup_restore", { backupId, deleteOldFiles: !!deleteOldFiles }, userEmail, userIp); return { status: 200, body: { ok: true } }; } async function performPanelDeleteBackup(req, serverName, backupIdRaw, expectedServerId) { const targetServer = String(serverName || "").trim(); const accessCheck = await checkServerAccess(req, targetServer); if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; const suspendedResult = await resolveIfServerSuspended(targetServer); if (suspendedResult) return suspendedResult; if (!(await checkUserPerm(req, targetServer, "backups_delete"))) { return { status: 403, body: { error: "forbidden", detail: "You do not have permission to delete backups" } }; } const ctx = await remoteContext(targetServer, expectedServerId); if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; const backupId = String(backupIdRaw || "").trim(); if (!backupId) return { status: 400, body: { error: "missing backup id" } }; // adpanel:backup-dial-canonical — dial the canonical storage name (see // performPanelListBackups), not the request alias. const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(ctx.nodeServerName)}/backups/${encodeURIComponent(backupId)}`); const { status, json, text } = await httpJson(url, { method: "DELETE", headers: nodeHeaders(ctx.node), // The daemon's os.RemoveAll of a large backup is disk-bound and can // outlive a 30s relay; match the files-archive relay's 330000 (the // archive-relay 330s precedent) so a slow delete no longer // surfaces as a spurious 502. 330000 = the daemon's own // backupDeleteCallerWaitBudget (5 * time.Minute) + the same 30s slack the // create relay keeps over its daemon budget, so a delete finishing just // past the daemon's boundary completes on the node but would report // failure here and drift the panel's accounting. timeoutMs: 330000, }); if (status === 0) { return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; } // Daemon 409 = the per-server backup op lock is already held (create/ // restore/delete in flight). Pass the daemon status/body through instead of // masking it as a generic 502 so the UI can surface "backup operation // already in progress" for an overlapping retry. if (status === 409 && json) { return { status: 409, body: json }; } // Daemon 404 = backup not found (wrong or already deleted id) — a // structured id-only body with no node paths; 403 is accepted symmetrically // (no backup endpoint writes a 403 with sensitive content today). Pass both // through instead of masking as a generic 502 so the UI can surface "backup // not found" as-is. if ((status === 403 || status === 404) && json && json.error) { return { status, body: json }; } if (status !== 200 || !json || !json.ok) { // Daemon error bodies stay out of the client response (same disclosure // concern as create/restore above): log the full error server-side only // and return a generic, user-safe detail. The `error` key is unchanged. console.warn(`[backups] Delete failed on node: server=${targetServer} node=${ctx.node.name || ctx.node.uuid} status=${status} detail=${String(json?.error || text || "no body")}`); return { status: 502, body: { error: "node_backup_delete_failed", detail: "Backup delete failed on node" } }; } const userEmail = req.session?.user || "unknown"; const userIp = getRequestIp(req); recordActivity(getCanonicalServerName(ctx.server, targetServer), "backup_delete", { backupId }, userEmail, userIp); return { status: 200, body: { ok: true } }; } // ─── adpanel:backup-count-cap: shared panel-side backup hygiene ───────────── // Mirrors index.js SCHEDULER_MAX_BACKUPS_PER_SERVER (same env override, same // built-in 50): the interactive create relay refuses at the ceiling the // scheduler enforces, so the two paths cannot disagree about the cap. The // pre-2026-11 interactive behavior PRUNED to this cap after a successful // create — removed deliberately: the relay's actor proves only // backups_create, and a backups_create holder must never be able to destroy // other users' (or scheduled) backups — deleting backups is backups_delete's // job. Refuse-at-cap also matches the scheduler's pre-create count check and // the daemon's backupsMax quota semantics: all three ceilings now refuse, // none prune. const MAX_BACKUPS_PER_SERVER = (() => { const configured = Number(process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER); return Number.isInteger(configured) && configured > 0 ? configured : 50; })(); // GET the server's backup list from the node with one retry on failure — // both the scheduler's pre-create count check (index.js case "backup") and // the interactive create relay's pre-create cap check (above) need this // list, and a transient node hiccup used to silently disable the cap // (fail-open). Direct node-API calls (httpJson + // nodeHeaders) instead of performPanelListBackups: the performers require a // session req, which the scheduler worker does not have. serverName is // dialed verbatim — callers MUST pass the resolved canonical storage name // (ctx.nodeServerName; adpanel:backup-dial-canonical), never the request // alias. Returns // { ok: true, backups } or { ok: false, error }; never throws. async function listServerBackupsForHygiene(node, serverName) { const targetServer = String(serverName || "").trim(); if (!node || !targetServer) return { ok: false, error: "missing node or server" }; const url = nodeUrl(node, `/v1/servers/${encodeURIComponent(targetServer)}/backups`); let lastError = "list failed"; for (let attempt = 0; attempt < 2; attempt += 1) { try { const { status, json } = await httpJson(url, { method: "GET", headers: nodeHeaders(node), timeoutMs: 15000 }); if (status === 200 && json?.ok) { // A 200-ok body is a successful listing even when the daemon omits // the array: count it as empty (performPanelListBackups' // json.backups || [] semantics) instead of fail-open unknown, so a // malformed body cannot silently disable the cap. return { ok: true, backups: Array.isArray(json.backups) ? json.backups : [] }; } lastError = `list status ${status}`; } catch (err) { lastError = err?.message || String(err); } } return { ok: false, error: lastError }; } // Relay a performer { status, body } result to the HTTP client. Suspension // refusals (423) carry the same no-store contract as the direct-route 423s. function relayPanelResult(res, result) { if (result && result.status === 423) { res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); } return res.status(result.status).json(result.body); } app.post("/api/nodes/server/:name/action", async (req, res) => { try { const result = await performPanelServerAction(req, req.params.name, req.body && (req.body.cmd || req.body.action)); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — the 500 detail must stay path/credential-free. // These relays' pre-flight chains unwrap DB-backed legs (access check, // suspension gate, remote-context), so a raw e.message here can surface // mysql2 text (internal host/port, user fragments, ER_*) to any // authenticated user. The body keeps the bridge_failed contract with a // generic detail; the full error is logged server-side only — same // posture as the [/api/nodes] and /info pre-flight catches and the // delete-batch backstop. console.error("[/api/nodes/server/:name/action] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); app.post("/api/nodes/server/:name/eula/accept", async (req, res) => { try { const result = await performPanelEulaAccept(req, req.params.name); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/server/:name/eula/accept] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // Same cross-site read guard as the file relays (utils/cross-site-read-guard.js): // the EULA status is a session-facing file read (eula.txt), so it rejects // exactly what they reject. app.get("/api/nodes/server/:name/eula", rejectCrossSiteRead, async (req, res) => { try { const result = await performPanelEulaStatus(req, req.params.name); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/server/:name/eula] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); app.post("/api/nodes/server/:name/command", async (req, res) => { try { const result = await performPanelConsoleCommand(req, req.params.name, req.body && req.body.command, req.body && req.body.requestId); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/server/:name/command] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); app.post("/api/nodes/:id/server/action", async (req, res) => { try { const name = String((req.body && req.body.name) || "").trim(); const cmd = String((req.body && req.body.cmd) || "").trim(); if (!name || !cmd) return res.status(400).json({ error: "missing name/cmd" }); const result = await performPanelServerAction(req, name, req.body && req.body.cmd); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/:id/server/action] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); app.post("/api/nodes/:id/server/command", async (req, res) => { try { const name = String((req.body && req.body.name) || "").trim(); const command = String((req.body && req.body.command) || "").trim(); if (!name || !command) return res.status(400).json({ error: "missing name/command" }); const result = await performPanelConsoleCommand(req, name, req.body && req.body.command, req.body && req.body.requestId); return relayPanelResult(res, result); } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/:id/server/command] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); app.post("/api/nodes/server/:name/create", nodeFsRateLimiterGate, requireNodeFileActionToken("POST /api/servers/:name/files/mkdir"), async (req, res) => { try { const ctx = await remoteContext(req.params.name); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); const accessCheck = await checkServerAccess(req, req.params.name); if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); if (!(await checkUserPerm(req, req.params.name, "files_create"))) { return res.status(403).json({ error: "permission denied", permission: "files_create" }); } if (isServerSuspended(ctx.server)) return sendSuspendedServerJson(res, ctx.server); const typeRaw = String((req.body && req.body.type) || "").toLowerCase(); const nameRaw = String((req.body && req.body.name) || ""); const relPath = String((req.body && req.body.path) || ""); if (typeRaw !== "file" && typeRaw !== "folder") return res.status(400).json({ error: "invalid_type" }); // Mirror the panel POST /create name validation exactly (empty, "..", "/" // and "\") plus "." and control characters. These must be REJECTED here, // not left to the sanitizer: "." would resolve to the server root and make // the folder branch drop a stray .keep marker there, while a sanitizer // silently rewrites ".."-adjacent, separator and control characters into // legal-looking names the panel route would have refused. const nameTrimmed = nameRaw.trim(); if ( !nameTrimmed || nameTrimmed === "." || nameTrimmed.includes("..") || /[\\/]/.test(nameTrimmed) || // eslint-disable-next-line no-control-regex /[\u0000-\u001f\u007f]/.test(nameTrimmed) ) { return res.status(400).json({ error: "invalid_name" }); } // adpanel:sanitizer-lockstep — file/folder names bind the canonical // file-name mirror (utils/upload-filename.js, Go sanitizeUploadFilename), // not the server-storage mirror: leading dots (.env) and valid non-ASCII // are legitimate names the panel /create route passes through and the // daemon's upload path preserves. The drifted local sanitizeName this // route previously borrowed 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 (spec D11) is unchanged. const safeName = sanitizeUploadFilename(nameRaw); if (!safeName) return res.status(400).json({ error: "invalid_name" }); try { const relativePosix = path.posix.join(relPath || "", safeName); const target = safeJoinUnix(ctx.baseDir, relativePosix); // mode: "create" makes the daemon reject (409) when the target already // exists, so this endpoint can never overwrite an existing file's // content — including the folder .keep marker. Back-compat: older // daemons ignore `mode` and keep the legacy either-behavior. const payload = buildFsCreatePayload(target, ctx.nodeServerName, { directory: typeRaw === "folder" }); // The dial + response mapping moved into services/node-fs-relay.js // (relayFsJson + renderFsCreateOutcome, spec §3 "relay" bodies): 507 // quota passthrough, the daemon existence-error texts (exist/EEXIST) → // 400 already_exists with the type-bearing message, everything else → // 502 node_create_failed. 120000 is the write-timeout parity with // index.js's fs-relay dial (this route runs the same daemon endpoint as // the file-write relay, so it must not inherit a shorter cutoff). const outcome = await relayFsJson(NODES_FS_RELAY_DEPS, ctx.node, "/v1/fs/write", payload, 120000); const out = renderFsCreateOutcome(outcome, relativePosix, { variant: "relay", type: typeRaw }); if (out.status !== 200) return res.status(out.status).json(out.json); const userEmail = req.session?.user || "unknown"; const actionType = typeRaw === "folder" ? "folder_create" : "file_create"; recordActivity(getCanonicalServerName(ctx.server, req.params.name), actionType, { path: relativePosix, type: typeRaw }, userEmail, getRequestIp(req)); return res.json(out.json); } catch (e) { return res.status(400).json({ error: maskPathErrorMessage(e) }); } } catch (e) { // adpanel:relay-error-mask — generic detail; raw error logged server-side only. console.error("[/api/nodes/server/:name/create] relay failed:", e); return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // Same cross-site read guard as the file relays (utils/cross-site-read-guard.js): // backup listings expose names/sizes/timestamps to session-authenticated // browsers, so they reject exactly what the file relays reject. The POST/ // DELETE backup relays below verify the same session-bound action tokens as // the file-mutation relays (requireNodeFileActionToken — the generic // parameterized relay gate): backupCreate/backupRestore/backupDelete are // minted fresh by GET /permissions because no panel mirror routes exist (the // node daemon owns backup storage), gated on exactly the perms the performers // enforce (backups_create for create+restore, backups_delete for delete) — so // a cookie-authenticated request from a CSRF_ALLOWED_HOSTS-trusted origin, // the one vector sameOriginProtection deliberately permits, needs the token // too, same as every sibling mutating relay. // adpanel:backups-list-brake — this read route used to be the only backups // relay without a rate brake: each list dial holds a 15s node budget and // triggers the daemon's orphan-backup sweep, and the global throttles are // no-ops on the shipped default (security.rate_limiting is false in // security.json), so a backups_view holder could stream unbounded panel→node // list dials. The ALWAYS-ON nodeBackupsListRateLimiter (index.js, mirroring // the scheduler read brake: 120/10min, per-account key, own // "node-backups-list:" store instance) is injected via setUploadPolicyHooks // and mounted after rejectCrossSiteRead, before any handler code — exactly // like schedulerTasksReadRateLimiter on the scheduler tasks GET. It brakes // THIS route only: the mutating siblings below keep their // nodeUploadRateLimiterGate mounts, and listServerBackupsForHygiene's // internal dials are not client-facing. app.get("/api/nodes/server/:name/backups", rejectCrossSiteRead, nodeBackupsListRateLimiterGate, async (req, res) => { try { const result = await performPanelListBackups(req, req.params.name); return relayPanelResult(res, result); } catch (e) { console.error("[backups] List error:", e); // adpanel:relay-error-mask — generic detail; raw error stays in the log above. return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // adpanel:backup-relay-brake — the three mutating backups relays are the same // cost-profile long daemon ops as the extract/archive/upload relays (create // holds a node listing of up to 2 attempts × 15s before the daemon's op-lock // 409; restore and delete hold the daemon's long copy/delete operations) and // were the only same-shape relays without the brake: a session-bound // backups_* holder could pin unbounded relay requests. They mount the same // nodeUploadRateLimiterGate the four siblings mount FIRST — the shared // per-user serverFsUploadRateLimiter budget (60/5min, session-keyed; // unauthenticated requests skip counting and are 403'd by the token gate // right after) — mirroring the sibling mounting exactly. app.post("/api/nodes/server/:name/backups", nodeUploadRateLimiterGate, requireNodeFileActionToken("POST /backups"), async (req, res) => { try { const result = await performPanelCreateBackup(req, req.params.name, req.body?.name, req.body?.description); return relayPanelResult(res, result); } catch (e) { console.error("[backups] Create error:", e); // adpanel:relay-error-mask — generic detail; raw error stays in the log above. return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // adpanel:backup-relay-brake — same gate-first brake as POST /backups above // (identical mounting to the extract/archive/upload siblings). app.post("/api/nodes/server/:name/backups/:backupId/restore", nodeUploadRateLimiterGate, requireNodeFileActionToken("POST /backups/:id/restore"), async (req, res) => { try { // Strict boolean: only an explicit JSON true wipes old files; absent or // non-boolean values restore as a merge (legacy daemon default). const result = await performPanelRestoreBackup(req, req.params.name, req.params.backupId, req.body?.deleteOldFiles === true); return relayPanelResult(res, result); } catch (e) { console.error("[backups] Restore error:", e); // adpanel:relay-error-mask — generic detail; raw error stays in the log above. return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // adpanel:backup-relay-brake — same gate-first brake as POST /backups above // (identical mounting to the extract/archive/upload siblings). app.delete("/api/nodes/server/:name/backups/:backupId", nodeUploadRateLimiterGate, requireNodeFileActionToken("DELETE /backups/:id"), async (req, res) => { try { const result = await performPanelDeleteBackup(req, req.params.name, req.params.backupId); return relayPanelResult(res, result); } catch (e) { console.error("[backups] Delete error:", e); // adpanel:relay-error-mask — generic detail; raw error stays in the log above. return res.status(500).json({ error: "bridge_failed", detail: "internal error" }); } }); // Same cross-site read guard as the file relays (utils/cross-site-read-guard.js): // server logs are file content gated by console_read, so they reject exactly // what the file relays reject. app.get("/api/nodes/server/:name/logs", rejectCrossSiteRead, async (req, res) => { try { const serverName = req.params.name; const accessCheck = await checkServerAccess(req, serverName); if (!accessCheck.ok) { return res.status(accessCheck.status).json({ error: accessCheck.error }); } if (await rejectIfServerSuspended(res, serverName)) return; if (!(await checkUserPerm(req, serverName, "console_read"))) { return res.status(403).json({ error: "permission denied", permission: "console_read" }); } const { node, server: logsServer } = await resolveNodeForServer(serverName); if (!node) return res.status(404).json({ error: "server_or_node_not_found" }); if (!_consoleLogSessionChecks) return res.status(503).json({ error: "node_logs_failed" }); const { getLoggedInUser, checkSocketSessionLiveness, withTimeout, recheckIntervalMs = 30_000 } = _consoleLogSessionChecks; const sessionId = req.sessionID; const userEmail = req.session.user; const canonicalName = logsServer.name || serverName; const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); const tailRaw = String(req.query?.tail || "").trim(); let tailQuery = ""; if (/^\d+$/.test(tailRaw)) { const tail = Math.max(0, Math.min(10000, parseInt(tailRaw, 10))); tailQuery = `?tail=${encodeURIComponent(String(tail))}`; } // adpanel:daemon-dial-canonical — dial the canonical storage name (the // same sanitizeNodeStorageName(srv.name) derivation remoteContext uses for // ctx.nodeServerName), not the request alias: the daemon derives identity // from the URL key, so legacy_id/bot access would otherwise stream a // nonexistent server's logs (spurious 404). The access, suspension and // permission checks above stay on serverName. const fullUrl = `${base}/v1/servers/${encodeURIComponent(sanitizeNodeStorageName(canonicalName))}/logs${tailQuery}`; // adpanel:console-stream-liveness - a live HTTP response cannot keep the // account, session or server grant it had when the request opened. let nreq; let recheckTimer; const recheck = async () => { try { const allowed = await withTimeout((async () => { const freshReq = { session: { user: userEmail } }; const user = await getLoggedInUser(freshReq); if (!user || user.suspended) return false; const { verdict } = await checkSocketSessionLiveness(sessionId, { user }); if (verdict !== "alive") return false; const access = await checkServerAccess(freshReq, canonicalName); if (!access.ok) return false; const server = access.server || await findServerByNameOrId(canonicalName); if (!server || isServerSuspended(server) || server.id !== logsServer.id || server.name !== logsServer.name || serverNodeRef(server) !== serverNodeRef(logsServer)) return false; return checkUserPerm(freshReq, canonicalName, "console_read"); })(), 5000, "console-log-access-timeout"); if (!allowed) return res.destroy(); if (!res.destroyed && !res.writableEnded) { recheckTimer = setTimeout(recheck, recheckIntervalMs).unref(); } } catch { res.destroy(); } }; if (res.destroyed || res.writableEnded) return; res.once("close", () => { clearTimeout(recheckTimer); nreq?.destroy(); }); recheckTimer = setTimeout(recheck, recheckIntervalMs).unref(); const { res: nres } = await openNodeConsoleLogStream(fullUrl, nodeHeaders(node), (request) => { nreq = request; }); if (res.destroyed || res.writableEnded) return; if (nres.destroyed) return res.status(502).json({ error: "node_logs_failed" }); if (nres.statusCode !== 200) { const chunks = []; let remaining = 16 * 1024; for await (const chunk of nres) { if (remaining > 0) chunks.push(chunk.subarray(0, remaining)); remaining -= chunk.length; } if (res.destroyed || res.writableEnded) return; const status = nres.statusCode || 502; const detail = Buffer.concat(chunks).toString("utf8").slice(0, 2000); return res.status(status).json({ error: "node_logs_failed", detail: detail || `status ${status}` }); } const endStream = () => { if (!res.destroyed && !res.writableEnded) res.end(); }; nres.on("error", endStream); nres.on("aborted", endStream); nres.once("close", endStream); res.setHeader("Content-Type", "text/event-stream"); res.setHeader("Cache-Control", "no-store, no-transform"); res.setHeader("Connection", "keep-alive"); res.setHeader("X-Accel-Buffering", "no"); res.flushHeaders?.(); nres.pipe(res); } catch { if (res.destroyed || res.writableEnded) return; if (!res.headersSent) return res.status(502).json({ error: "node_logs_failed" }); res.end(); } }); if (require.main === module) { // Standalone mode: no index.js startup sequence to gate on. startNodeHealthLoop(); app.listen(PORT, () => console.log(`[nodes.js] Nodes API on :${PORT}`)); } module.exports = app; module.exports.remoteContext = remoteContext; module.exports.httpJson = httpJson; module.exports.nodeUrl = nodeUrl; module.exports.nodeHeaders = nodeHeaders; module.exports.nodeUnderCloudflare = nodeUnderCloudflare; module.exports.callNodeApi = callNodeApi; module.exports.isOpenNodeBootstrapRoute = isOpenNodeBootstrapRoute; module.exports.setNodeBootstrapTransport = setNodeBootstrapTransport; module.exports.requireNodeBootstrapTransport = requireNodeBootstrapTransport; module.exports.resolveNodeForServer = resolveNodeForServer; module.exports.recordActivity = recordActivity; module.exports.flushActivityLogs = flushActivityLogs; module.exports.seedRuntimeOnNode = seedRuntimeOnNode; module.exports.rotateNodeToken = rotateNodeToken; module.exports.rotateNodeTokenPrelocked = rotateNodeTokenPrelocked; module.exports.buildConfigYml = buildConfigYml; module.exports.oneTimeCommand = oneTimeCommand; module.exports.setWebhookDispatcher = setWebhookDispatcher; module.exports.setPermissionCheckers = setPermissionCheckers; module.exports.setUploadPolicyHooks = setUploadPolicyHooks; module.exports.setServerActionObserver = setServerActionObserver; module.exports.setServerIndexWriters = setServerIndexWriters; module.exports.setServerCreateHelpers = setServerCreateHelpers; // adpanel:heartbeat-nonce-shared — index.js injects the session Redis client // accessors so the heartbeat nonce replay ledger is cluster-shared instead of // per-process (1/N effective under PM2 cluster). See heartbeatSharedNonceStore. module.exports.setHeartbeatSharedNonceDeps = setHeartbeatSharedNonceDeps; // adpanel:heartbeat-capture-integrated — index.js's pre-auth JSON dispatch // binds this ONE capture implementation onto the parser that actually parses // the heartbeat in integrated mode: its dispatch runs before // app.use(nodesRouter) and sets the body-parser req._body sentinel, so THIS // file's own heartbeat parser then skips without invoking verify (see the // capture comment above). HEARTBEAT_RAW_BODY_PROP travels with it so the // integrated mount writes exactly the prop the route's verifier reads // (req[HEARTBEAT_RAW_BODY_PROP]) — the two ends cannot drift. module.exports.captureHeartbeatRawBody = captureHeartbeatRawBody; module.exports.HEARTBEAT_RAW_BODY_PROP = HEARTBEAT_RAW_BODY_PROP; module.exports.startPayloadFor = startPayloadFor; module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand; module.exports.performPanelServerAction = performPanelServerAction; module.exports.performPanelEulaAccept = performPanelEulaAccept; module.exports.performPanelEulaStatus = performPanelEulaStatus; module.exports.performPanelConsoleCommand = performPanelConsoleCommand; module.exports.performPanelListBackups = performPanelListBackups; module.exports.performPanelCreateBackup = performPanelCreateBackup; module.exports.performPanelRestoreBackup = performPanelRestoreBackup; module.exports.performPanelDeleteBackup = performPanelDeleteBackup; module.exports.listServerBackupsForHygiene = listServerBackupsForHygiene; module.exports.findNodeByIdOrName = findNodeByIdOrName; module.exports.saveNode = saveNode; module.exports.normalizePorts = normalizePorts; module.exports.requireNodeAdmin = requireNodeAdmin; module.exports.saveNodeHealth = saveNodeHealth; module.exports.startNodeHealthLoop = startNodeHealthLoop; module.exports.hardenNode = hardenNode; module.exports.resolveNodeApiBindHost = resolveNodeApiBindHost; module.exports.isServerSuspended = isServerSuspended; module.exports.suspendedServerResult = suspendedServerResult; module.exports.resolveIfServerSuspended = resolveIfServerSuspended;