"use strict"; const { createHmac, randomBytes, timingSafeEqual } = require("node:crypto"); const fs = require("node:fs/promises"); const http = require("node:http"); const path = require("node:path"); const RPC_VERSION = 18; const RPC_PATH = `/agent-rpc/${RPC_VERSION}`; const WORKER_SOCKET = "/run/adpanel-agent/worker.sock"; const PANEL_SOCKET_DIRECTORY = "/run/adpanel-agent-panel"; const AUTH_WINDOW_MS = 30_000; const MAX_NONCES = 4096; const MAX_REQUEST_BYTES = 64 * 1024; const MAX_RESPONSE_BYTES = 256 * 1024; const MAX_CONNECTIONS = 96; const RPC_TIMEOUT_MS = 15_000; class AgentRpcError extends Error { constructor(status, code) { super(code); this.status = status; this.code = code; } } function deriveRpcSecret(sessionSecret) { if (typeof sessionSecret !== "string" || !sessionSecret.trim()) { throw new Error("Agent RPC requires the panel session secret"); } return createHmac("sha256", sessionSecret).update(`adpanel-agent-rpc:${RPC_VERSION}`).digest(); } function sign(secret, receiver, timestamp, nonce, body) { return createHmac("sha256", secret).update(`${receiver}\n${RPC_PATH}\n${timestamp}\n${nonce}\n`).update(body).digest(); } function readBounded(stream, limit) { return new Promise((resolve, reject) => { let total = 0; const chunks = []; stream.on("error", reject); stream.on("aborted", () => reject(new AgentRpcError(503, "agent_unavailable"))); stream.on("data", (chunk) => { total += chunk.length; if (total > limit) { reject(new AgentRpcError(413, "agent_rpc_too_large")); stream.destroy(); } else { chunks.push(chunk); } }); stream.on("end", () => resolve(Buffer.concat(chunks, total))); }); } function sendJson(response, status, payload) { if (response.destroyed) return; const body = Buffer.from(JSON.stringify(payload)); if (body.length > MAX_RESPONSE_BYTES) { return sendJson(response, 503, { code: "agent_rpc_too_large" }); } response.writeHead(status, { "Content-Type": "application/json", "Content-Length": body.length, Connection: "close" }); response.end(body); } async function startAgentRpcServer({ socketPath, secret, receiver, handlers, onError = () => {} }) { const directory = await fs.stat(path.dirname(socketPath)); if (!directory.isDirectory() || directory.uid !== process.getuid() || (directory.mode & 0o077)) { throw new Error("Agent RPC directory must be owner-only"); } const seen = new Map(); const sockets = new Set(); const server = http.createServer({ requestTimeout: RPC_TIMEOUT_MS, headersTimeout: 5000 }, async (request, response) => { response.on("error", () => {}); request.on("error", () => {}); if (request.method !== "POST" || request.url !== RPC_PATH) { return sendJson(response, 404, { code: "agent_rpc_version" }); } const timestamp = request.headers["x-agent-time"]; const nonce = request.headers["x-agent-nonce"]; const signature = request.headers["x-agent-signature"]; const now = Date.now(); if (!/^\d{13}$/.test(timestamp) || Math.abs(now - Number(timestamp)) > AUTH_WINDOW_MS || !/^[a-f0-9]{32}$/.test(nonce) || !/^[a-f0-9]{64}$/.test(signature)) { return sendJson(response, 403, { code: "agent_rpc_auth" }); } if (Number(request.headers["content-length"]) > MAX_REQUEST_BYTES) { return sendJson(response, 413, { code: "agent_rpc_too_large" }); } const controller = new AbortController(); response.once("close", () => controller.abort()); try { const body = await readBounded(request, MAX_REQUEST_BYTES); if (!timingSafeEqual(sign(secret, receiver, timestamp, nonce, body), Buffer.from(signature, "hex"))) { return sendJson(response, 403, { code: "agent_rpc_auth" }); } const verifiedAt = Date.now(); for (const [key, expires] of seen) { if (expires > verifiedAt) break; seen.delete(key); } if (Math.abs(verifiedAt - Number(timestamp)) > AUTH_WINDOW_MS || seen.has(nonce)) { return sendJson(response, 403, { code: "agent_rpc_auth" }); } if (seen.size >= MAX_NONCES) return sendJson(response, 503, { code: "agent_rpc_busy" }); seen.set(nonce, verifiedAt + 2 * AUTH_WINDOW_MS); const { operation, args } = JSON.parse(body); if (typeof operation !== "string" || !Object.hasOwn(handlers, operation)) { return sendJson(response, 404, { code: "agent_rpc_operation" }); } const result = await handlers[operation](args, controller.signal); return sendJson(response, 200, { result }); } catch (error) { if (error instanceof AgentRpcError) return sendJson(response, error.status, { code: error.code }); onError(); return sendJson(response, 503, { code: "agent_unavailable" }); } }); server.maxConnections = MAX_CONNECTIONS; server.on("connection", (socket) => { sockets.add(socket); socket.on("error", () => {}); socket.on("close", () => sockets.delete(socket)); socket.setTimeout(RPC_TIMEOUT_MS, () => socket.destroy()); }); await new Promise((resolve, reject) => { server.once("error", reject); server.listen(socketPath, resolve); }); server.on("error", onError); try { await fs.chmod(socketPath, 0o600); } catch (error) { server.close(); throw error; } return () => new Promise((resolve) => { server.close(resolve); for (const socket of sockets) socket.destroy(); }); } function createAgentRpcClient({ socketPath, secret, receiver, timeoutMs = RPC_TIMEOUT_MS }) { return async (operation, args = null, signal) => { signal?.throwIfAborted(); const body = Buffer.from(JSON.stringify({ operation, args })); if (body.length > MAX_REQUEST_BYTES) throw new AgentRpcError(413, "agent_rpc_too_large"); const timestamp = String(Date.now()); const nonce = randomBytes(16).toString("hex"); return new Promise((resolve, reject) => { const request = http.request({ socketPath, path: RPC_PATH, method: "POST", agent: false, signal, headers: { "Content-Type": "application/json", "Content-Length": body.length, "X-Agent-Time": timestamp, "X-Agent-Nonce": nonce, "X-Agent-Signature": sign(secret, receiver, timestamp, nonce, body).toString("hex"), } }, (response) => { readBounded(response, MAX_RESPONSE_BYTES).then((data) => { const payload = JSON.parse(data); if (response.statusCode !== 200) throw new AgentRpcError(response.statusCode, payload.code || "agent_unavailable"); resolve(payload.result); }).catch(reject); }); const deadline = setTimeout(() => request.destroy(new AgentRpcError(503, "agent_unavailable")), timeoutMs); request.on("error", (error) => reject(signal?.aborted ? signal.reason : error instanceof AgentRpcError ? error : new AgentRpcError(503, "agent_unavailable"))); request.on("close", () => clearTimeout(deadline)); request.end(body); }); }; } async function listPanelAgentSockets() { const names = await fs.readdir(PANEL_SOCKET_DIRECTORY); const sockets = []; for (const name of names) { const match = /^panel-(\d+)\.sock$/.exec(name); if (!match) continue; const socketPath = path.join(PANEL_SOCKET_DIRECTORY, name); try { process.kill(Number(match[1]), 0); } catch (error) { if (error.code === "ESRCH") await fs.unlink(socketPath).catch(() => {}); continue; } sockets.push(socketPath); } if (sockets.length > 48) throw new AgentRpcError(503, "agent_panel_busy"); return sockets; } function createPanelAgentRpcClient({ secret, listSockets = listPanelAgentSockets }) { const unavailablePeer = new Set(["agent_unavailable", "agent_rpc_version", "agent_rpc_auth"]); let lastHealthySocket; async function probe(generation, signal) { const sockets = await listSockets(); const controller = new AbortController(); const probeSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal; const preferred = lastHealthySocket; async function verify(socketPath) { const call = createAgentRpcClient({ socketPath, receiver: "panel", secret, timeoutMs: 200 }); const health = await call("health", null, probeSignal); if (health?.version !== RPC_VERSION || health.generation !== generation) { throw new AgentRpcError(503, "agent_panel_unavailable"); } return socketPath; } try { if (sockets.includes(preferred)) { try { await verify(preferred); return; } catch { } } lastHealthySocket = await Promise.any(sockets.filter((socketPath) => socketPath !== preferred).map(verify)); } catch { lastHealthySocket = undefined; signal?.throwIfAborted(); throw new AgentRpcError(503, "agent_panel_unavailable"); } finally { controller.abort(); } } async function request(operation, args, signal) { const sockets = await listSockets(); // adpanel:agent-auto-edit - a lost write response must not dispatch to another panel process. if (operation === "autoFileEdit") { if (!lastHealthySocket || !sockets.includes(lastHealthySocket)) throw new AgentRpcError(503, "agent_panel_unavailable"); return createAgentRpcClient({ socketPath: lastHealthySocket, receiver: "panel", secret, timeoutMs: 12_000 })(operation, args, signal); } const peers = lastHealthySocket && sockets.includes(lastHealthySocket) ? [lastHealthySocket, ...sockets.filter((socketPath) => socketPath !== lastHealthySocket)] : sockets; for (const socketPath of peers) { signal?.throwIfAborted(); const call = createAgentRpcClient({ socketPath, receiver: "panel", secret, timeoutMs: 12_000 }); try { return await call(operation, args, signal); } catch (error) { if (!(error instanceof AgentRpcError) || !unavailablePeer.has(error.code)) throw error; } } throw new AgentRpcError(503, "agent_panel_unavailable"); } return { probe, request }; } module.exports = { AgentRpcError, RPC_VERSION, WORKER_SOCKET, PANEL_SOCKET_DIRECTORY, MAX_RESPONSE_BYTES, deriveRpcSecret, startAgentRpcServer, createAgentRpcClient, listPanelAgentSockets, createPanelAgentRpcClient };