Files
Kelx/utils/node-bootstrap.js
2026-11-30 16:32:37 +00:00

422 lines
17 KiB
JavaScript

"use strict";
// Secret-free node bootstrap ("one-time setup command").
//
// Historically the setup command embedded the node's full config.yml — the
// daemon bearer token (twice) and the derived hmac_secret — inside a heredoc
// the admin pasted into a shell on the node host. Anything pasted into a
// terminal lands verbatim in ~/.bash_history / zsh history and scrollback, so
// a long-lived credential (and HMAC key) sat at rest on a third machine,
// outside the panel's encrypted-at-rest envelope.
//
// This module replaces that flow with a fetch-on-boot bootstrap:
//
// curl -fsSL "<panel>/api/node-bootstrap/<scriptId>" | bash
//
// GET /api/node-bootstrap/<scriptId> -> POSIX sh bootstrap script
// GET /api/node-bootstrap/<configId>/config.yml -> the node's config.yml
//
// The pasted command contains no credential material at all. Both IDs are
// 256-bit random, single-use (consumed on first download) and expire after a
// short TTL (default 10 minutes). The bootstrap script the node downloads
// fetches config.yml — token and hmac_secret included — over TLS from the
// panel, exactly once, writes it with mode 0640 and restarts the daemon. The
// secrets therefore only ever exist on the node as the intended 0640
// /var/lib/node/config.yml, never in shell history, scrollback or dotfile
// backups.
//
// adpanel:node-bootstrap-workers - issuance and downloads can reach different
// PM2 workers, so the panel supplies a shared private ledger.
const crypto = require("crypto");
const fs = require("fs");
const net = require("net");
const path = require("path");
const { atomicWriteFileSync } = require("./atomic-file");
const { createCrossProcessOperationMutex } = require("./cross-process-mutex");
const DEFAULT_ENROLL_TTL_MS = 10 * 60 * 1000;
const DEFAULT_MAX_ENROLLMENTS = 512; // script + config entries counted together
const DEFAULT_RATE_WINDOW_MS = 60 * 1000;
const DEFAULT_RATE_MAX = 30;
// 32 random bytes -> 43 base64url chars ([A-Za-z0-9_-], no padding).
const ENROLL_ID_BYTES = 32;
const ENROLL_ID_RE = /^[A-Za-z0-9_-]{43}$/;
const GONE_MESSAGE = [
"This bootstrap link is invalid, expired, or was already used.",
"Single-use links expire after a few minutes and die with the first download.",
"Generate a new one-time setup command in the panel (Nodes > Linking) and run it promptly.",
].join(" ");
function shellSingleQuote(value) {
return `'${String(value == null ? "" : value).replace(/'/g, `'\\''`)}'`;
}
function isEnrollId(value) {
return ENROLL_ID_RE.test(String(value || ""));
}
function nodeCredentialFingerprint(node) {
if (!node?.id || !node.token) return null;
return crypto.createHmac("sha256", node.token)
.update(JSON.stringify([String(node.id), node.uuid || "", node.token_id || ""]))
.digest("hex");
}
// adpanel:node-bootstrap-rotation - an outstanding link cannot reveal a replacement credential.
async function findEnrolledNode(findNode, enrollment) {
if (!enrollment.credentialFingerprint) return null;
const node = await findNode(enrollment.nodeId);
if (String(node?.id) !== enrollment.nodeId) return null;
return nodeCredentialFingerprint(node) === enrollment.credentialFingerprint ? node : null;
}
function createNodeBootstrapStore({ ttlMs = DEFAULT_ENROLL_TTL_MS, maxEntries = DEFAULT_MAX_ENROLLMENTS, now = Date.now, filePath } = {}) {
const local = new Map();
const mutex = filePath && createCrossProcessOperationMutex({
label: "[node-bootstrap]", lockFilePath: `${filePath}.lock`,
});
function readEntries() {
if (!mutex) return local;
try {
return new Map(JSON.parse(fs.readFileSync(filePath, "utf8")));
} catch (err) {
if (err.code !== "ENOENT") throw err;
return new Map();
}
}
function mutate(task) {
if (!mutex) return task(local);
fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
return mutex.runExclusive(() => {
const entries = readEntries();
const result = task(entries);
if (result) atomicWriteFileSync(filePath, JSON.stringify([...entries]), { mode: 0o600 });
return result;
});
}
// Mints a linked pair: the script enrollment (referenced by the pasted
// command) and the config enrollment (embedded in the served script).
function issue(node) {
const credentialFingerprint = nodeCredentialFingerprint(node);
if (!credentialFingerprint) throw new Error("Node enrollment requires an active credential.");
const nodeId = String(node.id);
return mutate(entries => {
const time = now();
for (const [id, rec] of entries) {
if (rec.expiresAt <= time) entries.delete(id);
}
while (entries.size && entries.size + 2 > maxEntries) entries.delete(entries.keys().next().value);
const scriptId = crypto.randomBytes(ENROLL_ID_BYTES).toString("base64url");
const configId = crypto.randomBytes(ENROLL_ID_BYTES).toString("base64url");
const expiresAt = time + ttlMs;
entries.set(scriptId, { nodeId, credentialFingerprint, kind: "script", configId, expiresAt });
entries.set(configId, { nodeId, credentialFingerprint, kind: "config", expiresAt });
return { scriptId, configId, expiresAt };
});
}
function liveEntry(entries, key) {
const rec = entries.get(key);
return rec && rec.expiresAt > now() ? rec : null;
}
function peek(id) {
const key = String(id || "");
return isEnrollId(key) ? liveEntry(readEntries(), key) : null;
}
function consume(id) {
const key = String(id || "");
if (!isEnrollId(key) || (mutex && !peek(key))) return null;
return mutate(entries => {
const rec = liveEntry(entries, key);
if (rec) entries.delete(key);
return rec;
});
}
return {
issue,
peek,
consume,
get size() {
return readEntries().size;
},
};
}
function createNodeBootstrapRateLimiter({ windowMs = DEFAULT_RATE_WINDOW_MS, max = DEFAULT_RATE_MAX, now = Date.now } = {}) {
const buckets = new Map(); // key -> { count, resetAt }
return {
allow(key) {
const t = now();
const k = String(key || "");
let bucket = buckets.get(k);
if (!bucket || bucket.resetAt <= t) {
// Hard cap so a spoofed-source flood cannot grow the map unbounded;
// clearing on overflow only widens the window, never admits extras.
if (buckets.size > 4096) buckets.clear();
bucket = { count: 0, resetAt: t + windowMs };
buckets.set(k, bucket);
}
bucket.count += 1;
return bucket.count <= max;
},
};
}
// The script the node pipes to bash. Constraints:
// - POSIX sh (the piping shell is bash per the suggested command, but the
// body must also survive `| sh` on minimal hosts);
// - never echoes the configuration or any credential;
// - fetches config.yml over TLS from the panel using the single-use config
// URL (no secret in the URL beyond the one-time ID itself);
// - refuses to overwrite an existing config with a payload that does not
// look like a node config (captive portals, proxy error pages, ...);
// - deploys with mode 0640 owned by the daemon user and restarts the
// service, mirroring the legacy heredoc command's behaviour.
function buildNodeBootstrapScript({ configUrl } = {}) {
const url = String(configUrl || "");
if (!url) throw new Error("configUrl is required");
return [
`#!/bin/sh`,
`# ADPanel node bootstrap - deploys config.yml from a single-use panel link.`,
`# No credentials are embedded here: the configuration (including the node`,
`# token) is downloaded over TLS, once, then written with mode 0640.`,
`set -eu`,
``,
`CONFIG_URL=${shellSingleQuote(url)}`,
`NODE_DIR=/var/lib/node`,
``,
`if [ "$(id -u)" -eq 0 ]; then SUDO=""; elif command -v sudo >/dev/null 2>&1; then SUDO="sudo"; else echo "Run as root or install sudo, then retry." >&2; exit 1; fi`,
``,
`TMP_CONFIG="$(mktemp /tmp/adpanel-node-config.XXXXXX)" || exit 1`,
`trap 'rm -f "$TMP_CONFIG"' EXIT INT TERM`,
``,
`echo "Downloading node configuration from the panel (single-use link)..."`,
`if ! curl -fsSL --retry 2 "$CONFIG_URL" -o "$TMP_CONFIG"; then`,
` echo "ERROR: could not download config.yml - the link may have expired or was already used." >&2`,
` echo "Generate a new setup command in the panel (Nodes > Linking) and run it promptly." >&2`,
` exit 1`,
`fi`,
``,
`# Refuse to clobber an existing config with something that is not a node`,
`# config (e.g. a captive portal or proxy error page).`,
`if ! grep -q '^uuid:' "$TMP_CONFIG" || ! grep -q '^token:' "$TMP_CONFIG"; then`,
` echo "ERROR: downloaded configuration failed validation; nothing was written." >&2`,
` exit 1`,
`fi`,
``,
`# Check the TLS fields written by the panel before replacing a working config.`,
`if grep -q '^ enabled: true$' "$TMP_CONFIG"; then`,
` CERT="\${API_TLS_CERT:-$(sed -n 's/^ cert: "\\(.*\\)"$/\\1/p' "$TMP_CONFIG")}"`,
` KEY="\${API_TLS_KEY:-$(sed -n 's/^ key: "\\(.*\\)"$/\\1/p' "$TMP_CONFIG")}"`,
` if ! $SUDO runuser -u adaemon -- sh -c 'for file do test -f "$file" && test -s "$file" && test -r "$file" || exit 1; done' sh "$CERT" "$KEY"; then`,
` echo "ERROR: TLS is enabled but the certificate or key is missing, empty, or unreadable by adaemon; the existing node configuration was not changed." >&2`,
` exit 1`,
` fi`,
`fi`,
``,
`$SUDO install -d -m 0750 "$NODE_DIR"`,
`$SUDO install -m 0640 "$TMP_CONFIG" "$NODE_DIR/config.yml"`,
`$SUDO chown adaemon:adaemon "$NODE_DIR/config.yml" 2>/dev/null || true`,
``,
`if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then`,
` $SUDO systemctl restart adaemon || $SUDO systemctl restart ADaemon`,
`elif command -v rc-service >/dev/null 2>&1; then`,
` $SUDO rc-service adaemon restart || $SUDO rc-service adaemon start`,
`else`,
` $SUDO service adaemon restart || $SUDO service adaemon start`,
`fi`,
``,
`echo "Node configuration deployed to $NODE_DIR/config.yml and the daemon service was restarted."`,
``,
].join("\n");
}
// M2: client IP extraction for the pre-auth node surfaces (heartbeat flood
// limiter, bootstrap downloads). The previous version took the LEFTMOST
// X-Forwarded-For value unconditionally, so any client could rotate that
// header per request and receive a fresh limiter bucket while every request
// still cost a node lookup. Now X-Forwarded-For is only honored when the
// DIRECT socket peer is a trusted proxy (loopback by default, extended via
// the same TRUSTED_PROXY_IPS env the panel's own getRequestIp uses), and the
// hop chain is then walked right-to-left to the first untrusted address —
// identical semantics to index.js getTrustedForwardedFor. A direct client is
// always keyed on its socket address, which it cannot spoof.
const TRUSTED_PROXY_IPS = new Set(
(process.env.TRUSTED_PROXY_IPS || "")
.split(",")
.map((s) => s.trim())
.filter(Boolean)
);
function normalizeBootstrapIp(raw) {
let ip = String(raw || "").trim();
if (ip.startsWith("::ffff:")) ip = ip.slice(7);
return ip;
}
function isLoopbackBootstrapIp(ip) {
return ip === "127.0.0.1" || ip === "::1";
}
function isTrustedBootstrapProxyIp(ip) {
const normalized = normalizeBootstrapIp(ip);
if (!normalized) return false;
if (isLoopbackBootstrapIp(normalized)) return true;
return TRUSTED_PROXY_IPS.has(normalized);
}
function clientIpFromReqDefault(req) {
try {
const direct = normalizeBootstrapIp(req?.socket?.remoteAddress || req?.connection?.remoteAddress || "");
if (direct && isTrustedBootstrapProxyIp(direct)) {
// Walk the X-Forwarded-For chain from the closest proxy back towards
// the client; the first untrusted hop is the client as seen through
// the trusted chain. Never trust a client-supplied leftmost value, and
// ignore entries that are not valid IP literals (same filter the
// panel's getTrustedForwardedFor applies).
const validIps = String(req?.get?.("x-forwarded-for") || "")
.split(",")
.map((part) => normalizeBootstrapIp(part))
.filter((ip) => ip && net.isIP(ip) !== 0);
for (let i = validIps.length - 1; i >= 0; i -= 1) {
if (!isTrustedBootstrapProxyIp(validIps[i])) return validIps[i];
}
return validIps[0] || direct;
}
} catch { }
try {
return normalizeBootstrapIp(req?.socket?.remoteAddress || req?.connection?.remoteAddress || "");
} catch {
return "";
}
}
function setSecretResponseHeaders(res, contentType) {
res.set("Cache-Control", "no-store, no-cache, must-revalidate, private");
res.set("Pragma", "no-cache");
res.set("X-Content-Type-Options", "nosniff");
res.set("Content-Type", contentType);
}
// GET /api/node-bootstrap/:id (id = script enrollment ID)
function createBootstrapScriptHandler(deps = {}) {
const {
store,
limiter = null,
findNode = async () => null,
buildPanelBaseUrl = () => "",
clientIpFromReq = clientIpFromReqDefault,
log = () => { },
} = deps;
return async (req, res) => {
try {
const ip = clientIpFromReq(req);
if (limiter && !limiter.allow(ip)) {
return res.status(429).set("Content-Type", "text/plain; charset=utf-8").send("too many requests");
}
const id = String(req.params?.id || "");
const rec = await store.consume(id);
if (!rec || rec.kind !== "script") {
log(`rejected script download (link unknown, expired or already used) from ${ip || "?"}`);
return res.status(410).set("Content-Type", "text/plain; charset=utf-8").send(GONE_MESSAGE);
}
// The paired config link must still be live for the script to work; if
// it is gone, fail closed here so the admin gets a clear signal instead
// of a command that dies on the node.
if (!store.peek(rec.configId)) {
log(`script download for node ${rec.nodeId || "?"} had no live config link (from ${ip || "?"})`);
return res.status(410).set("Content-Type", "text/plain; charset=utf-8").send(GONE_MESSAGE);
}
const node = await findEnrolledNode(findNode, rec);
if (!node) {
log(`script download no longer matches node ${rec.nodeId || "?"} (from ${ip || "?"})`);
return res.status(410).set("Content-Type", "text/plain; charset=utf-8").send(GONE_MESSAGE);
}
const base = String(buildPanelBaseUrl(req) || "").replace(/\/+$/, "");
const configUrl = `${base}/api/node-bootstrap/${encodeURIComponent(rec.configId)}/config.yml`;
const script = buildNodeBootstrapScript({ configUrl });
log(`served bootstrap script for node ${node.name || node.id || rec.nodeId} to ${ip || "?"}`);
setSecretResponseHeaders(res, "text/x-shellscript; charset=utf-8");
return res.send(script);
} catch (err) {
log(`script handler error: ${err?.message || err}`);
return res.status(500).set("Content-Type", "text/plain; charset=utf-8").send("internal error");
}
};
}
// GET /api/node-bootstrap/:id/config.yml (id = config enrollment ID)
// Serves the node's full config.yml — bearer token and hmac_secret included —
// exactly once: the enrollment ID is consumed before the config is built, so a
// replayed download can never retrieve a second copy.
function createBootstrapConfigHandler(deps = {}) {
const {
store,
limiter = null,
findNode = async () => null,
buildConfig = () => "",
clientIpFromReq = clientIpFromReqDefault,
log = () => { },
} = deps;
return async (req, res) => {
try {
const ip = clientIpFromReq(req);
if (limiter && !limiter.allow(ip)) {
return res.status(429).set("Content-Type", "text/plain; charset=utf-8").send("too many requests");
}
const id = String(req.params?.id || "");
const rec = await store.consume(id);
if (!rec || rec.kind !== "config") {
log(`rejected config download (link unknown, expired or already used) from ${ip || "?"}`);
return res.status(410).set("Content-Type", "text/plain; charset=utf-8").send(GONE_MESSAGE);
}
const node = await findEnrolledNode(findNode, rec);
if (!node) {
log(`config download no longer matches node ${rec.nodeId || "?"} (from ${ip || "?"})`);
return res.status(410).set("Content-Type", "text/plain; charset=utf-8").send(GONE_MESSAGE);
}
const yml = String(buildConfig(node, req) || "");
log(`served config.yml (single-use link) for node ${node.name || node.id || rec.nodeId} to ${ip || "?"}`);
setSecretResponseHeaders(res, "text/yaml; charset=utf-8");
return res.send(yml);
} catch (err) {
log(`config handler error: ${err?.message || err}`);
return res.status(500).set("Content-Type", "text/plain; charset=utf-8").send("internal error");
}
};
}
module.exports = {
DEFAULT_ENROLL_TTL_MS,
DEFAULT_MAX_ENROLLMENTS,
ENROLL_ID_RE,
GONE_MESSAGE,
buildNodeBootstrapScript,
clientIpFromReqDefault,
createBootstrapConfigHandler,
createBootstrapScriptHandler,
createNodeBootstrapRateLimiter,
createNodeBootstrapStore,
isEnrollId,
};