"use strict"; // Node -> panel heartbeat authentication. // // The heartbeat endpoint is reachable without an admin session (bootstrap by // design), so a long-lived bearer token alone is not enough: a heartbeat // captured on the wire (or a token that leaked once) could be replayed // forever, each replay refreshing last_seen/port_ok and keeping a dead or // fake node "online" through the whole link-node setup flow. // // When the panel has a per-node signing secret (PANEL_HMAC_SECRET configured, // secret derived via utils/node-hmac — the same secret the daemon already // persists as panel.hmac_secret in config.yml), heartbeats MUST carry the // x-node-ts / x-node-sign / x-node-nonce envelope: // base = heartbeat||| // x-node-sign = HMAC-SHA256(base, per-node secret) as hex // The timestamp bounds a captured heartbeat to a short drift window and the // single-use nonce makes every heartbeat unique inside that window, so // replay buys an attacker nothing. There is no bearer-token fallback behind // this envelope: the fleet master auto-resolves on healthy installs (see // utils/panel-hmac-secret.js), so a missing signing secret means a broken // install and the route handler rejects heartbeats fail-closed, without // mutating node state (adpanel:heartbeat-fallback-scoped in nodes.js). // // adpanel:heartbeat-body-binding — envelope v2 binds the request body. The v1 // base above covers only id/ts/nonce, so a captured (ts, nonce, sign) triple // stays valid for ANY body inside the drift window: an attacker could replay // it with a body that repoints api_port (where the panel later sends admin // and server traffic), flips port_ok, or refreshes last_seen. v2 closes that // with a body hash: // x-node-body-hash: // base = heartbeat|||| // The verifier hashes the raw bytes as received (the heartbeat route captures // them pre-parse; NEVER a JSON re-serialization, which is not byte-stable // across JSON writers), fails closed with the route's uniform 401 on a // tampered/mismatched body or on a v2 request whose raw bytes were not // captured, and only then applies body fields to node state. // // OPERATOR NOTE (transitional v1 acceptance): the v2 signer ships in the // deployed node-daemon binaries, NOT in this repo — there is no heartbeat // sender here (grep of *.go confirms: main.go only READS x-node-token), so // upgrading the fleet is a daemon release, not a panel change. Until then v1 // heartbeats are accepted unchanged (legacy daemons must not break) and each // acceptance triggers a ONE-TIME per-process warn (adpanel:heartbeat-body-binding // in nodes.js) that the body was accepted unbound. v1 is a documented // transitional state to be retired — v1 rejected — once the fleet signs v2. // v2 senders MUST send a JSON body (application/json) so the raw bytes are // captured; a v2 request without a capturable body fails closed. // // adpanel:heartbeat-nonce-shared — cluster-shared nonce replay protection. // The in-process cache (createNonceCache) is 1/N effective under PM2 cluster // (INSTANCES = cores - 2, utils/db-proxy.js): a captured heartbeat is // replayable once per worker. createSharedHeartbeatNonceStore moves the // arbiter to the shared Redis (SET NX PX; key includes the node id, TTL = // NONCE_TTL_MS > drift window) in the house style of // utils/login-attack-redis.js: injected clientOf/readyOf dependencies, every // op best-effort with a small hard timeout, pre-attached .catch, never // throws, never blocks the caller longer than the timeout. Fail posture: // when the shared store is unavailable (Redis down / not ready / op timeout) // the verifier falls back to the per-process cache and the route warns once // — availability of heartbeats outranks replay strictness during a Redis // outage, because the HMAC envelope still authenticates the sender, so // degrading the nonce ledger only widens the replay window (1/N effective, // the pre-fix posture) instead of opening an auth bypass. (The ledger's // opposite precedent is heartbeat-fallback-scoped: with the HMAC master // unresolvable there is NO authenticator left, so nodes honestly show // OFFLINE until it is restored.) The per-process cache stays as the // write-through degraded fallback and is never deleted. // // Parameters mirror the daemon's panel-signing constants on purpose; if they // ever change on one side they must change on both. const crypto = require("crypto"); const DRIFT_MS = 5 * 60 * 1000; const NONCE_TTL_MS = 6 * 60 * 1000; // must exceed DRIFT_MS const NONCE_MAX_LEN = 128; const NONCE_SWEEP_SIZE = 1024; // adpanel:heartbeat-body-binding — the v2 discriminator header. Its PRESENCE // (any value) marks the sender as a v2 signer; the value itself must be the // lowercase sha256 hex of the exact raw request bytes and is part of the // signed base, so a v2 signature can never verify against different bytes. const BODY_HASH_HEADER = "x-node-body-hash"; // adpanel:heartbeat-nonce-shared — ONE key namespace per mechanism (same // discipline as utils/login-attack-redis.js), distinct from every limiter // prefix. The node id is part of the key so two nodes can never evict or // collide with each other's nonces; nonces are strictly alphanumeric // (isValidNonce), so the ":"-joined key is collision-free. const HEARTBEAT_NONCE_KEY_PREFIX = "adpanel:heartbeat-nonce:"; const DEFAULT_SHARED_OP_TIMEOUT_MS = 250; const SHARED_OP_TIMEOUT = Symbol("heartbeat-nonce-op-timeout"); // Alphanumeric only, so a nonce can never smuggle the "|" field separator or // control characters into the signed base string or logs (same rule as the // daemon's validPanelNonce). function isValidNonce(nonce) { const s = String(nonce || ""); if (s.length < 16 || s.length > NONCE_MAX_LEN) return false; return /^[0-9A-Za-z]+$/.test(s); } function heartbeatSignatureBase(nodeId, ts, nonce, bodyHashHex) { const id = String(nodeId || "").trim(); const base = `heartbeat|${id}|${ts}${nonce ? `|${nonce}` : ""}`; // adpanel:heartbeat-body-binding — the optional fourth segment is the v2 // body hash. The verifier only reaches the signature step after proving the // declared hash equals sha256(exact raw bytes), so the signed base binds // what the panel actually received. return `${base}${bodyHashHex ? `|${bodyHashHex}` : ""}`; } // adpanel:heartbeat-body-binding — the one definition of the v2 body hash: // sha256 hex over the EXACT raw request bytes. Returns null when no raw bytes // exist (Buffer/string only) — callers must fail closed on v2 in that case; // hashing a re-serialized object would verify a body the panel never // received, since JSON stringification is not byte-stable across writers. function heartbeatBodySha256(rawBody) { if (Buffer.isBuffer(rawBody)) { return crypto.createHash("sha256").update(rawBody).digest("hex"); } if (typeof rawBody === "string") { return crypto.createHash("sha256").update(rawBody, "utf8").digest("hex"); } return null; } function timingSafeHexEqual(aHex, bHex) { const a = Buffer.from(String(aHex || ""), "utf8"); const b = Buffer.from(String(bHex || ""), "utf8"); if (a.length !== b.length || a.length === 0) return false; return crypto.timingSafeEqual(a, b); } // Single-use nonce cache. record() must only be called AFTER the signature // verified, so unauthenticated traffic can never poison the cache. The cache // is per-process and in-memory: replay protection only has to cover the // drift window, so surviving a panel restart is not required. // // adpanel:heartbeat-nonce-shared — this cache is the DEGRADED FALLBACK ONLY: // per-process state is 1/N effective under PM2 cluster, so the shared store // below is the arbiter whenever it is wired and reachable. Kept verbatim as // the fallback (do not delete): a Redis outage must not stop heartbeats. function createNonceCache() { const seen = new Map(); return { record(nonce, nowMs) { const now = Number(nowMs) || Date.now(); const exp = seen.get(nonce); if (exp !== undefined && exp > now) return false; if (seen.size >= NONCE_SWEEP_SIZE) { for (const [k, e] of seen) { if (e <= now) seen.delete(k); } } seen.set(nonce, now + NONCE_TTL_MS); return true; }, }; } // adpanel:heartbeat-nonce-shared — the cluster-shared nonce arbiter. One // atomic op per heartbeat: SET 1 NX PX answers OK for a // first-seen nonce and nil for a replay, which is why the send wrapper below // separates "Redis answered nil" ({ok:true, reply:null}) from "Redis did not // answer" ({ok:false}) — the verifier must only fall back to the per-process // cache on the latter, never on a genuine replay report. // // The Redis client is injected (clientOf/readyOf) exactly like // utils/login-attack-redis.js: the session client lives in index.js, which // wires it via nodes.js' setHeartbeatSharedNonceDeps. Every op is best-effort: // readiness-gated, bounded by a 250ms hard timeout with a pre-attached // .catch so an abandoned promise is never unhandled, never throws, and the // record() result degrades to { sharedAvailable: false } on ANY failure. function createSharedHeartbeatNonceStore(options = {}) { const clientOf = options.clientOf || (() => null); const readyOf = options.readyOf || (() => false); const opTimeoutMs = Number.isFinite(Number(options.opTimeoutMs)) && Number(options.opTimeoutMs) >= 1 ? Number(options.opTimeoutMs) : DEFAULT_SHARED_OP_TIMEOUT_MS; // TTL = drift window + margin (NONCE_TTL_MS, same margin the local cache // uses): a nonce must outlive every timestamp the verifier would still // accept, or the tail of the drift window becomes replayable. const ttlMs = Number.isFinite(Number(options.ttlMs)) && Number(options.ttlMs) >= 1 ? Number(options.ttlMs) : NONCE_TTL_MS; const logger = options.logger && typeof options.logger.debug === "function" ? options.logger : console; // The ONE Redis dial for this module. Resolves { ok: true, reply } when // Redis answered (reply may legitimately be null for a losing SET NX) and // { ok: false } for every unavailable shape: no client, not ready, dial // error, timeout, rejection. { ok: false } is the caller's signal to fall // back to the per-process cache. async function send(args) { let client = null; try { client = clientOf(); } catch (err) { logger.debug("[heartbeat-nonce-shared] clientOf failed:", err?.message || err); return { ok: false }; } if (!client || typeof client.sendCommand !== "function" || !readyOf()) return { ok: false }; let op; try { op = client.sendCommand(args.map((arg) => String(arg))); } catch (err) { logger.debug("[heartbeat-nonce-shared] Redis command error:", err?.message || err); return { ok: false }; } // The race below may abandon this promise on timeout; pre-attach a // rejection handler so a late connection error is never unhandled. op.catch(() => {}); let timer = null; try { const reply = await Promise.race([ op, new Promise((resolve) => { timer = setTimeout(() => resolve(SHARED_OP_TIMEOUT), opTimeoutMs); }), ]); if (reply === SHARED_OP_TIMEOUT) return { ok: false }; return { ok: true, reply }; } catch (err) { logger.debug("[heartbeat-nonce-shared] Redis op failed:", err?.message || err); return { ok: false }; } finally { if (timer) clearTimeout(timer); } } // Returns { sharedAvailable: true, replayed } when Redis answered, or // { sharedAvailable: false, replayed: false } when the caller must fall // back to its per-process cache. nowMs is accepted for interface parity // with the local cache's record(nonce, nowMs) but unused: Redis owns the // clock via the PX TTL. async function record(nodeId, nonce, nowMs) { const id = String(nodeId || "").trim(); const n = String(nonce || "").trim(); if (!id || !n) return { sharedAvailable: false, replayed: false }; const key = `${HEARTBEAT_NONCE_KEY_PREFIX}${id}:${n}`; const outcome = await send(["SET", key, "1", "NX", "PX", String(ttlMs)]); if (!outcome.ok) return { sharedAvailable: false, replayed: false }; return { sharedAvailable: true, replayed: outcome.reply !== "OK" }; } return { record }; } // Verifies the heartbeat envelope against the node's per-node signing secret. // headers is the request's headers object (Express req.headers or a plain // map). Returns a promise of { ok: true, envelope: "v1"|"v2", // nonceScope: "shared"|"local-fallback"|"local" } or // { ok: false, reason } with a stable machine readable reason mirroring the // daemon's vocabulary // (missing-signature/expired/bad-nonce/nonce-required/bad-signature/replayed) // plus the v2 body-binding reasons (bad-body-hash/body-unavailable/ // body-hash-mismatch) and nonce-cache-missing. The route renders EVERY // rejection as the same uniform 401 — reasons stay server-side only. // // rawBody — the EXACT raw request bytes (Buffer, or string) the // route captured pre-parse; required for v2, ignored // for v1. // nonceCache — the per-process cache (createNonceCache); fallback // arbiter and write-through companion of the shared // store. // sharedNonceStore — the cluster-shared arbiter // (createSharedHeartbeatNonceStore), when wired. // // record() is only ever called AFTER the signature verified, so // unauthenticated traffic can never poison either ledger. async function verifyHeartbeatEnvelope(headers, { secret, nodeId, nowMs, nonceCache, sharedNonceStore, rawBody }) { const h = headers || {}; const signingSecret = String(secret || "").trim(); if (!signingSecret) return { ok: false, reason: "hmac-not-configured" }; const ts = String(h["x-node-ts"] || "").trim(); const sig = String(h["x-node-sign"] || "").trim(); const nonce = String(h["x-node-nonce"] || "").trim(); if (!ts && !sig) return { ok: false, reason: "missing-signature" }; if (!ts || !sig) return { ok: false, reason: "missing-signature" }; const tsNum = Number(ts); if (!Number.isFinite(tsNum) || !/^-?\d{1,16}$/.test(ts)) return { ok: false, reason: "expired" }; const now = Number(nowMs) || Date.now(); const drift = Math.abs(now - tsNum); if (drift > DRIFT_MS) return { ok: false, reason: "expired" }; if (!nonce) return { ok: false, reason: "nonce-required" }; if (!isValidNonce(nonce)) return { ok: false, reason: "bad-nonce" }; // adpanel:heartbeat-body-binding — v2 discrimination by the presence of the // body-hash header. Fail closed on every degenerate v2 shape BEFORE the // signature step: a malformed hash, a mismatched hash (body tampered by // even one byte), or a v2 request whose raw bytes the server could not // capture. The last case is the anti-downgrade pin: v2 is NEVER verified // against re-serialized JSON, so a missing raw capture cannot be talked // into a pass — it is a uniform 401 like every other rejection. const declaredBodyHash = String(h[BODY_HASH_HEADER] || "").trim().toLowerCase(); let envelope = "v1"; let base; if (declaredBodyHash) { envelope = "v2"; if (!/^[0-9a-f]{64}$/.test(declaredBodyHash)) return { ok: false, reason: "bad-body-hash" }; const actualBodyHash = heartbeatBodySha256(rawBody); if (!actualBodyHash) return { ok: false, reason: "body-unavailable" }; if (!timingSafeHexEqual(actualBodyHash, declaredBodyHash)) { return { ok: false, reason: "body-hash-mismatch" }; } base = heartbeatSignatureBase(nodeId, ts, nonce, declaredBodyHash); } else { // v1 legacy envelope: id|ts|nonce only. Transitional acceptance — see the // operator note in the module header; the route warns once per process. base = heartbeatSignatureBase(nodeId, ts, nonce); } const expected = crypto.createHmac("sha256", signingSecret).update(base).digest("hex"); if (!timingSafeHexEqual(sig, expected)) return { ok: false, reason: "bad-signature" }; // Nonce replay: shared arbiter first, per-process cache as fallback and // write-through companion. "shared" = Redis decided; "local-fallback" = // Redis was wired but unavailable (route warns once); "local" = no shared // store wired (index.js has not injected the session client yet). const hasLocalCache = Boolean(nonceCache && typeof nonceCache.record === "function"); const hasSharedStore = Boolean(sharedNonceStore && typeof sharedNonceStore.record === "function"); if (!hasLocalCache && !hasSharedStore) return { ok: false, reason: "nonce-cache-missing" }; let nonceScope = "local"; if (hasSharedStore) { let shared = null; try { shared = await sharedNonceStore.record(nodeId, nonce, now); } catch (err) { shared = null; } if (shared && shared.sharedAvailable) { nonceScope = "shared"; if (shared.replayed) return { ok: false, reason: "replayed" }; // Write-through: keeps the local fallback warm, so a Redis outage // mid-window still catches replays on the workers that already saw // the nonce. if (hasLocalCache) nonceCache.record(nonce, now); } else { nonceScope = "local-fallback"; } } if (nonceScope !== "shared") { if (!hasLocalCache) return { ok: false, reason: "nonce-cache-missing" }; if (!nonceCache.record(nonce, now)) return { ok: false, reason: "replayed" }; } return { ok: true, envelope, nonceScope }; } module.exports = { DRIFT_MS, NONCE_TTL_MS, BODY_HASH_HEADER, HEARTBEAT_NONCE_KEY_PREFIX, isValidNonce, heartbeatSignatureBase, heartbeatBodySha256, createNonceCache, createSharedHeartbeatNonceStore, verifyHeartbeatEnvelope, };