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

+1 -3
View File
@@ -1654,9 +1654,6 @@ function createDashboardAssistantToolRunner(deps) {
}
let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker);
if (sanitizedDocker && Array.isArray(sanitizedDocker.ports) && sanitizedDocker.ports.length > 1) {
sanitizedDocker.ports = [sanitizedDocker.ports[0]];
}
const payload = {
name,
@@ -1717,6 +1714,7 @@ function createDashboardAssistantToolRunner(deps) {
volumes: sanitizedDocker.volumes,
env: sanitizedDocker.env,
ports: sanitizedDocker.ports,
portProtocols: sanitizedDocker.portProtocols,
};
}
+501
View File
@@ -0,0 +1,501 @@
"use strict";
/**
* Panel metrics collector for the admin-only /status monitoring page.
*
* Design goals (best-practice, ultra-low overhead):
* - Collect host + panel-process resource usage (CPU, RAM, storage) cheaply
* using only Node core modules (os, fs) plus a single `pm2 jlist` poll for
* aggregate Node/PM2 network counters. No heavy native deps.
* - Live data lives in RAM. We only run the intensive 1s sampling loop while at
* least one admin is actually watching the page (driven by socket room size).
* When nobody watches, the loop stops -> zero ongoing cost.
* - Persistence is RRD-like: one row per minute in `panel_metrics`. A monthly
* cleanup keeps the table at a fixed, small size (~31 days). Writes happen
* once per minute (averaged), never per second.
* - All reads are wrapped so a transient failure never throws into the loop.
*
* This module is intentionally framework-agnostic: index.js wires it to the
* existing socket.io server, admin auth, and MySQL pool.
*/
const os = require("os");
const fsp = require("fs/promises");
const { execFile } = require("child_process");
// ---------------------------------------------------------------------------
// Tunables (overridable via env, sane defaults for cheap VPS).
// ---------------------------------------------------------------------------
const LIVE_SAMPLE_MS = clampInt(process.env.PANEL_METRICS_LIVE_MS, 1000, 250, 10000);
const PERSIST_INTERVAL_MS = clampInt(process.env.PANEL_METRICS_PERSIST_MS, 60_000, 10_000, 600_000);
const RETENTION_DAYS = clampInt(process.env.PANEL_METRICS_RETENTION_DAYS, 31, 7, 366);
const PM2_POLL_MS = clampInt(process.env.PANEL_METRICS_PM2_MS, 5000, 2000, 60_000);
const CLEANUP_INTERVAL_MS = 6 * 60 * 60 * 1000; // run retention sweep 4x/day
function clampInt(value, def, min, max) {
const n = parseInt(value, 10);
if (!Number.isFinite(n)) return def;
return Math.min(Math.max(n, min), max);
}
function nowMs() {
return Date.now();
}
// ---------------------------------------------------------------------------
// CPU sampling: delta of os.cpus() times between two reads -> busy percentage.
// Cheap: a single os.cpus() call (reads /proc/stat once on Linux).
// ---------------------------------------------------------------------------
function cpuTotals() {
const cpus = os.cpus() || [];
let idle = 0;
let total = 0;
for (const c of cpus) {
const t = c.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total, cores: cpus.length || 1 };
}
// ---------------------------------------------------------------------------
// Storage: usage of the filesystem holding the panel working directory.
// Uses statfs when available (Node >= 18.15), else falls back to null.
// ---------------------------------------------------------------------------
async function readStorage() {
try {
if (typeof fsp.statfs === "function") {
const s = await fsp.statfs(process.cwd());
const total = s.blocks * s.bsize;
const free = s.bfree * s.bsize;
const used = total - free;
if (total > 0) {
return { usedBytes: used, totalBytes: total, percent: round1((used / total) * 100) };
}
}
} catch (_) { /* ignore */ }
return { usedBytes: null, totalBytes: null, percent: null };
}
function round1(n) {
return Math.round(n * 10) / 10;
}
// ---------------------------------------------------------------------------
// PM2 network counters. `pm2 jlist` exposes per-process monit + env; PM2 does
// not natively expose net bytes, so we read aggregate NIC counters from
// /proc/net/dev (sum of all non-loopback interfaces) and derive a per-second
// rate from deltas. This reflects the whole Node/PM2 host traffic, which is the
// closest reliable "panel network" signal without per-socket accounting.
// ---------------------------------------------------------------------------
async function readNetCounters() {
try {
const raw = await fsp.readFile("/proc/net/dev", "utf8");
let rx = 0;
let tx = 0;
const lines = raw.split("\n");
for (const line of lines) {
const idx = line.indexOf(":");
if (idx === -1) continue;
const iface = line.slice(0, idx).trim();
if (!iface || iface === "lo") continue;
const parts = line.slice(idx + 1).trim().split(/\s+/);
if (parts.length < 9) continue;
rx += Number(parts[0]) || 0; // bytes received
tx += Number(parts[8]) || 0; // bytes transmitted
}
return { rxBytes: rx, txBytes: tx };
} catch (_) {
return { rxBytes: null, txBytes: null };
}
}
function pm2List() {
return new Promise((resolve) => {
try {
execFile("pm2", ["jlist"], { timeout: 4000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
if (err || !stdout) return resolve(null);
try {
resolve(JSON.parse(stdout));
} catch (_) {
resolve(null);
}
});
} catch (_) {
resolve(null);
}
});
}
// ---------------------------------------------------------------------------
// Collector
// ---------------------------------------------------------------------------
class PanelMetricsCollector {
constructor(options = {}) {
this.db = options.db || null; // { query }
this.io = options.io || null; // socket.io server
this.room = options.room || "monitor";
this.startTime = options.startTime || nowMs();
this.panelVersion = options.panelVersion || null;
this.getServiceStatus = typeof options.getServiceStatus === "function"
? options.getServiceStatus
: async () => ({});
// Live state
this._prevCpu = cpuTotals();
this._prevNet = null;
this._prevNetAt = 0;
this._reqCounter = 0; // incremented by middleware
this._prevReqCount = 0;
this._prevReqAt = nowMs();
this._pm2Cache = { at: 0, data: null };
this._svcCache = { at: 0, data: null };
this._svcTtlMs = clampInt(process.env.PANEL_METRICS_SVC_MS, 5000, 2000, 60_000);
// Minute-accumulator for persistence (average over the window)
this._acc = this._freshAcc();
// Timers
this._liveTimer = null;
this._persistTimer = null;
this._cleanupTimer = null;
this._lastSample = null;
}
_freshAcc() {
return {
count: 0,
cpu: 0,
memUsed: 0,
memTotal: 0,
diskUsed: 0,
diskTotal: 0,
netRx: 0,
netTx: 0,
rps: 0,
};
}
/**
* The request counter (`_reqCounter`) is incremented directly by a tiny
* Express middleware in index.js (one integer add per request, no allocation).
* The collector only reads/diffs it; it never touches the hot request path
* beyond that single increment.
*/
start() {
// Persistence + cleanup always run (cheap, once per minute / few hours).
if (!this._persistTimer) {
this._persistTimer = setInterval(() => this._persist().catch(() => {}), PERSIST_INTERVAL_MS);
this._persistTimer.unref?.();
}
if (!this._cleanupTimer) {
// Run once shortly after boot, then on interval.
setTimeout(() => this._cleanup().catch(() => {}), 30_000).unref?.();
this._cleanupTimer = setInterval(() => this._cleanup().catch(() => {}), CLEANUP_INTERVAL_MS);
this._cleanupTimer.unref?.();
}
// Drive the live loop from room occupancy.
this._refreshLiveLoop();
}
stop() {
for (const t of [this._liveTimer, this._persistTimer, this._cleanupTimer]) {
if (t) clearInterval(t);
}
this._liveTimer = this._persistTimer = this._cleanupTimer = null;
}
/** Called by index.js whenever a client joins/leaves the monitor room. */
onRoomChange() {
this._refreshLiveLoop();
}
_watcherCount() {
try {
const room = this.io?.sockets?.adapter?.rooms?.get(this.room);
return room ? room.size : 0;
} catch (_) {
return 0;
}
}
_refreshLiveLoop() {
const watching = this._watcherCount() > 0;
if (watching && !this._liveTimer) {
// Prime baselines so the first emitted sample is sane.
this._prevCpu = cpuTotals();
this._liveTimer = setInterval(() => this._tick().catch(() => {}), LIVE_SAMPLE_MS);
this._liveTimer.unref?.();
// Emit one immediately.
this._tick().catch(() => {});
} else if (!watching && this._liveTimer) {
clearInterval(this._liveTimer);
this._liveTimer = null;
}
}
async _readPm2() {
const now = nowMs();
if (this._pm2Cache.data && (now - this._pm2Cache.at) < PM2_POLL_MS) {
return this._pm2Cache.data;
}
const list = await pm2List();
let memBytes = 0;
let cpuPercent = 0;
let found = false;
if (Array.isArray(list)) {
for (const proc of list) {
const monit = proc?.monit || {};
if (typeof monit.memory === "number") memBytes += monit.memory;
if (typeof monit.cpu === "number") cpuPercent += monit.cpu;
found = true;
}
}
const data = found ? { memBytes, cpuPercent: round1(cpuPercent) } : null;
this._pm2Cache = { at: now, data };
return data;
}
/** Build one live sample (cheap). */
async _collect() {
const now = nowMs();
// CPU (host) via delta
const cur = cpuTotals();
let cpuPercent = 0;
const idleDiff = cur.idle - this._prevCpu.idle;
const totalDiff = cur.total - this._prevCpu.total;
if (totalDiff > 0) {
cpuPercent = round1((1 - idleDiff / totalDiff) * 100);
if (cpuPercent < 0) cpuPercent = 0;
if (cpuPercent > 100) cpuPercent = 100;
}
this._prevCpu = cur;
// Memory (host)
const memTotal = os.totalmem();
const memFree = os.freemem();
const memUsed = memTotal - memFree;
// Storage
const storage = await readStorage();
// Network rate (bytes/sec) from /proc/net/dev deltas
const net = await readNetCounters();
let rxRate = null;
let txRate = null;
if (net.rxBytes != null && this._prevNet && this._prevNetAt) {
const dt = (now - this._prevNetAt) / 1000;
if (dt > 0) {
rxRate = Math.max(0, Math.round((net.rxBytes - this._prevNet.rxBytes) / dt));
txRate = Math.max(0, Math.round((net.txBytes - this._prevNet.txBytes) / dt));
}
}
if (net.rxBytes != null) {
this._prevNet = net;
this._prevNetAt = now;
}
// RPS from request counter delta
const dtReq = (now - this._prevReqAt) / 1000;
let rps = 0;
if (dtReq > 0) {
rps = round1((this._reqCounter - this._prevReqCount) / dtReq);
if (rps < 0) rps = 0;
}
this._prevReqCount = this._reqCounter;
this._prevReqAt = now;
// PM2 process aggregate (cached)
const pm2 = await this._readPm2();
const sample = {
ts: now,
cpu: cpuPercent,
cores: cur.cores,
memUsed,
memTotal,
memPercent: memTotal > 0 ? round1((memUsed / memTotal) * 100) : 0,
diskUsed: storage.usedBytes,
diskTotal: storage.totalBytes,
diskPercent: storage.percent,
netRx: rxRate,
netTx: txRate,
rps,
pm2MemBytes: pm2 ? pm2.memBytes : null,
pm2Cpu: pm2 ? pm2.cpuPercent : null,
uptimeMs: now - this.startTime,
};
// Feed the minute accumulator (averages).
const a = this._acc;
a.count++;
a.cpu += sample.cpu;
a.memUsed += sample.memUsed;
a.memTotal += sample.memTotal;
if (sample.diskUsed != null) a.diskUsed += sample.diskUsed;
if (sample.diskTotal != null) a.diskTotal += sample.diskTotal;
if (sample.netRx != null) a.netRx += sample.netRx;
if (sample.netTx != null) a.netTx += sample.netTx;
a.rps += sample.rps;
this._lastSample = sample;
return sample;
}
async _services() {
const now = nowMs();
if (this._svcCache.data && (now - this._svcCache.at) < this._svcTtlMs) {
return this._svcCache.data;
}
let data = {};
try {
data = await this.getServiceStatus();
} catch (_) {
data = {};
}
this._svcCache = { at: now, data };
return data;
}
async _tick() {
const sample = await this._collect();
if (!this.io) return;
const services = await this._services();
this.io.to(this.room).emit("monitor:sample", { ...sample, services });
}
/** Persist one averaged row per minute. */
async _persist() {
if (!this.db || typeof this.db.query !== "function") return;
const a = this._acc;
this._acc = this._freshAcc();
let row;
if (a.count > 0) {
row = {
cpu: round1(a.cpu / a.count),
memPercent: a.memTotal > 0 ? round1((a.memUsed / a.memTotal) * 100) : 0,
diskPercent: a.diskTotal > 0 ? round1((a.diskUsed / a.diskTotal) * 100) : 0,
netRx: Math.round(a.netRx / a.count),
netTx: Math.round(a.netTx / a.count),
rps: round1(a.rps / a.count),
};
} else {
// No live watchers this window: take one cheap point-in-time read so the
// history graph stays continuous without running the 1s loop.
const s = await this._collect();
// Reset accumulator again (the collect above pushed into it).
this._acc = this._freshAcc();
row = {
cpu: s.cpu,
memPercent: s.memPercent,
diskPercent: s.diskPercent ?? 0,
netRx: s.netRx ?? 0,
netTx: s.netTx ?? 0,
rps: s.rps,
};
}
try {
const d = new Date();
// Bucket to the minute (UTC) for a stable RRD-style key.
const bucket = Math.floor(d.getTime() / 60000) * 60000;
await this.db.query(
`INSERT INTO panel_metrics
(bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
cpu_percent = VALUES(cpu_percent),
mem_percent = VALUES(mem_percent),
disk_percent = VALUES(disk_percent),
net_rx_bps = VALUES(net_rx_bps),
net_tx_bps = VALUES(net_tx_bps),
rps = VALUES(rps)`,
[bucket, row.cpu, row.memPercent, row.diskPercent, row.netRx, row.netTx, row.rps]
);
} catch (err) {
// Never let persistence crash the loop.
if (!String(err && err.message).includes("panel_metrics")) {
// table missing or transient; stay silent in prod, log once otherwise.
}
}
}
/** Retention sweep: drop anything older than RETENTION_DAYS. */
async _cleanup() {
if (!this.db || typeof this.db.query !== "function") return;
try {
const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000;
await this.db.query("DELETE FROM panel_metrics WHERE bucket_ts < ?", [cutoff]);
} catch (_) { /* ignore */ }
}
/** Admin REST: fetch history rows for a given UTC day (YYYY-MM-DD). */
async getHistoryForDay(dayStr) {
if (!this.db || typeof this.db.query !== "function") return [];
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dayStr || ""));
if (!m) return [];
const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 0, 0, 0);
const end = start + 24 * 60 * 60 * 1000;
const rows = await this.db.query(
`SELECT bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps
FROM panel_metrics
WHERE bucket_ts >= ? AND bucket_ts < ?
ORDER BY bucket_ts ASC`,
[start, end]
);
return (rows || []).map((r) => ({
ts: Number(r.bucket_ts),
cpu: Number(r.cpu_percent),
mem: Number(r.mem_percent),
disk: Number(r.disk_percent),
netRx: Number(r.net_rx_bps),
netTx: Number(r.net_tx_bps),
rps: Number(r.rps),
}));
}
/** Admin REST: daily averages across the retained window (for the calendar). */
async getDailySummary() {
if (!this.db || typeof this.db.query !== "function") return [];
const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000;
const rows = await this.db.query(
`SELECT
FLOOR(bucket_ts / 86400000) AS day_idx,
AVG(cpu_percent) AS cpu,
AVG(mem_percent) AS mem,
AVG(disk_percent) AS disk,
AVG(net_rx_bps) AS net_rx,
AVG(net_tx_bps) AS net_tx,
AVG(rps) AS rps,
COUNT(*) AS samples
FROM panel_metrics
WHERE bucket_ts >= ?
GROUP BY day_idx
ORDER BY day_idx ASC`,
[cutoff]
);
return (rows || []).map((r) => ({
ts: Number(r.day_idx) * 86400000,
cpu: round1(Number(r.cpu)),
mem: round1(Number(r.mem)),
disk: round1(Number(r.disk)),
netRx: Math.round(Number(r.net_rx)),
netTx: Math.round(Number(r.net_tx)),
rps: round1(Number(r.rps)),
samples: Number(r.samples),
}));
}
/** Current snapshot for the initial REST hydrate when a watcher opens. */
async getSnapshot() {
const sample = this._lastSample || (await this._collect());
const services = await this._services();
return { ...sample, services, panelVersion: this.panelVersion, startTime: this.startTime };
}
}
module.exports = { PanelMetricsCollector };
+205 -34
View File
@@ -2,6 +2,152 @@
const { getTechnicalServerName } = require("./server-name");
function isRemoteMissingResponse(response) {
const status = Number(response?.status || 0);
if (status === 404 || status === 410) return true;
const raw = String(response?.json?.error || response?.json?.detail || response?.json?.message || "").toLowerCase();
return raw.includes("not found") || raw.includes("not exist") || raw.includes("no such server") || raw.includes("no such container");
}
async function remoteServerExists(deps, baseUrl, headers, technicalName, timeoutMs = 8000) {
const response = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`,
"GET",
headers,
null,
timeoutMs
);
if (response.status === 200 && response.json && (response.json.ok === true || response.json.name || response.json.status)) {
return true;
}
if (isRemoteMissingResponse(response)) return false;
return null;
}
function deleteStatusShowsActiveGone(response) {
const body = response?.json || {};
return response?.status === 200 &&
body.deleteStatus === true &&
(body.deleted === true || (
body.containerExists === false &&
body.serverDirExists === false &&
body.metaExists === false &&
body.backupsDirExists === false
));
}
async function waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs = 3_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const timeout = Math.min(1200, Math.max(500, deadline - Date.now()));
const status = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/delete-status`,
"GET",
headers,
null,
timeout
).catch(() => null);
if (deleteStatusShowsActiveGone(status)) return true;
const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, timeout).catch(() => null);
if (exists === false) return true;
await new Promise((resolve) => setTimeout(resolve, 250));
}
return false;
}
async function requestRemoteDeleteAndConfirm(deps, { name, technicalName, baseUrl, headers, timeoutMs = 3_000 }) {
try {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000);
} catch {
}
const response = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`,
"DELETE",
headers,
null,
6_000
);
if (isRemoteMissingResponse(response)) return { accepted: true, confirmed: true };
if (!((response.status === 200 || response.status === 202) && response.json && response.json.ok) && response.status !== 0) {
const message = response.json && (response.json.error || response.json.detail || response.json.message)
? (response.json.error || response.json.detail || response.json.message)
: `remote delete failed (${response.status})`;
console.warn(`[delete] Remote delete request for ${name} did not complete cleanly: ${message}`);
return { accepted: false, confirmed: false };
}
const confirmed = await waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs);
return { accepted: true, confirmed };
}
function withTimeout(promise, ms, label = "timeout") {
let timer;
return Promise.race([
Promise.resolve(promise),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(label)), ms);
}),
]).finally(() => clearTimeout(timer));
}
function queueRemoteDelete(deps, { name, technicalName, baseUrl, headers }) {
setImmediate(async () => {
try {
try {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000);
console.log(`[delete] Force-stopped server ${name}`);
} catch (error) {
console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`);
}
const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`, "DELETE", headers, null, 8_000);
if ((response.status === 200 || response.status === 202) && response.json && response.json.ok) {
console.log(`[delete] Remote delete queued for ${name} on node.`);
return;
}
if (isRemoteMissingResponse(response)) {
console.log(`[delete] Remote server ${name} is already gone.`);
return;
}
if (response.status === 0) {
const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, 8_000);
if (exists === false) {
console.log(`[delete] Remote delete for ${name} timed out, but follow-up check confirms it is gone.`);
return;
}
}
const message = response.json && (response.json.error || response.json.detail)
? (response.json.error || response.json.detail)
: `remote delete failed (${response.status})`;
console.warn(`[delete] Background remote delete for ${name} did not complete cleanly: ${message}`);
} catch (error) {
console.warn(`[delete] Background remote delete failed for ${name}: ${error?.message || error}`);
}
});
}
function deleteNameCandidates(entry, requestedName, technicalName) {
const values = [
technicalName,
entry?.bot,
entry?.legacyId,
entry?.legacy_id,
entry?.name,
entry?.id,
requestedName,
];
const out = [];
const seen = new Set();
for (const value of values) {
const clean = String(value || "").trim();
if (!clean || seen.has(clean)) continue;
seen.add(clean);
out.push(clean);
}
return out;
}
async function deleteServerByName(deps, rawName) {
if (!deps || typeof deps !== "object") {
throw new Error("Server delete dependencies are required.");
@@ -45,49 +191,74 @@ async function deleteServerByName(deps, rawName) {
const headers = deps.nodeAuthHeadersFor(node, true);
try {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 30_000);
console.log(`[delete] Force-stopped server ${name}`);
} catch (error) {
console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`);
if (typeof deps.markServerDeletingStatus === "function") {
await withTimeout(deps.markServerDeletingStatus(name), 5000, "mark-delete-status-timeout").catch((error) => {
console.warn(`[delete] Could not mark ${name} as deleting: ${error?.message || error}`);
});
}
try {
const backupsRes = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups`, "GET", headers, null, 10_000);
if (backupsRes.status === 200 && backupsRes.json?.backups) {
for (const backup of backupsRes.json.backups) {
if (!backup?.id) continue;
await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups/${encodeURIComponent(backup.id)}`,
"DELETE",
headers,
null,
30_000
);
console.log(`[delete] Deleted backup ${backup.id} for server ${name}`);
}
let deleteAccepted = false;
let confirmedDeleted = false;
let attemptedName = technicalName;
for (const candidate of deleteNameCandidates(entry, name, technicalName)) {
attemptedName = candidate;
const outcome = await requestRemoteDeleteAndConfirm(deps, {
name,
technicalName: candidate,
baseUrl,
headers,
timeoutMs: 3_000,
}).catch((error) => {
console.warn(`[delete] Could not confirm remote delete for ${name} using ${candidate}: ${error?.message || error}`);
return { accepted: false, confirmed: false };
});
deleteAccepted = !!outcome.accepted;
confirmedDeleted = !!outcome.confirmed;
if (confirmedDeleted) break;
if (deleteAccepted) break;
}
if (confirmedDeleted) {
await withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => {
console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`);
});
try {
await withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout");
} catch (error) {
console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`);
}
} catch (error) {
console.log(`[delete] Could not delete backups for ${name}: ${error.message}`);
await withTimeout(deps.removeServerIndexEntry(name), 8000, "delete-index-timeout");
return {
ok: true,
remote: true,
deleted: true,
queued: false,
};
}
await deps.deleteServerSchedules(name);
const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, "DELETE", headers, null, 60_000);
if (response.status !== 200 || !(response.json && response.json.ok)) {
const message = response.json && (response.json.error || response.json.detail)
? (response.json.error || response.json.detail)
: `remote delete failed (${response.status})`;
return { ok: false, statusCode: 502, error: message };
if (typeof deps.enqueueServerDeleteJob === "function") {
await deps.enqueueServerDeleteJob({ name, technicalName: attemptedName, node });
if (typeof deps.kickServerDeleteWorker === "function") deps.kickServerDeleteWorker();
} else {
queueRemoteDelete(deps, { name, technicalName: attemptedName, baseUrl, headers });
}
try {
await deps.removeAccessForServerName(name);
} catch {
withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => {
console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`);
});
if (typeof deps.removeAccessForServerName === "function") {
withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout").catch((error) => {
console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`);
});
}
await deps.removeServerIndexEntry(name);
return { ok: true, remote: true };
return {
ok: true,
remote: true,
deleting: true,
queued: true,
accepted: deleteAccepted,
};
}
module.exports = {
+1 -1
View File
@@ -406,7 +406,7 @@ function buildDefaultStartupCommand({ name, templateId, docker, hostPort, resour
const serverName = cleanString(name) || "{SERVER_NAME}";
const externalPort = toPositiveNumber(hostPort);
const containerPort = getContainerPort(normalizedTemplateId, docker, hostPort);
const parts = ["docker run -d -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"];
const parts = ["docker run -d -i -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"];
parts.push(...buildResourceArgs(resources));
+67 -6
View File
@@ -1,5 +1,7 @@
"use strict";
const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function cleanString(value) {
return String(value ?? "").trim();
}
@@ -17,6 +19,41 @@ function toFiniteNumber(value) {
return Number.isFinite(numeric) ? numeric : null;
}
function normalizePortProtocol(value) {
const protocol = cleanString(value).toLowerCase();
return protocol === "tcp" || protocol === "udp" || protocol === "sctp" ? protocol : "";
}
function sanitizePortProtocolPayload(portProtocols, ports = []) {
if (!portProtocols || typeof portProtocols !== "object" || Array.isArray(portProtocols)) return null;
const allowedPorts = new Set(
(Array.isArray(ports) ? ports : [])
.map((entry) => toFiniteNumber(entry))
.filter((entry) => Number.isInteger(entry) && entry > 0)
.map((entry) => String(entry))
);
const out = {};
for (const [rawPort, rawProtocols] of Object.entries(portProtocols)) {
const port = toFiniteNumber(rawPort);
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
const portKey = String(port);
if (allowedPorts.size && !allowedPorts.has(portKey)) continue;
const source = Array.isArray(rawProtocols) ? rawProtocols : [rawProtocols];
const protocols = [];
const seen = new Set();
for (const entry of source) {
const protocol = normalizePortProtocol(entry);
if (!protocol || seen.has(protocol)) continue;
seen.add(protocol);
protocols.push(protocol);
}
if (protocols.length) out[portKey] = protocols;
}
return Object.keys(out).length ? out : null;
}
function cleanAbsoluteContainerPath(value, fallback = "") {
let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/");
if (!raw) return fallback;
@@ -31,6 +68,7 @@ function sanitizeEnvPayload(env) {
const out = {};
for (const [key, value] of Object.entries(env)) {
const envKey = cleanString(key);
if (POLLUTION_KEYS.has(envKey)) continue;
if (!envKey) continue;
out[envKey] = String(value ?? "");
}
@@ -44,7 +82,6 @@ function sanitizeDockerInstallPayload(install) {
if (!script) return null;
const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian";
const entrypoint = cleanString(install.entrypoint) || "bash";
const mountPath = cleanAbsoluteContainerPath(
install.mountPath || install.containerPath || install.container_path || install.serverPath,
"/mnt/server"
@@ -54,24 +91,26 @@ function sanitizeDockerInstallPayload(install) {
"/home/container"
);
const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds || install.timeout);
const timeoutSeconds = timeoutRaw && timeoutRaw > 0
? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200))
: 1800;
const minimumStorageRaw = toFiniteNumber(install.minimumStorageMb || install.minimum_storage_mb);
const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0
? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024))
: 0;
const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds);
const timeoutSeconds = timeoutRaw && timeoutRaw > 0
? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200))
: 1800;
const payload = {
image,
script,
entrypoint,
mountPath,
runtimePath,
timeoutSeconds,
};
if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb;
if (install.allowEmpty === true || install.allowEmptyResult === true) {
payload.allowEmpty = true;
}
const env = sanitizeEnvPayload(install.env);
if (env) payload.env = env;
@@ -104,6 +143,10 @@ function sanitizeDockerTemplatePayload(docker) {
const restartPolicy = cleanString(docker.restartPolicy);
if (restartPolicy) payload.restartPolicy = restartPolicy;
if (docker.runAsRoot === true || docker.run_as_root === true) {
payload.runAsRoot = true;
}
const ports = Array.isArray(docker.ports)
? docker.ports
.map((entry) => {
@@ -114,6 +157,12 @@ function sanitizeDockerTemplatePayload(docker) {
: [];
if (ports.length) payload.ports = ports;
const portProtocols = sanitizePortProtocolPayload(
docker.portProtocols || docker.port_protocols || docker.protocols,
ports
);
if (portProtocols) payload.portProtocols = portProtocols;
const volumes = Array.isArray(docker.volumes)
? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean)
: [];
@@ -132,6 +181,17 @@ function sanitizeDockerTemplatePayload(docker) {
);
if (adpanelStartup) payload.adpanelStartup = adpanelStartup;
const startupDisplay = cleanScript(
docker.startupDisplay ||
docker.startup_display ||
docker.startupPreview ||
docker.startup_preview ||
docker.imageDefaultStartup ||
docker.image_default_startup,
32768
);
if (startupDisplay) payload.startupDisplay = startupDisplay;
const install = sanitizeDockerInstallPayload(docker.install || docker.installation);
if (install) payload.install = install;
@@ -146,4 +206,5 @@ module.exports = {
sanitizeDockerTemplatePayload,
sanitizeDockerInstallPayload,
sanitizeEnvPayload,
sanitizePortProtocolPayload,
};