Initial upload

This commit is contained in:
antonn committed 2026-06-10 17:04:11 +00:00
1 parent b0bf3b7167
commit a022f29e34
65 files changed
+46484 -4339

No files matched your search

+370 -71
View File
@@ -173,11 +173,15 @@ function sanitizeConsoleCommand(rawValue) {
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) {
@@ -191,6 +195,31 @@ async function checkUserPerm(req, serverName, permKey) {
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" };
@@ -210,6 +239,9 @@ 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 {
@@ -244,6 +276,25 @@ function safeCompare(a, b) {
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;
@@ -985,6 +1036,108 @@ function defaultNodeTlsPaths(node) {
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 };
@@ -1124,15 +1277,7 @@ async function activeCheckNode(node, opts = { force: false }) {
}
}
function buildConfigYml(node, req) {
let panelUrl;
if (PANEL_PUBLIC_URL) {
panelUrl = PANEL_PUBLIC_URL;
} else {
console.warn("[SECURITY] PANEL_PUBLIC_URL not set - config.yml panel URL 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");
panelUrl = `${proto}://${host}`;
}
const panelUrl = buildPanelPublicUrl(req);
const sslEnabled = !!node.ssl_enabled;
const tlsPaths = defaultNodeTlsPaths(node);
const lines = [
@@ -1153,8 +1298,6 @@ function buildConfigYml(node, req) {
` upload_limit: ${node.max_upload_mb || 10240}`,
`system:`,
` data: /var/lib/node`,
` sftp:`,
` bind_port: ${node.sftp_port || 2022}`,
`allowed_mounts: []`,
`panel:`,
` url: ${panelUrl}`,
@@ -1165,34 +1308,30 @@ function buildConfigYml(node, req) {
}
return lines.join("\n") + "\n";
}
function oneTimeCommand(node, req) {
let base;
if (PANEL_PUBLIC_URL) {
base = PANEL_PUBLIC_URL;
} else {
const host = req.get("x-forwarded-host") || req.get("host") || "localhost";
const proto = (req.get("x-forwarded-proto") || req.protocol || "http");
base = `${proto}://${host}`;
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");
}
const url = `${base}/api/nodes/${encodeURIComponent(node.uuid)}/config.yml`;
const header = NODE_BOOTSTRAP_TOKEN ? `-H "X-Node-Bootstrap: ${NODE_BOOTSTRAP_TOKEN}" ` : "";
return `set -e
mkdir -p /var/lib/node
curl -fsSL ${header}"${url}" -o /var/lib/node/config.yml
restart_adaemon() {
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
systemctl restart ADaemon 2>/dev/null || systemctl restart adaemon 2>/dev/null || systemctl restart adpanel-daemon 2>/dev/null
elif command -v rc-service >/dev/null 2>&1; then
rc-service adaemon restart 2>/dev/null || rc-service ADaemon restart 2>/dev/null || rc-service adpanel-daemon restart 2>/dev/null
elif command -v service >/dev/null 2>&1; then
service adaemon restart 2>/dev/null || service ADaemon restart 2>/dev/null || service adpanel-daemon restart 2>/dev/null
else
echo "No supported service manager found; start ADaemon manually." >&2
return 1
fi
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");
}
restart_adaemon
echo "Config saved to /var/lib/node/config.yml and ADaemon restarted"`;
function oneTimeCommand(node, req) {
return buildNodeConfigRestartCommand(buildConfigYml(node, req));
}
const app = express();
app.use(express.json({ limit: "2mb" }));
@@ -1240,22 +1379,28 @@ const NODES_PUBLIC_ROUTES = new Set([
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((req, res, next) => {
const path = req.path || "";
app.use(async (req, res, next) => {
try {
const path = req.path || "";
if (path === "/health") return next();
if (path === "/health") return next();
if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next();
if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next();
if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next();
if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next();
if (path.startsWith("/api/nodes")) {
if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" });
if (await isOpenNodeInstallerRoute(req)) return next();
if (path.startsWith("/api/nodes")) {
if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" });
}
}
}
next();
return next();
} catch (err) {
return next(err);
}
});
app.get("/health", (_req, res) => res.json({ ok: true }));
@@ -1322,6 +1467,19 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => {
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";
@@ -1339,7 +1497,7 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => {
const { status, json } = await callNodeApi(
node, "/v1/servers/create", "POST",
{ name, templateId, mcFork, mcVersion, hostPort, autoStart },
{ name, templateId, mcFork, mcVersion, hostPort, autoStart, ...(diskId ? { diskId } : {}) },
LONG_NODE_TIMEOUT_MS
);
if (status === 200 && json && json.ok) return res.json(json);
@@ -1532,10 +1690,35 @@ app.get("/api/nodes/:id/config.yml", async (req, res) => {
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) });
res.json({
command: oneTimeCommand(node, req),
});
});
app.post("/api/nodes/:id/heartbeat", async (req, res) => {
try {
@@ -1781,7 +1964,7 @@ async function fetchRemoteReplacementBytes(ctx, absDir, originalName, timeoutMs
return size && size > 0 ? size : 0;
}
function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb) {
function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb, serverName) {
return new Promise((resolve) => {
let settled = false;
let nodeReq = null;
@@ -1798,6 +1981,13 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
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` +
@@ -1811,7 +2001,7 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
const fileFooter = `\r\n--${boundary}--\r\n`;
const preamble = Buffer.from(dirPart + fileHeader, "utf8");
const preamble = Buffer.from(serverPart + dirPart + fileHeader, "utf8");
const epilogue = Buffer.from(fileFooter, "utf8");
const headers = {
@@ -1890,9 +2080,22 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
}
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;
@@ -1914,6 +2117,55 @@ function mapFsEntries(entries) {
});
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 };
@@ -1923,7 +2175,15 @@ async function remoteContext(serverName) {
if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) };
const volRoot = getNodeVolumesDir(node);
const nodeServerName = sanitizeName(srv.name || serverName);
const baseDir = `${volRoot}/${nodeServerName}`;
// 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,
@@ -1987,17 +2247,12 @@ app.get("/api/nodes/server/:name/entries", async (req, res) => {
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" });
if (!_nodeVolumeDirCache.has(String(ctx.node.uuid || ctx.node.id || ""))) {
try { await activeCheckNode(ctx.node, { force: true }); } catch { }
const volRoot = getNodeVolumesDir(ctx.node);
ctx.baseDir = `${volRoot}/${sanitizeName(serverName)}`;
}
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, depth: 1 } }
{ 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 || []) });
@@ -2025,7 +2280,7 @@ app.get("/api/nodes/server/:name/file", async (req, res) => {
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, encoding: "utf8" } }
{ 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 : "" });
@@ -2052,7 +2307,7 @@ app.get("/api/nodes/server/:name/download", async (req, res) => {
try {
const full = safeJoinUnix(ctx.baseDir, rel);
const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http");
const postData = JSON.stringify({ path: full });
const postData = JSON.stringify({ path: full, server: ctx.nodeServerName });
const url = new URL(nodeUrl(ctx.node, "/v1/fs/download"));
const reqOpts = {
hostname: url.hostname,
@@ -2090,8 +2345,9 @@ app.post("/api/nodes/server/:name/file", async (req, res) => {
return res.status(accessCheck.status).json({ error: accessCheck.error });
}
if (!(await checkUserPerm(req, serverName, "files_create"))) {
return res.status(403).json({ error: "permission denied", permission: "files_create" });
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);
@@ -2103,15 +2359,23 @@ app.post("/api/nodes/server/:name/file", async (req, res) => {
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, content, encoding: "utf8" } }
{ 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 }, userEmail, getRequestIp(req));
recordActivity(req.params.name, "file_edit", { path: rel, created: json.existed === false }, userEmail, getRequestIp(req));
return res.json({ ok: true });
} catch (e) {
@@ -2135,7 +2399,7 @@ app.post("/api/nodes/server/:name/delete", async (req, res) => {
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, isDir } }
{ 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" });
@@ -2179,7 +2443,7 @@ app.post("/api/nodes/server/:name/delete-batch", async (req, res) => {
{
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { items: fullItems },
body: { items: fullItems, server: ctx.nodeServerName },
timeoutMs: 120000
}
);
@@ -2220,7 +2484,7 @@ app.post("/api/nodes/server/:name/rename", async (req, res) => {
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, newName } }
{ 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" });
@@ -2248,7 +2512,7 @@ app.post("/api/nodes/server/:name/extract", async (req, res) => {
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 } }
{ 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);
@@ -2281,11 +2545,36 @@ app.post("/api/nodes/server/:name/archive", async (req, res) => {
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, destDir }, timeoutMs: 300000 }
{ 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);
@@ -2363,7 +2652,7 @@ app.post("/api/nodes/server/:name/upload", async (req, res) => {
fileStream.resume();
return { status: 507, json: diskLimitError };
}
return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb);
return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb, ctx.nodeServerName);
})();
uploadPromise.then((result) => {
@@ -2504,7 +2793,7 @@ app.post("/api/nodes/server/:name/upload-url", async (req, res) => {
{
method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { dir: full, url: validatedUrl.toString() },
body: { dir: full, server: ctx.nodeServerName, url: validatedUrl.toString() },
timeoutMs: 30 * 60 * 1000
}
);
@@ -2641,6 +2930,13 @@ async function performPanelServerAction(req, serverName, cmdRaw) {
}
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}`;
@@ -3087,11 +3383,14 @@ 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;