"use strict"; // adpanel:server-create-consolidation — ONE shared implementation of the // server-creation pipeline. The reference surface is the panel route // POST /api/servers/create (index.js, "panel" variant); the node proxy // (nodes.js, "proxy" variant) runs its shared steps — name guards, in-lock // duplicate check, storage-collision scan, guarded commit + compensation — // through this module, and the dashboard-assistant create_server tool runs // its name guards, ownership-guarded compensating delete and guarded commit // through the same outcome codes with its own "tool" renderer. // // Design constraints (see .campaign/spec-server-create.md): // - This module requires ONLY pure utils/* modules (no index.js, no nodes.js, // no routes/* — index.js requires this module, never the reverse). Every // boot-time capability (DB, node HTTP client, daemon clients, audit log, // index writers) arrives through the injected `deps` object, following the // dependency-injection pattern of utils/dashboard-assistant-tools.js. // - Outcomes are transport-neutral: { ok: false, code, data } on failure, // { ok: true, code: "success", data } on success. NO message text lives in // outcomes — every wire-visible string OF THE SHARED STEPS is rendered per // variant by renderServerCreateOutcome so each entry point keeps its // byte-identical contract (Path 1 "invalid name" vs Path 2 "invalid_name" // vs Path 3 prose; the two template-deleted sentences). The strings the // entry points own deliberately — the three 429 contention shapes, the // proxy's port/disk/daemon-failure bodies, the tool's prose envelopes — // are rendered by their adapters, NOT here. // - The caller owns authentication and the cross-process create lock: the // orchestrator refuses to run without a lock release function (fail-closed) // but never acquires the lock itself. The structural pin "step-up must run // before the create lock" stays in the panel adapter. // - deps.dbQuery is db.query under the ROWS-ONLY contract (it resolves to the // row array): nothing here may read insertId/affectedRows from it. const { sanitizeNodeStorageName, sanitizeDisplayNameToken, } = require("../utils/server-name"); const { isIP } = require("node:net"); const { withKeyedLock } = require("../utils/keyed-async-lock"); const { resolveMcFork, resolveMcVersion, SUPPORTED_MC_FORKS, } = require("../utils/minecraft-versions"); // adpanel:backup-cap-daemon-enforced — the panel's per-server backup cap, // resolved from the SAME env the scheduler/relay count checks read. The // creation payload below transmits it as resources.backupsMax so the // daemon's op-lock bound and the panel's count-then-create fast-fail agree. const { resolveBackupsMaxFromInput } = require("../utils/backup-cap"); const { extractNodeAddressHost } = require("../utils/node-ssrf-guard"); function resolveServerCreateBindAddress(node, port, { preserveLegacyRangeBind = false } = {}) { const allocations = node?.ports?.allocations; const allocation = Array.isArray(allocations) && allocations.find(entry => Number(entry?.port) === Number(port)); const primary = String(node?.address || node?.host_ip || node?.bind_ip || "").trim(); const address = String(allocation?.ip || "").trim() || primary; const parsedAddress = extractNodeAddressHost(address); const host = parsedAddress.host || address; if (Number(port) > 0 && node?.under_cloudflare) { const family = parsedAddress.ok ? isIP(host) : 0; const canonical = family === 6 ? new URL(`http://[${host}]`).hostname : host; if (!family || canonical === "0.0.0.0" || canonical === "[::]" || canonical === "[::ffff:0:0]") { return { error: { ok: false, code: "port_bind_address_required", data: { port } } }; } } // adpanel:node-port-bind - explicit Settings allocations must not widen to a wildcard bind. const useLegacyBind = preserveLegacyRangeBind && (node?.ports?.mode === "range" || !allocation) && host === (extractNodeAddressHost(primary).host || primary); return { address: useLegacyBind ? "" : host }; } async function checkServerCreatePort(deps, node, requirement, name) { const port = requirement.hostPort; if (port <= 0) return null; if (!deps.isPortInNodeAllocation(node, port)) { const alloc = node.ports || {}; let allocDesc = "none"; if (alloc.mode === "range") allocDesc = `range ${alloc.start}–${alloc.start + alloc.count - 1}`; else if (alloc.mode === "list" && Array.isArray(alloc.ports)) allocDesc = `list [${alloc.ports.slice(0, 10).join(", ")}${alloc.ports.length > 10 ? "…" : ""}]`; return { ok: false, code: "port_not_in_allocation", data: { port, allocDesc } }; } const conflict = await deps.findServerUsingNodePort(node, port, name); if (conflict) { return { ok: false, code: "port_assigned_to_server", data: { port, displayName: conflict.displayName || conflict.name || conflict.bot, server: conflict.name || conflict.bot || null, } }; } const livePort = await deps.checkRemoteNodePortAvailability(node, port, requirement.protocols); if (livePort.verified && livePort.available === false) { return { ok: false, code: "port_in_use_live", data: { port, owner: livePort.owner || null, reason: livePort.reason || null, } }; } return null; } // adpanel:node-storage-name — sanitizeServerToken keeps names the node's own // sanitizer (main.go sanitizeName, mirrored in sanitizeNodeStorageName) would // trim to nothing, and Go would then have no storable directory name at all. // Refuse before any provisioning work. // adpanel:node-storage-name — the node's storage namespace is the // sanitizeNodeStorageName form, while every baseDir validation on the panel // demands the sanitizeServerToken form. A name whose two forms differ // (leading/trailing "_" or ".") is stored under a different name on the node // than the panel looks for, so the whole Files tab 400s for that server // forever — refuse those names outright. // Transport-neutral version of the entry points' name guards (empty; the // reserved wildcard token; no node-storable form; storage form ≠ token // form): null means the name passed all four. The caller renders the // variant's exact 400 bodies. function serverNameGuardOutcome(name) { if (!name) { return { ok: false, code: "invalid_name_empty" }; } // adpanel:reserved-server-name — "all" is the user_access wildcard token: // userHasAccessToServer (index.js) grants EVERY server when a user_access // row equals "all" (case-insensitively, both sides lowercased), so a server // literally named "all" would turn any per-server grant of it into a // panel-wide grant. sanitizeServerToken accepts the name and there is no // rename route, so the shared name guard at this ONE creation choke point // (panel route, node proxy, assistant tool) is the only place to reserve // it. The comparison lowercases and trims defensively even though every // entry point hands the guard the already-sanitizeServerToken'd name — the // sanitizer trims but does NOT lowercase, so "ALL" would otherwise slip // through and still match the lowercased access row. if (String(name).trim().toLowerCase() === "all") { return { ok: false, code: "invalid_name_reserved" }; } if (!sanitizeNodeStorageName(name)) { return { ok: false, code: "invalid_name_no_storage_form" }; } if (sanitizeNodeStorageName(name) !== name) { return { ok: false, code: "invalid_name_storage_mismatch" }; } return null; } // M4: refuse a duplicate server name before anything else runs. servers.name // is UNIQUE and the index writer previously used ON DUPLICATE KEY UPDATE, so // creating "foo" on node B silently repointed the index row of "foo" on node // A — orphaning the original container (still running, still holding its // port). findServer matches name/legacy_id/bot, so technical-name collisions // are refused too. Detection is equivalent to the node proxy's former local // panelServerNameConflict (same three LOWER(alias) legs, case-insensitive); // the panel's extra row ranking only picks WHICH row is reported, never // whether one is. // Bounded like the reads inside the body on the panel: a slow DB must fail // the create (via the caller's catch) instead of holding the request open // before the check that guards the UNIQUE name. The 5000ms / label pair leaks // into the panel's 500 detail strings — keep it EXACT. The bound is caller // wiring, not the helper's contract: the node proxy has never bounded this // read (a slow DB rejects into its route wrapper), so a deps object without // withTimeout awaits the lookup directly instead of gaining a new bound. async function duplicateServerNameOutcome(deps, name) { const lookup = Promise.resolve().then(() => deps.findServer(name)); const existingServer = typeof deps.withTimeout === "function" ? await deps.withTimeout(lookup, 5000, "server-create-name-check-timeout") : await lookup; if (existingServer) { return { ok: false, code: "server_name_exists", data: { name, onNode: existingServer.nodeId ? ` (on node ${existingServer.nodeId})` : "", }, }; } return null; } // adpanel:proxy-create-race (review fix) — ownership-aware compensating // delete for the create pipeline's three failure paths after the daemon // create succeeded (node deleted mid-create, template deleted during the // guarded commit, index commit failure). On every one of them this request's // own index commit never landed (the guarded writer refuses before its // INSERT, and a thrown INSERT committed nothing), so a committed row claiming // the name can only belong to another writer — a rename, transfer or import // that interleaved with the slow daemon round-trips (non-create writers do // not take the per-name create lock). For that writer the daemon server named // may be its LIVE server (e.g. a rename that just re-pointed a server // on this node), and an unconditional by-name DELETE would destroy its // container and directory. Canonical home of the guard the panel route and // the node proxy share: re-read the committed index rows matching the // name/legacy_id/bot aliases and delete only when the name is unclaimed or // claimed on a DIFFERENT node (the daemon server here is then still this // request's orphan); withhold when a row claims the name on THIS node (node // id/uuid/name or the address, compared case-insensitively like the SQL // node_id = ?/ip = ? scans) and when a matching row carries no node_id/ip at // all (fail closed: it cannot be located elsewhere, so it may describe a live // server in this very directory). Withholding leaves at worst an unmanageable // orphan for the admin to review — never destroyed data. Never throws: // callers log withheld/error and must not mask the original failure. The two // error outcomes carry `phase` "read" | "delete" so mode-aware callers (the // assistant tool's log router) can pick their exact line; panel and proxy // ignore it. // deps: { // readClaimRows — async (name) => array of { name, node_id, ip }-shaped // rows matching the name/legacy_id/bot aliases; a throw is a read // failure. Caller-owned data source: the assistant tool feeds the guard // from its injected servers-index readers (it has no SQL access; its // deleting-row-inclusive reader preference lives there). // dbQuery — rows-only db.query; the fallback claim read (panel + proxy do // not pass readClaimRows), with the canonical SQL kept byte-identical to // the pre-consolidation query. // deleteServerOnNode — the compensating-delete leg. // } async function deleteOwnOrphanServerOnNodeForCreate(deps, node, name) { const needle = String(name || "").trim().toLowerCase(); if (!needle) return { deleted: false, error: new Error("empty server name") }; let rows; try { // adpanel:server-create-consolidation — caller-owned claim-row read: when // readClaimRows is wired it replaces the SQL read (the tool's reader-chain // source over the injected index readers); otherwise the canonical query // below stays byte-identical to the pre-consolidation panel/proxy read. rows = typeof deps.readClaimRows === "function" ? await deps.readClaimRows(name) : await deps.dbQuery( "SELECT name, node_id, ip FROM servers WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ?", [needle, needle, needle] ); } catch (err) { return { deleted: false, error: err, phase: "read" }; } const nodeIdentifiers = [ String(node?.id || "").trim().toLowerCase(), String(node?.uuid || node?.id || "").trim().toLowerCase(), String(node?.name || "").trim().toLowerCase(), ]; for (const row of rows || []) { const rowNodeId = String(row?.node_id || "").trim().toLowerCase(); const rowIp = String(row?.ip || "").trim().toLowerCase(); const rowClaimsThisNode = (!!rowNodeId && nodeIdentifiers.includes(rowNodeId)) || (!!rowIp && rowIp === String(node?.address || "").trim().toLowerCase()); if (rowClaimsThisNode || (!rowNodeId && !rowIp)) { return { deleted: false, withheld: true, row }; } } try { await deps.deleteServerOnNode(node, name); } catch (err) { return { deleted: false, error: err, phase: "delete" }; } return { deleted: true }; } // adpanel:node-storage-collision (MEDIUM #2c) — ONE home for the same-node // storage-collision scan shared by the panel route (variant "panel") and the // node proxy. The node's filesystem namespace is Go's sanitizeName, so two // panel names whose sanitizeNodeStorageName forms collide share one node // directory, and the daemon's create handler only refuses while the directory // still holds meta — its stale-dir branch os.RemoveAll's the remainder. // Creating a name whose storage form matched a meta-less legacy alias // directory (the name/legacy_id/bot of another row on this node) silently // WIPED that server's files — user data loss. Refuse NEW collisions here: // compare this name's node-storage form against every alias of every other // server already registered on the node. // The node-identity legs are deliberately caller-owned (see spec section 4): // - panel: 3-way `node_id = id OR node_id = uuid OR LOWER(node_id) = name`, // no ip leg, and uuid WITHOUT the id fallback — preserved byte-for-byte; // - proxy: the same three legs plus `OR ip = ?` (the node address), and uuid // falls back to the node id (`uuidFallbackId`). Include both options from // the caller; never unify them silently. // A DB throw propagates (panel: rejects through the caller's withTimeout into // its 500 catch; proxy: escapes to its route wrapper's 500 node_create_failed) // — a slow DB must fail the create instead of skipping the guard. // `name` must be the sanitized token form; the requested storage form is // derived here (both callers pre-validate it non-empty, and the panel keeps // its historical `requestedStorageName &&` guard while the proxy's is vacuous // because the handler guarantees name === storage form). Returns null when // the name is free, else the transport-neutral collision outcome. async function scanNodeStorageCollisions(deps, node, name, { includeIpLeg = false, uuidFallbackId = false, excludeName = name } = {}) { const sql = includeIpLeg ? "SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR node_id = ? OR LOWER(node_id) = ? OR ip = ?" : "SELECT name, legacy_id, bot FROM servers WHERE node_id = ? OR node_id = ? OR LOWER(node_id) = ?"; const params = [ String(node.id || "").trim(), String(node.uuid || (uuidFallbackId ? node.id : "") || "").trim(), String(node.name || "").trim().toLowerCase(), ]; if (includeIpLeg) { params.push(String(node.address || "").trim()); } const nodeServerRows = await deps.dbQuery(sql, params); const requestedStorageName = sanitizeNodeStorageName(name); const collidingRow = (nodeServerRows || []).find((row) => { // Create has a separate exact-name check; reinstall excludes its own // canonical row even when that row uses a different daemon name. if (String(row?.name || "").trim().toLowerCase() === String(excludeName || "").trim().toLowerCase()) return false; const storageForms = [row?.name, row?.legacy_id, row?.bot] .map((alias) => sanitizeNodeStorageName(alias)) .filter(Boolean); return storageForms.includes(requestedStorageName); }); if (requestedStorageName && collidingRow) { const collidingName = String(collidingRow.name || "").trim() || String(collidingRow.legacy_id || "").trim() || "unknown"; return { ok: false, code: "server_name_storage_collision", data: { collidingName, name } }; } return null; } // Central renderer for every wire-visible server-create string, per variant. // "panel" is the reference contract (POST /api/servers/create, index.js); // "proxy" is the node proxy's (POST /api/nodes/:id/servers/create, nodes.js); // "tool" is the dashboard-assistant create_server tool's prose contract — // failure returns { envelope } where envelope is the tool's ready-to-return // { ok: false, ... } response object (the tool case returns it verbatim; the // tool builds its own success envelope via buildSuccess, so a success outcome // throws here exactly like for the proxy). Codes are shared, strings are not. // The "tool" variant renders ONLY the codes its shared steps // (serverNameGuardOutcome + commitCreatedServer) and its tool-side collision // outcome can produce — anything else throws so a future variant code cannot // silently render the wrong variant's contract (or leak a { status, body } // HTTP shape into a tool envelope). An unmapped code or variant throws. const TOOL_RENDERABLE_CODES = new Set([ // Defensive only: the tool's own empty-name check fires before the guard, // so the tool can never produce this code today — mapped to the tool's // empty-name envelope so the guard's full code set renders for the variant. "invalid_name_empty", "invalid_name_reserved", "invalid_name_no_storage_form", "invalid_name_storage_mismatch", "server_name_exists", "server_name_storage_collision", "template_deleted_during_create", "index_commit_failed", ]); function renderServerCreateOutcome(outcome, variant) { if (variant !== "panel" && variant !== "proxy" && variant !== "tool") { throw new Error(`renderServerCreateOutcome: unknown variant "${variant}"`); } if (outcome && outcome.ok) { if (variant !== "panel") { throw new Error(`renderServerCreateOutcome: variant "${variant}" renders its success body itself (no shared success contract)`); } return { json: { ok: true, name: outcome.data.name, displayName: outcome.data.displayName } }; } if (variant === "tool" && !TOOL_RENDERABLE_CODES.has(outcome && outcome.code)) { throw new Error(`renderServerCreateOutcome: unmapped outcome code "${outcome && outcome.code}" for variant "tool"`); } const data = (outcome && outcome.data) || {}; switch (outcome && outcome.code) { case "invalid_name_empty": if (variant === "tool") return { envelope: { ok: false, error: "A valid server name is required." } }; if (variant === "proxy") return { status: 400, body: { error: "missing_name" } }; return { status: 400, body: { error: "invalid name" } }; case "invalid_name_no_storage_form": if (variant === "tool") { return { envelope: { ok: false, error: "That name has no node-storable form. Choose a name made of letters, numbers, dots, dashes or underscores.", code: "invalid_name", } }; } if (variant === "proxy") return { status: 400, body: { error: "invalid_name", detail: "name has no node-storable form" } }; return { status: 400, body: { error: "invalid name", detail: "name has no node-storable form" } }; case "invalid_name_reserved": // adpanel:reserved-server-name — per-variant bodies mirror the sibling // name-guard cases: the tool's prose sentence envelope (code // "invalid_name", like the other name guards), the proxy's // invalid_name token with a detail, the panel's "invalid name" token // with a detail. if (variant === "tool") { return { envelope: { ok: false, error: "\"all\" is a reserved server name - choose a different name.", code: "invalid_name", } }; } if (variant === "proxy") return { status: 400, body: { error: "invalid_name", detail: "\"all\" is a reserved server name - choose a different name" } }; return { status: 400, body: { error: "invalid name", detail: "\"all\" is a reserved server name - choose a different name" } }; case "invalid_name_storage_mismatch": if (variant === "tool") { return { envelope: { ok: false, error: "Names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them.", code: "invalid_name", } }; } if (variant === "proxy") return { status: 400, body: { error: "invalid_name", detail: "names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them" } }; return { status: 400, body: { error: "invalid name", detail: "names with leading or trailing underscores/dots are stored under a different name on the node, which breaks the file manager - choose a name without them" } }; case "server_name_exists": if (variant === "tool") { // Tool contract: the plain sentence. The tool's own duplicate // pre-check uses a DIFFERENT prose envelope ("That server name is // already in use.") that never routes through here; this code reaches // the tool only from commitCreatedServer's ER_DUP_ENTRY backstop, // whose outcome carries the panel-only "(on node X)" suffix data the // tool (like the proxy) ignores. return { envelope: { ok: false, error: `A server named "${data.name}" already exists. Choose a different name.`, code: "server_name_exists", } }; } if (variant === "proxy") { // Proxy contract: the plain 409 — never the panel's "(on node X)" // suffix, even though duplicateServerNameOutcome carries one for the // panel. data.onNode is intentionally ignored here. return { status: 409, body: { error: `A server named "${data.name}" already exists. Choose a different name.`, code: "server_name_exists" } }; } return { status: 409, body: { error: `A server named "${data.name}" already exists${data.onNode || ""}. Choose a different name.`, code: "server_name_exists" } }; case "server_name_storage_collision": // Identical body on panel and proxy (verified against index.js and // nodes.js before extraction) — one shared rendering. The tool's // sentence is byte-identical too (verified against the former inline // buildMaskedError before its JS-detected outcome was routed here), so // the tool renders the same envelope. if (variant === "tool") { return { envelope: { ok: false, error: `A server named "${data.collidingName}" already exists on this node, and the name "${data.name}" would collide with it at the node's storage layer. Choose a different name.`, code: "server_name_exists", } }; } return { status: 409, body: { error: `A server named "${data.collidingName}" already exists on this node, and the name "${data.name}" would collide with it at the node's storage layer. Choose a different name.`, code: "server_name_exists" } }; case "template_deleted_during_create": if (variant === "tool") { // The tool uses the PANEL's sentence (verified against the former // inline buildMaskedError) with template.name || template.id || // normalizedTemplateId as the shown name. return { envelope: { ok: false, error: `Template "${data.templateName}" was deleted while the server was being created. Choose another template and retry.`, code: "template_deleted_during_create", } }; } if (variant === "proxy") { // Proxy sentence: names the raw templateId (it never resolves the // template row), not the panel's display-name sentence. return { status: 409, body: { error: `Template "${data.templateName}" is not available on the panel (it may have been deleted while the server was being created). Choose another template and retry.`, code: "template_deleted_during_create" } }; } return { status: 409, body: { error: `Template "${data.templateName}" was deleted while the server was being created. Choose another template and retry.`, code: "template_deleted_during_create" } }; case "index_commit_failed": // Proxy code AND tool code: the proxy renders this body for its // non-dup commit failures; the tool renders its non-dup commit failure // as the same prose envelope its daemon-create failure uses. The panel // rethrows non-dup commit failures into its route 500 catch instead of // rendering this body. if (variant === "tool") { return { envelope: { ok: false, error: "Failed to create that server.", detail: data.detail } }; } if (variant === "proxy") return { status: 500, body: { error: "index_commit_failed", detail: data.detail } }; throw new Error('renderServerCreateOutcome: unmapped outcome code "index_commit_failed" for variant "panel"'); case "missing_template_id": return { status: 400, body: { error: "missing templateId" } }; case "unknown_template": return { status: 400, body: { error: "unknown template" } }; case "node_id_required": return { status: 400, body: { error: "nodeId required" } }; case "no_nodes_configured": return { status: 400, body: { error: "No nodes configured. Add a node before creating servers." } }; case "node_not_found": return { status: 400, body: { error: "node not found" } }; case "disk_not_on_node": return { status: 400, body: { error: "Target disk does not belong to this node." } }; case "disk_verify_failed": return { status: 502, body: { error: "Failed to verify target disk on node." } }; case "invalid_mc_fork": return { status: 400, body: { error: `Invalid mcFork (supported: ${SUPPORTED_MC_FORKS.join(", ")})` } }; case "invalid_mc_version": return { status: 400, body: { error: "Invalid mcVersion (expected e.g. 1.21.8, 1.21.8-pre1, 24w14a)" } }; case "invalid_import_url": return { status: 400, body: { error: "Invalid importUrl (must be http(s) and a supported archive extension)" } }; case "unsafe_import_url": return { status: 400, body: { error: `Unsafe importUrl: ${data.reason}` } }; case "ram_limit_exceeded": return { status: 400, body: { error: `RAM limit cannot exceed node maximum (${data.limit} MB).` } }; case "cpu_limit_exceeded": return { status: 400, body: { error: `CPU cores cannot exceed node maximum (${data.limit} cores).` } }; case "storage_limit_exceeded": return { status: 400, body: { error: `Storage limit cannot exceed node maximum (${data.limit} MB).` } }; case "invalid_resource_options": return { status: 400, body: { error: data.message || "Invalid resource limits." } }; case "java_version_non_minecraft": return { status: 400, body: { error: "Java version selection is only available for Minecraft templates." } }; case "java_version_unsupported": return { status: 400, body: { error: "Unsupported Minecraft Java version." } }; case "startup_command_unsupported": return { status: 400, body: { error: "Raw Docker startup commands are no longer supported. Server containers are now created from structured template settings only." } }; case "invalid_command": return { status: 400, body: { error: data.message } }; case "invalid_port": return { status: 400, body: { error: "Invalid port. Choose a value between 1 and 65535." } }; case "node_deleted_during_create": return { status: 410, body: { error: "node deleted during create" } }; case "duplicate_template_port_mapping": return { status: 400, body: { error: `Port ${data.port} would be used by more than one mapping. Choose a different main port or adjust the template ports.` } }; case "port_not_in_allocation": return { status: 400, body: { error: `Port ${data.port} is not in this node's allocated ports (${data.allocDesc}). Choose ports within the node's allocation.` } }; case "port_bind_address_required": return { status: 400, body: { error: `Allocate port ${data.port} to a local interface IP on this node, not its Cloudflare management address.`, code: "port_bind_address_required" } }; case "port_assigned_to_server": return { status: 409, body: { error: `Port ${data.port} is already assigned to server "${data.displayName}" on this node.`, code: "port_in_use", port: data.port, server: data.server } }; case "port_in_use_live": return { status: 409, body: { error: `Port ${data.port} is already in use on the node${data.owner ? ` by ${data.owner}` : ""}.`, code: "port_in_use", port: data.port, owner: data.owner || null, reason: data.reason || null } }; default: throw new Error(`renderServerCreateOutcome: unmapped outcome code "${outcome && outcome.code}"`); } } // Compensation log strings for the guarded commit, per caller. Log lines are // not wire contracts, but the panel's and the proxy's wording deliberately // differs ("a committed" vs "the committed", "writer's" vs "worker's", // console.warn vs console.error), so each caller keeps its exact strings — // passed as message builders; the shared commit only picks the builder and // the console level. The panel's set (below) is the default so the panel call // site stays lean; the proxy passes its own from nodes.js. The assistant tool // uses NEITHER set: its compensation logging is mode-aware (a distinct line // for a missing deleteServerOnNode dep, a missing index reader, a failed // ownership re-read, a withhold and a failed delete, with the failure reason // baked in), which the builder shape cannot express without duplicating the // strings — it passes ctx.compensate instead and keeps its lines in one // router beside the tool. function panelCommitLog(logTag) { return { tag: logTag, level: "warn", templateDeletedWithheld: (name) => `template deleted during create and compensating delete of "${name}" was WITHHELD — a committed index row claims this name on this node, so the daemon server may belong to another writer's live create; it was left intact`, templateDeletedError: (name) => `template deleted during create and compensating delete of "${name}" failed — server is orphaned on the node:`, commitWithheld: (name) => `index commit failed and compensating delete of "${name}" was WITHHELD — a committed index row claims this name on this node, so the daemon server belongs to another writer's live create; winner left intact`, commitError: (name) => `index commit failed and compensating delete of "${name}" failed — server is orphaned on the node:`, }; } // ONE home for the guarded-commit choreography shared by every server-create // path (panel route, node proxy, assistant tool): commit through // insertServerIndexEntryGuarded and, on every failure, best-effort remove the // just-created daemon server through the ownership-guarded compensating // delete before reporting the failure. // // M3/M4: insert-only commit. The UNIQUE servers.name key arbitrates // cross-worker races that the per-worker create lock and the duplicate // pre-check cannot serialize (a same-name create on another pm2 worker can // commit its row between this request's pre-check and its commit). The commit // goes through insertServerIndexEntryGuarded, which re-checks the template // under the same "templates-write" key the template DELETE route holds across // its "template in use" check: that check reads the servers index, which does // not yet contain this row, so an unguarded commit would let a delete racing // the slow node round-trips remove the template this server is about to // reference. On a lost race (template deleted mid-create) — or any commit // failure — the just-created daemon server would be unmanageable, so it is // best-effort removed again and the request fails loudly instead of // repointing a row. // // adpanel:proxy-create-race (review fix) — the ownership guard on every // compensating delete below: this request's own index commit never landed // (the guarded writer refuses before its INSERT, and a thrown INSERT commits // nothing), so a committed row claiming the name can only belong to another // writer — on ER_DUP_ENTRY by definition, whose old unconditional // DELETE /v1/servers/ was a destroy primitive that removed the winner's // live container and directory. deleteOwnOrphanServerOnNodeForCreate deletes // only when the name is uncommitted or claimed on a DIFFERENT node; when a // row claims it on this node the winner is left intact and the failure // outcome is the only answer. Compensation failures are only logged — never // mask the original failure. // // ctx: { // entry — the servers-index row to commit (the caller's lean or // full serverEntry; the row shape stays caller-owned), // name — the sanitized server name (compensation needle + 409), // node — the node row the daemon server was created on (the // caller's freshNode: the ownership guard matches rows // against THIS node's identities), // templateName — the string the template-deleted 409 shows (panel: the // template's display name or the requested id; proxy: the // raw requested templateId — the proxy never resolves the // template row), // logTag — console prefix when ctx.log is omitted (panel default), // notWiredDetail — proxy wiring: when set and the guarded writer dep is // missing, run the compensating delete and return // index_commit_failed with this detail instead of letting // the call throw (fail closed: without the guarded writer // the created server would be unmanageable, and falling // back to an unguarded insert would reopen the // template-delete-vs-create race). The panel leaves this // unset — its writer is module-local and can never be // missing, so a missing dep falls through to the natural // TypeError in the try below (compensate + rethrow), its // historical behavior. // rethrowNonDup — panel: rethrow non-ER_DUP commit errors so the route's // 500 catch renders "create failed" exactly as before; // proxy: render them as index_commit_failed instead. // compensate — optional per-caller compensation override: called as // compensate(kind) with kind "not_wired" | // "template_deleted" | "commit_failed" INSTEAD of the // built-in deleteOwnOrphanServerOnNodeForCreate call and // the logCfg emission. For callers whose compensation // logging is mode-aware beyond the builder config (the // assistant tool logs a distinct line per failure mode, // with the failure reason baked into the string). The // override fully owns the compensation call AND its // logging (its return value is ignored); the failure // outcome choreography below is unchanged. When absent // (panel + proxy) the built-in guard + logCfg path runs // exactly as before. // log — optional per-caller compensation log strings (see // panelCommitLog); defaults to the panel's strings built // from logTag. Unused when compensate is set. // } // Returns null on success; a transport-neutral failure outcome (codes // template_deleted_during_create / server_name_exists / index_commit_failed) // for the caller's renderer. The rethrowNonDup path throws through. async function commitCreatedServer(deps, ctx) { const { entry, name, node, templateName, notWiredDetail, rethrowNonDup } = ctx; // Compensation ownership: the built-in path runs the canonical guard and // emits the caller's logCfg lines; a ctx.compensate caller replaces BOTH // (its hook owns the guard call and the logging), so only the failure // outcome choreography below stays shared. const callerCompensates = typeof ctx.compensate === "function"; const runCompensation = (kind) => ( callerCompensates ? ctx.compensate(kind) : deleteOwnOrphanServerOnNodeForCreate(deps, node, name) ); const logCfg = ctx.log || panelCommitLog(ctx.logTag); const logCompensation = (message, errDetail) => { const line = `${logCfg.tag} ${message}`; if (errDetail === undefined) { if (logCfg.level === "error") console.error(line); else console.warn(line); return; } if (logCfg.level === "error") console.error(line, errDetail); else console.warn(line, errDetail); }; if (typeof deps.insertServerIndexEntryGuarded !== "function" && notWiredDetail != null) { // Fail closed (proxy wiring): remove the just-created daemon server via // the ownership guard instead of leaving it orphaned, then refuse. const comp = await runCompensation("not_wired"); if (!callerCompensates) { // The panel's default log config defines no not-wired builders (its // writer is module-local, so this branch is unreachable there) — guard // the builders so a future notWiredDetail caller without its own log // config cannot TypeError after compensation has already run. if (comp.withheld) { if (typeof logCfg.notWiredWithheld === "function") logCompensation(logCfg.notWiredWithheld(name)); } else if (comp.error) { if (typeof logCfg.notWiredError === "function") logCompensation(logCfg.notWiredError(name), comp.error?.message || comp.error); } } return { ok: false, code: "index_commit_failed", data: { detail: notWiredDetail } }; } let committed; try { committed = await deps.insertServerIndexEntryGuarded(entry); if (!committed || committed.ok === false) { // template_deleted: mirror the node-deleted compensation — best-effort // remove the just-created daemon server, then fail loudly. The commit // never ran (the guarded writer refuses before its INSERT), so the // ownership guard withholds whenever the row it finds belongs to // another writer. const comp = await runCompensation("template_deleted"); if (!callerCompensates) { if (comp.withheld) { logCompensation(logCfg.templateDeletedWithheld(name)); } else if (comp.error) { logCompensation(logCfg.templateDeletedError(name), comp.error?.message || comp.error); } } return { ok: false, code: "template_deleted_during_create", data: { templateName } }; } } catch (entryErr) { const comp = await runCompensation("commit_failed"); if (!callerCompensates) { if (comp.withheld) { logCompensation(logCfg.commitWithheld(name)); } else if (comp.error) { logCompensation(logCfg.commitError(name), comp.error?.message || comp.error); } } console.error(`${logCfg.tag} index commit failed:`, entryErr?.message || entryErr); if (entryErr && entryErr.code === "ER_DUP_ENTRY") { return { ok: false, code: "server_name_exists", data: { name, onNode: "" } }; } if (rethrowNonDup) throw entryErr; return { ok: false, code: "index_commit_failed", data: { detail: entryErr?.message || String(entryErr) } }; } ctx.onCommitted?.(committed); return null; } // The locked provisioning pipeline behind the panel create route (variant // "panel"): displayName resolution through the guarded index commit, the // post-commit access grant, the two audit records and the deferred import. // // input: { // name — ALREADY sanitizeServerToken'd by the adapter (the route // sanitizes before auth so the step-up subject shows the // sanitized name), // rawName — the raw client name (display-name fallback), // displayNameInput — client displayName (may be empty), // templateId, nodeId — as sent, // body — the raw req.body (optional-chained throughout), // sessionUser — req.session?.user (audit falls back to "admin"), // clientIp — adapter-resolved request IP for the audit records, // logTag — console log prefix, e.g. "[/api/servers/create]", // lock — { release } — REQUIRED. The cross-process create lock // is acquired (and released in the adapter's finally) by // the CALLER, after step-up: no provisioning may run // without it, so its absence throws before any work. // } // Returns a transport-neutral outcome; renderServerCreateOutcome maps it to // the caller's HTTP contract. Any thrown error propagates to the caller's // 500 catch exactly like the monolithic route's did. async function createServerOnNode(deps, input) { // adpanel:server-create-mutex — fail closed: a caller that does not hold // the per-name cross-process create lock must not reach the daemon. The // check runs before any await so nothing whatsoever is provisioned without // the lock release handle proving the caller holds it. if (!input || !input.lock || typeof input.lock.release !== "function") { throw new Error("createServerOnNode: lock.release is required — the caller must hold the cross-process server create lock"); } const { name, rawName, displayNameInput, templateId, nodeId, body, sessionUser, clientIp, logTag, } = input; const displayName = sanitizeDisplayNameToken(displayNameInput || rawName) || name; if (!templateId) return { ok: false, code: "missing_template_id" }; const template = deps.findTemplateById(templateId); if (!template) return { ok: false, code: "unknown_template" }; const tpl = deps.normalizeTemplateId(templateId); const targetNodeId = String(nodeId || "").trim(); if (!targetNodeId || targetNodeId === "local") return { ok: false, code: "node_id_required" }; // Mutating operation: both DB reads are bounded and a timeout rejects // into the caller's catch (500 "create failed") — an empty-node fallback // would answer a DB outage with the misleading "No nodes configured", and // the create must not proceed on partially resolved node data. const configuredNodes = await deps.withTimeout(Promise.resolve().then(() => deps.loadNodes()), 5000, "server-create-nodes-timeout"); if (!configuredNodes.length) { return { ok: false, code: "no_nodes_configured" }; } const node = await deps.withTimeout(Promise.resolve().then(() => deps.findNodeByIdOrName(targetNodeId)), 5000, "server-create-node-lookup-timeout"); if (!node) return { ok: false, code: "node_not_found" }; // adpanel:node-storage-name — the node filesystem namespace is Go's // sanitizeName, not the panel's sanitizeServerToken (Go Trim's "-_." from // both ends and strips leading non-alphanumerics), so two panel names // whose Go forms collide share one node directory — see the shared // scanNodeStorageCollisions for the full rationale. Bounded like the // sibling reads; a slow DB rejects into the caller's catch (500 "create // failed") instead of skipping the guard. const collisionOutcome = await deps.withTimeout( Promise.resolve().then(() => scanNodeStorageCollisions(deps, node, name, { includeIpLeg: false })), 5000, "server-create-node-name-collision-timeout" ); if (collisionOutcome) return collisionOutcome; // adpanel:multidisk - resolve and verify the requested target disk belongs to // this node. Empty/"primary" => default primary disk (back-compat). let targetDiskId = String(body?.diskId || "").trim(); if (targetDiskId && targetDiskId !== "primary") { try { const diskRes = await deps.httpRequestJson( `${deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, deps.nodeUnderCloudflare(node))}/v1/disks`, "GET", { Authorization: `Bearer ${node.token}` }, null, 8000 ); const disks = (diskRes.status === 200 && diskRes.json?.ok && Array.isArray(diskRes.json.disks)) ? diskRes.json.disks : []; if (!disks.some((d) => String(d.id) === targetDiskId)) { return { ok: false, code: "disk_not_on_node" }; } } catch (_) { return { ok: false, code: "disk_verify_failed" }; } } else { targetDiskId = ""; } // adpanel:F8 - mcFork/mcVersion are interpolated by the node daemon into // the PaperMC/Purpur API URL path, so a bare lowercase/trim is not enough. // Validate against the strict allowlist/grammar and reject instead of // sanitizing silently; the daemon re-validates at its own trust boundary. const mcFork = resolveMcFork(body?.mcFork); const mcVersion = resolveMcVersion(body?.mcVersion); if (tpl === "minecraft") { if (mcFork === null) { return { ok: false, code: "invalid_mc_fork" }; } if (mcVersion === null) { return { ok: false, code: "invalid_mc_version" }; } } const safeMcFork = mcFork === null ? "paper" : mcFork; const safeMcVersion = mcVersion === null ? "1.21.8" : mcVersion; let importUrl = body?.importUrl ? String(body.importUrl).trim() : null; if (importUrl) { if (!deps.isValidArchiveUrl(importUrl)) { return { ok: false, code: "invalid_import_url" }; } try { await deps.assertSafeRemoteUrl(importUrl); } catch (e) { return { ok: false, code: "unsafe_import_url", data: { reason: e.message } }; } } const reqResources = body?.resources || {}; const resources = {}; const parsePositiveIntOrNull = (value) => { if (value === null || value === undefined || String(value).trim() === "") return null; const parsed = parseInt(value, 10); return Number.isFinite(parsed) && parsed > 0 ? parsed : null; }; const parsePositiveFloatOrNull = (value) => { if (value === null || value === undefined || String(value).trim() === "") return null; const parsed = parseFloat(value); return Number.isFinite(parsed) && parsed > 0 ? parsed : null; }; const effectiveNodeCapacity = await deps.getEffectiveNodeCapacity(node); const requestedRamMb = parsePositiveIntOrNull(reqResources.ramMb); const requestedCpuCores = parsePositiveFloatOrNull(reqResources.cpuCores); const requestedStorageMb = parsePositiveIntOrNull(reqResources.storageMb); const requestedStorageGb = parsePositiveIntOrNull(reqResources.storageGb); const effectiveDiskMb = effectiveNodeCapacity.diskGb > 0 ? Math.trunc(effectiveNodeCapacity.diskGb * 1024) : 0; if (requestedRamMb != null) { if (effectiveNodeCapacity.ramMb > 0 && requestedRamMb > effectiveNodeCapacity.ramMb) { return { ok: false, code: "ram_limit_exceeded", data: { limit: effectiveNodeCapacity.ramMb } }; } resources.ramMb = requestedRamMb; } else if (effectiveNodeCapacity.ramMb > 0) { resources.ramMb = effectiveNodeCapacity.ramMb; } if (requestedCpuCores != null) { if (effectiveNodeCapacity.cpuCores > 0 && requestedCpuCores > effectiveNodeCapacity.cpuCores) { return { ok: false, code: "cpu_limit_exceeded", data: { limit: effectiveNodeCapacity.cpuCores } }; } resources.cpuCores = requestedCpuCores; } else if (effectiveNodeCapacity.cpuCores > 0) { resources.cpuCores = effectiveNodeCapacity.cpuCores; } if (requestedStorageMb != null) { if (effectiveDiskMb > 0 && requestedStorageMb > effectiveDiskMb) { return { ok: false, code: "storage_limit_exceeded", data: { limit: effectiveDiskMb } }; } resources.storageMb = requestedStorageMb; } else if (requestedStorageGb != null) { const requestedStorageFromGb = requestedStorageGb * 1024; if (effectiveDiskMb > 0 && requestedStorageFromGb > effectiveDiskMb) { return { ok: false, code: "storage_limit_exceeded", data: { limit: effectiveDiskMb } }; } resources.storageMb = requestedStorageFromGb; } else if (effectiveDiskMb > 0) { resources.storageMb = effectiveDiskMb; } if (reqResources.swapMb != null) resources.swapMb = parseInt(reqResources.swapMb, 10); // adpanel:backup-cap-daemon-enforced — the panel-side count-then-create // checks (scheduler fire path, interactive relay) 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, checked under the // per-server op lock + upload-scope lock over an untruncated ReadDir of // ALL backup subdirs — stricter at the margins than the panel's // meta-valid-dir listing) is the authoritative bound. The daemon treats a // MISSING or non-positive backupsMax as "no cap" (`if backupsMax > 0`), // so the default below is always the resolved positive panel cap — never // 0/undefined, which would disable the daemon layer. An explicit client // value (including 0 = deliberately no daemon cap, the settings UI's // "unlimited") still passes through untouched. // adpanel:backup-cap-parse-hardening — the parse/degrade lives in the ONE // shared helper (utils/backup-cap.js): garbage/negative explicit values // degrade to the panel cap, never to unlimited. // Design consequence of explicit 0: the panel's own 409 count-checks still // bound at the env cap, so an explicit 0 ("unlimited") never delivers more // than SCHEDULER_MAX_BACKUPS_PER_SERVER via panel paths — the daemon cap // only raises the ceiling for direct/daemon-side counts. resources.backupsMax = resolveBackupsMaxFromInput(reqResources.backupsMax); if (reqResources.maxSchedules != null) resources.maxSchedules = parseInt(reqResources.maxSchedules, 10) || 0; try { Object.assign(resources, deps.collectResourcePerformanceOptions(reqResources)); Object.assign(resources, deps.collectResourceAntiAbuseOptions(reqResources)); } catch (e) { return { ok: false, code: "invalid_resource_options", data: { message: e.message } }; } let sanitizedDocker = deps.normalizeTemplateDockerForRuntime(templateId, template.docker); const requestedJavaVersion = Object.prototype.hasOwnProperty.call(body || {}, "javaVersion") ? deps.normalizeMinecraftJavaVersionInput(body?.javaVersion) : ""; if (Object.prototype.hasOwnProperty.call(body || {}, "javaVersion") && tpl !== "minecraft") { return { ok: false, code: "java_version_non_minecraft" }; } if (Object.prototype.hasOwnProperty.call(body || {}, "javaVersion") && !requestedJavaVersion) { return { ok: false, code: "java_version_unsupported" }; } if (tpl === "minecraft" && requestedJavaVersion) { sanitizedDocker.image = deps.DEFAULT_MINECRAFT_PROCESS_IMAGE; sanitizedDocker.tag = deps.minecraftJavaTag(requestedJavaVersion); sanitizedDocker.javaVersion = requestedJavaVersion; } if (body?.startupCommand && String(body.startupCommand).trim()) { return { ok: false, code: "startup_command_unsupported" }; } const requestedCommand = deps.normalizeLegacyRuntimeProcessCommandInput(templateId, body?.command); const requestedCommandError = deps.validateRuntimeProcessCommandInput(requestedCommand); if (requestedCommandError) { return { ok: false, code: "invalid_command", data: { message: requestedCommandError } }; } if (requestedCommand) { sanitizedDocker.command = requestedCommand; } const requestedHostPort = body?.hostPort ?? body?.port; // adpanel:server-create-port - authorize the actual binding, not an absent request value. const resolvedPort = requestedHostPort != null && String(requestedHostPort).trim() !== "" ? deps.validatePort(requestedHostPort) : deps.validatePort(template.defaultPort) || (tpl === "minecraft" ? 25565 : deps.validatePort(sanitizedDocker?.ports?.[0]) || 8080); if (!resolvedPort) return { ok: false, code: "invalid_port" }; const requiredHostPorts = deps.dockerTemplateHostPortRequirements(sanitizedDocker, resolvedPort); // Port-allocation checks and the create commit race with concurrent // port-removal PATCHes (nodes.js) and the /api/nodes/:id/servers/create // proxy: all three take the same per-node lock around check -> commit, so // a server can never claim a port that is being removed (or the removal // commit a claim) in between. In-process only — the same residual // cross-worker window withServersIndexWriteLock already accepts. const createOutcome = await withKeyedLock(`node-ports:${node.id}`, async () => { // Re-read under the lock: a concurrent port update may have re-pointed // the allocation while this request was queued behind it. F5: fail // closed when the node row was deleted meanwhile — committing onto a // stale in-memory copy would orphan the server on a node the panel no // longer knows. const freshNode = await deps.findNodeByIdOrName(node.id); if (!freshNode) { return { ok: false, code: "node_deleted_during_create" }; } const seenRequiredPorts = new Set(); for (const requirement of requiredHostPorts) { if (seenRequiredPorts.has(requirement.hostPort)) { return { ok: false, code: "duplicate_template_port_mapping", data: { port: requirement.hostPort } }; } seenRequiredPorts.add(requirement.hostPort); } for (const requirement of requiredHostPorts) { const portOutcome = await checkServerCreatePort(deps, freshNode, requirement, name); if (portOutcome) return portOutcome; } const bind = resolveServerCreateBindAddress(freshNode, resolvedPort); if (bind.error) return bind.error; const nodeBindIP = bind.address; if (nodeBindIP && sanitizedDocker) { sanitizedDocker.bind_ip = nodeBindIP; sanitizedDocker.host_ip = nodeBindIP; } const payload = { name, templateId, mcFork: safeMcFork, mcVersion: safeMcVersion, hostPort: resolvedPort, bind_ip: nodeBindIP || undefined, host_ip: nodeBindIP || undefined, docker: deps.dockerConfigForNodeRequest(sanitizedDocker), autoStart: !importUrl, asyncSetup: true, resources: Object.keys(resources).length > 0 ? resources : null }; if (targetDiskId) { payload.diskId = targetDiskId; } if (tpl === "minecraft" && sanitizedDocker?.javaVersion) { payload.javaVersion = sanitizedDocker.javaVersion; } const createResult = await deps.createOnRemoteNode(freshNode, payload); // F5: the node row may have been deleted while the daemon call was in // flight. Re-check inside the same keyed lock BEFORE committing the // index entry; if it is gone, best-effort remove the just-created // server from the node (never mask the original error — compensation // failures are only logged) and abort with the same 410 as above. if (!(await deps.findNodeByIdOrName(node.id))) { // adpanel:proxy-create-race (review fix) — ownership-guarded // compensation: a committed row claiming this name belongs to another // writer (this request's commit has not run yet) and must never be // deleted by name alone. const comp = await deleteOwnOrphanServerOnNodeForCreate(deps, freshNode, name); if (comp.withheld) { console.warn(`${logTag} node deleted during create and compensating delete of "${name}" was WITHHELD — a committed index row claims this name on this node, so the daemon server may belong to another writer's live create; it was left intact`); } else if (comp.error) { console.warn(`${logTag} compensating remote delete failed (node deleted during create):`, comp.error?.message || comp.error); } return { ok: false, code: "node_deleted_during_create" }; } const savedPort = resolvedPort; const serverEntry = { name, displayName, template: templateId, mcFork: tpl === "minecraft" ? safeMcFork : undefined, mcVersion: tpl === "minecraft" ? safeMcVersion : undefined, start: tpl === "minecraft" ? "server.jar" : (tpl === "nodejs" || tpl === "discord-bot" ? "index.js" : (tpl === "python" ? "main.py" : null)), nodeId: freshNode.uuid || freshNode.id || freshNode.name, ip: nodeBindIP || freshNode.address || null, bind_ip: nodeBindIP || undefined, host_ip: nodeBindIP || undefined, status: createResult?.asyncSetup ? (String(createResult?.meta?.setupStatus || "").toLowerCase() === "failed" ? "error" : "installing") : undefined, setupStatus: createResult?.asyncSetup ? (createResult?.meta?.setupStatus || "queued") : undefined, }; if (savedPort != null) serverEntry.port = savedPort; if (createResult?.meta?.setupMessage) serverEntry.setupMessage = createResult.meta.setupMessage; if (Object.keys(resources).length > 0) serverEntry.resources = resources; if (sanitizedDocker) serverEntry.docker = sanitizedDocker; if (sanitizedDocker) { serverEntry.runtime = { image: sanitizedDocker.image, tag: sanitizedDocker.tag, command: sanitizedDocker.command, volumes: sanitizedDocker.volumes, workdir: sanitizedDocker.workdir, env: sanitizedDocker.env, ports: sanitizedDocker.ports, portProtocols: sanitizedDocker.portProtocols, javaVersion: sanitizedDocker.javaVersion, runAsRoot: sanitizedDocker.runAsRoot === true, readonlyRootfs: sanitizedDocker.readonlyRootfs === true, bind_ip: nodeBindIP || undefined, host_ip: nodeBindIP || undefined, adpanelStartup: sanitizedDocker.adpanelStartup, startupDisplay: sanitizedDocker.startupDisplay, install: sanitizedDocker.install, }; } // M3/M4: insert-only commit. The UNIQUE servers.name key arbitrates // cross-worker races that the per-worker create lock and the route-level // findServer pre-check cannot serialize (a same-name create on another // pm2 worker can commit its row between this request's pre-check and // its commit); the commit itself goes through insertServerIndexEntryGuarded, // which re-checks the template under the same "templates-write" key the // template DELETE route holds across its "template in use" check, so an // unguarded commit could never let a delete racing the slow node // round-trips above remove the template this server references. Full // choreography — template-deleted and commit-failure compensations with // the ownership guard, ER_DUP_ENTRY mapping, non-dup rethrow into this // route's 500 "create failed" catch — is ONE shared implementation: // commitCreatedServer above. let rowId; const commitOutcome = await commitCreatedServer(deps, { entry: serverEntry, name, node: freshNode, templateName: template.name || templateId, logTag, rethrowNonDup: true, onCommitted: committed => { rowId = committed.rowId; }, }); if (commitOutcome) return commitOutcome; // adpanel:server-create-grant-race — the access grant runs only AFTER the // index commit above has succeeded. Before the commit, a concurrent // saveServersIndex companion cleanup could capture the fresh user_access // row in the grant->commit gap (the name was not yet owned by any servers // row) and DELETE it, locking the new owner out; it also granted on the // template-deleted / commit-failure paths for a server that never // committed. After the commit, the NOT EXISTS ownership guard sees the // committed servers row, so the grant survives any concurrent cleanup. // Best-effort and non-fatal: the server is already committed here, so a // grant failure must never fail the create. try { const me = sessionUser; const u = await deps.findUserByEmail(me); if (!(u && u.admin)) await deps.addAccessForEmail(me, name); } catch (grantErr) { console.warn(`${logTag} post-commit access grant failed:`, grantErr?.message || grantErr); } return { ok: true, code: "success", data: { createResult, serverEntry, savedPort, displayName, template, templateId, tpl, node: freshNode, rowId, targetNodeId, importUrl, resources, } }; }); if (!createOutcome.ok) return createOutcome; const { savedPort } = createOutcome.data; const userEmail = sessionUser || "admin"; try { deps.recordActivity(name, "server_create", { template: createOutcome.data.template.name || createOutcome.data.templateId, node: createOutcome.data.node.name || createOutcome.data.node.uuid || createOutcome.data.targetNodeId, port: savedPort || "auto", displayName: displayName !== name ? displayName : undefined }, userEmail, clientIp); deps.recordActivity("_system", "server_create", { server: name, template: createOutcome.data.template.name || createOutcome.data.templateId, node: createOutcome.data.node.name || createOutcome.data.node.uuid || createOutcome.data.targetNodeId, port: savedPort || "auto" }, userEmail, clientIp); } catch (actErr) { console.warn(`${logTag} Failed to record activity:`, actErr?.message || actErr); } if (createOutcome.data.importUrl) { // Panel-proxied import: the node never receives the raw URL (see // runDeferredServerImport). Runs after the response so a slow archive // download cannot block server creation. deps.runDeferredServerImport(createOutcome.data.node, name, createOutcome.data.importUrl, createOutcome.data.rowId).catch(() => { }); } return { ok: true, code: "success", data: { name, displayName } }; } module.exports = { createServerOnNode, checkServerCreatePort, resolveServerCreateBindAddress, serverNameGuardOutcome, duplicateServerNameOutcome, scanNodeStorageCollisions, commitCreatedServer, renderServerCreateOutcome, deleteOwnOrphanServerOnNodeForCreate, };