"use strict"; // Tests for the F4 remediation: deleteServerByName used to iterate legacy-name // candidates (bot / legacyId / legacy_id / name / id / requestedName) and // delete whatever the node has under each name until one confirmed. A stale // alias that now names a DIFFERENT server on that node (recreated/imported // under a colliding name) could get that server's container and files deleted // — delete-by-unverified-alias. // // The remediation makes every non-technical-name candidate a "legacy alias" // that must pass two gates before any destructive call: // 1. existence — the node must positively confirm a server under the alias // (unknown presence refuses too), and // 2. ownership — no other panel entry may claim the alias // (deps.findServerAliasConflict; missing or failing dep refuses). // The primary technical name keeps its original behaviour (404 = confirmed // gone). index.js additionally re-runs the ownership check in the durable // delete worker when the job targets a name that is no longer the entry's // current technical name. // // utils/server-delete.js is policy-only (deps injected), so behaviour is // tested directly with fakes; the index.js wiring is locked with source-order // assertions because index.js boots servers on require and cannot be loaded // in-process (same technique as transfer-recovery / reinstall-route-protection). const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const { deleteNameCandidates, deleteServerByName, verifyLegacyDeleteCandidate, waitForRemoteDeleteConfirmation } = require("../utils/server-delete"); const { getTechnicalServerName } = require("../utils/server-name"); test("deleting a missing server never cleans up by its reusable name", async () => { const noMutation = () => assert.fail("a missing row grants no ownership of server state"); const result = await deleteServerByName({ findServer: async () => null, markServerDeletingStatus: noMutation, deleteServerSchedules: noMutation, removeServerIndexEntry: noMutation, httpRequestJson: noMutation, }, "alpha"); assert.deepEqual(result, { ok: false, statusCode: 404, error: "server not found" }); }); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); // --------------------------------------------------------------------------- // Fakes // --------------------------------------------------------------------------- const ENTRY = { rowId: 11, id: "legacy-9", // mapServerRow prefers legacy_id for the public id name: "alpha", bot: "alpha-node-1", legacyId: "legacy-9", nodeId: "node-1", template: "minecraft", status: "running", }; // Routes node API calls by (method, path). Everything unknown 404s like the // node does for missing servers. function makeNodeHttp(script = {}) { const calls = []; const respond = (handler, name, fallback) => handler ? handler(name) : fallback; return { calls, httpRequestJson: async (url, method) => { const parsed = new URL(url); const match = parsed.pathname.match(/^\/v1\/servers\/([^/]+)(?:\/([^/]+))?$/); calls.push({ method, path: parsed.pathname }); if (!match) return { status: 404, json: { error: "not found" } }; const name = decodeURIComponent(match[1]); const action = match[2] || ""; if (action === "kill") { return respond(script.kill, name, { status: 200, json: { ok: true } }); } if (action === "delete-status") { return respond(script.deleteStatus, name, { status: 200, json: { deleteStatus: true, deleted: true } }); } if (method === "GET") { return respond(script.get, name, { status: 404, json: { error: "not found" } }); } if (method === "DELETE") { return respond(script.del, name, { status: 404, json: { error: "not found" } }); } return { status: 404, json: { error: "not found" } }; }, }; } function makeDeps({ nodeHttp, findServerAliasConflict, findServer } = {}) { const calls = { schedules: [], indexRemovals: [], access: [], marking: [], enqueued: [], conflicts: [], }; const deps = { findServer: findServer || (async (needle) => { const n = String(needle || "").toLowerCase(); if (n === "alpha" || n === "legacy-9" || n === "alpha-node-1") return { ...ENTRY }; return null; }), withReinstallSuspensionLock: async (_name, _busy, operation) => operation(), isRemoteEntry: () => true, findNodeByIdOrName: async () => ({ name: "node-1", address: "node.test", api_port: 8080 }), dbQuery: async () => [], buildNodeBaseUrl: () => "http://node.test", nodeUnderCloudflare: () => false, nodeAuthHeadersFor: () => ({}), httpRequestJson: nodeHttp.httpRequestJson, deleteServerSchedules: async (n) => calls.schedules.push(n), removeServerIndexEntry: async (n) => calls.indexRemovals.push(n), removeAccessForServerName: async (n) => calls.access.push(n), markServerDeletingStatus: async (n) => calls.marking.push(n), enqueueServerDeleteJob: async (job) => calls.enqueued.push(job), kickServerDeleteWorker: () => { }, }; if (findServerAliasConflict !== undefined) { deps.findServerAliasConflict = async (alias, entry) => { calls.conflicts.push({ alias, entry }); if (typeof findServerAliasConflict === "function") return findServerAliasConflict(alias, entry); return findServerAliasConflict; // scripted value (null or conflict object) }; } return { deps, calls }; } const serverPaths = (calls) => calls.map((c) => c.path); const deletePaths = (calls) => calls.filter((c) => c.method === "DELETE").map((c) => c.path); // --------------------------------------------------------------------------- // deleteNameCandidates classification // --------------------------------------------------------------------------- test("deleteNameCandidates marks every value except the technical name as requiring verification", () => { const candidates = deleteNameCandidates(ENTRY, "legacy-9", "alpha-node-1"); assert.deepEqual(candidates, [ { name: "alpha-node-1", requiresVerification: false }, { name: "legacy-9", requiresVerification: true }, // legacyId + id + requestedName dedup { name: "alpha", requiresVerification: true }, // entry.name ]); }); test("deleteNameCandidates keeps the requested name trusted only when it is the technical name", () => { const candidates = deleteNameCandidates(ENTRY, "alpha-node-1", "alpha-node-1"); assert.deepEqual(candidates, [ { name: "alpha-node-1", requiresVerification: false }, { name: "legacy-9", requiresVerification: true }, { name: "alpha", requiresVerification: true }, ]); }); test("deleteNameCandidates drops empty values and keeps first-seen order", () => { const entry = { name: "solo", bot: null, legacyId: "", id: "solo" }; const candidates = deleteNameCandidates(entry, null, "solo"); assert.deepEqual(candidates, [{ name: "solo", requiresVerification: false }]); }); // --------------------------------------------------------------------------- // Primary technical-name behaviour (unchanged by the fix) // --------------------------------------------------------------------------- test("delete refuses a same-node normalized storage claimant before claiming the row", async () => { const nodeHttp = makeNodeHttp(); const { deps, calls } = makeDeps({ nodeHttp }); deps.dbQuery = async () => [ENTRY, { name: "other", legacy_id: "_alpha-node-1" }]; const result = await deleteServerByName(deps, "alpha"); assert.equal(result.statusCode, 409); assert.match(result.error, /ambiguous storage ownership/); assert.deepEqual(calls.marking, []); assert.deepEqual(nodeHttp.calls, []); }); test("an overlapping delete retry cannot dispatch against the same canonical server", async () => { let releaseKill; let observeKill; const killStarted = new Promise(resolve => { observeKill = resolve; }); const nodeHttp = makeNodeHttp({ kill: () => { observeKill(); return new Promise(resolve => { releaseKill = resolve; }); } }); const { deps, calls } = makeDeps({ nodeHttp }); let locked = false; deps.withReinstallSuspensionLock = async (name, busy, operation) => { assert.equal(name, "alpha"); if (locked) return busy; locked = true; try { return await operation(); } finally { locked = false; } }; const first = deleteServerByName(deps, "alpha"); await Promise.race([killStarted, first]); try { assert.equal((await deleteServerByName(deps, "legacy-9")).statusCode, 409); assert.deepEqual(calls.marking, ["alpha"]); } finally { releaseKill?.({ status: 200, json: { ok: true } }); } assert.equal((await first).deleted, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); }); test("a delete claim timeout responds without unlocking an unsettled claim", { timeout: 8000 }, async () => { const nodeHttp = makeNodeHttp(); const { deps } = makeDeps({ nodeHttp }); let settleClaim; let finishOperation; const settled = new Promise(resolve => { finishOperation = resolve; }); deps.markServerDeletingStatus = () => new Promise(resolve => { settleClaim = resolve; }); let locked = false; deps.withReinstallSuspensionLock = async (_name, busy, operation) => { if (locked) return busy; locked = true; try { return await operation(); } finally { locked = false; finishOperation(); } }; try { assert.equal((await deleteServerByName(deps, "alpha")).statusCode, 503); assert.equal((await deleteServerByName(deps, "legacy-9")).statusCode, 409); } finally { settleClaim?.({ ok: true }); } await settled; assert.deepEqual(nodeHttp.calls, []); }); test("primary delete answered 404 still requires delete-status confirmation", async () => { const nodeHttp = makeNodeHttp({ del: () => ({ status: 404, json: { error: "not found" } }), }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: () => { throw new Error("ownership check must not run for the primary name"); }, }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.equal(result.deleted, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); assert.ok(serverPaths(nodeHttp.calls).includes("/v1/servers/alpha-node-1/delete-status")); assert.equal(calls.enqueued.length, 0); assert.equal(calls.conflicts.length, 0); }); test("delete keeps the index reserved when the server directory is gone but backups remain", async () => { const nodeHttp = makeNodeHttp({ deleteStatus: () => ({ status: 200, json: { deleteStatus: true, deleted: false, serverDirExists: false, backupsDirExists: true } }), }); const { deps, calls } = makeDeps({ nodeHttp }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.deleting, true); assert.equal(calls.enqueued.length, 1); assert.equal(calls.enqueued[0].serverRowId, ENTRY.rowId); assert.deepEqual(calls.indexRemovals, []); assert.equal(nodeHttp.calls.some(({ method, path }) => method === "GET" && !path.endsWith("/delete-status")), false); }); test("delete confirmation rejects an inconclusive Docker inspection", async () => { const nodeHttp = makeNodeHttp({ deleteStatus: () => ({ status: 200, json: { deleteStatus: true, deleted: false, containerCheckOk: false, containerExists: false, serverDirExists: false, metaExists: false, backupsDirExists: false } }), }); assert.equal(await waitForRemoteDeleteConfirmation(nodeHttp, "http://node.test", {}, "alpha", { timeoutMs: 30, intervalMs: 5 }), false); }); test("primary delete accepted and confirmed via delete-status; no fallback attempted", async () => { const nodeHttp = makeNodeHttp({ del: () => ({ status: 200, json: { ok: true } }), }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: () => { throw new Error("ownership check must not run for the primary name"); }, }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.equal(result.deleted, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); assert.deepEqual(calls.indexRemovals, ["alpha"]); assert.deepEqual(calls.access, [], "only the alias-aware index cleanup may remove access rows"); assert.equal(calls.enqueued.length, 0); }); // --------------------------------------------------------------------------- // F4 collision scenario: stale legacy alias claimed by another server // --------------------------------------------------------------------------- test("stale legacy alias claimed by another entry is never deleted; durable job retries the technical name", async () => { // The user deletes by the legacy id; findServer resolves it to the entry // whose technical name is alpha-node-1. The node rejects that delete // (500), which is what sends the old code into the alias candidates. const nodeHttp = makeNodeHttp({ del: (name) => name === "alpha-node-1" ? { status: 500, json: { error: "boom" } } : { status: 200, json: { ok: true } }, get: (name) => name === "legacy-9" ? { status: 200, json: { ok: true, name, status: "running" } } : { status: 404, json: { error: "not found" } }, }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: (alias) => alias === "legacy-9" ? { name: "legacy-9", bot: "other-node-2", legacyId: null } : null, }); const result = await deleteServerByName(deps, "legacy-9"); assert.equal(result.ok, true); assert.equal(result.queued, true); assert.equal(result.accepted, false); // Only the primary technical name may be destructively called. assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); // The ownership check ran for the colliding alias and named the claimant. assert.deepEqual(calls.conflicts.map((c) => c.alias), ["legacy-9"]); // The worker owns cleanup after remote confirmation. Until then the row // reserves the name and ports, and retries never target the refused alias. assert.deepEqual(calls.schedules, []); assert.deepEqual(calls.indexRemovals, []); assert.equal(calls.enqueued.length, 1); assert.equal(calls.enqueued[0].name, "alpha"); assert.equal(calls.enqueued[0].technicalName, "alpha-node-1"); }); test("a failed durable delete enqueue leaves the index and its reservations intact", async () => { const nodeHttp = makeNodeHttp({ del: () => ({ status: 503, json: { error: "node unavailable" } }) }); const { deps, calls } = makeDeps({ nodeHttp }); deps.enqueueServerDeleteJob = async () => { throw new Error("queue unavailable"); }; await assert.rejects(deleteServerByName(deps, "alpha"), /queue unavailable/); assert.deepEqual(calls.marking, ["alpha"]); assert.deepEqual(calls.indexRemovals, []); assert.deepEqual(calls.schedules, []); assert.deepEqual(calls.access, []); }); test("legacy alias with unknown node presence is skipped without ownership check or delete", async () => { const nodeHttp = makeNodeHttp({ del: () => ({ status: 500, json: { error: "boom" } }), get: () => ({ status: 0, json: null }), // node unreachable for GETs }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: () => { throw new Error("ownership check must not run before existence is confirmed"); }, }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.equal(result.queued, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); assert.equal(calls.enqueued[0].technicalName, "alpha-node-1"); }); test("missing ownership-check dep refuses legacy aliases (fail-safe)", async () => { const nodeHttp = makeNodeHttp({ del: (name) => name === "alpha-node-1" ? { status: 500, json: { error: "boom" } } : { status: 200, json: { ok: true } }, get: () => ({ status: 200, json: { ok: true, name: "legacy-9", status: "running" } }), }); const { deps, calls } = makeDeps({ nodeHttp }); // no findServerAliasConflict dep const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); assert.equal(calls.enqueued[0].technicalName, "alpha-node-1"); }); test("failing ownership check refuses legacy aliases (fail-safe)", async () => { const nodeHttp = makeNodeHttp({ del: (name) => name === "alpha-node-1" ? { status: 500, json: { error: "boom" } } : { status: 200, json: { ok: true } }, get: () => ({ status: 200, json: { ok: true, name: "legacy-9", status: "running" } }), }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: async () => { throw new Error("db down"); }, }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.deepEqual(deletePaths(nodeHttp.calls), ["/v1/servers/alpha-node-1"]); assert.equal(calls.enqueued[0].technicalName, "alpha-node-1"); }); // --------------------------------------------------------------------------- // Intended legacy cleanup still works — but only with positive verification // --------------------------------------------------------------------------- test("unclaimed legacy alias that exists is deleted after verification", async () => { const nodeHttp = makeNodeHttp({ del: (name) => name === "alpha-node-1" ? { status: 500, json: { error: "boom" } } : { status: 200, json: { ok: true } }, get: (name) => name === "legacy-9" ? { status: 200, json: { ok: true, name, status: "stopped" } } : { status: 404, json: { error: "not found" } }, }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: () => null }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.equal(result.deleted, true); assert.deepEqual(deletePaths(nodeHttp.calls), [ "/v1/servers/alpha-node-1", "/v1/servers/legacy-9", ]); // Verification (GET) happens before the destructive call for the alias. const callsPaths = serverPaths(nodeHttp.calls); const getIndex = callsPaths.indexOf("/v1/servers/legacy-9"); const deleteIndex = nodeHttp.calls.findIndex((c) => c.method === "DELETE" && c.path === "/v1/servers/legacy-9"); assert.ok(getIndex >= 0 && getIndex < deleteIndex, "existence GET must precede alias DELETE"); assert.equal(calls.enqueued.length, 0); }); test("verified legacy alias that then fails to delete becomes the durable retry target", async () => { const nodeHttp = makeNodeHttp({ del: () => ({ status: 500, json: { error: "boom" } }), get: (name) => name === "legacy-9" ? { status: 200, json: { ok: true, name, status: "stopped" } } : { status: 404, json: { error: "not found" } }, }); const { deps, calls } = makeDeps({ nodeHttp, findServerAliasConflict: () => null }); const result = await deleteServerByName(deps, "alpha"); assert.equal(result.ok, true); assert.equal(result.queued, true); // Both names were genuinely attempted (primary first, verified alias after). assert.deepEqual(deletePaths(nodeHttp.calls), [ "/v1/servers/alpha-node-1", "/v1/servers/legacy-9", ]); // The job retries the last actually-attempted name — a verified alias — // and the worker re-checks ownership before that retry deletes anything. assert.equal(calls.enqueued[0].technicalName, "legacy-9"); }); // --------------------------------------------------------------------------- // verifyLegacyDeleteCandidate contract // --------------------------------------------------------------------------- test("verifyLegacyDeleteCandidate distinguishes absent, unknown and owned aliases", async () => { const baseDeps = (get) => makeDeps({ nodeHttp: makeNodeHttp({ get }) }).deps; const absent = await verifyLegacyDeleteCandidate(baseDeps( () => ({ status: 404, json: { error: "not found" } }), ), { candidate: "legacy-9", entry: ENTRY, requesterName: "alpha", baseUrl: "http://node.test", headers: {}, }); assert.deepEqual(absent, { allowed: false, absent: true, reason: "not present on node" }); const unknown = await verifyLegacyDeleteCandidate(baseDeps( () => ({ status: 500, json: { error: "boom" } }), ), { candidate: "legacy-9", entry: ENTRY, requesterName: "alpha", baseUrl: "http://node.test", headers: {}, }); assert.equal(unknown.allowed, false); assert.equal(unknown.absent, false); const conflicted = await verifyLegacyDeleteCandidate(baseDeps( () => ({ status: 200, json: { ok: true, name: "legacy-9", status: "running" } }), ), { candidate: "legacy-9", entry: ENTRY, requesterName: "alpha", baseUrl: "http://node.test", headers: {}, }); // baseDeps builds deps without findServerAliasConflict, so a present // alias cannot be proven unowned and must be refused (fail-safe). assert.equal(conflicted.allowed, false); assert.equal(conflicted.absent, false); const allowed = await verifyLegacyDeleteCandidate((() => { const { deps } = makeDeps({ nodeHttp: makeNodeHttp({ get: () => ({ status: 200, json: { ok: true, name: "legacy-9", status: "running" } }) }), findServerAliasConflict: () => null, }); return deps; })(), { candidate: "legacy-9", entry: ENTRY, requesterName: "alpha", baseUrl: "http://node.test", headers: {}, }); assert.deepEqual(allowed, { allowed: true }); }); // --------------------------------------------------------------------------- // index.js wiring (source assertions — index.js cannot be required in-process) // --------------------------------------------------------------------------- test("index.js wires the alias guard through a shared deps factory at every delete call site", () => { assert.ok(indexSource.includes("async function findServerAliasConflict("), "findServerAliasConflict must be defined"); assert.ok(indexSource.includes("function serverDeleteDeps()"), "shared delete deps factory must exist"); const factoryStart = indexSource.indexOf("function serverDeleteDeps()"); const factoryBody = indexSource.slice(factoryStart, factoryStart + 700); assert.ok(factoryBody.includes("findServerAliasConflict,"), "factory must provide the ownership guard"); // No call site builds the deps object inline anymore. assert.equal(indexSource.split("deleteServerByName({").length - 1, 0, "no inline delete deps objects"); assert.equal(indexSource.split("deleteServerByName(serverDeleteDeps(), name)").length - 1, 1, "assistant wiring uses the factory"); assert.equal(indexSource.split("deleteServerByName(serverDeleteDeps(), serverName, serverEntry)").length - 1, 1, "admin route passes the selected row to the shared service"); }); test("index.js delete worker re-checks alias ownership before the destructive call", () => { const start = indexSource.indexOf("async function processServerDeleteJob"); assert.ok(start >= 0, "worker must exist"); const body = indexSource.slice(start, start + 6000); const guardIndex = body.indexOf("findServerAliasConflict(technicalName, deleteJobEntry)"); const refuseIndex = body.indexOf("Refusing to delete"); const killIndex = body.indexOf("await requestRemoteDeleteAndConfirm("); assert.ok(guardIndex >= 0, "worker must re-run the ownership check for non-technical names"); assert.ok(refuseIndex >= 0, "worker must refuse claimed aliases"); assert.ok(killIndex >= 0, "worker must still perform the remote delete"); assert.ok(guardIndex < killIndex, "ownership check must precede the kill call"); assert.ok(refuseIndex < killIndex, "refusal path must precede the kill call"); assert.ok(body.includes("DELETE FROM server_delete_jobs WHERE id = ?"), "refused jobs must be abandoned, not retried forever"); assert.ok(body.includes("alias ownership check for"), "check failures must surface as retryable job errors"); assert.match(indexSource, /withReinstallSuspensionLock\(job\.server_name, null, async \(\) => \{[\s\S]*?server_row_id <=> \?[\s\S]*?await processServerDeleteJob\(job\)/); }); test("the queued delete only dispatches for its original deleting row and waits for confirmation", async () => { const start = indexSource.indexOf("async function processServerDeleteJob("); const end = indexSource.indexOf("async function runServerDeleteJobsOnce(", start); const queries = []; const context = vm.createContext({ findNodeByIdOrName: async () => ({ id: "node-1", address: "fixture.invalid" }), buildNodeBaseUrl: () => "http://fixture.invalid", nodeUnderCloudflare: () => false, nodeAuthHeadersFor: () => ({}), getTechnicalServerName, requestRemoteDeleteAndConfirm: () => assert.fail("a queued job without its original deleting row must not dial"), db: { query: async (sql, params) => queries.push([sql, ...params]) }, console: { warn() {} }, }); vm.runInContext(indexSource.slice(start, end), context, { timeout: 1000 }); const deleting = { ...ENTRY, status: "deleting" }; for (const [entry, rowId] of [[null, ENTRY.rowId], [deleting, ENTRY.rowId + 1], [deleting, null]]) { context.findServer = async () => entry; await context.processServerDeleteJob({ id: 7, server_name: "alpha", server_row_id: rowId, technical_name: "alpha-node-1", node_id: "node-1" }); assert.deepEqual(queries.splice(0), [["DELETE FROM server_delete_jobs WHERE id = ?", 7]]); } const effects = []; const job = { id: 7, server_name: "alpha", server_row_id: ENTRY.rowId, technical_name: ENTRY.bot, node_id: ENTRY.nodeId }; context.findServer = async () => deleting; context.verifyDeleteStorageOwner = async () => true; context.httpRequestJson = () => assert.fail("the worker must use the shared delete helper"); context.deleteServerSchedules = async name => effects.push(["schedules", name]); context.removeServerIndexEntry = async (name, rowId) => effects.push(["remove", name, rowId]); context.console.log = () => {}; context.requestRemoteDeleteAndConfirm = async (_deps, request) => { effects.push(["dispatch", request.technicalName]); return { confirmed: false }; }; await assert.rejects(context.processServerDeleteJob(job), /node did not confirm server deletion/); assert.deepEqual(effects.splice(0), [["dispatch", ENTRY.bot]]); assert.deepEqual(queries, []); context.requestRemoteDeleteAndConfirm = async (_deps, request) => { effects.push(["dispatch", request.technicalName]); return { confirmed: true }; }; await context.processServerDeleteJob(job); assert.deepEqual(effects, [["dispatch", ENTRY.bot], ["schedules", ENTRY.name], ["remove", ENTRY.name, ENTRY.rowId]]); assert.deepEqual(queries, [["DELETE FROM server_delete_jobs WHERE id = ?", 7]]); }); // --------------------------------------------------------------------------- // findServerAliasConflict & mapServerRow behavioral tests (extracted via vm) // --------------------------------------------------------------------------- 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}`); while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) { i += 1; if (source[i - 1] === ";") break; } return source.slice(start, i); } function createVmConflictChecker(mockDb) { const sandbox = { db: mockDb, console, }; vm.createContext(sandbox); const code = extractBlock(indexSource, "async function findServerAliasConflict("); vm.runInContext(`${code}\nthis.findServerAliasConflict = findServerAliasConflict;`, sandbox); return sandbox.findServerAliasConflict; } test("findServerAliasConflict: entry with legacy_id in DB does not self-conflict", async () => { const mockDb = { async query() { return [{ id: 1, name: "alpha", legacy_id: "legacy-9", bot: "alpha-node-1" }]; }, }; const fn = createVmConflictChecker(mockDb); const entry = { id: "legacy-9", name: "alpha", bot: "alpha-node-1", legacyId: "legacy-9", legacy_id: "legacy-9" }; const conflict = await fn("legacy-9", entry); assert.equal(conflict, null, "entry must not conflict with its own database row"); }); test("findServerAliasConflict: entry where legacyId is omitted still correctly ignores its own row by unique name", async () => { const mockDb = { async query() { return [{ id: 1, name: "alpha", legacy_id: "legacy-9", bot: "alpha-node-1" }]; }, }; const fn = createVmConflictChecker(mockDb); const entryWithoutLegacyProp = { id: "legacy-9", name: "alpha", bot: "alpha-node-1" }; const conflict = await fn("legacy-9", entryWithoutLegacyProp); assert.equal(conflict, null, "entry must match its own row by name and not self-conflict"); }); test("findServerAliasConflict: returns claimant when another server claims the alias", async () => { const mockDb = { async query() { return [ { id: 1, name: "alpha", legacy_id: "legacy-9", bot: "alpha-node-1" }, { id: 2, name: "beta", legacy_id: null, bot: "legacy-9" }, ]; }, }; const fn = createVmConflictChecker(mockDb); const entry = { id: "legacy-9", name: "alpha", bot: "alpha-node-1" }; const conflict = await fn("legacy-9", entry); assert.ok(conflict, "must find conflict when another server claims the alias"); assert.equal(conflict.name, "beta"); assert.equal(conflict.bot, "legacy-9"); }); test("findServerAliasConflict: returns claimant when entry is null", async () => { const mockDb = { async query() { return [{ id: 2, name: "beta", legacy_id: "legacy-9", bot: "beta-bot" }]; }, }; const fn = createVmConflictChecker(mockDb); const conflict = await fn("legacy-9", null); assert.ok(conflict, "must return conflict when entry is null and row exists"); assert.equal(conflict.name, "beta"); }); test("mapServerRow in index.js includes legacyId and legacy_id properties", () => { const parseDbJson = () => null; const sandbox = { parseDbJson }; vm.createContext(sandbox); const code = extractBlock(indexSource, "function mapServerRow("); vm.runInContext(`${code}\nthis.mapServerRow = mapServerRow;`, sandbox); const mapped = sandbox.mapServerRow({ id: 42, name: "test-srv", legacy_id: "leg-42", bot: "test-bot", }); assert.equal(mapped.name, "test-srv"); assert.equal(mapped.legacyId, "leg-42"); assert.equal(mapped.legacy_id, "leg-42"); assert.equal(mapped.id, "leg-42"); });