Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+843
View File
@@ -0,0 +1,843 @@
"use strict";
// adpanel:backup-cap-daemon-enforced — pins for the wiring that transmits the
// panel's per-server backup cap to the node daemon as resources.backupsMax.
//
// Background: the panel's count-then-create checks (index.js scheduler fire
// path at SCHEDULER_MAX_BACKUPS_PER_SERVER, nodes.js interactive relay at
// MAX_BACKUPS_PER_SERVER) are a TOCTOU fast-fail — N parallel creates can all
// count the same snapshot before any commits. The daemon's backupsMax
// (main.go backup create: read from server meta, counted over an untruncated
// ReadDir of ALL backup subdirs, checked under the per-server op lock AND the
// per-scope upload lock) is the authoritative bound — but it is opt-in: the
// daemon treats a MISSING or non-positive backupsMax as "no cap" (`if
// backupsMax > 0`), and nothing in the panel used to set one. These tests pin
// that every panel→node resources transmission point now carries the cap:
//
// create payloads (POST /v1/servers/create)
// - services/server-create.js (panel route pipeline) — resolved-cap
// default when the request names none; explicit values pass through;
// - nodes.js node proxy create — the panel cap constant in scope;
// - utils/dashboard-assistant-tools.js create_server tool — resolved-cap
// default when the request names none;
// resources relays (PATCH /v1/servers/:name/resources)
// - index.js PATCH /api/settings/servers/:name/resources (payload AND the
// index-entry mirror the settings editor prefills from);
// - index.js transfer flow — the destination apply (authoritative) and
// the best-effort source-side re-apply.
//
// The lockstep section evaluates the REAL monolith constants from source
// (same technique as backup-create-cap-refusal.test.js) against the shared
// resolver in utils/backup-cap.js — the monolith constants must NOT be
// replaced by the resolver (their source is slice-evaluated here and by that
// test); the resolver exists for the modules that cannot require index.js.
//
// Section 4 is BEHAVIORAL: the REAL PATCH /api/settings/servers/:name/resources
// handler is extracted from source and executed end-to-end with injected
// stubs. It exists because the first version of the PATCH wiring compiled
// fine and every structural pin passed while the normal successful path
// threw ReferenceError (effectiveBackupsMax declared in a sibling scope to
// its reader) — nothing in the suite executed the handler, so the regression
// shipped invisible. It also pins the adpanel:backup-cap-parse-hardening
// contract (garbage/negative/coercible-to-zero-garbage -> cap; deliberate 0
// and 12 pass through; absent -> cap) on payload AND index mirror.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const NODES_JS = path.join(ROOT, "nodes.js");
const INDEX_JS = path.join(ROOT, "index.js");
const SERVICE_JS = path.join(ROOT, "services", "server-create.js");
const TOOLS_JS = path.join(ROOT, "utils", "dashboard-assistant-tools.js");
const CAP_UTIL_JS = path.join(ROOT, "utils", "backup-cap.js");
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const serviceSource = fs.readFileSync(SERVICE_JS, "utf8");
const toolsSource = fs.readFileSync(TOOLS_JS, "utf8");
// Strip full-line comments so prose mentioning the markers cannot satisfy
// the source-level assertions.
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
const nodesCode = stripFullLineComments(nodesSource);
const indexCode = stripFullLineComments(indexSource);
const serviceCode = stripFullLineComments(serviceSource);
const toolsCode = stripFullLineComments(toolsSource);
function sliceFrom(source, startMarker, endMarker, label) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `${label}: start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `${label}: end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
const { resolvePanelBackupsCap, resolveBackupsMaxFromInput, PANEL_BACKUPS_CAP_DEFAULT } = require("../utils/backup-cap");
// The REAL storage-name sanitizer: the daemon-dial-canonical pin below must
// exercise the derivation the handler performs, not a stub of it.
const { sanitizeNodeStorageName } = require("../utils/server-name");
// ---------------------------------------------------------------------------
// 1. The resolver: same parse semantics as the two monolith IIFEs, and never
// 0/undefined (the daemon reads either as "no cap").
// ---------------------------------------------------------------------------
test("resolvePanelBackupsCap: built-in 50, env override only for finite integers > 0", () => {
const original = process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
try {
delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
assert.strictEqual(resolvePanelBackupsCap(), 50, "shipped default cap must be 50");
assert.strictEqual(PANEL_BACKUPS_CAP_DEFAULT, 50);
for (const [raw, expected] of [
["7", 7],
["12", 12],
["0", 50], // 0 would disable the daemon cap — keeps the default
["-3", 50],
["abc", 50],
["7.5", 50], // non-integer: same Number.isInteger gate as the IIFEs
["", 50],
]) {
process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = raw;
assert.strictEqual(resolvePanelBackupsCap(), expected, `env=${JSON.stringify(raw)}`);
}
assert.ok(resolvePanelBackupsCap() > 0, "the resolver must never return 0/undefined");
} finally {
if (original === undefined) delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
else process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = original;
}
});
// ---------------------------------------------------------------------------
// 2. Lockstep: utils/backup-cap.js vs the REAL index.js and nodes.js cap
// constants, evaluated from source under several env values.
// ---------------------------------------------------------------------------
function evalNodesCap() {
return new Function(
sliceFrom(
nodesSource,
"const MAX_BACKUPS_PER_SERVER",
"// GET the server's backup list",
"nodes.js backup cap constant"
) + "\nreturn MAX_BACKUPS_PER_SERVER;"
)();
}
function evalIndexCap() {
return new Function(
sliceFrom(
indexSource,
"const SCHEDULER_MAX_BACKUPS_PER_SERVER",
"\nfunction scheduleToCron(",
"index.js backup cap constant"
) + "\nreturn SCHEDULER_MAX_BACKUPS_PER_SERVER;"
)();
}
test("backup cap lockstep: monolith constants (source-evaluated) === shared resolver", () => {
const original = process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
try {
for (const raw of [undefined, "7", "0", "abc"]) {
if (raw === undefined) delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
else process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = raw;
const resolved = resolvePanelBackupsCap();
assert.strictEqual(evalNodesCap(), resolved, `nodes.js constant must match the resolver (env=${JSON.stringify(raw)})`);
assert.strictEqual(evalIndexCap(), resolved, `index.js constant must match the resolver (env=${JSON.stringify(raw)})`);
assert.ok(resolved > 0);
}
} finally {
if (original === undefined) delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
else process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = original;
}
});
// ---------------------------------------------------------------------------
// 3. Structural pins: every panel→node resources transmission point carries
// the cap, defaulted from the resolved cap — never 0/undefined.
// ---------------------------------------------------------------------------
// adpanel:backup-cap-parse-hardening — the shared parse/degrade helper: a
// garbage or negative explicit value must degrade to the panel cap (never to
// unlimited, which the daemon's `if backupsMax > 0` would read as "no cap").
// The deliberate-zero set is EXACTLY a number 0, or an empty/whitespace-only
// string — the settings UI's zero field — meaning deliberate unlimited;
// every other garbage shape (including coercible-to-zero [] and false,
// Number([]) === Number(false) === 0) degrades to the panel cap. Finite
// numbers >= 0 and numeric strings pass through truncated toward zero;
// absent degrades to the cap.
test("resolveBackupsMaxFromInput: garbage/negative/coercible-to-zero shapes degrade to the cap; deliberate zero and values pass through; absent -> cap", () => {
const original = process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
try {
delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
const cap = resolvePanelBackupsCap();
for (const [raw, expected] of [
[undefined, cap],
[null, cap],
["abc", cap],
[-5, cap],
["-5", cap],
[Number.NaN, cap],
[{ nested: true }, cap],
[[], cap], // Number([]) === 0 must NOT read as a deliberate zero
[false, cap], // Number(false) === 0 must NOT read as a deliberate zero
[0, 0],
["0", 0],
["", 0], // the settings UI's empty/zero field — deliberate no-cap
[" ", 0], // whitespace-only string: the same settings-UI zero field
[12, 12],
["12", 12],
["12.9", 12],
["0.5", 0], // trunc semantics: the floor of 0.5 IS 0 (kept, documented)
[" 7 ", 7],
]) {
assert.strictEqual(resolveBackupsMaxFromInput(raw), expected, `input=${JSON.stringify(raw)}`);
}
// The degrade target tracks the SAME env override the panel's count
// checks refuse at — not a test-local constant.
process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = "7";
assert.strictEqual(resolveBackupsMaxFromInput("abc"), 7);
assert.strictEqual(resolveBackupsMaxFromInput(undefined), 7);
assert.strictEqual(resolveBackupsMaxFromInput(0), 0);
} finally {
if (original === undefined) delete process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER;
else process.env.SCHEDULER_MAX_BACKUPS_PER_SERVER = original;
}
});
test("services/server-create.js create payload resolves backupsMax through the ONE shared parse helper", () => {
assert.ok(
serviceCode.includes('const { resolveBackupsMaxFromInput } = require("../utils/backup-cap");'),
"the service must parse/degrade backupsMax through the shared util"
);
// Every branch (explicit pass-through, garbage/negative degrade, absent ->
// cap) lives in the ONE helper call — no per-site parseInt || 0 copy.
assert.ok(
serviceCode.includes("resources.backupsMax = resolveBackupsMaxFromInput(reqResources.backupsMax);"),
"the create payload's backupsMax must flow through resolveBackupsMaxFromInput"
);
assert.ok(
!serviceCode.includes("parseInt(reqResources.backupsMax"),
"the old parseInt(x, 10) || 0 copy (garbage/negative -> 'no cap') must be gone"
);
});
test("utils/dashboard-assistant-tools.js create_server payload resolves backupsMax through the ONE shared parse helper", () => {
assert.ok(
toolsCode.includes('const { resolveBackupsMaxFromInput } = require("./backup-cap");'),
"the tool must parse/degrade backupsMax through the shared util"
);
assert.ok(
toolsCode.includes("resources.backupsMax = resolveBackupsMaxFromInput(inputResources.backupsMax);"),
"the tool payload's backupsMax must flow through resolveBackupsMaxFromInput"
);
assert.ok(
!toolsCode.includes("parseInt(inputResources.backupsMax"),
"the old parseInt(x, 10) || 0 copy (garbage/negative -> 'no cap') must be gone"
);
// The tool's former post-hoc negative rejection is unreachable under the
// degrade-to-cap helper and was dropped with it (consistent semantics).
assert.ok(
!toolsCode.includes("Backups limit must be greater than or equal to 0."),
"the unreachable negative rejection must not come back as dead code"
);
});
test("nodes.js proxy create transmits and commits the panel cap (MAX_BACKUPS_PER_SERVER)", () => {
// The daemon dial: the create payload must carry the field.
const dialSlice = sliceFrom(
nodesCode,
'"/v1/servers/create", "POST"',
"LONG_NODE_TIMEOUT_MS",
"nodes.js proxy create dial"
);
assert.ok(
dialSlice.includes("resources: { backupsMax: MAX_BACKUPS_PER_SERVER }"),
"the proxy create payload must transmit resources.backupsMax = the in-scope panel cap"
);
// The committed row: mirrors what was transmitted (the settings editor
// prefills from it and the transfer flows re-apply it).
const entrySlice = sliceFrom(
nodesCode,
"setupMessage: (json && json.meta && json.meta.setupMessage) || undefined,",
"\n };",
"nodes.js proxy create committed entry"
);
assert.ok(
entrySlice.includes("resources: { backupsMax: MAX_BACKUPS_PER_SERVER }"),
"the proxy's committed index entry must mirror the transmitted cap"
);
});
test("index.js resources PATCH relay: handler-slice pins (default, explicit branch, payload, index mirror)", () => {
const handlerSlice = sliceFrom(
indexCode,
'app.patch("/api/settings/servers/:name/resources"',
'app.get("/api/settings/servers/:name/resources"',
"index.js resources PATCH relay handler"
);
assert.ok(
handlerSlice.includes("let effectiveBackupsMax = SCHEDULER_MAX_BACKUPS_PER_SERVER;"),
"a server with no configured backupsMax must default to the in-scope panel cap"
);
assert.ok(
handlerSlice.includes("if (Number.isFinite(parsedBackupsMax) && parsedBackupsMax >= 0) effectiveBackupsMax = parsedBackupsMax;"),
"the explicit-value branch must pass a finite >= 0 value through (garbage/negative degrade to the cap)"
);
assert.ok(
handlerSlice.includes("payload.resources.backupsMax = effectiveBackupsMax;"),
"the relayed payload must always carry resources.backupsMax"
);
assert.ok(
handlerSlice.includes("{ ...lockedEntry.resources, ...applied.resources }") && handlerSlice.includes("toDbJson(indexedResources)"),
"the row mirror must record the accepted PATCH resource values, including backupsMax"
);
});
test("index.js transfer flow carries the cap on both resources PATCHes", () => {
const transferCode = stripFullLineComments(fs.readFileSync(path.join(ROOT, "services", "server-transfer.js"), "utf8"));
const destSlice = sliceFrom(
transferCode,
"const resources = computeTransferEffectiveResources(serverEntry.resources, sourceNode, current);",
"const patch = await deps.httpRequestJson(",
"transfer destination apply"
);
assert.ok(
destSlice.includes("if (resources.backupsMax == null) resources.backupsMax = defaultBackupsMax;"),
"the destination apply must default backupsMax to the panel cap"
);
assert.match(indexCode, /serverTransfer\.finalizeTransferDestination\([\s\S]+?defaultBackupsMax: SCHEDULER_MAX_BACKUPS_PER_SERVER/);
assert.match(transferCode, /"PATCH", deps\.nodeAuthHeadersFor\(current, true\), \{\s*resources,/);
// Source-side best-effort re-apply before stopping.
const srcSlice = sliceFrom(
indexCode,
"const patchResources = { ...resources };",
".catch(() => { });",
"index.js transfer source-side re-apply"
);
assert.ok(
srcSlice.includes("if (patchResources.backupsMax == null) patchResources.backupsMax = SCHEDULER_MAX_BACKUPS_PER_SERVER;"),
"the source-side re-apply must default backupsMax to the panel cap"
);
assert.ok(
srcSlice.includes("{ resources: patchResources }"),
"the source-side re-apply must send the cap-carrying clone, not the raw entry"
);
});
// ---------------------------------------------------------------------------
// 4. ReferenceError regression + adpanel:backup-cap-parse-hardening —
// BEHAVIORAL: the REAL PATCH /api/settings/servers/:name/resources route
// handler is extracted from source and executed end-to-end with injected
// stubs (the repo's new Function/extract technique, as
// scheduler-timezone.test.js does for its route). The first version of
// the daemon-cap wiring declared effectiveBackupsMax inside `if
// (resources)` while the index mirror read it from a SIBLING scope inside
// withServersIndexWriteLock — a ReferenceError on the NORMAL successful
// path (500 "failed to update resources" AFTER the daemon applied the
// change; saveServersIndex skipped; stop/start restart skipped). Nothing
// else in the suite executes this handler, so these tests are the only
// guard for that regression class.
// ---------------------------------------------------------------------------
function extractResourcesPatchHandlerSource() {
const startMarker = 'app.patch("/api/settings/servers/:name/resources"';
const endMarker = 'app.get("/api/settings/servers/:name/resources"';
const start = indexSource.indexOf(startMarker);
assert.ok(start >= 0, "PATCH handler: start marker not found");
const end = indexSource.indexOf(endMarker, start);
assert.ok(end > start, "PATCH handler: end marker not found after start");
const routeCall = indexSource.slice(start, end);
const prefix = startMarker + ", ";
assert.ok(routeCall.startsWith(prefix), "PATCH handler: unexpected route call shape");
// Drop the trailing `);` of the app.patch(...) call so only the async
// (req, res) arrow remains; new Function returns it.
const arrow = routeCall.slice(prefix.length).replace(/\)\s*;\s*$/, "");
assert.ok(arrow.endsWith("}"), "PATCH handler: extraction must end at the handler body");
return arrow;
}
const RESOURCES_PATCH_HANDLER_SRC = extractResourcesPatchHandlerSource();
// Every module-scope identifier the handler references (beyond req/res and
// JS globals) is injected; the harness below stubs each one.
const PATCH_HANDLER_DEPS = [
"isAuthenticated", "isAdmin", "userHasAccessToServer", "findServer",
"isRemoteEntry", "isServerSuspended", "sendSuspendedServerJson",
"serverOperationConflict", "findNodeByIdOrName", "buildNodeBaseUrl",
"nodeUnderCloudflare", "normalizeTemplateId", "findTemplateById",
"isMinecraftTemplateLike", "normalizeMinecraftJavaVersionInput",
"normalizeLegacyRuntimeProcessCommandInput", "validateRuntimeProcessCommandInput",
"validatePortListInput", "isPortInNodeAllocation", "validatePortAllocationsInput",
"getEffectiveNodeCapacity", "collectResourcePerformanceOptions", "parseOptionalIntegerResource",
"collectResourceAntiAbuseOptions", "SCHEDULER_MAX_BACKUPS_PER_SERVER",
"validatePort", "withKeyedLock", "findServerUsingNodePort",
"checkRemoteNodePortAvailability", "dockerPortProtocolsFor", "collectPortList",
"serverOpGuard", "nodeAuthHeadersFor",
"loadServersIndexIncludingDeleting",
"db", "toDbJson", "invalidateServerIndexCache", "httpRequestJson", "stopServerOnNode", "minecraftJavaTag",
"DEFAULT_MINECRAFT_PROCESS_IMAGE", "serverCreateService",
// adpanel:daemon-dial-canonical — module-scope name the route's four node
// dials now reference; the REAL implementation is injected below.
"sanitizeNodeStorageName",
];
function makePatchHandlerHarness(opts = {}) {
const calls = {
daemonPatches: [], // { url, method, body } dials to the node's resources PATCH
indexSaves: [], // server rows targeted by the scoped UPDATE
restarts: [], // { url, method, body } stop/start dials
suspensionLocks: 0,
nodeLockAtWrites: [],
};
const row = { rowId: 17, name: "srv01", nodeId: "node-1", port: 25565, status: "running", template: "minecraft", resources: { ramMb: 512 }, ...opts.row };
let nodeLockHeld = false;
const deps = {
isAuthenticated: async () => opts.authenticated !== false,
isAdmin: async () => opts.admin !== false,
userHasAccessToServer: async () => true,
// opts.row lets a test resolve an ALIAS request to a differently-named
// row (the daemon-dial-canonical pin); default row name stays "srv01".
findServer: async () => row,
isRemoteEntry: () => true,
isServerSuspended: () => false,
sendSuspendedServerJson: () => { throw new Error("sendSuspendedServerJson must not be reached"); },
serverOperationConflict: () => { throw new Error("serverOperationConflict must not be reached"); },
findNodeByIdOrName: async () => opts.node || { id: "node-1", name: "node-1", address: "203.0.113.10", api_port: 8080, ssl_enabled: false },
buildNodeBaseUrl: () => "http://203.0.113.10:8080",
nodeUnderCloudflare: () => false,
normalizeTemplateId: (t) => String(t || ""),
findTemplateById: () => null,
isMinecraftTemplateLike: () => false,
normalizeMinecraftJavaVersionInput: () => "",
normalizeLegacyRuntimeProcessCommandInput: (_t, c) => String(c || ""),
validateRuntimeProcessCommandInput: () => null,
validatePortListInput: (ports) => ports,
isPortInNodeAllocation: (_node, port) => !opts.removedPort || !nodeLockHeld || port !== opts.removedPort,
validatePortAllocationsInput: (allocations) => allocations,
getEffectiveNodeCapacity: async () => ({ ramMb: 0, cpuCores: 0, diskGb: 0 }),
collectResourcePerformanceOptions: () => ({}),
parseOptionalIntegerResource: new Function(sliceFrom(indexSource, "function parseOptionalIntegerResource(", "function collectResourcePerformanceOptions(", "resource number parser") + "\nreturn parseOptionalIntegerResource;")(),
collectResourceAntiAbuseOptions: (input) => Object.fromEntries(
Object.entries(input).filter(([key]) => ["networkInboundLimitMb", "networkOutboundLimitMb", "networkResetMinutes"].includes(key))
),
SCHEDULER_MAX_BACKUPS_PER_SERVER: resolvePanelBackupsCap(),
validatePort: (port) => Number(port) || null,
withKeyedLock: async (key, cb) => {
assert.strictEqual(key, "node-ports:node-1");
assert.strictEqual(nodeLockHeld, false);
nodeLockHeld = true;
try { return await cb(); } finally { nodeLockHeld = false; }
},
findServerUsingNodePort: async () => null,
checkRemoteNodePortAvailability: opts.checkRemoteNodePortAvailability || (async () => ({ verified: false })),
dockerPortProtocolsFor: (_runtime, _port, defaults) => defaults,
collectPortList: (value) => value || [],
serverOpGuard: {
requireServerSettingsTarget: require("../utils/server-op-guard").requireServerSettingsTarget,
async withReinstallSuspensionLock(name, busy, cb) {
assert.equal(name, row.name);
calls.suspensionLocks += 1;
return opts.suspensionLockBusy ? busy : cb();
},
},
nodeAuthHeadersFor: () => ({ Authorization: "Bearer node-token" }),
loadServersIndexIncludingDeleting: async () => [],
toDbJson: JSON.stringify,
invalidateServerIndexCache() {},
db: {
async query(sql, params) {
if (sql.startsWith("SELECT name, legacy_id, bot FROM servers")) return opts.storageRows || [row];
assert.match(sql, /WHERE id = \? AND node_id = \? AND suspended = 0 AND .*NOT IN \('transferring', 'deleting', 'reinstalling'\)/);
assert.deepEqual(params.slice(-2), [row.rowId, row.nodeId]);
if (sql.startsWith("SELECT id")) return opts.indexMissing ? [] : [{ id: row.rowId }];
assert.match(sql, /^UPDATE servers SET /);
const [resources, runtime, docker, port, ip] = params;
calls.indexSaves.push([{ resources: JSON.parse(resources), runtime: JSON.parse(runtime), docker: JSON.parse(docker), port, ip }]);
calls.nodeLockAtWrites.push(nodeLockHeld);
if (opts.indexError) throw opts.indexError;
return { affectedRows: opts.indexNoop || opts.indexMissing ? 0 : 1 };
},
},
httpRequestJson: async (url, method, _headers, body) => {
if (method === "PATCH") {
calls.daemonPatches.push({ url, method, body });
calls.nodeLockAtWrites.push(nodeLockHeld);
return opts.patchResponse || { status: 200, json: { ok: true } };
}
calls.restarts.push({ url, method, body });
if (new URL(url).pathname.endsWith("/stop")) return opts.stopResponse || { status: 200, json: { ok: true, stopped: true } };
return { status: 200, json: { ok: true } };
},
minecraftJavaTag: () => "latest",
DEFAULT_MINECRAFT_PROCESS_IMAGE: "ghcr.io/example/mc",
serverCreateService: require("../services/server-create"),
sanitizeNodeStorageName,
};
const stopSource = sliceFrom(indexSource, "async function stopServerOnNode(", "async function waitForServerReady(", "stop helper");
const stopDeps = ["buildNodeBaseUrl", "nodeUnderCloudflare", "nodeAuthHeadersFor", "sanitizeNodeStorageName", "httpRequestJson"];
deps.stopServerOnNode = new Function(...stopDeps, '"use strict";\nreturn (' + stopSource.trim() + ');')(...stopDeps.map(name => deps[name]));
// String concatenation, not a template literal: the handler source itself
// contains backticks/${} template literals.
const handler = new Function(...PATCH_HANDLER_DEPS, '"use strict";\nreturn (' + RESOURCES_PATCH_HANDLER_SRC + ');')(
...PATCH_HANDLER_DEPS.map((name) => deps[name])
);
async function run(resources, extra = {}) {
const resBody = { statusCode: 0, body: null };
const res = {
headersSent: false,
status(code) { resBody.statusCode = code; return this; },
json(payload) { resBody.body = payload; return payload; },
};
const req = {
// opts.alias plays a legacy_id/bot request alias resolving to the row.
params: { name: opts.alias || "srv01" },
session: { user: "admin@example.com" },
body: { resources, expectedTargetId: row.rowId, ...extra },
};
await handler(req, res);
return { resBody, calls };
}
return { run, calls };
}
test("PATCH resources handler denies ordinary server access before any write", async () => {
for (const [opts, statusCode] of [[{ authenticated: false }, 401], [{ admin: false }, 403]]) {
const fixture = makePatchHandlerHarness(opts);
const { resBody, calls } = await fixture.run({ backupsMax: 0 }, { mainPort: 25566 });
assert.equal(resBody.statusCode, statusCode);
assert.deepEqual(calls.daemonPatches, []);
assert.deepEqual(calls.indexSaves, []);
assert.deepEqual(calls.restarts, []);
}
});
test("PATCH resources handler refuses a lifecycle conflict before writing or restarting", async () => {
const fixture = makePatchHandlerHarness({ alias: "legacy", suspensionLockBusy: true });
const { resBody, calls } = await fixture.run({ ramMb: 1024 });
assert.equal(resBody.statusCode, 409);
assert.deepEqual(calls.daemonPatches, []);
assert.deepEqual(calls.indexSaves, []);
assert.deepEqual(calls.restarts, []);
});
test("PATCH resources refuses a replacement row before writing or restarting", async () => {
const fixture = makePatchHandlerHarness({ row: { rowId: 18 } });
const { resBody, calls } = await fixture.run({ ramMb: 1024 }, { expectedTargetId: 17 });
assert.equal(resBody.statusCode, 409);
assert.equal(resBody.body.code, "server-target-changed");
assert.deepEqual([calls.daemonPatches, calls.indexSaves, calls.restarts], [[], [], []]);
});
test("PATCH resources handler checks the fresh pool and holds the node lock through both writes", async () => {
for (const main of [true, false]) {
const fixture = makePatchHandlerHarness({ removedPort: 25566 });
const result = await fixture.run(main ? {} : { ports: [25566] }, main ? { mainPort: 25566 } : {});
assert.strictEqual(result.resBody.statusCode, 400);
assert.match(result.resBody.body.error, /25566.*not in this node's allocated ports/);
assert.deepStrictEqual(fixture.calls.nodeLockAtWrites, []);
}
const fixture = makePatchHandlerHarness();
const result = await fixture.run({ ports: [25567] }, { mainPort: 25566 });
assert.strictEqual(result.resBody.body.ok, true);
assert.deepStrictEqual(fixture.calls.nodeLockAtWrites, [true, true]);
assert.strictEqual(fixture.calls.restarts.length, 2);
});
test("PATCH resources derives bind addresses from the locked node pool", async () => {
const allocations = [{ port: 25565, ip: "192.0.2.11" }, { port: 25566, ip: "192.0.2.12" }];
const fixture = makePatchHandlerHarness({
node: { id: "node-1", address: "192.0.2.10", ports: { mode: "list", allocations } },
});
const { resBody, calls } = await fixture.run({
ports: [25566], portAllocations: [{ port: 25565, ip: "192.0.2.20" }, { port: 25566, ip: "192.0.2.21" }],
}, { ip: "192.0.2.20" });
assert.equal(resBody.body.ok, true);
assert.deepEqual(calls.nodeLockAtWrites, [true, true]);
assert.equal(calls.daemonPatches[0].body.bind_ip, allocations[0].ip);
assert.deepEqual(calls.daemonPatches[0].body.resources.portAllocations, allocations);
assert.equal(calls.indexSaves[0][0].ip, allocations[0].ip);
assert.deepEqual(calls.indexSaves[0][0].resources.portAllocations, allocations);
});
test("PATCH resources checks the allocation even when only the address changes", async () => {
const allocation = { port: 25565, ip: "192.0.2.11" };
const fixture = makePatchHandlerHarness({
node: { id: "node-1", address: "192.0.2.10", ports: { mode: "list", allocations: [allocation] } },
});
const { resBody, calls } = await fixture.run(undefined, { ip: "192.0.2.20" });
assert.equal(resBody.body.ok, true);
assert.deepEqual(calls.nodeLockAtWrites, [true, true]);
assert.equal(calls.daemonPatches[0].body.ip, allocation.ip);
assert.equal(calls.daemonPatches[0].body.bind_ip, allocation.ip);
assert.equal(calls.indexSaves[0][0].ip, allocation.ip);
});
test("PATCH resources validates the pool even for allocation-only metadata", async () => {
const fixture = makePatchHandlerHarness({ removedPort: 25565 });
const { resBody, calls } = await fixture.run({ portAllocations: [{ port: 25565, ip: "192.0.2.11" }] });
assert.equal(resBody.statusCode, 400);
assert.deepEqual(calls.nodeLockAtWrites, []);
assert.deepEqual(calls.restarts, []);
});
test("PATCH resources handler (real, executed): explicit 12 reaches the daemon payload AND the index mirror; restart fires", async () => {
const h = makePatchHandlerHarness();
const { resBody, calls } = await h.run({ ramMb: "1024", backupsMax: 12 });
assert.strictEqual(resBody.statusCode, 0, "no error status may be produced (the ReferenceError regression answered 500 after the daemon had already applied the change)");
assert.deepStrictEqual(resBody.body, { ok: true, message: "Resources updated" });
// The daemon PATCH carried the explicit value.
assert.strictEqual(calls.daemonPatches.length, 1);
assert.strictEqual(calls.daemonPatches[0].method, "PATCH");
assert.ok(calls.daemonPatches[0].url.includes("/v1/servers/srv01/resources"), calls.daemonPatches[0].url);
assert.strictEqual(calls.daemonPatches[0].body.resources.backupsMax, 12);
// The scoped index mirror wrote the same value.
assert.strictEqual(calls.indexSaves.length, 1);
assert.strictEqual(calls.indexSaves[0][0].resources.backupsMax, 12);
assert.strictEqual(
calls.indexSaves[0][0].resources.backupsMax,
calls.daemonPatches[0].body.resources.backupsMax,
"the index mirror must equal the value the PATCH sent to the daemon"
);
// The stop/start restart fired (RAM/CPU changes take effect on the live container).
assert.strictEqual(calls.restarts.length, 2, "stop then start");
assert.ok(calls.restarts[0].url.endsWith("/stop?wait=true"), calls.restarts[0].url);
assert.ok(calls.restarts[1].url.endsWith("/start"), calls.restarts[1].url);
assert.strictEqual(calls.suspensionLocks, 1);
});
test("PATCH resources handler leaves power alone if the row commit fails", async () => {
for (const [opts, status] of [[{ indexMissing: true }, 409], [{ indexError: new Error("synthetic write failure") }, 500]]) {
const fixture = makePatchHandlerHarness(opts);
const { resBody, calls } = await fixture.run({ ramMb: 1024 });
assert.equal(resBody.statusCode, status);
assert.match(resBody.body.error, /updated on the node/);
assert.equal(calls.indexSaves.length, 1);
assert.deepEqual(calls.restarts, []);
}
const unchanged = await makePatchHandlerHarness({ indexNoop: true }).run({ ramMb: 1024 });
assert.equal(unchanged.resBody.body.ok, true);
});
test("PATCH resources handler does not claim success for an unsupported quota", async () => {
const fixture = makePatchHandlerHarness({ patchResponse: { status: 400, json: { error: 'json: unknown field "networkInboundLimitMb"' } } });
const { resBody, calls } = await fixture.run({ networkInboundLimitMb: 128 });
assert.equal(resBody.statusCode, 502);
assert.equal(calls.daemonPatches.length, 1);
assert.deepEqual(calls.indexSaves, []);
assert.deepEqual(calls.restarts, []);
});
test("PATCH resources handler applies quota settings without changing power", async () => {
const fixture = makePatchHandlerHarness({ row: { resources: { networkOutboundLimitMb: 64, backupsMax: 3 } } });
const { resBody, calls } = await fixture.run({ networkInboundLimitMb: 128, networkOutboundLimitMb: 0 });
assert.equal(resBody.body.restarted, false);
assert.deepEqual(calls.daemonPatches[0].body.resources, { networkInboundLimitMb: 128, networkOutboundLimitMb: 0, backupsMax: 3 });
assert.deepEqual(calls.indexSaves[0][0].resources, { networkInboundLimitMb: 128, backupsMax: 3 });
assert.deepEqual(calls.restarts, []);
const empty = await makePatchHandlerHarness().run();
assert.equal(empty.resBody.body.restarted, false);
assert.deepEqual(empty.calls.daemonPatches, []);
assert.deepEqual(empty.calls.restarts, []);
});
test("PATCH resources preserves daemon setup and binding conflicts without saving or restarting", async () => {
for (const [code, error, fields] of [
["server_installing", "server is currently installing", {}],
["port_in_use", "required host port 25566 is in use", { mainPort: 25566 }],
]) {
const patchResponse = { status: 409, json: { code, error } };
const { resBody, calls } = await makePatchHandlerHarness({ patchResponse }).run({ ramMb: 1024 }, fields);
assert.equal(resBody.statusCode, 409);
assert.equal(resBody.body.error, error);
assert.equal(calls.indexSaves.length + calls.restarts.length, 0);
}
});
test("PATCH resources handler does not start a server unless the stop is confirmed", async () => {
for (const stopResponse of [{ status: 409, json: { ok: false } }, { status: 200, json: { ok: true, stopping: true } }]) {
const fixture = makePatchHandlerHarness({ stopResponse });
const { resBody, calls } = await fixture.run({ ramMb: 1024 });
assert.equal(resBody.statusCode, 502);
assert.equal(calls.restarts.length, 1);
assert.ok(calls.restarts[0].url.endsWith("/stop?wait=true"));
}
const stopped = makePatchHandlerHarness({ stopResponse: { status: 200, json: { ok: true, note: "not running" } } });
const { resBody, calls } = await stopped.run({ ramMb: 1024 });
assert.equal(resBody.body.ok, true);
assert.equal(calls.restarts.length, 2);
});
test("PATCH resources handler: omitted backupsMax defaults payload AND mirror to the resolved panel cap", async () => {
const h = makePatchHandlerHarness();
const { resBody, calls } = await h.run({ ramMb: "1024" });
assert.deepStrictEqual(resBody.body, { ok: true, message: "Resources updated" });
const cap = resolvePanelBackupsCap();
assert.strictEqual(calls.daemonPatches[0].body.resources.backupsMax, cap);
assert.strictEqual(calls.indexSaves[0][0].resources.backupsMax, cap);
assert.strictEqual(
calls.indexSaves[0][0].resources.backupsMax,
calls.daemonPatches[0].body.resources.backupsMax,
"the index mirror must equal the value the PATCH sent to the daemon when the field is omitted"
);
});
test("PATCH resources handler: an unrelated save preserves the server's backup limit", async () => {
for (const backupsMax of [0, resolvePanelBackupsCap() + 1]) {
const row = { name: "srv01", nodeId: "node-1", status: "running", resources: { backupsMax } };
const fixture = makePatchHandlerHarness({ row });
const { resBody, calls } = await fixture.run({ ramMb: 1024 });
assert.equal(resBody.body.ok, true);
assert.equal(calls.daemonPatches[0].body.resources.backupsMax, backupsMax);
assert.equal(calls.indexSaves[0][0].resources.backupsMax, backupsMax);
}
});
test("PATCH resources handler: garbage/negative explicit values degrade payload AND mirror to the panel cap (adpanel:backup-cap-parse-hardening)", async () => {
for (const raw of ["abc", -5, { nested: true }]) {
const h = makePatchHandlerHarness();
const { resBody, calls } = await h.run({ ramMb: "1024", backupsMax: raw });
assert.deepStrictEqual(resBody.body, { ok: true, message: "Resources updated" }, JSON.stringify(raw));
const cap = resolvePanelBackupsCap();
assert.strictEqual(calls.daemonPatches[0].body.resources.backupsMax, cap, `daemon payload must degrade to the cap for ${JSON.stringify(raw)}`);
assert.strictEqual(calls.indexSaves[0][0].resources.backupsMax, cap, `index mirror must degrade to the cap for ${JSON.stringify(raw)}`);
}
});
test("PATCH resources handler: explicit 0 (the deliberate no-daemon-cap) passes through to payload AND mirror", async () => {
const h = makePatchHandlerHarness();
const { resBody, calls } = await h.run({ ramMb: "1024", backupsMax: 0 });
assert.deepStrictEqual(resBody.body, { ok: true, message: "Resources updated" });
assert.strictEqual(calls.daemonPatches[0].body.resources.backupsMax, 0);
assert.strictEqual(calls.indexSaves[0][0].resources.backupsMax, 0);
});
test("PATCH resources handler: the settings UI's string shapes (\"12\", \"\") mirror their payload values", async () => {
const explicit = makePatchHandlerHarness();
const explicitRun = await explicit.run({ ramMb: "1024", backupsMax: "12" });
assert.strictEqual(explicitRun.calls.daemonPatches[0].body.resources.backupsMax, 12);
assert.strictEqual(explicitRun.calls.indexSaves[0][0].resources.backupsMax, 12);
const empty = makePatchHandlerHarness();
const emptyRun = await empty.run({ ramMb: "1024", backupsMax: "" });
assert.strictEqual(emptyRun.calls.daemonPatches[0].body.resources.backupsMax, 0, "empty string is the settings UI's zero field (deliberate no-daemon-cap)");
assert.strictEqual(emptyRun.calls.indexSaves[0][0].resources.backupsMax, 0);
});
// adpanel:daemon-dial-canonical — the daemon derives identity from the URL
// key (sanitizeName), so the PATCH dial and the stop/start restart pair must
// carry the resolved canonical storage name, never the raw request alias: a
// legacy_id/bot alias resolves the row, passes every check, then lands on a
// nonexistent (or, on legacy rows, another server's) container/dir.
test("PATCH resources refuses a normalized storage collision before mutation", async () => {
const harness = makePatchHandlerHarness({ row: { name: "_srv01" }, storageRows: [{ name: "srv01" }] });
const { resBody, calls } = await harness.run({ ramMb: 1024 });
assert.equal(resBody.statusCode, 409);
assert.match(resBody.body.error, /ambiguous storage ownership/);
assert.equal(calls.daemonPatches.length + calls.indexSaves.length + calls.restarts.length, 0);
});
test("PATCH resources rejects limits below Docker minimums before writing or restarting", async () => {
for (const resources of [{ ramMb: 5 }, { cpuCores: 0.005 }]) {
const { resBody, calls } = await makePatchHandlerHarness().run(resources);
assert.equal(resBody.statusCode, 400);
assert.equal(calls.daemonPatches.length + calls.indexSaves.length + calls.restarts.length, 0);
}
const { calls } = await makePatchHandlerHarness().run({ ramMb: 6, cpuCores: 0.01 });
assert.equal(calls.daemonPatches[0].body.resources.ramMb, 6);
assert.equal(calls.daemonPatches[0].body.resources.cpuCores, 0.01);
assert.equal(calls.restarts.length, 2);
});
test("PATCH resources rejects invalid hardware values before writing or restarting", async () => {
for (const resources of [{ ramMb: "512junk" }, { ramMb: 512.5 }, { cpuCores: "2cores" }, { storageMb: 0 }, { swapMb: -2 }, { maxSchedules: -1 }]) {
const { resBody, calls } = await makePatchHandlerHarness().run(resources);
assert.equal(resBody.statusCode, 400, JSON.stringify(resources));
assert.equal(calls.daemonPatches.length + calls.indexSaves.length + calls.restarts.length, 0);
}
const { calls } = await makePatchHandlerHarness().run({ ramMb: 1e3, cpuCores: 1.5, storageMb: 250, swapMb: -1 });
const { ramMb, cpuCores, storageMb, swapMb } = calls.daemonPatches[0].body.resources;
assert.deepEqual([ramMb, cpuCores, storageMb, swapMb], [1000, 1.5, 250, -1]);
});
test("PATCH resources rejects a busy Minecraft secondary port before writing or restarting", async () => {
const checks = [];
const harness = makePatchHandlerHarness({
row: { resources: { ports: [25566] } },
checkRemoteNodePortAvailability: async (_node, port, protocols, timeoutMs) => {
assert.ok(timeoutMs > 0 && timeoutMs <= 10_000);
checks.push([port, ...protocols]);
return { verified: true, available: false };
},
});
const { resBody, calls } = await harness.run({ ports: [25566, 25567] });
assert.equal(resBody.statusCode, 409);
assert.equal(resBody.body.code, "port_in_use");
assert.deepEqual(checks, [[25567, "tcp", "udp"]]);
assert.equal(calls.daemonPatches.length + calls.indexSaves.length + calls.restarts.length, 0);
});
test("PATCH resources handler (real, executed): the PATCH and the stop/start restart dial the canonical storage name, not the request alias", async () => {
const h = makePatchHandlerHarness({
// "srv01-legacy" plays the legacy_id/bot alias; findServer resolves the
// row whose stored name is "srv01".
alias: "srv01-legacy",
row: { name: "srv01", nodeId: "node-1", port: 25565, status: "running", template: "minecraft", resources: { ramMb: 512 } },
});
const { resBody, calls } = await h.run({ ramMb: "1024" });
assert.deepStrictEqual(resBody.body, { ok: true, message: "Resources updated" });
assert.strictEqual(calls.daemonPatches.length, 1);
assert.ok(calls.daemonPatches[0].url.endsWith("/v1/servers/srv01/resources"), `PATCH must dial the canonical storage name: ${calls.daemonPatches[0].url}`);
assert.ok(!calls.daemonPatches[0].url.includes("srv01-legacy"), "no dial may carry the raw request alias");
assert.strictEqual(calls.restarts.length, 2, "stop then start");
assert.ok(calls.restarts[0].url.endsWith("/v1/servers/srv01/stop?wait=true"), `stop must dial the canonical storage name: ${calls.restarts[0].url}`);
assert.ok(calls.restarts[1].url.endsWith("/v1/servers/srv01/start"), `start must dial the canonical storage name: ${calls.restarts[1].url}`);
assert.ok(!calls.restarts.some((c) => c.url.includes("srv01-legacy")), "no restart dial may carry the raw request alias");
});
// adpanel:daemon-dial-canonical — the sibling GET route dials the same URL
// key class; a source pin keeps its derivation from silently reverting (the
// behavioral harness above executes the PATCH handler only).
test("the resources GET dial carries the same canonical storage-name derivation", () => {
const getStart = indexCode.indexOf('app.get("/api/settings/servers/:name/resources"');
assert.ok(getStart >= 0, "resources GET route present");
const getEnd = indexCode.indexOf("app.", getStart + 10);
assert.ok(getEnd > getStart, "GET route window bounded");
const getBody = indexCode.slice(getStart, getEnd);
assert.ok(
getBody.includes("${baseUrl}/v1/servers/${encodeURIComponent(sanitizeNodeStorageName(serverEntry.name || name))}/resources"),
"the GET dial must derive the storage name from the resolved serverEntry, not the raw request alias"
);
assert.ok(RESOURCES_PATCH_HANDLER_SRC.includes('stopServerOnNode(node, serverEntry.name, { wait: true })'));
assert.ok(RESOURCES_PATCH_HANDLER_SRC.includes('httpRequestJson(`${serverUrl}/start`'));
assert.ok(RESOURCES_PATCH_HANDLER_SRC.includes('const storageName = sanitizeNodeStorageName(lockedEntry.name);'));
assert.ok(RESOURCES_PATCH_HANDLER_SRC.includes('${baseUrl}/v1/servers/${encodeURIComponent(storageName)}/resources'));
});
test("resource reads deny non-admins before looking up configuration", async () => {
const marker = 'app.get("/api/settings/servers/:name/resources", ';
const start = indexSource.indexOf(marker) + marker.length;
const source = indexSource.slice(start, indexSource.indexOf("\n});", start) + 2);
const handler = new Function("return (" + source + ");")();
for (const [req, status] of [[{}, 401], [{ currentUser: {}, isAdmin: false }, 403]]) {
const res = { status(code) { return { json: () => code }; } };
assert.equal(await handler(req, res), status);
}
});