Files
Kelx/utils/server-reinstall.js
T
2026-11-30 16:32:37 +00:00

432 lines
25 KiB
JavaScript

"use strict";
const { createHash, randomBytes } = require("node:crypto");
const { isDeepStrictEqual } = require("node:util");
const { tryWithKeyedLock } = require("./keyed-async-lock");
const { createCrossProcessOperationMutex } = require("./cross-process-mutex");
const { getRememberLoginFingerprint } = require("./remember-login-fingerprint");
const { credentialGenerationMismatch } = require("./session-account-binding");
const { getTechnicalServerName, sanitizeNodeStorageName } = require("./server-name");
const { scanNodeStorageCollisions } = require("../services/server-create");
const { hasVerifiedNodeHttps } = require("../services/node-http");
const REINSTALL_NODE_TIMEOUT_MS = 145 * 60 * 1000;
const REINSTALL_ADMISSION_MS = 5 * 60 * 1000;
const REINSTALL_RESULT_TIMEOUT_MS = 50_000;
const REINSTALL_CONFIRMED_CONFLICTS = new Set([
"server_op_in_progress", "server_stop_in_progress", "reinstall_in_progress", "backup_in_progress", "runtime_seed_in_progress",
"reinstall_template_mismatch",
]);
function getReinstallNodeServerName(entry, fallback) {
return sanitizeNodeStorageName(getTechnicalServerName(entry, fallback));
}
// adpanel:reinstall-transport - the signature does not bind the runtime
// configuration or the outcome. Require authenticated transport for both.
function validateReinstallTransport(baseUrl) {
if (!baseUrl) return { ok: false, statusCode: 400, error: "invalid node address" };
if (!hasVerifiedNodeHttps(baseUrl)) {
return {
ok: false, statusCode: 503, code: "reinstall-insecure-node-transport",
error: "Reinstall requires a node HTTPS connection with certificate and hostname verification enabled. Contact an administrator.",
};
}
return { ok: true, baseUrl };
}
// adpanel:reinstall-template-claim - deletion must not remove a template
// while a rebuild is replacing files but has not committed its index row.
function acquireReinstallTemplateLock(templatesFile, templateId) {
const key = createHash("sha256").update(templateId).digest("hex");
return createCrossProcessOperationMutex({
label: "[reinstall-template]", lockFilePath: `${templatesFile}.reinstall-${key}.lock`,
}).tryAcquire();
}
// adpanel:reinstall-port-claim - a free port stays protected through the
// rebuild and index commit, using the same node lock as create and pool edits.
function withReinstallNodePortLock({ findNodeByIdOrName }, node, operation) {
if (!node) return operation(null);
const attempt = tryWithKeyedLock(`node-ports:${node.id}`, async () => {
const refreshed = await findNodeByIdOrName(node.id);
// adpanel:reinstall-node-identity - a fallback alias is not the node whose ports are locked.
const sameNode = refreshed?.id === node.id && (refreshed.uuid || refreshed.id) === (node.uuid || node.id);
return operation(sameNode ? refreshed : null);
});
if (attempt) return attempt;
return {
ok: false, statusCode: 409, code: "node_port_operation_in_progress",
error: "Another operation is using this node's port allocation. Confirm the reinstall again after it completes.",
};
}
// adpanel:reinstall-port-admission - every rebuild needs a strictly parsed,
// allocated host port; missing legacy ports must not fall back on the daemon.
async function resolveReinstallHostPort({ validatePort, isPortInNodeAllocation, findFreeNodePoolPort, findServerUsingNodePort, checkDestinationNodePort }, node, entry, fallbackPort = null) {
const storedPort = validatePort(entry.port);
let hostPort = storedPort;
if (storedPort && isPortInNodeAllocation(node, storedPort) && await findServerUsingNodePort(node, storedPort, entry.name)) {
return { ok: false, statusCode: 409, error: `Port ${storedPort} is also assigned to another server on this node; fix the allocation before reinstalling.` };
}
const templatePort = validatePort(fallbackPort);
// adpanel:reinstall-default-port-claim - a template default is not an
// existing allocation; verify its ownership before authorizing a wipe.
if (!hostPort && templatePort && isPortInNodeAllocation(node, templatePort) && typeof checkDestinationNodePort === "function") {
const availability = await checkDestinationNodePort(node, templatePort, { excludeName: entry.name });
if (availability?.ok === true) hostPort = templatePort;
}
if (!hostPort || !isPortInNodeAllocation(node, hostPort)) {
hostPort = validatePort(await findFreeNodePoolPort(node, entry.name));
if (!hostPort || !isPortInNodeAllocation(node, hostPort)) {
return {
ok: false, statusCode: 409,
error: storedPort
? `Port ${storedPort} is not in this node's allocated ports and the pool has no free port; adjust the node's port allocation first.`
: "No usable host port is stored for this server and the node's allocation pool has no free port; adjust the node's port allocation first.",
};
}
}
return { ok: true, hostPort };
}
// adpanel:reinstall-target-snapshot - step-up and claim acquisition are
// asynchronous; a completed transfer or template edit invalidates the target.
async function validateReinstallTarget({ findServer }, expectedEntry) {
const currentEntry = await findServer(expectedEntry.name);
const fields = ["name", "rowId", "id", "bot", "nodeId", "template", "start", "ip", "port", "runtime", "docker", "resources", "acl", "suspended"];
if (!currentEntry || fields.some((field) => !isDeepStrictEqual(expectedEntry[field], currentEntry[field]))) {
return {
ok: false, statusCode: 409, code: "reinstall-target-changed",
error: "Server configuration or ownership changed while the reinstall was being authorized. Reload the server and confirm again before retrying.",
};
}
return { ok: true };
}
// adpanel:reinstall-actor-admission - pending step-up and port checks must
// not promote a revoked session, account, role or access grant into a wipe.
async function validateReinstallAuthorization(deps, req, expectedUser, serverName, { adminOnly = false, expectedEntry = null, node = null, technicalName = "" } = {}) {
const denied = {
ok: false, statusCode: 403, code: "reinstall-authorization-changed",
error: "Reinstall authorization changed while the request was pending. Reload the server and verify your current access before retrying.",
};
if (!req.session?.user || !req.sessionID || expectedUser?.id == null || !expectedUser.password ||
await deps.isSessionSidRevoked(req.sessionID)) return denied;
const currentUser = await deps.findUserByEmail(req.session.user);
if (!currentUser || !currentUser.password || currentUser.suspended || currentUser.totpSealedError === true ||
String(currentUser.id) !== String(expectedUser.id) ||
String(currentUser.email || "").trim().toLowerCase() !== String(expectedUser.email || "").trim().toLowerCase() ||
credentialGenerationMismatch(expectedUser.session_epoch, currentUser.session_epoch) ||
getRememberLoginFingerprint(expectedUser) !== getRememberLoginFingerprint(currentUser) ||
((adminOnly || expectedUser.admin) && !currentUser.admin)) return denied;
if (!currentUser.admin) {
if (!await deps.userHasAccessToServer(req.session.user, serverName)) return denied;
const permissions = await deps.getEffectivePermsForUserOnServer(req.session.user, serverName);
if (!permissions?.server_reinstall) return denied;
}
// adpanel:reinstall-storage-owner - the canonical row must be the only
// panel record claiming the daemon directory, including legacy aliases.
if (node && await scanNodeStorageCollisions(deps, node, technicalName, {
includeIpLeg: !!String(node.address || "").trim(), uuidFallbackId: true, excludeName: expectedEntry?.name,
})) {
return {
ok: false, statusCode: 409, code: "reinstall-storage-conflict",
error: "The server's storage ownership is ambiguous. Contact an administrator before retrying.",
};
}
// adpanel:reinstall-dispatch-target - a snapshot checked before awaited
// allocation or signing retries is not permission to wipe a changed server.
return expectedEntry ? validateReinstallTarget(deps, expectedEntry) : { ok: true };
}
async function callAuthorizedReinstall(deps, req, expectedUser, serverName, { url, headers, payload }, options) {
const authorization = await validateReinstallAuthorization(deps, req, expectedUser, serverName, options);
if (!authorization.ok) return { authorization };
return deps.httpRequestJsonPruningUnknownFields(url, "POST", headers, payload, REINSTALL_NODE_TIMEOUT_MS, "node-reinstall",
() => validateReinstallAuthorization(deps, req, expectedUser, serverName, options));
}
function createReinstallSigningRetry({ nodeAdminSigningSecrets, ensureNodePanelHmacSecret, signPanelAdminReinstallHeaders, isLegacySigningRejection }) {
return async function retryReinstallAfterSigningRejection(node, headers, technicalName, templateId, doCall) {
const secrets = nodeAdminSigningSecrets(node);
let attempt = null;
if (secrets.length <= 1) return attempt;
const rotated = await ensureNodePanelHmacSecret(node);
if (rotated && signPanelAdminReinstallHeaders(headers, node, technicalName, templateId, { secret: secrets[0] })) {
attempt = await doCall();
if (!isLegacySigningRejection(attempt.res)) return attempt;
}
for (let secretIndex = 1; secretIndex < secrets.length; secretIndex += 1) {
for (const legacy of [false, true]) {
if (!signPanelAdminReinstallHeaders(headers, node, technicalName, templateId, { secret: secrets[secretIndex], legacy })) continue;
attempt = await doCall();
if (!isLegacySigningRejection(attempt.res)) return attempt;
}
}
return attempt;
};
}
// adpanel:reinstall-outcome - EULA consent gates starting Minecraft, not
// committing a rebuild that has already replaced the server's files.
function isNodeReinstallAwaitingEula(result, templateId) {
return templateId === "minecraft" && result?.status === 409 &&
result.json?.code === "minecraft_eula_required";
}
function isNodeReinstallComplete(result, templateId) {
return (result?.status === 200 && result.json?.ok === true) || isNodeReinstallAwaitingEula(result, templateId);
}
function getNodeReinstallPowerState(result, templateId) {
const body = result?.json;
if (isNodeReinstallAwaitingEula(result, templateId)) return "stopped";
if (isNodeReinstallComplete(result, templateId)) {
if (body.serverStopped === true) return "stopped";
if (body.serverRunning === true) return "running";
} else if (result?.status >= 400 && body?.ok === false &&
(body.serverStopped === true || (result.status === 500 && body.reinstalled === true && body.code === "reinstall_install_failed"))) {
return "stopped";
}
return null;
}
const PERSISTED_REINSTALL_FAILURES = Object.freeze({
reinstall_start_failed: { status: 500, code: "reinstall-start-failed", reason: "the container could not start" },
reinstall_start_unconfirmed: { status: 500, code: "reinstall-start-unconfirmed", reason: "container startup could not be confirmed" },
reinstall_install_failed: { status: 500, code: "reinstall-install-failed", reason: "the template installer did not complete" },
reinstall_cleanup_failed: { status: 500, code: "reinstall-cleanup-failed", reason: "the previous files could not be fully removed" },
reinstall_image_pull_failed: { status: 500, code: "reinstall-image-pull-failed", reason: "the runtime image could not be prepared" },
reinstall_jar_resolution_failed: { status: 500, code: "reinstall-jar-resolution-failed", reason: "the Minecraft jar could not be resolved" },
reinstall_download_failed: { status: 500, code: "reinstall-download-failed", reason: "the Minecraft jar could not be downloaded" },
reinstall_disk_limit_exceeded: { status: 507, code: "reinstall-disk-limit-exceeded", reason: "the Minecraft jar exceeds the storage allowance" },
});
// adpanel:reinstall-partial-commit - a startup failure after a persisted
// rebuild still owns its new port and template, but must never mean success.
function getNodeReinstallFailure(result, templateId) {
if (isNodeReinstallComplete(result, templateId)) return null;
const body = result?.json;
if (result?.status === 409 && body?.ok === false && REINSTALL_CONFIRMED_CONFLICTS.has(body.code)) {
return {
ok: false, statusCode: 409, code: body.code,
error: body.error || "Another server operation is in progress. Try again after it completes.",
...(body.detail ? { detail: body.detail } : {}),
};
}
const persistedFailure = Object.hasOwn(PERSISTED_REINSTALL_FAILURES, body?.code)
? PERSISTED_REINSTALL_FAILURES[body.code] : null;
const legacyStartFailure = result?.status === 500 && body?.ok === false &&
body.error === "server files reinstalled but container failed to start";
const failure = body?.ok === false && body.reinstalled === true && persistedFailure?.status === result?.status
? persistedFailure : (legacyStartFailure ? PERSISTED_REINSTALL_FAILURES.reinstall_start_failed : null);
if (failure) {
return {
ok: false, statusCode: 502, code: failure.code, reinstalled: true,
error: `Server files were replaced, but ${failure.reason}. Check the console or contact an administrator before retrying.`,
};
}
if (!result?.status || (result.status >= 200 && result.status < 300) || [502, 503, 504].includes(result.status) ||
body?.code === "reinstall_startup_pending" || body?.code === "reinstall_operation_recorded" ||
(result.status >= 500 && body?.ok !== false)) {
return {
ok: false, statusCode: 502, code: "reinstall-result-unconfirmed",
error: "The node did not confirm the reinstall result. It may still be running or may have completed. Check the server state before retrying.",
};
}
return {
ok: false, statusCode: 502,
error: String(body?.error || body?.detail || `reinstall failed (${result?.status || 0})`),
};
}
// adpanel:reinstall-dispatch-journal - reserve both the previous and proposed
// allocations until the node outcome and the panel row agree.
async function reserveReinstallDispatch(db, entry, node, technicalName, payload, update = null) {
const operationId = randomBytes(16).toString("hex");
const acceptUntil = Date.now() + REINSTALL_ADMISSION_MS;
const intent = JSON.stringify({ technicalName, nodeUuid: node.uuid || node.id, acceptUntil, update });
const inserted = await db.query(
`INSERT INTO server_reinstall_dispatch (server_id, operation_id, host_port, template_id, intent)
SELECT id, ?, ?, ?, ? FROM servers WHERE id = ? AND name = ? AND node_id = ? AND LOWER(status) = 'reinstalling'`,
[operationId, payload.hostPort, payload.templateId, intent, entry.rowId, entry.name, entry.nodeId],
);
if (inserted?.affectedRows !== 1) throw new Error("Could not reserve reinstall dispatch for the claimed server");
return { ...payload, operationId, acceptUntil };
}
async function clearReinstallDispatch(db, rowId, operationId) {
await db.query("DELETE FROM server_reinstall_dispatch WHERE server_id = ? AND operation_id = ?", [rowId, operationId]);
}
async function readReinstallDispatchResult({ httpRequestJson }, { url, headers, operationId, acceptUntil, hostPort, templateId }) {
const params = new URLSearchParams({ id: operationId, acceptUntil: String(acceptUntil) });
const result = await httpRequestJson(`${url}-result?${params}`, "GET", headers, null, REINSTALL_RESULT_TIMEOUT_MS);
const body = result?.json;
if (result?.status !== 200 || body?.operationId !== operationId) return null;
const powerState = ["running", "stopped", "unknown"].includes(body.powerState) ? body.powerState : null;
if (body.state === "absent" && Date.now() > acceptUntil) {
return { absent: true, powerState };
}
if (body.state !== "completed" || body.hostPort !== hostPort || body.template !== templateId) return null;
if (body.outcome === "eula" && templateId === "minecraft") {
return { result: { status: 409, json: { ok: false, code: "minecraft_eula_required" } }, powerState };
}
if (body.outcome !== "running" && body.outcome !== "stopped") return null;
return { result: { status: 200, json: { ok: true, serverRunning: body.outcome === "running", serverStopped: body.outcome === "stopped" } }, powerState };
}
async function settleReinstallDispatch(deps, entry, { url, headers, payload }, attempt) {
if (attempt.authorization) {
await clearReinstallDispatch(deps.db, entry.rowId, payload.operationId);
return attempt;
}
const failure = getNodeReinstallFailure(attempt.res, payload.templateId);
if (failure?.code === "reinstall-result-unconfirmed") {
const recovered = await readReinstallDispatchResult(deps, { url, headers, ...payload });
if (recovered?.result) return { res: recovered.result, powerState: recovered.powerState };
if (!recovered?.absent) return attempt;
await clearReinstallDispatch(deps.db, entry.rowId, payload.operationId);
return { ...attempt, powerState: recovered.powerState, failure: {
ok: false, statusCode: 502, code: "reinstall-not-applied",
error: "The node confirmed that the reinstall did not commit replacement files. Check the server state before retrying.",
} };
}
if (failure && !failure.reinstalled) await clearReinstallDispatch(deps.db, entry.rowId, payload.operationId);
return attempt;
}
function buildReinstallTemplateUpdate(templateId, template, docker) {
const start = { minecraft: "server.jar", nodejs: "index.js", "discord-bot": "index.js", python: "main.py" };
const update = { template: String(template.id || templateId), start: Object.hasOwn(start, templateId) ? start[templateId] : null };
if (docker) {
update.docker = docker;
update.runtime = {
image: docker.image, tag: docker.tag, command: docker.command, volumes: docker.volumes,
workdir: docker.workdir, env: docker.env, ports: docker.ports, portProtocols: docker.portProtocols,
restart: docker.restart, runAsRoot: docker.runAsRoot === true, console: docker.console,
adpanelStartup: docker.adpanelStartup, startupDisplay: docker.startupDisplay, install: docker.install,
};
}
return update;
}
// adpanel:reinstall-index-commit - a rebuild only owns its claimed row and
// must never overwrite unrelated rows, permissions or suspension state.
async function commitCompletedReinstall(deps, expectedEntry, { reboundHostPort = null, updateEntry = (entry) => entry, reinstalled = true, operationId = null, finalStatus = null, absent = false } = {}) {
const failed = {
ok: false, statusCode: 500, code: "reinstall-index-save-failed", reinstalled,
error: reinstalled
? "Server files were reinstalled, but the panel record could not be saved. Contact an administrator before retrying."
: "Failed to save the server's panel record.",
};
try {
return await deps.withServersIndexWriteLock(async () => {
const connection = await deps.db.pool.getConnection();
try {
await connection.beginTransaction();
const [rows] = await connection.execute("SELECT * FROM servers WHERE name = ? FOR UPDATE", [expectedEntry.name]);
const entry = deps.mapServerRow(rows[0]);
if (!entry || entry.name !== expectedEntry.name || entry.rowId !== expectedEntry.rowId ||
entry.nodeId !== expectedEntry.nodeId || String(entry.status || "").toLowerCase() !== "reinstalling") {
await connection.rollback();
return {
ok: false, statusCode: entry || reinstalled ? 409 : 404, code: entry ? "reinstall-index-target-changed" : "reinstall-index-entry-missing", reinstalled,
error: reinstalled
? "Server files were reinstalled, but the panel record is no longer available for this operation. Contact an administrator before retrying."
: (entry ? "server state changed; reload the server before retrying" : "server not found"),
};
}
const updatedEntry = { ...updateEntry(entry) };
if (reboundHostPort != null) updatedEntry.port = reboundHostPort;
delete updatedEntry.startupCommand;
for (const field of ["runtime", "docker"]) {
if (updatedEntry[field] && typeof updatedEntry[field] === "object") {
updatedEntry[field] = { ...updatedEntry[field] };
delete updatedEntry[field].startupCommand;
}
}
const [result] = absent ? [{ affectedRows: 1 }] : await connection.execute(
"UPDATE servers SET port = ?, template = ?, start = ?, runtime = ?, docker = ? WHERE id = ?",
[updatedEntry.port ?? null, updatedEntry.template ?? null, updatedEntry.start ?? null,
deps.toDbJson(updatedEntry.runtime), deps.toDbJson(updatedEntry.docker), entry.rowId],
);
if (result?.affectedRows !== 1) throw new Error("Reinstall commit did not match the locked server row");
if (operationId) {
const [dispatch] = await connection.execute("DELETE FROM server_reinstall_dispatch WHERE server_id = ? AND operation_id = ?", [entry.rowId, operationId]);
if (dispatch?.affectedRows !== 1) throw new Error("Reinstall commit did not match the reserved dispatch");
}
if (finalStatus) await connection.execute("UPDATE servers SET status = ? WHERE id = ?", [entry.suspended ? "stopped" : finalStatus, entry.rowId]);
await connection.commit();
deps.invalidateServerIndexCache();
return { ok: true, server: updatedEntry };
} catch (error) {
try { await connection.rollback(); } catch { }
throw error;
} finally {
connection.release();
}
});
} catch (error) {
(deps.logger || console).error("[reinstall] Completed rebuild index commit failed:", error);
return failed;
}
}
async function recoverPendingReinstall(deps, name) {
const entry = await deps.findServer(name);
if (!entry) return false;
const [dispatch] = await deps.db.query("SELECT operation_id, host_port, template_id, intent FROM server_reinstall_dispatch WHERE server_id = ?", [entry.rowId]);
if (!dispatch) return false;
const intent = typeof dispatch.intent === "string" ? JSON.parse(dispatch.intent) : dispatch.intent;
if (!intent || !entry.nodeId || getReinstallNodeServerName(entry, name) !== intent.technicalName) return true;
const node = await deps.findNodeByIdOrName(entry.nodeId);
if (!node || (node.uuid || node.id) !== intent.nodeUuid) return true;
await withReinstallNodePortLock(deps, node, async (freshNode) => {
if (!freshNode) return;
const transport = validateReinstallTransport(deps.buildNodeBaseUrl(freshNode.address, freshNode.api_port || 8080, freshNode.ssl_enabled, deps.nodeUnderCloudflare(freshNode)));
if (!transport.ok) return;
const recovered = await readReinstallDispatchResult(deps, {
url: `${transport.baseUrl}/v1/servers/${encodeURIComponent(intent.technicalName)}/reinstall`, headers: deps.nodeAuthHeadersFor(freshNode, true),
operationId: dispatch.operation_id, hostPort: Number(dispatch.host_port), templateId: dispatch.template_id, acceptUntil: intent.acceptUntil,
});
if (!recovered) return;
const powerState = recovered.powerState || (recovered.absent ? "unknown" : getNodeReinstallPowerState(recovered.result, dispatch.template_id));
const commit = await commitCompletedReinstall(deps, entry, {
operationId: dispatch.operation_id, finalStatus: powerState, reinstalled: !recovered.absent, absent: recovered.absent,
reboundHostPort: Number(dispatch.host_port), updateEntry: (current) => ({ ...current, ...intent.update }),
});
if (commit.ok) {
await deps.setCachedServerStatus(name, { nodeId: entry.nodeId, status: commit.server.suspended ? "stopped" : powerState });
}
});
return true;
}
async function recordReinstallActivity({ recordActivity, logger = console }, { name, templateId, email, actorLabel, ip, templateChange = false, failureCode }) {
const action = templateChange ? "server_template_change" : "reinstall";
const event = failureCode ? `${action}_failed` : action;
const details = failureCode ? { templateId, filesReplaced: true, code: failureCode }
: templateChange ? { changedBy: email, templateId } : `Server reinstalled by ${actorLabel || "unknown"}`;
try {
await recordActivity(name, event, details, email, ip);
if (templateChange) await recordActivity("_system", event, { server: name, ...details }, email, ip);
} catch (error) {
logger.warn("[reinstall] Failed to record activity:", error);
}
}
// adpanel:reinstall-release-containment - cleanup runs after the response
// is determined; its failure must not become a second response or rejection.
async function releaseReinstallClaim({ releaseReinstallOperation, setCachedServerStatus, logger = console }, serverName, prevStatus, { powerState, nodeId } = {}) {
try {
const release = await releaseReinstallOperation(serverName, powerState || prevStatus);
if (powerState && release?.restored) await setCachedServerStatus(serverName, { status: release.status || powerState, nodeId });
} catch (error) {
logger.error("[reinstall] Failed to release operation claim:", error);
}
}
module.exports = { getReinstallNodeServerName, acquireReinstallTemplateLock, withReinstallNodePortLock, resolveReinstallHostPort, validateReinstallTarget, validateReinstallTransport, validateReinstallAuthorization, callAuthorizedReinstall, createReinstallSigningRetry, isNodeReinstallAwaitingEula, isNodeReinstallComplete, getNodeReinstallPowerState, getNodeReinstallFailure, buildReinstallTemplateUpdate, reserveReinstallDispatch, settleReinstallDispatch, commitCompletedReinstall, recoverPendingReinstall, recordReinstallActivity, releaseReinstallClaim };