"use strict"; // N10 regression tests for the admin template-change route // (POST /api/settings/servers/:name/template). // // The node daemon writes the reinstall payload's hostPort verbatim into its // server meta and re-binds the container to it, so the panel row must record // exactly the port the payload carried. The route used to overwrite the row // with template.defaultPort whenever no pool re-bind occurred, so a template // switch desynchronized the row from the node: the panel displayed — and every // later start sent — a port the server was never bound to, while the pool scan // treated the real port as free for re-allocation (port_in_use on next start). // // These tests execute the REAL route handler (extracted from index.js and run // in a vm sandbox with stubbed collaborators — index.js boots servers on // require and cannot be loaded in-process, same technique as // reinstall-route-protection) plus the REAL validatePort / isRemoteEntry / // isPortInNodeAllocation / normalizeTemplateId helpers, and lock in: // 1. a stored port that is still a pool member wins and is what the row // records (the reported corruption), // 2. a stored port outside the pool is re-bound to a free pool port, // 3. an exhausted pool refuses with 409 before any node call or row write, // 4. a missing stored port falls back to the template default only through // the same pool-checked path, // 5. a failed reinstall leaves the row untouched, // 6. local entries keep following template.defaultPort (no reinstall there). // 7. a template deleted while the reinstall was running refuses the row // commit with 409 and leaves the previous reference in place. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const vm = require("node:vm"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); // Slice a `{ ... }`-balanced block starting at startMarker (braces inside // template-literal expressions, object literals and regexes are balanced, so // plain counting is safe — same technique as reinstall-route-protection). function extractBlock(source, startMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `marker not found: ${startMarker}`); const bodyStart = source.indexOf("{", start); let depth = 0; let i = bodyStart; for (; i < source.length; i += 1) { if (source[i] === "{") depth += 1; else if (source[i] === "}") { depth -= 1; if (depth === 0) { i += 1; break; } } } assert.ok(depth === 0, `unbalanced braces after: ${startMarker}`); // Swallow the statement terminator (and any closing paren of the call). while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) { i += 1; if (source[i - 1] === ";") break; } return source.slice(start, i); } // Extract the full `app.post("/api/settings/servers/:name/template", ...);` // registration call, including the async handler it passes. function extractTemplateRoute(source) { const marker = 'app.post("/api/settings/servers/:name/template"'; const start = source.indexOf(marker); assert.ok(start >= 0, "template-change route registration not found"); // The handler body is the first brace-balanced block after the marker; walk // out to the terminating `});` of the app.post call itself. const block = extractBlock(source, marker); assert.ok(block.trimEnd().endsWith("});"), "template-change route slice must end at its registration terminator"); // Sentinel: guards against the brace-balanced slice silently drifting to a // smaller/larger region after future edits add unbalanced braces in strings // or comments inside the route. assert.ok(block.includes("boundHostPort = hostPort"), "route slice must contain the N10 port binding"); assert.ok(block.includes("applyTemplateChange"), "route slice must contain the row write"); return block; } const HELPER_MARKERS = [ "function validatePort(port)", "function normalizeTemplateId(tpl)", "function isRemoteEntry(entry)", "function isPortInNodeAllocation(node, port)", ]; function buildSandbox(overrides = {}) { const captured = { handler: null, reinstallCalls: [], savedLists: [], releasedClaims: [], cachedStatuses: [], freePortQueue: null, dispatch: null, }; const sandbox = { console: { log() { }, error() { }, warn() { } }, // Faithful mirror of index.js's withTimeout: the route bounds its // loadServersIndex read with it. The stubs here settle immediately, so // the timer never fires unless a test overrides loadServersIndex with a // never-settling promise on purpose. 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)); }, app: { post: (...args) => { captured.handler = args[args.length - 1]; }, }, // Route middleware identifiers only appear as registration arguments. sessionRevoke2faRateLimiter: () => { }, serverTemplateChangeRateLimiter: () => { }, // --- auth / step-up gates: pass through ------------------------------- isAdmin: async () => true, requireActionTokenOr403: async () => true, findUserByEmail: async () => ({ id: 7, email: "admin@example.com", admin: true, password: "synthetic-password-hash" }), isSessionSidRevoked: async () => false, requireDestructiveActionStepUp: async () => ({ ok: true, graceExpiresAt: 0 }), getVerifiedSessionRevokeGraceState: async () => null, // --- servers index ----------------------------------------------------- snapshotList: [], serverOpGuard: require("../utils/server-op-guard"), loadServersIndex: async () => sandbox.snapshotList.map((entry, index) => ({ rowId: index + 1, ...entry })), loadServersIndexFresh: async () => sandbox.loadServersIndex(), findServer: async (name) => (await sandbox.loadServersIndex()).find((entry) => entry.name === name) || null, db: { query: async (sql, values) => { if (sql.startsWith("INSERT INTO server_reinstall_dispatch")) { assert.equal(captured.dispatch, null); const [operation_id, host_port, template_id, intent] = values; captured.dispatch = { operation_id, host_port, template_id, intent }; return { affectedRows: 1 }; } if (sql.startsWith("DELETE FROM server_reinstall_dispatch")) { assert.equal(captured.dispatch?.operation_id, values[1]); captured.dispatch = null; return { affectedRows: 1 }; } return sandbox.snapshotList; }, pool: { getConnection: async () => ({ beginTransaction: async () => {}, commit: async () => {}, rollback: async () => {}, release() {}, async execute(sql, values) { if (sql.startsWith("DELETE FROM server_reinstall_dispatch")) return [await sandbox.db.query(sql, values)]; const [port, template, start, runtime, docker, rowId] = values; const rows = await sandbox.loadServersIndex(); if (sql.startsWith("SELECT")) { const current = rows.find((entry) => entry.name === port); return [current ? [{ ...current, status: "reinstalling" }] : []]; } const updatedRows = rows.map((entry) => entry.rowId === rowId ? { ...entry, port, template, start, runtime: JSON.parse(runtime), docker: JSON.parse(docker) } : entry); return [{ affectedRows: await sandbox.saveReinstallRow(updatedRows) ? 1 : 0 }]; }, }) }, }, mapServerRow: (row) => row, toDbJson: (value) => value == null ? null : JSON.stringify(value), invalidateServerIndexCache() {}, withServersIndexWriteLock: (fn) => fn(), // The commit path wraps the above in the template DELETE route's // "templates-write" key (mirror of insertServerIndexEntryGuarded). withKeyedLock: (key, fn) => fn(), saveReinstallRow: async function (list) { captured.savedLists.push(list); return true; }, // --- reinstall operation claim ----------------------------------------- claimReinstallOperation: async () => ({ ok: true, prevStatus: "stopped" }), releaseReinstallOperation: async (name, prev) => { captured.releasedClaims.push({ name, prev }); return { restored: true }; }, setCachedServerStatus: async (...args) => { captured.cachedStatuses.push(args); }, serverOperationConflict: () => ({ statusCode: 409, error: "conflict" }), // --- node plumbing ------------------------------------------------------- nodeRow: { id: "node1", uuid: "node1", address: "10.0.0.5", api_port: 8080, ssl_enabled: false, ports: { mode: "range", start: 30001, count: 10 }, }, findNodeByIdOrName: async () => sandbox.nodeRow, buildNodeBaseUrl: () => "https://10.0.0.5:8080", nodeUnderCloudflare: () => false, nodeAuthHeadersFor: () => ({}), signPanelAdminReinstallHeaders: () => true, isLegacySigningRejection: () => false, ...require("../utils/server-reinstall"), isServerSuspended: require("../services/node-fs-relay").isServerSuspended, sendSuspendedServerJson: require("../services/node-fs-relay").sendSuspendedServerJson, retryReinstallAfterSigningRejection: async () => null, httpRequestJson: async () => ({ status: 0, json: null }), httpRequestJsonPruningUnknownFields: async (url, method, headers, payload) => { captured.reinstallCalls.push({ url, method, payload }); if (captured.reinstallResponse) return { res: captured.reinstallResponse }; if (typeof captured.reinstallFailure === "number") { return { res: { status: captured.reinstallFailure, json: { ok: false, error: "node exploded" } } }; } return { res: { status: 200, json: { ok: true } } }; }, // N10: test-controlled free-port allocator (null = pool exhausted). findFreeNodePoolPort: async () => captured.freePortQueue, findServerUsingNodePort: async () => null, checkDestinationNodePort: async (_node, port, { excludeName }) => ({ ok: !sandbox.snapshotList.some((entry) => entry.name !== excludeName && Number(entry.port) === port), }), // --- template/docker helpers (not under test) --------------------------- TEMPLATES_FILE: "synthetic-templates.json", acquireReinstallTemplateLock: () => () => {}, findTemplateById: (id) => ({ id, name: String(id), defaultPort: 8080, docker: { image: "node", tag: "20", ports: [3000] }, }), normalizeTemplateDockerForRuntime: (id, docker) => (docker ? { ...docker } : null), dockerConfigForNodeRequest: (d) => d, defaultStartFileForTemplate: () => "index.js", recordActivity: () => { }, getRequestIp: () => "127.0.0.1", // Faithful mirror of index.js's stripLogControlChars // (adpanel:log-email-control-chars): the route's [SECURITY] console line // strips its identity fields before interpolating them. stripLogControlChars: (value) => String(value || "").replace(/[\x00-\x1f\x7f]/g, ""), }; for (const [key, value] of Object.entries(overrides)) { sandbox[key] = value; } return { sandbox, captured }; } function makeReq(body = {}) { return { params: { name: "srv1" }, session: { user: "admin@example.com" }, sessionID: "synthetic-session-id", is: () => true, body: { expectedTargetId: 1, ...body }, }; } function makeRes() { const out = { statusCode: 200, body: null, headers: {}, }; out.set = (k, v) => { out.headers[k] = v; return out; }; out.setHeader = out.set; out.status = (c) => { out.statusCode = c; return out; }; out.json = (b) => { out.body = b; return out; }; return out; } function loadHandler() { const { sandbox, captured } = buildSandbox(); const pieces = HELPER_MARKERS.map((m) => extractBlock(indexSource, m)); pieces.push(extractTemplateRoute(indexSource)); vm.runInNewContext(pieces.join("\n;\n"), sandbox, { filename: "template-route-sandbox.js" }); assert.ok(typeof captured.handler === "function", "route handler was not captured"); return { sandbox, captured }; } const NODEJS_TEMPLATE = { id: "nodejs", name: "NodeJS", defaultPort: 8080, docker: { image: "node", tag: "20", ports: [3000] }, }; test("template change: completed Minecraft reinstall awaiting EULA commits template and port", async () => { const { sandbox, captured } = loadHandler(); sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" }); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "nodejs", port: 25000, start: "index.js" }, ]; captured.freePortQueue = 30005; captured.reinstallResponse = { status: 409, json: { ok: false, error: "minecraft_eula_required", code: "minecraft_eula_required", detail: "Server files reinstalled. Accept the Minecraft EULA in the console to start the server.", }, }; const response = makeRes(); await captured.handler(makeReq({ templateId: "minecraft" }), response); assert.equal(response.statusCode, 200, JSON.stringify(response.body)); assert.equal(captured.reinstallCalls.length, 1); assert.equal(response.body.eulaRequired, true); assert.equal(response.body.server.template, "minecraft"); assert.equal(response.body.server.port, 30005); assert.equal(captured.savedLists.at(-1)[0].template, "minecraft"); assert.deepEqual(captured.releasedClaims, [{ name: "srv1", prev: "stopped" }]); assert.deepEqual(captured.cachedStatuses, [["srv1", { status: "stopped", nodeId: "node1" }]]); }); test("template change: completed rebuild without a runtime releases to stopped", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "running" }); captured.reinstallResponse = { status: 200, json: { ok: true, serverStopped: true } }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 200); assert.equal(response.body.ok, true); assert.deepEqual(captured.releasedClaims, [{ name: "srv1", prev: "stopped" }]); assert.deepEqual(captured.cachedStatuses, [["srv1", { status: "stopped", nodeId: "node1" }]]); }); test("template change: confirmed startup does not restore the old stopped status", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.claimReinstallOperation = async () => ({ ok: true, prevStatus: "stopped" }); captured.reinstallResponse = { status: 200, json: { ok: true, serverStopped: false, serverRunning: true } }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 200); assert.deepEqual(captured.releasedClaims, [{ name: "srv1", prev: "running" }]); assert.deepEqual(captured.cachedStatuses, [["srv1", { status: "running", nodeId: "node1" }]]); }); test("template change: suspended remote servers are refused before a reinstall is authorized", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001, suspended: true }]; sandbox.requireDestructiveActionStepUp = async () => assert.fail("suspension must refuse before step-up"); sandbox.claimReinstallOperation = async () => assert.fail("suspension must refuse before claiming a rebuild"); const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 423); assert.equal(response.body.code, "server-suspended"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); }); test("template change: ambiguous storage ownership refuses the shared reinstall dispatch", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; const journalQuery = sandbox.db.query; sandbox.db.query = async (sql, args) => /server_reinstall_dispatch/.test(sql) ? journalQuery(sql, args) : [sandbox.snapshotList[0], { name: "other-server", legacy_id: "srv1" }]; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409); assert.equal(response.body.code, "reinstall-storage-conflict"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: plaintext nodes are refused before port checks or reinstall dispatch", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.buildNodeBaseUrl = () => "http://10.0.0.5:8080"; sandbox.findServerUsingNodePort = async () => assert.fail("refusal must precede port checks"); sandbox.nodeAuthHeadersFor = () => assert.fail("refusal must precede node credential use"); const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 503); assert.equal(response.body.code, "reinstall-insecure-node-transport"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: a replacement row is refused before step-up or reinstall", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ rowId: 2, name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.requireDestructiveActionStepUp = async () => { throw new Error("stale target reached step-up"); }; sandbox.claimReinstallOperation = async () => { throw new Error("stale target reached the reinstall claim"); }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409); assert.equal(response.body.code, "server-target-changed"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); }); test("template change: a completed transfer during step-up must not reinstall the old node", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.requireDestructiveActionStepUp = async () => { sandbox.snapshotList = [{ name: "srv1", nodeId: "node2", template: "minecraft", port: 30008 }]; return { ok: true }; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409, "the old node must not be wiped after ownership moves"); assert.equal(response.body.code, "reinstall-target-changed"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: actor authority changed during step-up refuses before the node wipe", async () => { for (const changed of [{ admin: false }, { suspended: true }, { password: "replacement-password-hash", session_epoch: 5 }, { secret: "replacement-2fa-seed", session_epoch: 5 }, { id: 8 }]) { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; const actor = { id: 7, email: "admin@example.com", admin: true, suspended: false, password: "proved-password-hash", secret: null, session_epoch: 4 }; let liveActor = { ...actor }; sandbox.findUserByEmail = async () => ({ ...liveActor }); sandbox.requireDestructiveActionStepUp = async () => { liveActor = { ...liveActor, ...changed }; return { ok: true }; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 403, "changed actor authority must invalidate a pending admin rebuild"); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); } }); test("template change: local changes cannot commit after the acting admin is demoted", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "local", template: "minecraft", port: 25565 }]; let actor = { id: 7, email: "admin@example.com", admin: true, password: "synthetic-password-hash" }; sandbox.findUserByEmail = async () => ({ ...actor }); sandbox.requireDestructiveActionStepUp = async () => { actor = { ...actor, admin: false }; return { ok: true }; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 403); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: confirmed node completion still commits after the actor loses access", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; let actor = { id: 7, email: "admin@example.com", admin: true, password: "synthetic-password-hash" }; sandbox.findUserByEmail = async () => ({ ...actor }); const send = sandbox.httpRequestJsonPruningUnknownFields; sandbox.httpRequestJsonPruningUnknownFields = async (...args) => { const completed = await send(...args); actor = { ...actor, admin: false }; return completed; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 200); assert.equal(captured.reinstallCalls.length, 1); assert.equal(captured.savedLists[0][0].template, "nodejs", "an already completed rebuild must remain authoritative"); assert.equal(captured.releasedClaims.length, 1); }); test("template change: failed index commit reports the completed node wipe without success", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 25000 }]; captured.freePortQueue = 30005; sandbox.saveReinstallRow = async (list) => { captured.savedLists.push(list); return false; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 500); assert.equal(response.body.code, "reinstall-index-save-failed"); assert.equal(response.body.reinstalled, true); assert.equal(captured.reinstallCalls.length, 1); assert.equal(captured.releasedClaims.length, 1); }); test("template change: stored in-pool port wins — row records the port the node actually bound", async () => { const { sandbox, captured } = loadHandler(); // The reported scenario: server lives on 30001 (inside the 30001-30010 pool), // the new template defaults to 8080. The node binds 30001, so the row must // keep 30001 — writing 8080 here is the corruption this file locks out. sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 30001, start: "server.jar" }, ]; captured.freePortQueue = 30002; // must never be consulted in this scenario const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200, `expected success, got ${res.statusCode}: ${JSON.stringify(res.body)}`); assert.strictEqual(captured.reinstallCalls.length, 1, "reinstall must be called exactly once"); assert.strictEqual(captured.reinstallCalls[0].payload.hostPort, 30001, "payload must carry the stored in-pool port"); assert.strictEqual(res.body.server.port, 30001, "row must record the port the node bound, not template.defaultPort"); assert.strictEqual(captured.savedLists.at(-1)[0].port, 30001, "persisted row port must be the bound port"); assert.strictEqual(res.body.server.template, "nodejs", "template must still be updated"); }); test("template change: a duplicate stored allocation is refused before the node call", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.findServerUsingNodePort = async (_node, port, excludeName) => { assert.equal(port, 30001); assert.equal(excludeName, "srv1"); return { name: "other", status: "stopped" }; }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: stored port outside the pool is re-bound and the re-bound port is recorded", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 25000, start: "server.jar" }, ]; captured.freePortQueue = 30005; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); assert.strictEqual(captured.reinstallCalls[0].payload.hostPort, 30005, "payload must carry the re-bound pool port"); assert.strictEqual(res.body.server.port, 30005, "row must record the re-bound port"); }); test("template change: concurrent rebindings share the node-port lock through commit", async () => { const first = loadHandler(); const second = loadHandler(); first.sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 25000 }]; second.sandbox.snapshotList = [{ name: "srv2", nodeId: "node1", template: "minecraft", port: 25001 }]; first.captured.freePortQueue = 30005; second.captured.freePortQueue = 30005; let completeFirst; let signalFirst; const firstEntered = new Promise((resolve) => { signalFirst = resolve; }); const firstComplete = new Promise((resolve) => { completeFirst = resolve; }); first.sandbox.httpRequestJsonPruningUnknownFields = async (url, method, headers, payload) => { first.captured.reinstallCalls.push({ url, method, payload }); signalFirst(); await firstComplete; return { res: { status: 200, json: { ok: true } } }; }; first.sandbox.saveReinstallRow = async (list) => { first.captured.savedLists.push(list); second.captured.freePortQueue = null; return true; }; const firstResponse = makeRes(); const secondResponse = makeRes(); const firstAttempt = first.captured.handler(makeReq({ templateId: "nodejs" }), firstResponse); await firstEntered; const secondRequest = makeReq({ templateId: "nodejs" }); secondRequest.params.name = "srv2"; const secondAttempt = second.captured.handler(secondRequest, secondResponse); let prematureNodeCalls; try { await new Promise(setImmediate); prematureNodeCalls = second.captured.reinstallCalls.length; } finally { completeFirst(); await Promise.all([firstAttempt, secondAttempt]); } assert.equal(prematureNodeCalls, 0); assert.equal(firstResponse.statusCode, 200); assert.equal(secondResponse.statusCode, 409); assert.equal(second.captured.reinstallCalls.length, 0); assert.equal(second.captured.savedLists.length, 0); assert.equal(first.captured.releasedClaims.length, 1); assert.equal(second.captured.releasedClaims.length, 1); }); test("template change: exhausted pool refuses with 409 before any node call or row write", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 25000, start: "server.jar" }, ]; captured.freePortQueue = null; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 409, "exhausted pool must refuse with 409"); assert.match(String(res.body.error), /25000/); assert.match(String(res.body.error), /allocation/); assert.strictEqual(captured.reinstallCalls.length, 0, "no reinstall may be attempted"); assert.strictEqual(captured.savedLists.length, 0, "no row write may happen"); assert.strictEqual(captured.releasedClaims.length, 1, "the reinstall claim must be released on the 409 path"); }); test("template change: unclaimed template default cannot bypass an exhausted host-port pool", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: null }, { name: "other", nodeId: "node1", template: "nodejs", port: 8080 }, ]; sandbox.nodeRow = { ...sandbox.nodeRow, ports: { mode: "range", start: 8080, count: 1 } }; captured.freePortQueue = null; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409, "pool membership is not a port claim when another server already owns it"); assert.equal(captured.reinstallCalls.length, 0, "port conflict must refuse before wiping files"); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: occupied template default uses a verified free allocation", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: null }, { name: "other", nodeId: "node1", template: "nodejs", port: 8080 }, ]; sandbox.nodeRow = { ...sandbox.nodeRow, ports: { mode: "range", start: 8080, count: 2 } }; captured.freePortQueue = 8081; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 200); assert.equal(captured.reinstallCalls[0].payload.hostPort, 8081); assert.equal(captured.savedLists[0][0].port, 8081); assert.equal(captured.savedLists[0][1].port, 8080, "another server's allocation must remain untouched"); }); test("template change: failed default-port ownership check refuses before wiping and releases claim", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: null }]; sandbox.nodeRow = { ...sandbox.nodeRow, ports: { mode: "range", start: 8080, count: 2 } }; sandbox.checkDestinationNodePort = async () => { throw new Error("ownership lookup unavailable"); }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 500); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); assert.equal(captured.releasedClaims.length, 1); }); test("template change: a stalled servers-index lookup refuses with 500 before any claim or node call", async () => { const { sandbox, captured } = loadHandler(); // Mirrors the DB-stall scenario: loadServersIndex never settles. The route // must bound the read with withTimeout and stop with 500 instead of hanging // the request or acting on uncertain state. sandbox.loadServersIndex = () => new Promise(() => { }); const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 500, "a stalled servers-index lookup must refuse with 500"); assert.match(String(res.body.error), /servers index unavailable/); assert.strictEqual(captured.reinstallCalls.length, 0, "no reinstall may be attempted"); assert.strictEqual(captured.savedLists.length, 0, "no row write may happen"); assert.strictEqual(captured.releasedClaims.length, 0, "no claim may be taken before the index resolves"); }); test("template change: missing stored port falls back to the template default only via the pool-checked path", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: null, start: "server.jar" }, ]; // 8080 (nodejs default) is not inside the 30001-30010 pool → re-bind. captured.freePortQueue = 30007; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); assert.strictEqual(captured.reinstallCalls[0].payload.hostPort, 30007); assert.strictEqual(res.body.server.port, 30007); }); test("template change: template default inside the pool is sent and recorded verbatim", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: null, start: "server.jar" }, ]; sandbox.nodeRow = { ...sandbox.nodeRow, ports: { mode: "range", start: 8080, count: 5 }, // 8080-8084 }; captured.freePortQueue = 30002; // must never be consulted const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); assert.strictEqual(captured.reinstallCalls[0].payload.hostPort, 8080); assert.strictEqual(res.body.server.port, 8080); }); test("template change: malformed stored port is re-bound instead of being sent raw to the node", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: "0", start: "server.jar" }, ]; captured.freePortQueue = 30003; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); const sent = captured.reinstallCalls[0].payload.hostPort; assert.strictEqual(typeof sent, "number", "payload hostPort must be a number the daemon can unmarshal"); assert.strictEqual(sent, 30003); assert.strictEqual(res.body.server.port, 30003); }); test("template change: numeric string stored port is normalized and recorded verbatim", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: "30001", start: "server.jar" }, ]; captured.freePortQueue = 30002; // must never be consulted const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); const sent = captured.reinstallCalls[0].payload.hostPort; assert.strictEqual(typeof sent, "number", "payload hostPort must be a number the daemon can unmarshal"); assert.strictEqual(sent, 30001); assert.strictEqual(res.body.server.port, 30001); }); test("template change: out-of-range stored port is re-bound instead of being sent raw to the node", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 70000, start: "server.jar" }, ]; captured.freePortQueue = 30004; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); const sent = captured.reinstallCalls[0].payload.hostPort; assert.strictEqual(typeof sent, "number"); assert.strictEqual(sent, 30004); assert.strictEqual(res.body.server.port, 30004); }); test("template change: failed reinstall leaves the row untouched", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 30001, start: "server.jar" }, ]; captured.reinstallFailure = 500; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 502); assert.strictEqual(captured.savedLists.length, 0, "no row write may happen after a failed reinstall"); assert.strictEqual(captured.releasedClaims.length, 1, "the reinstall claim must be released on the failure path"); }); test("template change: confirmed rebuild with a failed start commits template and port but returns failure", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 25000, start: "server.jar" }]; captured.freePortQueue = 30005; captured.reinstallResponse = { status: 500, json: { ok: false, code: "reinstall_start_failed", reinstalled: true, error: "server files reinstalled but container failed to start", } }; const activities = []; sandbox.recordActivity = (...args) => { activities.push(args); }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 502); assert.equal(response.body.ok, false); assert.equal(response.body.reinstalled, true); assert.equal(captured.savedLists.length, 1); assert.equal(captured.savedLists[0][0].template, "nodejs"); assert.equal(captured.savedLists[0][0].port, 30005); assert.deepEqual(activities.map((activity) => activity.slice(0, 2)), [ ["srv1", "server_template_change_failed"], ["_system", "server_template_change_failed"], ]); assert.deepEqual(activities[0][2], { templateId: "nodejs", filesReplaced: true, code: "reinstall-start-failed" }); assert.equal(captured.releasedClaims.length, 1); }); test("template change: installer failure retains rebuilt template and port without success or retry", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 25000, start: "server.jar" }]; captured.freePortQueue = 30005; captured.reinstallResponse = { status: 500, json: { ok: false, code: "reinstall_install_failed", reinstalled: true } }; const activities = []; sandbox.recordActivity = (_name, action) => { activities.push(action); }; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 502); assert.equal(response.body.ok, false); assert.equal(response.body.code, "reinstall-install-failed"); assert.equal(response.body.reinstalled, true); assert.equal(captured.savedLists.length, 1); assert.equal(captured.savedLists[0][0].template, "nodejs"); assert.equal(captured.savedLists[0][0].port, 30005); assert.equal(captured.reinstallCalls.length, 1); assert.deepEqual(activities, ["server_template_change_failed", "server_template_change_failed"]); assert.equal(captured.releasedClaims.length, 1); }); test("template change: local entry keeps following template.defaultPort (no reinstall)", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "local", template: "minecraft", port: 25565, start: "server.jar" }, ]; captured.freePortQueue = 30002; // must never be consulted const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 200); assert.strictEqual(captured.reinstallCalls.length, 0, "local entries must not trigger a node reinstall"); assert.strictEqual(res.body.server.port, 8080, "local row port follows the new template's default"); assert.strictEqual(captured.savedLists.at(-1)[0].port, 8080); }); test("template change: a conflicting template operation refuses before dispatch", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.acquireReinstallTemplateLock = () => null; const response = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), response); assert.equal(response.statusCode, 409); assert.equal(captured.reinstallCalls.length, 0); assert.equal(captured.savedLists.length, 0); }); test("template deletion cannot race a pending rebuild and sees the committed template afterward", async (t) => { const { sandbox, captured } = loadHandler(); const directory = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-template-reinstall-")); t.after(() => fs.rmSync(directory, { recursive: true, force: true })); sandbox.TEMPLATES_FILE = path.join(directory, "templates.json"); sandbox.acquireReinstallTemplateLock = require("../utils/server-reinstall").acquireReinstallTemplateLock; sandbox.snapshotList = [{ name: "srv1", nodeId: "node1", template: "minecraft", port: 30001 }]; sandbox.loadTemplatesFile = ({ fresh }) => { assert.equal(fresh, true); return [NODEJS_TEMPLATE]; }; sandbox.findTemplateIndexForMutation = (list, id) => list.findIndex((template) => template.id === id); sandbox.saveTemplatesFile = () => assert.fail("an in-use template must not be deleted"); const saveRow = sandbox.saveReinstallRow; sandbox.saveReinstallRow = async (list) => { if (!await saveRow(list)) return false; sandbox.snapshotList = list; return true; }; sandbox.app.delete = (...args) => { captured.deleteHandler = args.at(-1); }; vm.runInNewContext(extractBlock(indexSource, 'app.delete("/api/settings/templates/:id"'), sandbox); let markDispatched; let finishRebuild; const dispatched = new Promise((resolve) => { markDispatched = resolve; }); const rebuildPending = new Promise((resolve) => { finishRebuild = resolve; }); const callNode = sandbox.httpRequestJsonPruningUnknownFields; sandbox.httpRequestJsonPruningUnknownFields = async (...args) => { const response = await callNode(...args); markDispatched(); await rebuildPending; return response; }; const rebuildResponse = makeRes(); const rebuild = captured.handler(makeReq({ templateId: "nodejs" }), rebuildResponse); const deleteRequest = { ...makeReq(), params: { id: "nodejs" } }; try { await Promise.race([dispatched, rebuild]); assert.equal(captured.reinstallCalls.length, 1); const during = makeRes(); await captured.deleteHandler(deleteRequest, during); assert.equal(during.statusCode, 409); assert.match(during.body.error, /template operation in progress/); } finally { finishRebuild(); await rebuild; } assert.equal(rebuildResponse.statusCode, 200); const after = makeRes(); await captured.deleteHandler(deleteRequest, after); assert.equal(after.statusCode, 400); assert.equal(after.body.error, "template in use"); }); test("template change: template deleted mid-reinstall refuses the commit with 409", async () => { const { sandbox, captured } = loadHandler(); sandbox.snapshotList = [ { name: "srv1", nodeId: "node1", template: "minecraft", port: 30001, start: "server.jar" }, ]; // The up-front lookup still resolves the template, but it is deleted while // the node reinstall is in flight, so the commit-time re-check (the // insertServerIndexEntryGuarded mirror) must refuse the row write instead of // committing a reference to a template that no longer exists. let templateDeleted = false; sandbox.findTemplateById = (id) => (templateDeleted ? null : { ...NODEJS_TEMPLATE, id }); const innerReinstall = sandbox.httpRequestJsonPruningUnknownFields; sandbox.httpRequestJsonPruningUnknownFields = async (...args) => { const out = await innerReinstall(...args); templateDeleted = true; // the delete lands mid-reinstall return out; }; const res = makeRes(); await captured.handler(makeReq({ templateId: "nodejs" }), res); assert.strictEqual(res.statusCode, 409, "a template deleted mid-reinstall must refuse the commit with 409"); assert.match(String(res.body.error), /deleted while the reinstall was running/); assert.strictEqual(captured.reinstallCalls.length, 1, "the reinstall itself already completed on the node"); assert.strictEqual(captured.savedLists.length, 0, "the row must not be rewritten to a deleted template"); assert.strictEqual(captured.releasedClaims.length, 1, "the reinstall claim must be released on the 409 path"); });