Files
Kelx/nodes.js
T
2026-06-10 17:04:11 +00:00

3402 lines
133 KiB
JavaScript

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");
let _Busboy; function getLazyBusboy() { if (!_Busboy) _Busboy = require("busboy"); return _Busboy; }
const db = require("./db");
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 || "", 15) || 5000;
try { fs.mkdirSync(ACTIVITY_LOGS_DIR, { recursive: true }); } catch { }
const activityLogBuffers = new Map();
const activityLogWriteTimers = new Map();
function getActivityLogPath(serverName) {
const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_");
return path.join(ACTIVITY_LOGS_DIR, `${safeName}.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;
const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_");
const rotatedPath = logPath.replace(/\.log$/, `.${Date.now()}.log`);
await fsp.rename(logPath, rotatedPath);
setImmediate(async () => {
try {
const files = await fsp.readdir(ACTIVITY_LOGS_DIR);
const serverFiles = files
.filter(f => f.startsWith(safeName + ".") && f.endsWith(".log") && f !== `${safeName}.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 { }
}
async function flushActivityLogs(serverName) {
const buffer = activityLogBuffers.get(serverName);
if (!buffer || buffer.length === 0) return;
activityLogBuffers.set(serverName, []);
activityLogWriteTimers.delete(serverName);
const logPath = getActivityLogPath(serverName);
const lines = buffer.map(entry => JSON.stringify(entry)).join("\n") + "\n";
try {
await rotateActivityLogIfNeeded(serverName);
await fsp.appendFile(logPath, lines, "utf8");
} catch (err) {
console.error(`[activity-log] Write error for ${serverName}:`, err?.message || err);
}
}
let _webhookDispatcher = null;
function setWebhookDispatcher(fn) { _webhookDispatcher = fn; }
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);
}
}
}
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);
}
}
function getRequestIp(req) {
const xff = req.headers["x-forwarded-for"];
if (xff) {
const first = String(xff).split(",")[0].trim();
if (first) return first;
}
return req.ip || req.connection?.remoteAddress || "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 _serverActionObserver = null;
function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn) {
_getEffectivePermsForUserOnServer = getPerms;
_isAdmin = isAdminFn;
_userHasAccessToServer = hasAccessFn || null;
}
function setServerActionObserver(fn) {
_serverActionObserver = typeof fn === "function" ? fn : null;
}
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" };
}
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) {
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 PANEL_HMAC_SECRET = (process.env.PANEL_HMAC_SECRET || "").trim();
const DAEMON_INSTALL_SCRIPT_PATH = path.join(__dirname, "install-daemon.sh");
const NODE_INSTALLER_TOKEN_TTL_MS = parseInt(process.env.NODE_INSTALLER_TOKEN_TTL_MS || "", 10) || 60 * 60 * 1000;
const NODE_INSTALLER_TOKEN_SECRET = (process.env.NODE_INSTALLER_TOKEN_SECRET || process.env.SESSION_SECRET || "").trim();
(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);
}
}
})();
function safeCompare(a, b) {
if (typeof a !== "string" || typeof b !== "string") 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 b64urlEncode(input) {
const buf = Buffer.isBuffer(input) ? input : Buffer.from(String(input));
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function b64urlDecode(input) {
const value = String(input || "").trim().replace(/-/g, "+").replace(/_/g, "/");
const pad = value.length % 4 ? "=".repeat(4 - (value.length % 4)) : "";
return Buffer.from(value + pad, "base64");
}
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(/=+$/, "");
}
function sanitizeName(raw) {
let s = String(raw || "").trim();
if (!s) return "";
s = s.replace(/[^\w\-. ]+/g, " ").replace(/\s+/g, " ").trim();
s = s.replace(/\s/g, "-");
if (s.length > 100) s = s.slice(0, 100);
return s;
}
function isInt(n) { return Number.isInteger(n); }
function toInt(n, def = 0) { const x = Number(n); return Number.isFinite(x) ? Math.round(x) : def; }
function clampPort(p) {
const n = toInt(p, 8080);
if (n < 1 || n > 65535) return 8080;
return n;
}
function normalizePorts(input) {
if (!input) return { mode: "range", start: 25565, count: 10 };
if (Array.isArray(input)) {
const ports = Array.from(new Set(input.map(p => toInt(p)).filter(p => p >= 1 && p <= 65535)));
return { mode: "list", ports };
}
if (typeof input === "object") {
if (input.mode === "range") {
let start = toInt(input.start, 25565);
let count = toInt(input.count, 10);
if (start < 1 || start > 65535) start = 25565;
if (count < 1) count = 1;
if (start + count - 1 > 65535) count = 65535 - start + 1;
return { mode: "range", start, count };
}
if (input.mode === "list") {
const ports = Array.from(new Set((input.ports || [])
.map(p => toInt(p))
.filter(p => p >= 1 && p <= 65535)));
return { mode: "list", ports };
}
}
return { mode: "range", start: 25565, count: 10 };
}
function isPortInNodeAllocation(node, port) {
const p = Number(port);
if (!Number.isFinite(p) || p < 1 || p > 65535) return false;
const alloc = node && node.ports;
if (!alloc) return true;
if (alloc.mode === "range") {
const start = Number(alloc.start || 0);
const count = Number(alloc.count || 0);
if (start <= 0 || count <= 0) return true;
return p >= start && p < start + count;
}
if (alloc.mode === "list" && Array.isArray(alloc.ports)) {
if (alloc.ports.length === 0) return true;
return alloc.ports.includes(p);
}
return true;
}
function truthyFlag(value) {
if (typeof value === "boolean") return value;
if (typeof value === "number") return value === 1;
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on";
}
return false;
}
const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]);
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;
function cloudflareHttpsEdgePort(port) {
const p = clampPort(port || 443);
return CLOUDFLARE_HTTPS_EDGE_PORTS.has(p) ? p : 443;
}
function isCloudflareHttpsPort(port) {
return CLOUDFLARE_HTTPS_EDGE_PORTS.has(clampPort(port || 0));
}
function hasExplicitHostPort(host) {
const value = String(host || "").trim();
if (value.startsWith("[")) return /\]:\d+$/.test(value);
return /^[^:]+:\d+$/.test(value);
}
function explicitHostPort(host) {
const value = String(host || "").trim();
const match = value.startsWith("[")
? value.match(/\]:(\d+)$/)
: value.match(/^[^:]+:(\d+)$/);
return match ? Number(match[1]) : null;
}
function stripExplicitHostPort(host) {
const value = String(host || "").trim();
if (!hasExplicitHostPort(value)) return value;
if (value.startsWith("[")) return value.replace(/\]:\d+$/, "]");
return value.replace(/:\d+$/, "");
}
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")));
});
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;
}
function extractHostnameForCloudflareCheck(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) : "";
} 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 "";
return /^[a-z0-9.-]+$/i.test(host) ? host : "";
}
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) {
const hostname = extractHostnameForCloudflareCheck(address);
if (!hostname) {
return {
ok: false,
error: "Under Cloudflare requires a public hostname, not an IP address or localhost.",
};
}
const [{ ips, resolver, error }, ranges] = await Promise.all([
resolvePublicHostnameIps(hostname),
getCloudflareIpRanges(),
]);
if (!ips.length) {
return {
ok: false,
error: `Could not resolve ${hostname} in public DNS for Cloudflare proxy verification.`,
detail: error || 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 };
}
function nodeUnderCloudflare(node) {
const bc = (node && typeof node.buildConfig === "object") ? node.buildConfig : {};
return truthyFlag(node?.under_cloudflare)
|| truthyFlag(node?.cloudflare_proxy)
|| truthyFlag(bc.under_cloudflare)
|| truthyFlag(bc.cloudflare_proxy);
}
function hardenNode(n) {
const clone = Object.assign({
id: uid(),
uuid: "",
name: "node",
address: "",
ram_mb: 0,
disk_gb: 0,
ports: { mode: "range", start: 25565, count: 10 },
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 = sanitizeName(clone.name || "node");
clone.address = String(clone.address || "").trim();
clone.ports = normalizePorts(clone.ports);
if (!clone.token_id) clone.token_id = randTokenId();
if (!clone.token) clone.token = randSecret();
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 : {};
clone.under_cloudflare = nodeUnderCloudflare(clone);
clone.buildConfig.under_cloudflare = !!clone.under_cloudflare;
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, { mode: "range", start: 25565, count: 10 }),
token_id: row.token_id,
token: row.token,
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,
});
}
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));
const offset = (page - 1) * limit;
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);
}
// MariaDB on this project rejects prepared placeholders inside LIMIT/OFFSET.
dataSql += ` ORDER BY name ASC LIMIT ${limit} OFFSET ${offset}`;
const [countRows, dataRows] = await Promise.all([
db.query(countSql, countParams),
db.query(dataSql, params)
]);
const total = Number(countRows[0]?.total || 0);
return { nodes: dataRows.map(mapNodeRow), total, page, limit, totalPages: Math.ceil(total / limit) || 1 };
}
async function findNodeByIdOrName(idOrName) {
const key = String(idOrName || "").trim().toLowerCase();
if (!key) return null;
const rows = await db.query(
"SELECT * FROM nodes WHERE id = ? OR uuid = ? OR LOWER(name) = ? LIMIT 1",
[key, key, key]
);
return rows.length ? mapNodeRow(rows[0]) : 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, 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,
payload.token,
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) {
const payload = hardenNode(node);
const online = computeOnline(payload);
await db.query(
`UPDATE nodes SET
uuid = ?, name = ?, address = ?, ram_mb = ?, disk_gb = ?, ports = ?, token_id = ?, token = ?, 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,
payload.token,
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;
}
async function deleteNode(nodeId) {
await db.query("DELETE FROM nodes WHERE id = ? OR uuid = ?", [nodeId, nodeId]);
}
function sanitizeUpdatePayload(body) {
const out = {};
if (typeof body.name !== "undefined") out.name = sanitizeName(body.name);
if (typeof body.address !== "undefined") out.address = String(body.address || "").trim();
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;
out.ports = normalizePorts(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) {
const fresh = !!(n.last_seen && (Date.now() - Number(n.last_seen)) < HEARTBEAT_TTL_MS);
return !!(fresh && n.port_ok === true);
}
function toPublic(n, includeSecrets = false) {
const bc = n.buildConfig || {};
const out = {
id: n.id,
uuid: n.uuid,
name: n.name,
address: n.address,
cpu_cores: bc.cpu_cores || 0,
ram_mb: n.ram_mb,
disk_gb: n.disk_gb,
ports: n.ports,
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),
port_ok: n.port_ok,
last_seen: n.last_seen,
online: computeOnline(n),
buildConfig: bc
};
if (includeSecrets) {
out.token_id = n.token_id;
out.token = n.token;
}
return out;
}
function includeNodeSecrets(req) {
return !!(req && req.isAdmin);
}
function buildNodeBaseUrl(address, port, sslEnabled, underCloudflare = false) {
let base = String(address || "").trim();
if (!base) return null;
const cloudflareProxy = truthyFlag(underCloudflare);
if (/^https?:\/\//i.test(base)) {
try {
const u = new URL(base);
u.hash = "";
u.search = "";
u.pathname = "";
if (cloudflareProxy) {
u.protocol = "https:";
const edgePort = cloudflareHttpsEdgePort(u.port || port);
u.port = edgePort === 443 ? "" : String(edgePort);
return u.origin;
}
if (!u.port) u.port = String(port || 8080);
return u.toString().replace(/\/$/, "");
} catch {
}
}
if (cloudflareProxy) {
base = base.split(/[/?#]/)[0];
const edgePort = cloudflareHttpsEdgePort(explicitHostPort(base) || port);
base = stripExplicitHostPort(base);
if (edgePort !== 443) base += `:${edgePort}`;
return `https://${base}`;
}
const proto = sslEnabled ? "https" : "http";
return `${proto}://${base}:${clampPort(port || 8080)}`;
}
function httpRequestJson(fullUrl, method = "GET", headers = {}, timeoutMs = 2500) {
return new Promise((resolve) => {
try {
const lib = fullUrl.startsWith("https:") ? https : http;
const req = lib.request(fullUrl, { method, headers }, (res) => {
const { statusCode } = res;
const chunks = [];
res.on("data", (d) => chunks.push(d));
res.on("end", () => {
const bodyStr = Buffer.concat(chunks).toString("utf8");
try {
const json = bodyStr ? JSON.parse(bodyStr) : null;
resolve({ status: statusCode, json });
} catch {
resolve({ status: statusCode, json: null });
}
});
});
req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); });
req.on("error", () => resolve({ status: 0, json: null }));
req.setTimeout(timeoutMs);
req.end();
} catch {
resolve({ status: 0, json: null });
}
});
}
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;
}
function isLoopbackAddress(value) {
const host = String(value || "").trim().toLowerCase();
return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]";
}
function callNodeApiOnce(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = DEFAULT_NODE_TIMEOUT_MS) {
return new Promise((resolve) => {
try {
const isHttps = fullUrl.startsWith("https:");
const lib = isHttps ? https : http;
const req = lib.request(fullUrl, { method, headers }, (res) => {
const chunks = [];
res.on("data", (d) => chunks.push(d));
res.on("end", () => {
const bodyStr = Buffer.concat(chunks).toString("utf8");
try {
const json = bodyStr ? JSON.parse(bodyStr) : null;
resolve({ status: res.statusCode, json, error: null });
} catch {
resolve({ status: res.statusCode, json: null, error: null });
}
});
});
req.on("timeout", () => {
try { req.destroy(new Error("timeout")); } catch { }
resolve({ status: 0, json: null, error: "timeout" });
});
req.on("error", (err) => resolve({ status: 0, json: null, error: err?.message || "request error" }));
req.setTimeout(timeoutMs);
if (body) req.write(JSON.stringify(body));
req.end();
} catch {
resolve({ status: 0, json: null, error: "request setup failed" });
}
});
}
async function resolveLoopbackNodeBase(node, timeoutMs = 1200) {
if (!node || isLoopbackAddress(node.address)) return null;
const candidates = [];
const primaryProto = node.ssl_enabled ? "https" : "http";
candidates.push(`${primaryProto}://127.0.0.1:${clampPort(node.api_port || 8080)}`);
candidates.push(`${primaryProto}://localhost:${clampPort(node.api_port || 8080)}`);
if (primaryProto === "https") {
candidates.push(`http://127.0.0.1:${clampPort(node.api_port || 8080)}`);
candidates.push(`http://localhost:${clampPort(node.api_port || 8080)}`);
}
const expectedUuid = String(node.uuid || node.id || "").trim();
for (const base of candidates) {
const probe = await callNodeApiOnce(`${base}/health`, "GET", {}, null, timeoutMs);
if (probe.status !== 200 || !probe.json) continue;
const gotUuid = String(probe.json.uuid || "").trim();
if (expectedUuid && gotUuid && gotUuid === expectedUuid) {
return base;
}
}
return null;
}
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",
};
const primaryRes = await callNodeApiOnce(`${base}${safeSuffix}`, method, headers, body, timeoutMs);
if (primaryRes.status !== 0) return primaryRes;
const fallbackBase = await resolveLoopbackNodeBase(node, Math.min(timeoutMs, 1500));
if (!fallbackBase || fallbackBase === base) return primaryRes;
const fallbackRes = await callNodeApiOnce(`${fallbackBase}${safeSuffix}`, method, headers, body, timeoutMs);
if (fallbackRes.status !== 0) {
return { ...fallbackRes, via: "loopback-fallback" };
}
return primaryRes;
}
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 replaceAllLiteral(value, search, replacement) {
return String(value).split(search).join(replacement);
}
function shellSingleQuote(value) {
return `'${String(value == null ? "" : value).replace(/'/g, `'\\''`)}'`;
}
function buildPanelPublicUrl(req) {
if (PANEL_PUBLIC_URL) return PANEL_PUBLIC_URL.replace(/\/+$/, "");
console.warn("[SECURITY] PANEL_PUBLIC_URL not set - node installer/config URLs are derived from request headers. Set PANEL_PUBLIC_URL for production.");
const host = req?.get?.("x-forwarded-host") || req?.get?.("host") || "localhost";
const proto = (req?.get?.("x-forwarded-proto") || req?.protocol || "http");
return `${proto}://${host}`.replace(/\/+$/, "");
}
function nodeInstallerSigningKey(node) {
return [
NODE_INSTALLER_TOKEN_SECRET,
node?.uuid || "",
node?.id || "",
node?.token_id || "",
node?.token || "",
].join("\n");
}
function signNodeInstallerPayload(payloadB64, node) {
return b64urlEncode(crypto.createHmac("sha256", nodeInstallerSigningKey(node)).update(payloadB64).digest());
}
function issueNodeInstallerToken(node) {
const payload = {
v: 1,
typ: "node-installer",
node: String(node?.uuid || node?.id || ""),
exp: Date.now() + NODE_INSTALLER_TOKEN_TTL_MS,
};
const payloadB64 = b64urlEncode(JSON.stringify(payload));
return `${payloadB64}.${signNodeInstallerPayload(payloadB64, node)}`;
}
function verifyNodeInstallerToken(token, node) {
const parts = String(token || "").trim().split(".");
if (parts.length !== 2) return false;
const expectedSig = signNodeInstallerPayload(parts[0], node);
if (!safeCompare(parts[1], expectedSig)) return false;
let payload;
try {
payload = JSON.parse(b64urlDecode(parts[0]).toString("utf8"));
} catch {
return false;
}
const allowedNodeIds = new Set([String(node?.uuid || ""), String(node?.id || "")].filter(Boolean));
return payload
&& payload.v === 1
&& payload.typ === "node-installer"
&& allowedNodeIds.has(String(payload.node || ""))
&& Number(payload.exp || 0) >= Date.now();
}
function getNodeInstallerTokenFromRequest(req) {
return String(req?.get?.("x-node-installer") || req?.query?.installer || "").trim();
}
function buildNodeInstallerUrl(node, req) {
const id = encodeURIComponent(String(node?.uuid || node?.id || ""));
const base = buildPanelPublicUrl(req);
const url = new URL(`/api/nodes/${id}/install-daemon.sh`, base);
url.searchParams.set("installer", issueNodeInstallerToken(node));
return url.toString();
}
function buildNodeConfigRestartCommand(configYml) {
const config = String(configYml || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n*$/, "\n");
return [
`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`,
`$SUDO install -d -m 0750 /var/lib/node`,
`$SUDO tee /var/lib/node/config.yml >/dev/null <<'ADPANEL_CONFIG_YML'`,
config,
`ADPANEL_CONFIG_YML`,
`$SUDO chown adaemon:adaemon /var/lib/node/config.yml 2>/dev/null || true`,
`$SUDO chmod 0640 /var/lib/node/config.yml`,
`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`,
].join("\n");
}
async function isOpenNodeInstallerRoute(req) {
if (String(req?.method || "GET").toUpperCase() !== "GET") return false;
const match = /^\/api\/nodes\/([^/]+)\/install-daemon\.sh$/.exec(String(req?.path || ""));
if (!match) return false;
const node = await findNodeByIdOrName(safeDecodeURIComponent(match[1]));
if (!node) return false;
return verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node);
}
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 };
}
function httpRequestJsonWithBody(fullUrl, method = "POST", body = null, headers = {}, timeoutMs = 8000) {
return new Promise((resolve) => {
try {
const lib = fullUrl.startsWith("https:") ? https : http;
const payload = body ? Buffer.from(JSON.stringify(body)) : null;
const req = lib.request(fullUrl, {
method,
headers: {
"Content-Type": "application/json",
...(payload ? { "Content-Length": payload.length } : {}),
...headers
}
}, (res) => {
const { statusCode } = res;
const chunks = [];
res.on("data", (d) => chunks.push(d));
res.on("end", () => {
const bodyStr = Buffer.concat(chunks).toString("utf8");
try {
const json = bodyStr ? JSON.parse(bodyStr) : null;
resolve({ status: statusCode, json });
} catch {
resolve({ status: statusCode, json: null });
}
});
});
req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); });
req.on("error", () => resolve({ status: 0, json: null }));
req.setTimeout(timeoutMs);
if (payload) req.write(payload);
req.end();
} catch {
resolve({ status: 0, json: null });
}
});
}
function httpJson(fullUrl, { method = "GET", headers = {}, body = null, timeoutMs = 5000 } = {}) {
return new Promise((resolve) => {
try {
const lib = fullUrl.startsWith("https:") ? https : http;
const opts = { method, headers };
const req = lib.request(fullUrl, opts, (res) => {
const chunks = [];
res.on("data", (d) => chunks.push(d));
res.on("end", () => {
const text = Buffer.concat(chunks).toString("utf8");
let json = null;
try { json = text ? JSON.parse(text) : null; } catch { }
resolve({ status: res.statusCode, json, text });
});
});
req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); });
req.on("error", () => resolve({ status: 0, json: null }));
req.setTimeout(timeoutMs);
if (body != null) {
const data = typeof body === "string" ? body : JSON.stringify(body);
if (!headers["Content-Type"]) req.setHeader("Content-Type", "application/json");
req.setHeader("Content-Length", Buffer.byteLength(data));
req.write(data);
}
req.end();
} catch {
resolve({ status: 0, json: null });
}
});
}
function tcpCheck(host, port, timeoutMs = 2000) {
return new Promise((resolve) => {
try {
const socket = new net.Socket();
let finished = false;
const done = (ok) => {
if (finished) return;
finished = true;
try { socket.destroy(); } catch { }
resolve(!!ok);
};
socket.setTimeout(timeoutMs);
socket.once("connect", () => done(true));
socket.once("timeout", () => done(false));
socket.once("error", () => done(false));
socket.connect(clampPort(port || 8080), host);
} catch {
resolve(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;
const baseUrl = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node));
if (baseUrl) {
const checkTimeout = 1500;
try {
const [infoRes, healthRes] = await Promise.all([
httpRequestJson(`${baseUrl}/v1/info`, "GET", { "Authorization": `Bearer ${node.token}` }, checkTimeout),
httpRequestJson(`${baseUrl}/health`, "GET", {}, checkTimeout)
]);
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);
}
}
if (!ok && healthRes.status === 200 && healthRes.json && healthRes.json.uuid) {
const uuid = String(healthRes.json.uuid || "");
if (uuid && (uuid === node.uuid || uuid === node.id)) ok = true;
}
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.`);
}
} catch {
ok = false;
}
}
node.port_ok = !!ok;
if (ok) {
node.last_seen = now;
}
}
function buildConfigYml(node, req) {
const panelUrl = buildPanelPublicUrl(req);
const sslEnabled = !!node.ssl_enabled;
const tlsPaths = defaultNodeTlsPaths(node);
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:`,
` host: 0.0.0.0`,
` port: ${node.api_port || 8080}`,
` 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}`
];
if (PANEL_HMAC_SECRET) {
lines.push(` hmac_secret: ${yamlDoubleQuote(PANEL_HMAC_SECRET)}`);
}
return lines.join("\n") + "\n";
}
function buildDaemonInstallScript(node, req) {
const configB64 = Buffer.from(buildConfigYml(node, req), "utf8").toString("base64");
if (!fs.existsSync(DAEMON_INSTALL_SCRIPT_PATH)) {
throw new Error("install-daemon.sh not found");
}
let script = fs.readFileSync(DAEMON_INSTALL_SCRIPT_PATH, "utf8");
if (script.includes("__ADPANEL_NODE_CONFIG_B64__")) {
return [
["__ADPANEL_NODE_CONFIG_B64__", configB64],
["__ADPANEL_NODE_API_PORT__", String(node.api_port || 8080)],
["__ADPANEL_NODE_SFTP_PORT__", String(node.sftp_port || 2022)],
].reduce((out, [search, replacement]) => replaceAllLiteral(out, search, replacement), script);
}
return [
"export ADPANEL_NODE_CONFIG_B64=" + shellSingleQuote(configB64),
"export ADPANEL_NODE_API_PORT=" + shellSingleQuote(String(node.api_port || 8080)),
"export ADPANEL_NODE_SFTP_PORT=" + shellSingleQuote(String(node.sftp_port || 2022)),
script,
].join("\n");
}
function oneTimeCommand(node, req) {
return buildNodeConfigRestartCommand(buildConfigYml(node, req));
}
const app = express();
app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true }));
const CORS_ALLOWED_ORIGINS = new Set(
(process.env.NODES_CORS_ORIGINS || "")
.split(",")
.map(s => s.trim())
.filter(Boolean)
);
function sameOrigin(req, origin) {
const host = req.get("host");
if (!host) return false;
const proto = (req.get("x-forwarded-proto") || req.protocol || "http");
const expected = `${proto}://${host}`;
return origin === expected;
}
function applyCors(req, res) {
const origin = req.get("origin");
if (!origin) return;
if (CORS_ALLOWED_ORIGINS.size > 0) {
if (!CORS_ALLOWED_ORIGINS.has(origin)) return;
} else if (!sameOrigin(req, 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");
}
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|extract|archive|backups(\/[^/]+)?(\/restore)?)$/;
app.use(async (req, res, next) => {
try {
const path = req.path || "";
if (path === "/health") return next();
if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next();
if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next();
if (await isOpenNodeInstallerRoute(req)) return next();
if (path.startsWith("/api/nodes")) {
if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" });
}
}
return next();
} catch (err) {
return next(err);
}
});
app.get("/health", (_req, res) => res.json({ ok: true }));
app.get("/api/nodes", async (req, res) => {
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, includeNodeSecrets(req))),
total: result.total,
page: result.page,
limit: result.limit,
totalPages: result.totalPages
});
}
const list = await loadNodes();
res.json({ nodes: list.map((n) => toPublic(n, includeNodeSecrets(req))) });
});
app.get("/api/nodes/:id", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
res.json(toPublic(node, includeNodeSecrets(req)));
});
app.post("/api/nodes/:id/check", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
await activeCheckNode(node, { force: true });
await saveNode(node);
const isOnline = computeOnline(node);
res.json({ ok: isOnline, node: toPublic(node, includeNodeSecrets(req)) });
});
app.get("/api/nodes/:id/ports/check", async (req, res) => {
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 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 });
});
app.post("/api/nodes/:id/servers/create", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "node_not_found" });
const name = String(req.body?.name || "").trim();
const templateId = String(req.body?.templateId || "minecraft");
const mcFork = String(req.body?.mcFork || "paper");
const mcVersion = String(req.body?.mcVersion || "1.21.8");
const requestedHostPort = req.body?.hostPort;
const hostPort = requestedHostPort == null || String(requestedHostPort).trim() === ""
? 25565
: validatePortInput(requestedHostPort);
const autoStart = !!req.body?.autoStart;
if (!name) return res.status(400).json({ error: "missing_name" });
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 = "";
}
if (hostPort > 0 && !isPortInNodeAllocation(node, hostPort)) {
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.status(400).json({ error: `Port ${hostPort} is not in this node's allocated ports (${allocDesc}).` });
}
if (hostPort > 0) {
const portCheck = await callNodeApi(node, `/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 res.status(409).json({ error: `Port ${hostPort} is already in use on this node${owner}.`, code: "port_in_use" });
}
}
const { status, json } = await callNodeApi(
node, "/v1/servers/create", "POST",
{ name, templateId, mcFork, mcVersion, hostPort, autoStart, ...(diskId ? { diskId } : {}) },
LONG_NODE_TIMEOUT_MS
);
if (status === 200 && json && json.ok) return res.json(json);
if (isRecoverableNodeCreateStatus(status)) {
const recovered = await waitForNodeServerReady(node, name, {
timeoutMs: nodeUnderCloudflare(node) ? 180_000 : 30_000,
intervalMs: 3000,
});
if (recovered) return res.json({ ok: true, name, recovered: true });
}
return res.status(500).json({ error: "node_create_failed", status, detail: json && json.error });
});
app.post("/api/nodes", async (req, res) => {
const body = req.body || {};
const name = sanitizeName(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();
const exists = await db.query("SELECT id FROM nodes WHERE LOWER(name) = ? LIMIT 1", [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;
const ports = normalizePorts(body.ports);
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." });
}
if (under_cloudflare) {
const cloudflareCheck = await verifyCloudflareProxiedAddress(address);
if (!cloudflareCheck.ok) {
return res.status(400).json({
error: cloudflareCheck.error,
detail: cloudflareCheck.detail || undefined,
});
}
}
const 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
}
});
res.json(toPublic(node, includeNodeSecrets(req)));
});
app.patch("/api/nodes/:id", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
const current = hardenNode(node);
const upd = sanitizeUpdatePayload(req.body || {});
if (typeof upd.name !== "undefined" && upd.name) current.name = upd.name;
if (typeof upd.address !== "undefined") current.address = upd.address;
if (typeof upd.cpu_cores !== "undefined" && upd.cpu_cores >= 0) {
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" && upd.ram_mb >= 0) current.ram_mb = upd.ram_mb;
if (typeof upd.disk_gb !== "undefined" && upd.disk_gb >= 0) current.disk_gb = upd.disk_gb;
if (typeof upd.ports !== "undefined") current.ports = normalizePorts(upd.ports);
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 (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare && !isCloudflareHttpsPort(current.api_port)) {
return res.status(400).json({ 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);
if (!cloudflareCheck.ok) {
return res.status(400).json({
error: cloudflareCheck.error,
detail: cloudflareCheck.detail || undefined,
});
}
}
current.last_check = null;
const saved = await saveNode(current);
res.json(toPublic(saved, includeNodeSecrets(req)));
});
app.delete("/api/nodes/:id", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
const assignedServers = await db.query(
"SELECT COUNT(*) AS cnt FROM servers WHERE node_id = ?",
[node.id]
);
const serverCount = Number(assignedServers[0]?.cnt || 0);
if (serverCount > 0) {
return res.status(409).json({
error: `Cannot delete node — ${serverCount} server${serverCount === 1 ? " is" : "s are"} still assigned to it. Reassign or delete them first.`
});
}
await deleteNode(node.id);
res.json({ ok: true, deleted: node.id });
});
app.get("/api/nodes/:id/build", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
res.json({ build: node.buildConfig || {} });
});
app.post("/api/nodes/:id/build", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
const incoming = (req.body && typeof req.body === "object") ? req.body : {};
const current = hardenNode(node);
const nextBuild = Object.assign({}, current.buildConfig || {}, incoming);
if (Object.prototype.hasOwnProperty.call(incoming, "ssl_enabled")) {
nextBuild.ssl_enabled = truthyFlag(incoming.ssl_enabled);
if (!nextBuild.ssl_enabled) nextBuild.under_cloudflare = false;
}
if (Object.prototype.hasOwnProperty.call(incoming, "under_cloudflare") || Object.prototype.hasOwnProperty.call(incoming, "cloudflare_proxy")) {
nextBuild.under_cloudflare = !!(nextBuild.ssl_enabled && truthyFlag(incoming.under_cloudflare ?? incoming.cloudflare_proxy));
}
current.buildConfig = nextBuild;
current.under_cloudflare = nodeUnderCloudflare(current);
if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare && !isCloudflareHttpsPort(current.api_port)) {
return res.status(400).json({ 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);
if (!cloudflareCheck.ok) {
return res.status(400).json({
error: cloudflareCheck.error,
detail: cloudflareCheck.detail || undefined,
});
}
}
Object.assign(node, current);
await saveNode(node);
res.json({ ok: true });
});
app.get("/api/nodes/:id/config.yml", async (req, res) => {
const bootstrapHeader = req.get("X-Node-Bootstrap") || "";
const bearerToken = (req.get("authorization") || "").replace(/^Bearer\s+/i, "");
const node = await findNodeByIdOrName(req.params.id);
if (req.isAdmin) {
}
else 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");
}
if (!node) return res.status(404).send("not found");
const yml = buildConfigYml(node, req);
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);
});
app.get("/api/nodes/:id/install-daemon.sh", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).send("not found");
if (!req.isAdmin && !verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node)) {
return res.status(401).send("authentication required");
}
let script;
try {
script = buildDaemonInstallScript(node, req);
} catch (err) {
console.error("[nodes] Failed to build daemon installer:", err?.message || err);
return res.status(500).send("failed to build installer");
}
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private");
res.setHeader("Pragma", "no-cache");
res.setHeader("Content-Type", "text/x-shellscript; charset=utf-8");
res.send(script);
});
app.get("/api/nodes/:id/one-time-command", async (req, res) => {
if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" });
}
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
res.json({
command: oneTimeCommand(node, req),
});
});
app.post("/api/nodes/:id/heartbeat", async (req, res) => {
try {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" });
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;
if (!bearer && !bodyToken) {
return res.status(401).json({ error: "authentication required" });
}
if (bearer && !safeCompare(bearer, current.token)) {
return res.status(401).json({ error: "invalid token" });
}
if (!bearer && bodyToken && !safeCompare(bodyToken, current.token)) {
return res.status(401).json({ error: "invalid token" });
}
if (bodyTokenId && !safeCompare(bodyTokenId, current.token_id)) {
return res.status(401).json({ error: "invalid token_id" });
}
if (typeof body.api_port !== "undefined") current.api_port = clampPort(body.api_port);
current.last_seen = Date.now();
current.port_ok = true;
current.last_check = Date.now();
await saveNode(current);
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;
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 saveNode(n);
} catch (_) { }
}
} catch (_) { }
}, HC_INTERVAL_MS);
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,
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;
const rows = await db.query(
"SELECT * FROM servers WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ? OR id = ? LIMIT 1",
[lower, lower, lower, numericId]
);
return rows.length ? mapServerRow(rows[0]) : 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 };
}
function nodeHeaders(node) {
return {
"Authorization": `Bearer ${node.token || ""}`,
"X-Node-Token": node.token || "",
"X-Node-Token-Id": node.token_id || ""
};
}
function nodeUrl(node, suffix) {
const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node));
return `${base}${suffix}`;
}
function finiteNumber(value) {
const num = Number(value);
return Number.isFinite(num) ? num : null;
}
function nodeUploadLimitMb(node) {
const configured = finiteNumber(node?.max_upload_mb);
return configured && configured > 0 ? configured : 10240;
}
function formatBytesForMessage(bytes) {
const num = finiteNumber(bytes);
if (!num || num <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB"];
let value = num;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`;
}
function parseNodeDiskSnapshot(payload) {
const disk = payload?.disk || {};
const statsDisk = payload?.stats?.disk || {};
let usedBytes = finiteNumber(disk.usedBytes);
let limitBytes = finiteNumber(disk.limitBytes);
if (usedBytes == null) {
const usedMb = finiteNumber(disk.usedMb ?? statsDisk.usedMb);
const usedGb = finiteNumber(disk.usedGb ?? statsDisk.usedGb);
if (usedMb != null) usedBytes = usedMb * 1024 * 1024;
else if (usedGb != null) usedBytes = usedGb * 1024 * 1024 * 1024;
}
if (limitBytes == null) {
const limitMb = finiteNumber(disk.limitMb ?? statsDisk.limitMb);
const limitGb = finiteNumber(disk.limitGb ?? statsDisk.limitGb);
if (limitMb != null) limitBytes = limitMb * 1024 * 1024;
else if (limitGb != null) limitBytes = limitGb * 1024 * 1024 * 1024;
}
usedBytes = Math.max(0, Math.round(usedBytes || 0));
limitBytes = limitBytes && limitBytes > 0 ? Math.round(limitBytes) : 0;
const remainingBytes = limitBytes > 0 ? Math.max(0, limitBytes - usedBytes) : null;
return {
usedBytes,
limitBytes,
remainingBytes,
percentUsed: limitBytes > 0 ? Math.min(100, (usedBytes / limitBytes) * 100) : 0,
};
}
async function fetchServerDiskSnapshot(ctx, serverName, timeoutMs = 5000) {
if (!ctx?.remote || !ctx.node) return null;
const nodeServerName = ctx.nodeServerName || sanitizeName(ctx.server?.name || serverName);
if (!nodeServerName) return null;
const result = await httpJson(nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(nodeServerName)}`), {
method: "GET",
headers: nodeHeaders(ctx.node),
timeoutMs,
});
if (result.status !== 200 || !result.json) return null;
return parseNodeDiskSnapshot(result.json);
}
function buildDiskLimitUploadError(snapshot, incomingBytes, replacedBytes = 0) {
const limitBytes = finiteNumber(snapshot?.limitBytes);
if (!limitBytes || limitBytes <= 0) return null;
const usedBytes = Math.max(0, Math.round(finiteNumber(snapshot?.usedBytes) || 0));
const uploadBytes = Math.max(0, Math.round(finiteNumber(incomingBytes) || 0));
const replaceBytes = Math.max(0, Math.round(finiteNumber(replacedBytes) || 0));
const extraBytes = Math.max(0, uploadBytes - replaceBytes);
const projectedBytes = usedBytes + extraBytes;
if (projectedBytes <= limitBytes) return null;
const remainingBytes = Math.max(0, limitBytes - usedBytes);
return {
ok: false,
error: "disk_limit_exceeded",
message: `Upload would exceed this server's disk limit. Used: ${formatBytesForMessage(usedBytes)} / ${formatBytesForMessage(limitBytes)}. File: ${formatBytesForMessage(uploadBytes)}. Remaining: ${formatBytesForMessage(remainingBytes)}.`,
usedBytes,
limitBytes,
remainingBytes,
incomingBytes: uploadBytes,
projectedBytes,
usedMb: usedBytes / (1024 * 1024),
limitMb: limitBytes / (1024 * 1024),
};
}
function sanitizeNodeUploadFilename(raw) {
let s = String(raw || "").trim().replace(/\\/g, "/");
s = path.posix.basename(s);
s = s.replace(/\s+/g, "-").replace(/[^\w\-_.]+/g, "").replace(/^[-_.]+|[-_.]+$/g, "");
while (s && !/^[A-Za-z0-9]/.test(s)) s = s.slice(1);
if (s.length > 120) s = s.slice(0, 120);
return s || "upload.bin";
}
async function fetchRemoteReplacementBytes(ctx, absDir, originalName, timeoutMs = 5000) {
if (!ctx?.remote || !ctx.node) return null;
const safeName = sanitizeNodeUploadFilename(originalName);
if (!safeName) return null;
const result = await httpJson(nodeUrl(ctx.node, "/v1/fs/list"), {
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { path: absDir, depth: 1 },
timeoutMs,
});
if (result.status !== 200 || !result.json || result.json.ok !== true || !Array.isArray(result.json.entries)) {
return null;
}
const existing = result.json.entries.find((entry) => entry && entry.name === safeName);
if (!existing || existing.type === "dir" || existing.isDir) return 0;
const size = finiteNumber(existing.size);
return size && size > 0 ? size : 0;
}
function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb, serverName) {
return new Promise((resolve) => {
let settled = false;
let nodeReq = null;
const done = (result) => {
if (settled) return;
settled = true;
resolve(result);
};
try {
const fullUrl = nodeUrl(node, "/v1/fs/upload");
const lib = fullUrl.startsWith("https:") ? https : http;
const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`;
const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_");
const safeServerName = String(serverName || "").replace(/[\r\n"]/g, "_");
const serverPart = safeServerName
? `--${boundary}\r\n` +
`Content-Disposition: form-data; name="server"\r\n\r\n` +
`${safeServerName}\r\n`
: "";
const dirPart =
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="dir"\r\n\r\n` +
`${destDir}\r\n`;
const fileHeader =
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="file"; filename="${safeOriginalName}"\r\n` +
`Content-Type: application/octet-stream\r\n\r\n`;
const fileFooter = `\r\n--${boundary}--\r\n`;
const preamble = Buffer.from(serverPart + dirPart + fileHeader, "utf8");
const epilogue = Buffer.from(fileFooter, "utf8");
const headers = {
...nodeHeaders(node),
"Content-Type": `multipart/form-data; boundary=${boundary}`,
};
nodeReq = lib.request(fullUrl, { method: "POST", headers }, (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 });
});
});
nodeReq.setTimeout(UPLOAD_TIMEOUT_MS);
nodeReq.on("timeout", () => {
try { nodeReq.destroy(); } catch { }
done({ status: 0, json: { error: "upload_timeout" } });
});
nodeReq.on("error", (err) => {
done({ status: 0, json: { error: "upload_network_error", detail: err.message } });
});
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();
});
sourceStream.on("error", (err) => {
if (settled) return;
try { nodeReq.destroy(); } catch { }
done({ status: 0, json: { error: "upload_stream_error", detail: err.message } });
});
} catch (err) {
try { if (nodeReq) nodeReq.destroy(); } catch { }
done({ status: 0, json: { error: "stream_error", detail: err.message } });
}
});
}
function safeJoinUnix(base, rel) {
// Reject NUL bytes outright: they can truncate paths in some syscalls and
// must never reach the node. (#3 hardening)
if (String(base || "").includes("\0") || String(rel || "").includes("\0")) {
throw new Error("path traversal");
}
const b = base.endsWith("/") ? base.slice(0, -1) : base;
const raw = String(rel || "").replace(/\\/g, "/");
// Reject traversal segments in the raw value before normalization collapses
// them, so we never depend solely on the post-join prefix check.
if (raw.split("/").includes("..")) {
throw new Error("path traversal");
}
const norm = path.posix.normalize("/" + raw).replace(/^\/+/, "");
if (norm.split("/").includes("..")) {
throw new Error("path traversal");
}
const joined = `${b}/${norm}`;
if (!joined.startsWith(b + "/") && joined !== b) throw new Error("path traversal");
return joined;
}
function maskPathErrorMessage(err, fallback = "bad_path") {
const msg = err && err.message ? String(err.message) : "";
const lower = msg.toLowerCase();
if (lower.includes("traversal") || lower.includes("path")) return "invalid path";
return msg || fallback;
}
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;
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 = sanitizeName(expectedName);
if (!safeName) return null;
// The directory that holds the server files must be named exactly after the
// sanitized server name (…/<root>/<server>). 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 = sanitizeName(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) {
const srv = await findServerByNameOrId(serverName);
if (!srv) return { exists: false };
const ref = serverNodeRef(srv);
if (!ref) return { exists: true, remote: false, info: buildServerInfo(srv) };
const node = await findNodeByIdOrName(ref);
if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) };
const volRoot = getNodeVolumesDir(node);
const nodeServerName = sanitizeName(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)
};
}
app.get("/api/nodes/server/:name/info", async (req, res) => {
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 });
}
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 });
});
app.get("/api/nodes/server/:name/entries", async (req, res) => {
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 checkUserPerm(req, serverName, "files_read"))) {
return res.status(403).json({ error: "permission denied", permission: "files_read" });
}
const 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" });
const rel = String(req.query.path || "");
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/list"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, depth: 1 } }
);
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_list_failed" });
return res.json({ path: rel, entries: mapFsEntries(json.entries || []) });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.get("/api/nodes/server/:name/file", async (req, res) => {
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 checkUserPerm(req, serverName, "files_read"))) {
return res.status(403).json({ error: "permission denied", permission: "files_read" });
}
const 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" });
const rel = String(req.query.path || "");
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/read"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, encoding: "utf8" } }
);
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_read_failed" });
return res.json({ path: rel, content: typeof json.content === "string" ? json.content : "" });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.get("/api/nodes/server/:name/download", async (req, res) => {
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 checkUserPerm(req, serverName, "files_read"))) {
return res.status(403).json({ error: "permission denied", permission: "files_read" });
}
const 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" });
const rel = String(req.query.path || "");
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http");
const postData = JSON.stringify({ path: full, server: ctx.nodeServerName });
const url = new URL(nodeUrl(ctx.node, "/v1/fs/download"));
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
};
const proxyReq = lib.request(reqOpts, (proxyRes) => {
if (proxyRes.statusCode !== 200) {
return res.status(proxyRes.statusCode || 502).json({ error: "download failed" });
}
if (proxyRes.headers["content-type"]) res.setHeader("Content-Type", proxyRes.headers["content-type"]);
if (proxyRes.headers["content-disposition"]) res.setHeader("Content-Disposition", proxyRes.headers["content-disposition"]);
if (proxyRes.headers["content-length"]) res.setHeader("Content-Length", proxyRes.headers["content-length"]);
proxyRes.pipe(res);
});
proxyReq.on("error", () => res.status(502).json({ error: "node connection failed" }));
proxyReq.on("timeout", () => { proxyReq.destroy(); res.status(504).json({ error: "download timeout" }); });
proxyReq.write(postData);
proxyReq.end();
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/file", async (req, res) => {
const serverName = req.params.name;
const accessCheck = await checkServerAccess(req, serverName);
if (!accessCheck.ok) {
return res.status(accessCheck.status).json({ error: accessCheck.error });
}
const writeMode = await resolveFsWriteMode(req, serverName);
if (!writeMode.ok) {
return res.status(403).json({ error: "permission denied", permission: writeMode.permission });
}
const 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" });
const rel = String(req.body.path || "");
const content = String((req.body && req.body.content) || "");
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/write"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, content, encoding: "utf8", mode: writeMode.mode } }
);
if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json);
}
// The node enforces create-vs-overwrite atomically. Surface those as a 403
// so the user understands it is a permission boundary, not a generic failure.
if (status === 409) {
return res.status(403).json({ error: "permission denied", permission: "files_write", detail: "overwriting existing files requires the files_write permission" });
}
if (status === 404 && json && json.existed === false) {
return res.status(403).json({ error: "permission denied", permission: "files_create", detail: "creating new files requires the files_create permission" });
}
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" });
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_edit", { path: rel, created: json.existed === false }, userEmail, getRequestIp(req));
return res.json({ ok: true });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/delete", async (req, res) => {
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_delete"))) {
return res.status(403).json({ error: "permission denied", permission: "files_delete" });
}
const rel = String(req.body.path || "");
const isDir = !!req.body.isDir;
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/delete"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, isDir } }
);
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" });
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_delete", { path: rel, isDir }, userEmail, getRequestIp(req));
return res.json({ ok: true });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/delete-batch", async (req, res) => {
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_delete"))) {
return res.status(403).json({ error: "permission denied", permission: "files_delete" });
}
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)" });
}
try {
const fullItems = items.map(item => ({
path: safeJoinUnix(ctx.baseDir, String(item.path || "")),
isDir: !!item.isDir
}));
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/delete-batch"),
{
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { items: fullItems, server: ctx.nodeServerName },
timeoutMs: 120000
}
);
if (status !== 200 || !json) {
return res.status(502).json({ error: "node_batch_delete_failed" });
}
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_delete_batch", {
count: items.length,
success: json.success || 0,
failed: json.failed || 0
}, userEmail, getRequestIp(req));
return res.json(json);
} catch (e) {
console.error("[delete-batch] Error:", e);
return res.status(500).json({ error: "batch_delete_error", detail: e.message });
}
});
app.post("/api/nodes/server/:name/rename", async (req, res) => {
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_rename"))) {
return res.status(403).json({ error: "permission denied", permission: "files_rename" });
}
const rel = String(req.body.path || "");
const newName = sanitizeName(req.body.newName || "");
if (!newName) return res.status(400).json({ error: "invalid newName" });
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/rename"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, newName } }
);
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" });
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_rename", { src: rel, dest: newName }, userEmail, getRequestIp(req));
return res.json({ ok: true });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/extract", async (req, res) => {
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" });
}
const rel = String(req.body.path || "");
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/extract"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName } }
);
if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json);
}
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_extract_failed" });
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_extract", { path: rel }, userEmail, getRequestIp(req));
return res.json({ ok: true, msg: json.msg || "Extracted" });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/archive", async (req, res) => {
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_archive"))) {
return res.status(403).json({ error: "permission denied", permission: "files_archive" });
}
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 {
const { status, json } = await httpJson(
nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(req.params.name)}/files/archive`),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { paths: cleanPaths, destDir }, timeoutMs: 300000 }
);
if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json);
}
if (status !== 200 || !json || !json.ok) {
return res.status(502).json({ error: json?.error || "archive failed" });
}
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_archive", { paths, destDir, archiveName: json.name }, userEmail, getRequestIp(req));
return res.json({ ok: true, path: json.path, name: json.name });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
});
app.post("/api/nodes/server/:name/upload", async (req, res) => {
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_upload"))) {
return res.status(403).json({ error: "permission denied", permission: "files_upload" });
}
let rel = "";
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 bb = getLazyBusboy()({
headers: req.headers,
limits: { files: 1, fields: 8, fieldSize: 64 * 1024 },
});
bb.on("field", (name, value) => {
if (name === "path") rel = String(value || "");
});
bb.on("file", (name, fileStream, info) => {
if (responded) {
fileStream.resume();
return;
}
if (name !== "file") {
fileStream.resume();
return;
}
if (fileSeen) {
fileStream.resume();
respond(400, { error: "too_many_files" });
return;
}
fileSeen = true;
uploadPromise = (async () => {
const originalName = String(info?.filename || "upload");
const full = safeJoinUnix(ctx.baseDir, rel ? rel : "");
const diskSnapshot = await fetchServerDiskSnapshot(ctx, req.params.name, 5000).catch(() => null);
const replacedBytes = await fetchRemoteReplacementBytes(ctx, full, originalName, 5000).catch(() => null);
const incomingLength = Number(req.headers["content-length"] || 0) || 0;
const diskLimitError = replacedBytes == null ? null : buildDiskLimitUploadError(diskSnapshot, incomingLength, replacedBytes);
if (diskLimitError) {
fileStream.resume();
return { status: 507, json: diskLimitError };
}
return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb, ctx.nodeServerName);
})();
uploadPromise.then((result) => {
if (responded) return;
if (result.status === 507 && result.json?.error === "disk_limit_exceeded") {
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(req.params.name, "file_upload", { path: rel, filename: info?.filename || "upload" }, userEmail, getRequestIp(req));
respond(200, { ok: true, msg: result.json.msg || "Uploaded" });
}).catch((e) => {
respond(400, { error: maskPathErrorMessage(e) });
});
});
bb.on("error", (err) => {
respond(400, { error: "bad_multipart", detail: err.message });
});
bb.on("finish", () => {
if (!responded && !fileSeen) {
respond(400, { error: "no_file" });
}
});
req.pipe(bb);
});
// ============= URL Uploader (remote node) =============
function isUploaderPrivateIPv4(ip) {
const parts = String(ip || "").split(".").map(Number);
if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return true;
const [a, b] = parts;
if (a === 0) return true;
if (a === 10) return true;
if (a === 127) return true;
if (a === 169 && b === 254) return true;
if (a === 172 && b >= 16 && b <= 31) return true;
if (a === 192 && b === 168) return true;
if (a === 100 && b >= 64 && b <= 127) return true;
if (a === 198 && (b === 18 || b === 19)) return true;
if (a >= 224) return true;
return false;
}
function isUploaderPrivateIPv6(ip) {
const v = String(ip || "").toLowerCase();
if (v === "::" || v === "::1") return true;
if (v.startsWith("fc") || v.startsWith("fd")) return true;
if (v.startsWith("fe8") || v.startsWith("fe9") || v.startsWith("fea") || v.startsWith("feb")) return true;
if (v.startsWith("::ffff:")) {
const tail = v.slice("::ffff:".length);
if (net.isIP(tail) === 4) return isUploaderPrivateIPv4(tail);
}
return false;
}
async function uploaderAssertSafeRemoteUrl(inputUrl) {
let s = String(inputUrl || "").trim();
if (!s) throw new Error("Empty URL");
if (s.length > 2048) throw new Error("URL too long");
if (/[\s\u0000-\u001F\u007F]/.test(s)) throw new Error("Invalid characters in URL");
if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\//.test(s)) s = "https://" + s;
let u;
try { u = new URL(s); } catch (_) { throw new Error("Invalid URL"); }
const proto = (u.protocol || "").toLowerCase();
if (proto !== "http:" && proto !== "https:") throw new Error("Only http(s) URLs are allowed");
if (u.username || u.password) throw new Error("Credentials in URL are not allowed");
if (!u.hostname) throw new Error("Invalid hostname");
const hostLower = u.hostname.toLowerCase();
if (hostLower === "localhost" || hostLower.endsWith(".localhost") || hostLower.endsWith(".local")) {
throw new Error("Localhost URLs are not allowed");
}
const dnsp = require("dns").promises;
if (net.isIP(u.hostname)) {
const t = net.isIP(u.hostname);
if (t === 4 ? isUploaderPrivateIPv4(u.hostname) : isUploaderPrivateIPv6(u.hostname)) {
throw new Error("Private IP is not allowed");
}
} else {
let answers = [];
try { answers = await dnsp.lookup(u.hostname, { all: true, verbatim: true }); } catch (_) { throw new Error("DNS lookup failed"); }
if (!answers || answers.length === 0) throw new Error("DNS lookup failed");
for (const a of answers) {
if (!a || !a.address) continue;
const t = net.isIP(a.address);
if ((t === 4 && isUploaderPrivateIPv4(a.address)) || (t === 6 && isUploaderPrivateIPv6(a.address))) {
throw new Error("Hostname resolves to a private/internal IP");
}
}
}
return u;
}
app.post("/api/nodes/server/:name/upload-url", async (req, res) => {
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_upload"))) {
return res.status(403).json({ error: "permission denied", permission: "files_upload" });
}
const rawUrl = String(req.body?.url || "").trim();
const 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" });
let validatedUrl;
try {
validatedUrl = await uploaderAssertSafeRemoteUrl(rawUrl);
} catch (err) {
return res.status(400).json({ error: "invalid_url", message: err.message || "Invalid URL" });
}
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const result = await httpJson(
nodeUrl(ctx.node, "/v1/fs/uploadUrl"),
{
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { dir: full, server: ctx.nodeServerName, url: validatedUrl.toString() },
timeoutMs: 30 * 60 * 1000
}
);
const { status, json } = result;
if (status === 507 && json?.error === "disk_limit_exceeded") {
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(
req.params.name,
"file_upload_url",
{ path: rel, url: validatedUrl.toString(), 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) {
const srv = await findServerByNameOrId(name);
// Node daemon /start accepts only hostPort + env; keep payload strict to avoid 400 invalid request body.
const chosenPort = validatePortInput(srv?.hostPort ?? srv?.port ?? srv?.server_port);
const payload = {};
if (chosenPort != null) payload.hostPort = chosenPort;
try {
const subs = await db.query("SELECT domain FROM subdomains WHERE server_id = ? AND status = 'approved'", [srv.id]);
if (subs.length > 0) {
const joined = subs.map(s => s.domain).join(",");
payload.env = { TRUSTED_SUBDOMAINS: joined };
}
} catch (e) {
console.error("Failed to fetch subdomains for payload:", e);
}
return payload;
}
async function seedRuntimeOnNode(node, name) {
try {
const srv = await findServerByNameOrId(name);
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,
};
await callNodeApi(
node,
`/v1/servers/${encodeURIComponent(name)}/runtime`,
"POST",
runtimePayload,
LONG_NODE_TIMEOUT_MS
).catch(() => { });
}
} catch (_) { }
}
async function performPanelServerAction(req, serverName, cmdRaw) {
const targetServer = String(serverName || "").trim();
const cmdValue = String(cmdRaw || "").toLowerCase();
const cmd = (cmdValue === "run") ? "start" : cmdValue;
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" } };
const accessCheck = await checkServerAccess(req, targetServer);
if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } };
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 } };
}
}
let path = null;
let method = "POST";
let payload = null;
if (cmd === "start") {
try {
if (ctx.node) await seedRuntimeOnNode(ctx.node, targetServer);
} catch (_) { }
path = `/v1/servers/${encodeURIComponent(targetServer)}/start?wait=false`;
payload = await startPayloadFor(targetServer);
} else if (cmd === "stop") {
path = `/v1/servers/${encodeURIComponent(targetServer)}/stop`;
} else if (cmd === "kill") {
path = `/v1/servers/${encodeURIComponent(targetServer)}/kill`;
} else if (cmd === "restart") {
path = `/v1/servers/${encodeURIComponent(targetServer)}/restart`;
} else if (cmd === "status") {
method = "GET";
path = `/v1/servers/${encodeURIComponent(targetServer)}`;
}
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(targetServer, actionName, null, userEmail, getRequestIp(req));
}
const timeoutMs = cmd === "start" ? LONG_NODE_TIMEOUT_MS : DEFAULT_NODE_TIMEOUT_MS;
let result = await callNodeApi(ctx.node, path, method, payload, timeoutMs);
if (result.status === 0 && cmd === "start") {
result = await callNodeApi(ctx.node, path, method, payload, timeoutMs);
}
const { status, json, error } = result;
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,
},
};
}
async function performPanelConsoleCommand(req, serverName, rawCommand, requestId = "") {
const targetServer = String(serverName || "").trim();
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" } };
const accessCheck = await checkServerAccess(req, targetServer);
if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } };
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(targetServer, "console_command", { command }, userEmail, getRequestIp(req));
const { status, json } = await callNodeApi(
ctx.node,
`/v1/servers/${encodeURIComponent(targetServer)}/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 } };
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" } };
const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/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) {
return { status: 502, body: { error: "node_backup_list_failed", detail: json?.error || text || `status ${status}` } };
}
return { status: 200, body: { ok: true, backups: json.backups || [] } };
}
async function performPanelCreateBackup(req, serverName, backupName, description) {
const targetServer = String(serverName || "").trim();
const accessCheck = await checkServerAccess(req, targetServer);
if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } };
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);
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 url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups`);
const { status, json, text } = await httpJson(url, {
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { name: backupName, description },
timeoutMs: 120000,
});
if (status === 0) {
return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } };
}
if (status === 507 && json?.error === "disk_limit_exceeded") {
return { status: 507, body: json };
}
if (status !== 200 || !json || !json.ok) {
return { status: 502, body: { error: "node_backup_create_failed", detail: json?.error || text || `status ${status}` } };
}
const userEmail = req.session?.user || "unknown";
const userIp = getRequestIp(req);
recordActivity(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) {
const targetServer = String(serverName || "").trim();
const accessCheck = await checkServerAccess(req, targetServer);
if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } };
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);
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" } };
const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/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 },
timeoutMs: 300000,
});
if (status === 0) {
return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } };
}
if (status === 507 && json?.error === "disk_limit_exceeded") {
return { status: 507, body: json };
}
if (status !== 200 || !json || !json.ok) {
return { status: 502, body: { error: "node_backup_restore_failed", detail: json?.error || text || `status ${status}` } };
}
const userEmail = req.session?.user || "unknown";
const userIp = getRequestIp(req);
recordActivity(targetServer, "backup_restore", { backupId, deleteOldFiles: !!deleteOldFiles }, userEmail, userIp);
return { status: 200, body: { ok: true } };
}
async function performPanelDeleteBackup(req, serverName, backupIdRaw) {
const targetServer = String(serverName || "").trim();
const accessCheck = await checkServerAccess(req, targetServer);
if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } };
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);
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" } };
const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups/${encodeURIComponent(backupId)}`);
const { status, json, text } = await httpJson(url, {
method: "DELETE",
headers: nodeHeaders(ctx.node),
timeoutMs: 30000,
});
if (status === 0) {
return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } };
}
if (status !== 200 || !json || !json.ok) {
return { status: 502, body: { error: "node_backup_delete_failed", detail: json?.error || text || `status ${status}` } };
}
const userEmail = req.session?.user || "unknown";
const userIp = getRequestIp(req);
recordActivity(targetServer, "backup_delete", { backupId }, userEmail, userIp);
return { status: 200, body: { ok: true } };
}
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 res.status(result.status).json(result.body);
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
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 res.status(result.status).json(result.body);
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
app.post("/api/nodes/server/:name/extract-image", 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 payload = {
image: req.body?.image || "",
tag: req.body?.tag || "",
extractPath: req.body?.extractPath || "",
paths: Array.isArray(req.body?.paths) ? req.body.paths : []
};
const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "extract_image", { image: payload.image || "(from meta)" }, userEmail, getRequestIp(req));
const { status, json } = await callNodeApi(
ctx.node,
`/v1/servers/${encodeURIComponent(req.params.name)}/extract-image`,
"POST",
payload,
LONG_NODE_TIMEOUT_MS
);
if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json);
}
if (status === 200 && json) return res.json(json);
return res.status(502).json({ error: "extract_failed", status, detail: json && json.error });
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
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 res.status(result.status).json(result.body);
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
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 res.status(result.status).json(result.body);
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
app.post("/api/nodes/server/:name/create", 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" });
}
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" });
const safeName = sanitizeName(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);
const payload = typeRaw === "folder"
? { path: safeJoinUnix(target, ".keep"), content: "", encoding: "utf8" }
: { path: target, content: "", encoding: "utf8" };
const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/write"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: payload }
);
if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json);
}
if (status !== 200 || !json || !json.ok) {
const errMsg = json?.error || '';
if (errMsg.includes('exist') || errMsg.includes('EEXIST')) {
return res.status(400).json({ error: "already_exists", message: `A ${typeRaw} with that name already exists` });
}
return res.status(502).json({ error: "node_create_failed", message: `Failed to create ${typeRaw}. It may already exist.` });
}
const userEmail = req.session?.user || "unknown";
const actionType = typeRaw === "folder" ? "folder_create" : "file_create";
recordActivity(req.params.name, actionType, { path: relativePosix, type: typeRaw }, userEmail, getRequestIp(req));
return res.json({ ok: true, path: relativePosix });
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
} catch (e) {
return res.status(500).json({ error: "bridge_failed", detail: e && e.message });
}
});
app.get("/api/nodes/server/:name/backups", async (req, res) => {
try {
const result = await performPanelListBackups(req, req.params.name);
return res.status(result.status).json(result.body);
} catch (e) {
console.error("[backups] List error:", e);
return res.status(500).json({ error: "bridge_failed", detail: e?.message });
}
});
app.post("/api/nodes/server/:name/backups", async (req, res) => {
try {
const result = await performPanelCreateBackup(req, req.params.name, req.body?.name, req.body?.description);
return res.status(result.status).json(result.body);
} catch (e) {
console.error("[backups] Create error:", e);
return res.status(500).json({ error: "bridge_failed", detail: e?.message });
}
});
app.post("/api/nodes/server/:name/backups/:backupId/restore", async (req, res) => {
try {
const result = await performPanelRestoreBackup(req, req.params.name, req.params.backupId, req.body?.deleteOldFiles);
return res.status(result.status).json(result.body);
} catch (e) {
console.error("[backups] Restore error:", e);
return res.status(500).json({ error: "bridge_failed", detail: e?.message });
}
});
app.delete("/api/nodes/server/:name/backups/:backupId", async (req, res) => {
try {
const result = await performPanelDeleteBackup(req, req.params.name, req.params.backupId);
return res.status(result.status).json(result.body);
} catch (e) {
console.error("[backups] Delete error:", e);
return res.status(500).json({ error: "bridge_failed", detail: e?.message });
}
});
app.get("/api/nodes/server/:name/logs", 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 checkUserPerm(req, serverName, "console_read"))) {
return res.status(403).json({ error: "permission denied", permission: "console_read" });
}
const { node } = await resolveNodeForServer(serverName);
if (!node) return res.status(404).json({ error: "server_or_node_not_found" });
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))}`;
}
const fullUrl = `${base}/v1/servers/${encodeURIComponent(serverName)}/logs${tailQuery}`;
const isHttps = fullUrl.startsWith("https:");
const lib = isHttps ? https : http;
const nreq = lib.request(fullUrl, {
method: "GET",
headers: {
...nodeHeaders(node),
"Accept": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive"
}
}, (nres) => {
if (nres.statusCode !== 200) {
const chunks = [];
nres.on("data", (chunk) => {
if (Buffer.concat(chunks).length < 16 * 1024) chunks.push(Buffer.from(chunk));
});
nres.on("end", () => {
const detail = Buffer.concat(chunks).toString("utf8").slice(0, 2000);
if (!res.headersSent) {
return res.status(nres.statusCode || 502).json({ error: "node_logs_failed", detail: detail || `status ${nres.statusCode || 502}` });
}
try { res.end(); } catch { }
});
return;
}
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders?.();
nres.on("data", (chunk) => {
try {
res.write(chunk);
res.flush?.();
} catch { }
});
nres.on("end", () => { try { res.end(); } catch { } });
});
nreq.on("socket", (socket) => {
try { socket.setNoDelay(true); } catch { }
});
nreq.on("error", () => { try { res.end(); } catch { } });
nreq.end();
req.on("close", () => { try { nreq.destroy(); } catch { } });
} catch {
try { res.end(); } catch { }
}
});
if (require.main === module) {
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.isOpenNodeInstallerRoute = isOpenNodeInstallerRoute;
module.exports.resolveNodeForServer = resolveNodeForServer;
module.exports.recordActivity = recordActivity;
module.exports.flushActivityLogs = flushActivityLogs;
module.exports.seedRuntimeOnNode = seedRuntimeOnNode;
module.exports.setWebhookDispatcher = setWebhookDispatcher;
module.exports.setPermissionCheckers = setPermissionCheckers;
module.exports.setServerActionObserver = setServerActionObserver;
module.exports.startPayloadFor = startPayloadFor;
module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand;
module.exports.performPanelServerAction = performPanelServerAction;
module.exports.performPanelConsoleCommand = performPanelConsoleCommand;
module.exports.performPanelListBackups = performPanelListBackups;
module.exports.performPanelCreateBackup = performPanelCreateBackup;
module.exports.performPanelRestoreBackup = performPanelRestoreBackup;
module.exports.performPanelDeleteBackup = performPanelDeleteBackup;