Files
Kelx/tests/update-plane-hardening.test.js
2026-11-30 16:32:37 +00:00

4337 lines
218 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";
// Tests for the update-plane hardening (panel + node update/install audit).
//
// The update surface previously differed from the rest of the destructive
// admin plane in every dimension that matters: installs needed only an admin
// session plus an action token (which any session can mint), downgrades were
// logged and permitted, the panel used a weaker unanchored version regex than
// the node path, panel-information.json (the version bookkeeping) was itself
// updatable by the payload it measures, downloads followed https→http
// redirects, extraction wrote through pre-planted symlinks, had no backup /
// rollback and no uncompressed-size budget, and the only rate limit was the
// global one.
//
// This file pins every one of those closures:
// - panel-information.json and .update-backups live in PROTECTED_FILES and
// panel-information.json is gone from UPDATABLE_PATHS;
// - installPanelUpdateInternal uses the strict isValidUpdateVersion,
// refuses strictly older targets (409) while keeping same-version repair
// installs, downloads with requireHttps and verifies the artifact against
// the integrity anchors before extraction;
// - extraction is bounded (declared-size pre-pass, per-entry inflate cap,
// actual-size accounting), resolves parents through symlinks (realpath
// containment), refuses symlink targets (lstat + O_NOFOLLOW), backs up
// every overwritten file and rolls back on failure;
// - the panel and node install routes mount the dedicated install limiter
// plus the credential limiter, the action-token gate, and the destructive
// action step-up (with a one-time token re-mint in the challenge body);
// the auto routes step-up only the disable direction; the check/auto
// routes carry the lightweight update-action limiter;
// - installNodeUpdateInternal resolves the node's live version and refuses
// downgrades before preparing the payload;
// - compareVersions orders prereleases per semver while keeping the
// historical (b − a) sign convention;
// - settings.js rides sendGuardedRequestWithStepUp for installs and the
// disable direction of both auto toggles, re-stashing the re-minted
// one-time token on every challenge.
// Integrity pins (data/update-checksums.json) are exercised end-to-end
// through the real file read: mismatch and requirePinned refusals happen
// before a single byte is extracted.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const vm = require("node:vm");
const crypto = require("node:crypto");
const zlib = require("node:zlib");
const { execFile, spawn } = require("node:child_process");
const { promisify } = require("node:util");
const AdmZip = require("adm-zip");
const { normalizeUpdateVersionTag, isValidUpdateVersion, isValidNodeUpdateVersion, compareVersions, isUpdateDowngrade, getLatestStableRelease } = require("../utils/update-version");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
const SETTINGS_EJS = path.join(ROOT, "views", "settings.ejs");
const CHECKSUMS_FILE = path.join(ROOT, "data", "update-checksums.json");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8");
const coordinatorSource = fs.readFileSync(path.join(ROOT, "services", "panel-update-coordinator.js"), "utf8");
const launcherPath = path.join("scripts", "panel-update-recovery.cjs");
const recoverySource = fs.readFileSync(path.join(ROOT, launcherPath), "utf8");
const panelFilesMarker = "async function applyPanelReleaseFiles(targetRelease, cleanTargetVersion, source, begin) {";
const execFileAsync = promisify(execFile);
// Slice a `{ ... }`-balanced block starting at startMarker. The marker may or
// may not include its opening brace: when it ends with "{", that brace opens
// the block; otherwise the first "{" after the marker does. (Starting the
// balance scan at the FIRST brace anywhere after the marker would stop at
// default-parameter `{}` in signatures such as `(url, opts = {}) {`.)
function extractBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
let depth;
let i;
if (startMarker.endsWith("{")) {
depth = 1;
i = start + startMarker.length;
} else {
i = start + startMarker.length;
while (i < source.length && /\s/.test(source[i])) i += 1;
assert.ok(i < source.length && source[i] === "{", `no opening brace after: ${startMarker}`);
depth = 1;
i += 1;
}
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 extractRoute(source, routeMarker, nextRouteMarker) {
const start = source.indexOf(routeMarker);
assert.ok(start >= 0, `route marker not found: ${routeMarker}`);
const end = source.indexOf(nextRouteMarker, start);
assert.ok(end > start, `next route marker not found after route: ${nextRouteMarker}`);
return source.slice(start, end);
}
function sliceBetween(source, startMarker, endMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `start marker not found: ${startMarker}`);
const end = source.indexOf(endMarker, start);
assert.ok(end > start, `end marker not found after start: ${endMarker}`);
return source.slice(start, end);
}
function sha256Hex(buffer) {
return crypto.createHash("sha256").update(buffer).digest("hex");
}
function makeTempPanelRoot() {
return fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-update-test-"));
}
// ---------------------------------------------------------------------------
// Static wiring: protected files, call-site policy, client contracts
// ---------------------------------------------------------------------------
test("panel-information.json and .update-backups are protected; panel-information.json is not updatable", () => {
const protectedBlock = sliceBetween(
indexSource,
"const PROTECTED_FILES = new Set([",
"const UPDATABLE_PATHS = new Set(["
);
assert.match(protectedBlock, /"panel-information\.json"/, "the version bookkeeping file must be protected from updates");
assert.match(protectedBlock, /"\.update-backups"/, "rollback snapshots must be protected from updates");
const updatableBlock = sliceBetween(
indexSource,
"const UPDATABLE_PATHS = new Set([",
"const UPDATABLE_DIRS = "
);
assert.doesNotMatch(updatableBlock, /"panel-information\.json"/, "the version bookkeeping file must not be updatable by updates");
assert.match(updatableBlock, /"index\.js"/);
});
test("both release downloads pin the whole chain to https", () => {
const httpGetRawBlock = extractBlock(indexSource, "function httpGetRaw(url, opts = {}) {");
assert.match(httpGetRawBlock, /require\("\.\/utils\/remote-http"\)/, "the buffered getter must delegate to its shared owning module");
assert.match(httpGetRawBlock, /\.httpGetRaw\(url, opts\)/, "the adapter must forward the https-only option unchanged");
const remoteSource = fs.readFileSync(path.join(__dirname, "..", "utils", "remote-http.js"), "utf8");
assert.match(remoteSource, /opts\.requireHttps === true/, "the shared getter must expose the requireHttps option");
assert.match(remoteSource, /if \(requireHttps && parsedUrl\.protocol !== "https:"\)/, "non-https hops must be refused");
assert.match(
remoteSource,
/visit\(nextUrl, redirectCount \+ 1\)\.catch\(fail\)/,
"redirect hops must stay inside the same https-policy and deadline closure"
);
const installBlock = extractBlock(indexSource, panelFilesMarker);
assert.match(installBlock, /requireHttps: true/, "panel release download must require https");
const nodePayloadBlock = extractBlock(indexSource, "async function prepareNodeUpdatePayload(targetVersion) {");
assert.match(nodePayloadBlock, /requireHttps: true/, "node release download must require https");
});
test("panel install uses the strict anchored version validator, not the old prefix regex", () => {
const installBlock = extractBlock(indexSource, 'async function installPanelUpdateInternal(targetVersion, source = "manual", checkedRelease) {');
assert.match(installBlock, /isValidUpdateVersion\(cleanTargetVersion\)/, "panel install must use the strict validator");
assert.doesNotMatch(installBlock, /\/\^v\?\\d\+\\\.\d\+\\\.\d\+\//, "the weak unanchored prefix regex must be gone");
});
test("panel install refuses downgrades before any release lookup or download", () => {
const installBlock = extractBlock(indexSource, 'async function installPanelUpdateInternal(targetVersion, source = "manual", checkedRelease) {');
const downgradeIdx = installBlock.indexOf("downgrade refused");
const releasesIdx = installBlock.indexOf("fetchPanelRelease(cleanTargetVersion)");
const applyIdx = installBlock.indexOf("applyPanelRelease(");
assert.ok(downgradeIdx > 0, "downgrade protection must be present");
assert.ok(releasesIdx > downgradeIdx, "the downgrade check must run before the release lookup");
assert.ok(applyIdx > releasesIdx, "the downgrade and release checks must run before delegating to the download");
assert.match(installBlock, /isUpdateDowngrade\(currentVersion, cleanTargetVersion\)/, "the downgrade gate must share the release parser");
assert.match(installBlock, /statusCode = 409/, "a downgrade is a client-side conflict, not a server error");
});
test("panel install verifies artifact integrity before extraction", () => {
const installBlock = extractBlock(indexSource, panelFilesMarker);
const verifyIdx = installBlock.indexOf("verifyUpdateArtifactIntegrity({");
const admZipIdx = installBlock.indexOf('require("adm-zip")');
assert.ok(verifyIdx > 0, "integrity verification must be present");
assert.match(installBlock, /channel: "panel"/);
assert.ok(admZipIdx > verifyIdx, "nothing may be decompressed before the artifact is verified");
assert.match(installBlock, /if \(!integrity\.ok\)/, "a failed verification must abort the install");
});
test("panel extraction carries the zip budget, parent containment, no-follow writes, backup and rollback", () => {
const installBlock = extractBlock(indexSource, panelFilesMarker);
const stageBlock = sliceBetween(recoverySource, " function openStage(id)", " function discardStage(id)");
const publishBlock = sliceBetween(recoverySource, " function publishStagedRelease(id, worker, deadlineAt)", " function begin(id, snapshotSources)");
assert.match(installBlock, /PANEL_UPDATE_MAX_TOTAL_UNCOMPRESSED/, "declared-size budget must be enforced");
assert.match(installBlock, /getUpdateEntryDataCapped\(entry, PANEL_UPDATE_MAX_ENTRY_UNCOMPRESSED\)/, "per-entry inflate must be capped");
assert.match(installBlock, /stageFile\(normalizedRelative, data\)/, "the installer stages files without touching the live tree");
assert.match(stageBlock, /checkPanelUpdateParent\(panelRoot, live\)\) updateTargetType\(live\)/, "staging refuses blocked live destinations");
assert.match(publishBlock, /checkPanelUpdateParent\(panelRoot, target, false, parent => \{[\s\S]*?snapshot\(id, parent, false, true\)/, "publish journals missing directories before creating them");
assert.match(publishBlock, /checkPanelUpdateParent\(panelRoot, target, true, parent => \{\s*if \(!directories\.has\(parent\)\) throw/, "publish refuses unjournaled parent creation");
const publishIdx = publishBlock.indexOf("writePanelUpdateFileNoFollow(target, data, { temporaryPath })");
const snapshotIdx = publishBlock.indexOf("snapshot(id, relative, parentExists && !!updateTargetType(target))");
assert.ok(snapshotIdx > 0 && snapshotIdx < publishIdx, "publish must flush the snapshots before the no-follow replacements");
assert.match(publishBlock, /snapshotTemporary\(temporaryPath\);\s*}\s*snapshotTemporary\(metadataTemporary\);\s*}\);/);
assert.match(coordinatorSource, /state\.recover\(id \|\| current\.pending\.id, reason\)/, "a failed extraction must discard its private stage");
assert.match(publishBlock, /enrollTrial\(id, worker, deadlineAt, true\)/, "publication must enroll under the journal without reopening the restart phase");
assert.match(recoverySource, /pruneBackups\(id\)/, "old snapshots must be pruned without touching the active backup");
assert.match(installBlock, /sha256: integrity\.computed/, "the installed artifact hash must be reported");
});
test("installNodeUpdateInternal resolves the node version and refuses downgrades before preparing the payload", () => {
const block = extractBlock(indexSource, "async function installNodeUpdateInternal(node, targetVersion, source = \"manual\") {");
const downgradeIdx = block.indexOf("downgrade refused");
const prepareIdx = block.indexOf("prepareNodeUpdatePayload(targetVersion)");
assert.ok(downgradeIdx > 0, "node downgrade protection must be present");
assert.ok(prepareIdx > downgradeIdx, "the version check must run before the archive is downloaded");
assert.match(block, /fetchNodeRuntimeInfo\(node\)/, "the node's live version is the source of truth");
assert.match(block, /statusCode = 409/);
});
test("prepareNodeUpdatePayload verifies node artifact integrity", () => {
const block = extractBlock(indexSource, "async function prepareNodeUpdatePayload(targetVersion) {");
const verifyIdx = block.indexOf("verifyUpdateArtifactIntegrity({");
assert.ok(verifyIdx > 0, "node artifact integrity verification must be present");
assert.match(block, /channel: "node"/);
assert.match(block, /if \(!integrity\.ok\)/);
});
// ---------------------------------------------------------------------------
// Route contracts: limiters, token gates, step-up gates, ordering
// ---------------------------------------------------------------------------
test("panel install route: install limiter + credential limiter + token gate + step-up before install", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/panel-update/install"',
'app.post("/api/settings/panel-update/auto"'
);
assert.match(
route,
/app\.post\("\/api\/settings\/panel-update\/install", updateInstallRateLimiter, sessionRevoke2faRateLimiter, async/,
"route must mount the dedicated install limiter and the credential limiter"
);
assert.match(
route,
/requireActionTokenOr403\(req, res, "POST \/api\/settings\/panel-update\/install"\)/,
"route must still verify the action token (CSRF layer)"
);
const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/panel-update/install")');
const userIdx = route.indexOf("findUserByEmail(req.session.user)");
const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser");
const installIdx = route.indexOf("installPanelUpdate(targetVersion");
assert.ok(userIdx > tokenIdx, "the acting admin must be resolved after the token gate");
assert.ok(stepUpIdx > userIdx, "step-up must come after the token gate");
assert.ok(installIdx > stepUpIdx, "the install itself must come after the step-up gate");
const stepUpCall = route.slice(stepUpIdx, installIdx);
assert.match(stepUpCall, /"Panel update install"/);
assert.match(
stepUpCall,
/failureResponseExtras/,
"the challenge response must re-mint the consumed one-time install token"
);
assert.match(stepUpCall, /installUpdate: issueActionToken\(req, "POST \/api\/settings\/panel-update\/install", \{\}, \{ ttlSeconds: 600, oneTime: true \}\)/);
});
test("panel auto route: action limiter + credential limiter, step-up only when disabling", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/panel-update/auto"',
"async function fetchNodeReleases() {"
);
assert.match(
route,
/app\.post\("\/api\/settings\/panel-update\/auto", updateActionRateLimiter, sessionRevoke2faRateLimiter, async/,
"route must mount the lightweight action limiter and the credential limiter"
);
const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/panel-update/auto")');
const disableIdx = route.indexOf("if (!enabled) {");
const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser");
const saveIdx = route.indexOf("setPanelAutoUpdateEnabled(enabled)");
assert.ok(tokenIdx > 0 && disableIdx > tokenIdx, "the token gate must precede the toggle");
assert.ok(stepUpIdx > disableIdx, "the disable-direction step-up must sit inside the !enabled branch");
assert.ok(saveIdx > stepUpIdx, "the setting must only be written after the step-up gate");
assert.match(route, /"Panel auto-update disable"/);
});
test("panel check route: lightweight action limiter", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/panel-update/check"',
'app.post("/api/settings/panel-update/install"'
);
assert.match(route, /app\.post\("\/api\/settings\/panel-update\/check", updateActionRateLimiter, async/);
});
test("node install route: install limiter + credential limiter + token gate + node-scoped step-up", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/node-update/install"',
'app.post("/api/settings/node-update/auto"'
);
assert.match(
route,
/app\.post\("\/api\/settings\/node-update\/install", updateInstallRateLimiter, sessionRevoke2faRateLimiter, async/,
"route must mount the dedicated install limiter and the credential limiter"
);
const tokenIdx = route.indexOf('requireActionTokenOr403(req, res, "POST /api/settings/node-update/install", resource)');
const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser");
const installIdx = route.indexOf("installNodeUpdateInternal(node, targetVersion");
assert.ok(stepUpIdx > tokenIdx, "step-up must come after the token gate");
assert.ok(installIdx > stepUpIdx, "the install must come after the step-up gate");
const stepUpCall = route.slice(stepUpIdx, installIdx);
assert.match(stepUpCall, /scopeKey: nodeStepUpScopeKey\(node, nodeId\)/, "the grant must be bound to the node");
assert.match(stepUpCall, /failureResponseExtras/, "the challenge must re-mint the consumed one-time token");
assert.match(stepUpCall, /installUpdate: issueActionToken\(req, "POST \/api\/settings\/node-update\/install", resource, \{ ttlSeconds: 600, oneTime: true \}\)/);
});
test("node auto route: action limiter + credential limiter, step-up only when disabling", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/node-update/auto"',
"const {\n AI_PROVIDER_CONFIGS,"
);
assert.match(
route,
/app\.post\("\/api\/settings\/node-update\/auto", updateActionRateLimiter, sessionRevoke2faRateLimiter, async/
);
const disableIdx = route.indexOf("if (!enabled) {");
const stepUpIdx = route.indexOf("requireDestructiveActionStepUp(req, res, currentUser");
const callIdx = route.indexOf('callNodeUpdateApi(node, "/v1/update/auto"');
assert.ok(disableIdx > 0 && stepUpIdx > disableIdx, "the disable-direction step-up must sit inside the !enabled branch");
assert.ok(callIdx > stepUpIdx, "the node call must come after the step-up gate");
assert.match(route, /`Node auto-update disable/);
});
test("node check route: lightweight action limiter", () => {
const route = extractRoute(
indexSource,
'app.post("/api/settings/node-update/check"',
'app.post("/api/settings/node-update/install"'
);
assert.match(route, /app\.post\("\/api\/settings\/node-update\/check", updateActionRateLimiter, async/);
});
// ---------------------------------------------------------------------------
// Rate limiter configs (vm sandbox with a stubbed express-rate-limit)
// ---------------------------------------------------------------------------
function runLimiter(marker) {
let captured = null;
const sandbox = {
rateLimit: (config) => {
captured = config;
return function middleware() { };
},
getRequestIp: () => "203.0.113.7",
securityLog: () => { },
console: { log() { }, warn() { }, error() { } },
// adpanel:per-limiter-redis-stores — the swept limiters reference the
// boot-time Redis client and the store factory. The harness has no
// Redis: a null client ⇒ `store: undefined` ⇒ the same MemoryStore
// fallback a Redis-less boot takes, so the assertions below keep
// pinning windowMs/max/keyGenerator exactly as before.
redisClient: null,
buildSharedRateLimitRedisStore: () => undefined,
buildAssistantRedisStore: () => undefined,
};
vm.createContext(sandbox);
vm.runInContext(extractBlock(indexSource, marker), sandbox);
assert.ok(captured, `${marker} did not run`);
return captured;
}
test("updateInstallRateLimiter: 10 per 15 minutes keyed per email+session, no skip (installs are always expensive)", () => {
const limiter = runLimiter("const updateInstallRateLimiter = rateLimit(");
assert.equal(limiter.windowMs, 15 * 60 * 1000);
assert.equal(limiter.max, 10);
assert.equal(limiter.skip, undefined, "every install attempt must count, credential or not");
const req = { session: { user: "User@Example.com" }, sessionID: "sid-1" };
assert.equal(limiter.keyGenerator(req), "update-install:user@example.com:sid-1");
let statusCode = 0;
let payload = null;
const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } };
limiter.handler(req, res);
assert.equal(statusCode, 429);
assert.equal(payload.code, "update-install-rate-limit");
});
test("updateActionRateLimiter: 30 per 10 minutes keyed per email+session", () => {
const limiter = runLimiter("const updateActionRateLimiter = rateLimit(");
assert.equal(limiter.windowMs, 10 * 60 * 1000);
assert.equal(limiter.max, 30);
const req = { session: { user: "User@Example.com" }, sessionID: "sid-2" };
assert.equal(limiter.keyGenerator(req), "update-action:user@example.com:sid-2");
let statusCode = 0;
let payload = null;
const res = { status(c) { statusCode = c; return { json(p) { payload = p; } }; } };
limiter.handler(req, res);
assert.equal(statusCode, 429);
assert.equal(payload.code, "update-rate-limit");
});
// ---------------------------------------------------------------------------
// Shared update version semantics
// ---------------------------------------------------------------------------
test("compareVersions keeps the historical sign convention: positive when b is newer", () => {
assert.ok(compareVersions("v1.0.0", "v1.1.0") > 0, "b newer must be positive");
assert.ok(compareVersions("v1.1.0", "v1.0.0") < 0, "a newer must be negative");
assert.equal(compareVersions("v1.0.0", "1.0.0"), 0, "v-prefix and bare forms are equal");
});
test("compareVersions orders prereleases per semver instead of ignoring them", () => {
// Sign convention: compareVersions(a, b) > 0 means b is the newer one.
assert.ok(compareVersions("v1.2.3", "v1.2.3-rc.1") < 0, "a release is newer than its own prerelease (b is the rc)");
assert.ok(compareVersions("v1.2.3-rc.1", "v1.2.3") > 0);
assert.ok(compareVersions("v1.2.3-alpha", "v1.2.3-alpha.1") > 0, "a longer prerelease list outranks its prefix (b carries the extra identifier)");
assert.ok(compareVersions("v1.2.3-alpha.1", "v1.2.3-alpha") < 0);
assert.ok(compareVersions("v1.2.3-alpha.1", "v1.2.3-beta") > 0, "beta (b) outranks alpha.1 (a)");
assert.ok(compareVersions("v1.2.3-1", "v1.2.3-alpha") > 0, "numeric identifiers sort below alphanumeric (alpha is newer)");
assert.ok(compareVersions("v1.2.3-rc.2", "v1.2.3-rc.10") > 0, "numeric identifiers compare numerically (rc.10 is newer)");
assert.equal(compareVersions("v1.2.3-rc.1+build.5", "v1.2.3-rc.1"), 0, "build metadata is ignored");
assert.ok(compareVersions("v2.0.0-rc1", "v2.0.0") !== 0, "an rc must not compare equal to its release");
assert.ok(compareVersions("v2.0.0-rc1", "v2.0.0") > 0, "the release (b) outranks its rc (a)");
});
test("compareVersions degrades safely for unparseable and unusual versions", () => {
assert.ok(compareVersions("unknown", "v0.0.1") > 0, "unparseable counts as 0.0.0 (update available)");
assert.equal(compareVersions("v1.2.3.4", "v1.2.3.5"), 0, "four-part tags fall back to their numeric prefix (1.2.3)");
assert.ok(compareVersions("v1.2.3.9", "v1.2.4") > 0, "the prefix fallback still orders against real releases");
});
test("release validation and downgrade ordering agree on accepted SemVer tags", () => {
for (const version of ["v1.0.0", "1.0.0", "v1.0.0-rc.1", "v1.0.0+build.7", "v1.0.0-rc.1+build.7"]) {
assert.equal(isValidUpdateVersion(version), true);
assert.ok(compareVersions("v2.0.0", version) < 0);
assert.equal(isUpdateDowngrade("v2.0.0", version), true);
}
for (const version of ["unknown", "", "v1.0", "latest", "v1.0.0-preview_name", "v1.00.0"]) {
assert.equal(isValidUpdateVersion(version), false);
}
assert.equal(isUpdateDowngrade("v2.0.0.4", "v1.9.9"), true);
assert.equal(isUpdateDowngrade("v02.0.00", "v1.9.9"), true);
assert.equal(isUpdateDowngrade("unknown", "v0.0.1"), false);
});
test("stable release selection rejects invalid tags, drafts, and unflagged prereleases", () => {
const stable = { tag_name: "v1.2.3+build.1" };
assert.equal(getLatestStableRelease([null, stable, { tag_name: "v2.0.0-rc.1", prerelease: false },
{ tag_name: "v3.0.0", draft: true }, { tag_name: "v4.0.0-preview_name" }]), stable);
});
test("node update preflight preserves the deployed daemon's wire version format", async () => {
const block = extractBlock(indexSource, "async function prepareNodeUpdatePayload(targetVersion) {");
const sandbox = vm.createContext({ normalizeUpdateVersionTag, isValidNodeUpdateVersion,
fetchNodeReleases() { throw new Error("must reject before fetching releases"); } });
vm.runInContext(block, sandbox);
assert.equal(isValidUpdateVersion("v1.2.3-rc.1+build.5"), true);
assert.equal(isValidNodeUpdateVersion("v1.2.3-rc.1"), true);
assert.equal(isValidNodeUpdateVersion("v1.2.3+build.5"), true);
await assert.rejects(vm.runInContext("prepareNodeUpdatePayload('v1.2.3-rc.1+build.5')", sandbox), { statusCode: 400 });
});
// ---------------------------------------------------------------------------
// verifyUpdateArtifactIntegrity (vm sandbox over the real helpers)
// ---------------------------------------------------------------------------
function buildIntegritySandbox(pins) {
const source = sliceBetween(
indexSource,
"function sha256Hex(buffer) {",
"function isAllowedNodeReleasePath(relativePath) {"
);
const warned = [];
const logged = [];
const sandbox = {
crypto,
zlib,
normalizeUpdateVersionTag,
fs: {
lstatSync() { return pins == null ? undefined : { isSymbolicLink: () => false, isFile: () => true }; },
readFileSync() {
if (pins == null) throw Object.assign(new Error("no pins file"), { code: "ENOENT" });
return JSON.stringify(pins);
},
},
path,
Buffer,
console: {
log: (...a) => logged.push(a.join(" ")),
warn: (...a) => warned.push(a.join(" ")),
error: () => { },
},
UPDATE_CHECKSUMS_FILE: "/nonexistent/update-checksums.json",
__dirname: "/nonexistent",
};
vm.createContext(sandbox);
vm.runInContext(source, sandbox);
return { sandbox, warned, logged };
}
test("verifyUpdateArtifactIntegrity: without anchors the computed hash is reported and the artifact passes", () => {
const { sandbox, logged, warned } = buildIntegritySandbox(undefined);
const artifact = Buffer.from("artifact-bytes-1");
sandbox.__artifact = artifact;
const out = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: '', artifact: __artifact })",
sandbox
);
assert.equal(out.ok, true);
assert.equal(out.computed, sha256Hex(artifact));
assert.ok(
logged.concat(warned).join("\n").includes(sha256Hex(artifact)),
"the computed hash must always be reported (log or no-anchor warning)"
);
});
test("verifyUpdateArtifactIntegrity: a pinned mismatch is fatal; a pin match passes for v- and bare keys", () => {
const artifact = Buffer.from("artifact-bytes-2");
const hash = sha256Hex(artifact);
const bad = buildIntegritySandbox({ panel: { "v1.0.0": "0".repeat(64) } });
bad.sandbox.__artifact = artifact;
const outBad = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: '', artifact: __artifact })",
bad.sandbox
);
assert.equal(outBad.ok, false);
assert.match(outBad.error, /pinned sha256 mismatch/);
assert.ok(bad.warned.join("\n").includes("[SECURITY]"), "a pin mismatch is a security event");
const good = buildIntegritySandbox({ panel: { "1.0.0": hash } });
good.sandbox.__artifact = artifact;
const outGood = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: '', artifact: __artifact })",
good.sandbox
);
assert.equal(outGood.ok, true, "pins must match with or without the v prefix");
const node = buildIntegritySandbox({ node: { "v1.0.0": hash } });
node.sandbox.__artifact = artifact;
const outNode = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'node', version: 'v1.0.0', releaseBody: '', artifact: __artifact })",
node.sandbox
);
assert.equal(outNode.ok, true, "pins are per channel");
});
test("verifyUpdateArtifactIntegrity: requirePinned refuses unpinned artifacts; declared-body mismatch is a loud advisory", () => {
const artifact = Buffer.from("artifact-bytes-3");
const hash = sha256Hex(artifact);
const strict = buildIntegritySandbox({ requirePinned: true, panel: {} });
strict.sandbox.__artifact = artifact;
const outStrict = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: '', artifact: __artifact })",
strict.sandbox
);
assert.equal(outStrict.ok, false);
assert.match(outStrict.error, /no pinned sha256/);
const advisory = buildIntegritySandbox(null);
advisory.sandbox.__artifact = artifact;
const outAdvisory = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: 'sha256: " + "a".repeat(64) + "', artifact: __artifact })",
advisory.sandbox
);
assert.equal(outAdvisory.ok, true, "release-notes checksums are advisory (asset tables can disagree)");
assert.ok(
advisory.warned.join("\n").includes("Release notes sha256 mismatch"),
"a declared checksum that disagrees with the artifact must be logged as a tamper signal"
);
const verified = buildIntegritySandbox(null);
verified.sandbox.__artifact = artifact;
const outVerified = vm.runInContext(
"verifyUpdateArtifactIntegrity({ channel: 'panel', version: 'v1.0.0', releaseBody: 'SHA256: " + hash + "', artifact: __artifact })",
verified.sandbox
);
assert.equal(outVerified.ok, true);
assert.ok(verified.logged.join("\n").includes("verified against release notes"));
});
// ---------------------------------------------------------------------------
// Extraction helpers: capped inflate, no-follow writes, rollback
// ---------------------------------------------------------------------------
test("getUpdateEntryDataCapped refuses entries that expand beyond the ceiling", () => {
const source = extractBlock(indexSource, "function getUpdateEntryDataCapped(entry, maxBytes) {");
const sandbox = { zlib, Buffer, console: { log() { }, warn() { }, error() { } } };
vm.createContext(sandbox);
vm.runInContext(source, sandbox);
const big = Buffer.alloc(1024 * 1024, 7);
const zip = new AdmZip();
zip.addFile("payload.bin", big);
const entry = zip.getEntries()[0];
assert.equal(entry.header.method, 8, "adm-zip deflates by default; the capped inflate path is the one under test");
sandbox.__entry = entry;
const ok = vm.runInContext("getUpdateEntryDataCapped(__entry, 2 * 1024 * 1024)", sandbox);
assert.equal(ok.length, big.length);
assert.ok(ok.equals(big));
assert.throws(
() => vm.runInContext("getUpdateEntryDataCapped(__entry, 1024)", sandbox),
(err) => err.code === "EUPDATEENTRYTOOLARGE",
"a 1 MB payload must be refused under a 1 KB ceiling"
);
});
test("node update extraction bounds inflation before accepting a release file", () => {
const archive = new AdmZip();
archive.addFile("release/main.go", Buffer.alloc(9 * 1024 * 1024, 0x61));
const sandbox = {
require: (name) => {
if (name === "adm-zip") return AdmZip;
return require(path.resolve(ROOT, name));
},
path, zlib, Buffer,
archive: archive.toBuffer(),
};
vm.createContext(sandbox);
vm.runInContext(
extractBlock(indexSource, "function getUpdateEntryDataCapped(entry, maxBytes) {") + "\n" +
extractBlock(indexSource, "function isAllowedNodeReleasePath(relativePath) {") + "\n" +
extractBlock(indexSource, "function extractNodeUpdateFilesFromRelease(targetRelease, zipBuffer) {"),
sandbox
);
assert.throws(
() => vm.runInContext("extractNodeUpdateFilesFromRelease({ tag_name: 'v1.0.0' }, archive)", sandbox),
(error) => error.code === "EUPDATEENTRYTOOLARGE",
"a selected file must hit the inflation ceiling, not allocate its full oversized body first"
);
});
test("node update extraction retains valid source and filters unrelated archive files", () => {
const archive = new AdmZip();
archive.addFile("release/main.go", Buffer.from("package main\n"));
archive.addFile("release/go.mod", Buffer.from("module test\n"));
archive.addFile("release/data/secret.go", Buffer.from("excluded"));
const sandbox = {
require: (name) => {
if (name === "adm-zip") return AdmZip;
return require(path.resolve(ROOT, name));
},
path, zlib, Buffer,
archive: archive.toBuffer(),
};
vm.createContext(sandbox);
vm.runInContext(
extractBlock(indexSource, "function getUpdateEntryDataCapped(entry, maxBytes) {") + "\n" +
extractBlock(indexSource, "function isAllowedNodeReleasePath(relativePath) {") + "\n" +
extractBlock(indexSource, "function extractNodeUpdateFilesFromRelease(targetRelease, zipBuffer) {"),
sandbox
);
const result = vm.runInContext("extractNodeUpdateFilesFromRelease({ tag_name: 'v1.0.0' }, archive)", sandbox);
assert.strictEqual(result.files.length, 2);
assert.strictEqual(result.filesSkipped, 1);
assert.strictEqual(result.sourceTag, "v1.0.0");
assert.strictEqual(Buffer.from(result.files.find((file) => file.path === "main.go").contentBase64, "base64").toString(), "package main\n");
});
test("node update extraction rejects aggregate budgets before inflating source entries", () => {
const { extractNodeUpdateFilesFromRelease } = require("../utils/node-update-archive");
const allowed = (name) => /^[A-Za-z0-9_.-]+\.go$/.test(name);
const fixtures = [];
const manyFiles = new AdmZip();
manyFiles.addFile("release/main.go", Buffer.from("package main\n"));
for (let count = 0; count < 32; count++) {
manyFiles.addFile(`release/source-${count}.go`, Buffer.from("package main\n"));
}
fixtures.push(manyFiles.toBuffer());
const largePayload = new AdmZip();
largePayload.addFile("release/main.go", Buffer.alloc(8 * 1024 * 1024, 0x61));
largePayload.addFile("release/source.go", Buffer.alloc(8 * 1024 * 1024, 0x62));
fixtures.push(largePayload.toBuffer());
for (const fixture of fixtures) {
let inflations = 0;
assert.throws(() => extractNodeUpdateFilesFromRelease({ tag_name: "v1.0.0" }, fixture, {
isAllowedNodeReleasePath: allowed,
getUpdateEntryDataCapped: () => { inflations++; return Buffer.from("source"); },
}), (error) => error.code === "EUPDATEPAYLOADTOOLARGE", "oversized file sets and base64 envelopes must be rejected at admission");
assert.strictEqual(inflations, 0, "a refused aggregate budget must allocate no decompressed entry");
}
});
const { atomicWriteFileSync } = require("../utils/atomic-file");
const { rollbackPanelUpdateFiles, writePanelUpdateFileNoFollow } = require("../services/panel-update-coordinator");
const { createPanelUpdateState } = require("../scripts/panel-update-recovery.cjs");
test("the panel update mutex locks a stable inode without creating a lock file", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const launcher = path.join(ROOT, launcherPath);
const { createPanelUpdateMutex } = require(launcher);
const release = createPanelUpdateMutex(info).tryAcquire();
assert.ok(release);
const probe = () => execFileAsync(process.execPath, ["-e", `
const release = require(process.argv[1]).createPanelUpdateMutex(process.argv[2]).tryAcquire();
if (!release) process.exitCode = 75;
else release();
`, launcher, info], { timeout: 5000 });
try {
await assert.rejects(probe(), { code: 75 });
} finally {
release();
}
await probe();
assert.deepEqual(fs.readdirSync(root), []);
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const release = require(process.argv[1]).createPanelUpdateMutex(process.argv[2]).tryAcquire();
if (!release) process.exit(2);
process.kill(process.pid, 'SIGKILL');
`, launcher, info], { timeout: 5000 }), { signal: "SIGKILL" });
await probe();
});
function beginFixtureUpdate(state, version) {
const id = state.prepare(version);
state.begin(id);
return id;
}
test("staging a panel release never replaces source used by a running worker", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const entry = path.join(root, "lazy-helper.js");
fs.writeFileSync(entry, "module.exports = 'previous';");
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("lazy-helper.js", "module.exports = 'candidate';");
stage.seal();
assert.equal(state.read().pending.phase, "restart");
assert.equal(state.read().pending.staged, true);
assert.equal(require(entry), "previous");
assert.equal(state.recover(id, "restart"), true);
assert.equal(state.read().failure.restored, null);
assert.equal(state.read().pending, undefined);
assert.equal(fs.readFileSync(entry, "utf8"), "module.exports = 'previous';");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
});
test("a blocked stage cleanup does not retry publication or tell operators to restore unchanged files", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
fs.writeFileSync(entry, "console.log('previous source');");
copyClusterFixture(root);
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.seal();
const remove = fs.rmSync;
const rejectCleanup = t.mock.method(fs, "rmSync", (target, options) => {
if (target.endsWith(`/.staged-${id}`)) throw Object.assign(new Error("fixture cleanup failed"), { code: "EIO" });
return remove(target, options);
});
assert.throws(() => state.recover(id, "restart"), { code: "EIO" });
rejectCleanup.mock.restore();
const status = require("../services/panel-update-coordinator").createPanelUpdateCoordinator({ panelInfoFile: info }).getPanelUpdateStatus();
assert.equal(status.updateBlocked, true);
assert.equal(status.restartPending, false);
assert.equal(status.failedUpdate.restored, null);
assert.match(status.updateError, /No panel files were changed.*staged update could not be cleaned up/);
assert.doesNotMatch(status.updateError, /restore from backup/i);
const previousBoot = await execFileAsync(process.execPath, [path.join(root, launcherPath)], { cwd: root, timeout: 5000 });
assert.equal(previousBoot.stdout.trim(), "previous source");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.reason, "restart");
assert.equal(state.read().failure?.restored, null);
});
for (const diskFull of [false, true]) test(`an interrupted discard cannot turn an abandoned stage back into a trial (disk full: ${diskFull})`, { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const launcher = path.join(root, launcherPath);
fs.writeFileSync(entry, "console.log('previous source');");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "throw new Error('the abandoned candidate must not run');");
stage.seal();
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const fs = require('node:fs');
const open = fs.openSync;
fs.openSync = (file, flags, ...options) => {
if (${diskFull} && flags === 'wx' && file.includes('/.update-state.json.')) {
throw Object.assign(new Error('fixture disk full'), { code: 'ENOSPC' });
}
return open(file, flags, ...options);
};
const remove = fs.rmSync;
fs.rmSync = (target, options) => {
if (target.endsWith('/.staged-' + process.argv[3])) process.kill(process.pid, 'SIGKILL');
return remove(target, options);
};
require(process.argv[1]).createPanelUpdateState(process.argv[2]).recover(process.argv[3], 'restart');
`, launcher, info, id], { cwd: root, timeout: 5000 }), { signal: "SIGKILL" });
const reason = diskFull ? "storage" : "restart";
assert.equal(state.read().pending?.phase, "preparing");
assert.equal(state.read().pending?.reason, reason);
const stagedEntry = path.join(root, ".update-backups", `.staged-${id}`, "index.js");
assert.ok(fs.existsSync(stagedEntry));
const previousBoot = await execFileAsync(process.execPath, [launcher], { cwd: root, timeout: 5000 });
assert.equal(previousBoot.stdout.trim(), "previous source");
assert.equal(fs.existsSync(stagedEntry), false);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.reason, reason);
assert.equal(state.read().failure?.restored, null);
});
test("publishing staged source uses the same journal and restores source and metadata on replay", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const previousInfo = JSON.stringify([{ "panel-version": "v0.9.0", "panel-last-update-at": "2020-01-02T03:04:05.000Z" }]);
fs.writeFileSync(info, previousInfo);
fs.writeFileSync(entry, "previous source");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.write("new-directory/asset.txt", "candidate asset");
stage.seal();
const worker = require(`../${launcherPath}`).panelWorkerIdentity(process.pid);
state.publishStagedRelease(id, { ...worker, startTicks: worker.startTicks + 1 }, Date.now() + 10000);
assert.equal(state.read().pending.phase, "starting");
assert.equal(state.read().pending.staged, undefined);
assert.equal(fs.readFileSync(entry, "utf8"), "candidate source");
assert.equal(readPanelInfoVersion(root), "v1.0.0");
assert.equal(state.recover(id, "startup"), true);
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
assert.equal(fs.existsSync(path.join(root, "new-directory")), false);
});
test("reboot rollback keeps unrelated runtime files in a directory created by the update", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const runtimeFile = path.join(root, "new-directory", "runtime.json");
writePanelInfo(root, "v0.9.0");
const previousInfo = fs.readFileSync(info, "utf8");
fs.writeFileSync(entry, "previous source");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.write("new-directory/asset.js", "candidate asset");
stage.seal();
const worker = require(`../${launcherPath}`).panelWorkerIdentity(process.pid);
state.publishStagedRelease(id, { ...worker, bootId: "previous-boot" }, Date.now() + 10000);
fs.writeFileSync(runtimeFile, "runtime data");
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
assert.equal(fs.readFileSync(runtimeFile, "utf8"), "runtime data");
assert.equal(fs.existsSync(path.join(root, "new-directory", "asset.js")), false);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.restored, true);
});
test("a full disk during the source backup leaves every live file unchanged", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const helper = path.join(root, "helper.js");
writePanelInfo(root, "v0.9.0");
const previousInfo = fs.readFileSync(info, "utf8");
fs.writeFileSync(entry, "previous source");
fs.writeFileSync(helper, "previous helper");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.write("helper.js", "candidate helper");
stage.seal();
const copyFile = fs.copyFileSync;
t.mock.method(fs, "copyFileSync", (source, target, flags) => {
if (source === helper) throw Object.assign(new Error("injected full disk"), { code: "ENOSPC" });
return copyFile(source, target, flags);
});
assert.throws(() => publishFixtureRelease(root, id), { code: "ENOSPC" });
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
assert.equal(fs.readFileSync(helper, "utf8"), "previous helper");
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
assert.equal(state.recover(id, "storage"), true);
assert.equal(state.read().failure?.restored, null);
assert.equal(fs.existsSync(path.join(root, ".update-backups", id)), false);
});
test("publication refuses changed staged bytes and replays replacements already made", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
fs.writeFileSync(entry, "console.log('previous source');");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "throw new Error('candidate must not run');");
stage.write("helper.js", "module.exports = 'verified content';");
stage.seal();
fs.writeFileSync(path.join(root, ".update-backups", `.staged-${id}`, "helper.js"), "module.exports = 'changed content';");
const previousBoot = await execFileAsync(process.execPath, [path.join(root, launcherPath)], { cwd: root, timeout: 5000 });
assert.equal(previousBoot.stdout.trim(), "previous source");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.reason, "integrity");
assert.equal(state.read().failure?.restored, true);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.existsSync(path.join(root, "helper.js")), false);
});
test("publication refuses a valid JSON manifest that lost an entry after staging", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
fs.writeFileSync(entry, "previous source");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.write("helper.js", "candidate helper");
stage.seal();
const manifest = path.join(root, ".update-backups", `.staged-${id}`, ".release-files.json");
const entries = JSON.parse(fs.readFileSync(manifest, "utf8"));
fs.writeFileSync(manifest, JSON.stringify(entries.slice(0, 1)));
assert.throws(() => publishFixtureRelease(root, id), { code: "PANEL_UPDATE_INTEGRITY_FAILED" });
assert.equal(state.recover(id, "integrity"), true);
assert.equal(state.read().failure.restored, null);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
});
test("a failed stage cleanup cannot prevent rollback of already-published files", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous source");
const state = createPanelUpdateState(info, { warn() {} });
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.seal();
const rename = fs.renameSync;
const interrupted = t.mock.method(fs, "renameSync", (source, target) => {
if (target === info) throw Object.assign(new Error("fixture publication failed"), { code: "EIO" });
return rename(source, target);
});
assert.throws(() => publishFixtureRelease(root, id), { code: "EIO" });
interrupted.mock.restore();
assert.equal(fs.readFileSync(entry, "utf8"), "candidate source");
const remove = fs.rmSync;
const stagedPath = path.join(root, ".update-backups", `.staged-${id}`);
t.mock.method(fs, "rmSync", (target, options) => {
if (target === stagedPath) throw Object.assign(new Error("fixture cleanup failed"), { code: "EIO" });
return remove(target, options);
});
assert.equal(state.recover(id, "install"), true);
assert.equal(fs.existsSync(stagedPath), true);
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.restored, true);
});
test("reboot rollback frees leftover staging space before restoring enrolled source", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous source");
const state = createPanelUpdateState(info, { error() {} });
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate source");
stage.seal();
const worker = require(`../${launcherPath}`).panelWorkerIdentity(process.pid);
state.publishStagedRelease(id, { ...worker, bootId: "previous-boot" }, Date.now() + 10000);
assert.equal(state.read().pending.staged, undefined);
const abandonedStage = path.join(root, ".update-backups", `.staged-${id}`);
fs.mkdirSync(abandonedStage, { recursive: true });
fs.writeFileSync(path.join(abandonedStage, "index.js"), "candidate source");
const reserve = path.join(root, ".update-backups", ".preflight-space-reserve");
const remove = fs.rmSync;
const cleanup = t.mock.method(fs, "rmSync", (target, options) => {
if (target === abandonedStage && fs.existsSync(reserve)) {
throw Object.assign(new Error("fixture storage full during cleanup"), { code: "ENOSPC" });
}
return remove(target, options);
});
const diskFullUntilStageRemoved = operation => (source, target, ...options) => {
if (target.endsWith("/.update-restore.tmp") && fs.existsSync(abandonedStage)) {
throw Object.assign(new Error("fixture storage full"), { code: "ENOSPC" });
}
return operation(source, target, ...options);
};
t.mock.method(fs, "copyFileSync", diskFullUntilStageRemoved(fs.copyFileSync));
t.mock.method(fs, "linkSync", diskFullUntilStageRemoved(fs.linkSync));
assert.equal(state.recover(id, "interrupted"), true);
assert.ok(cleanup.mock.calls.filter(call => call.arguments[0] === abandonedStage).length >= 2);
assert.equal(fs.existsSync(reserve), false);
assert.equal(fs.existsSync(abandonedStage), false);
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().failure.restored, true);
});
for (const boundary of ["live rename", "replacement temporary", "trial enrollment"]) test(`a stage publisher interrupted at ${boundary} is rolled back on the next launch`, { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const launcher = path.join(root, launcherPath);
const previous = "console.log('previous source');";
fs.writeFileSync(entry, previous);
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "throw new Error('the unverified source must not run');");
stage.write("new-directory/asset.txt", "candidate asset");
stage.seal();
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const journal = path.join(process.cwd(), '.update-backups', process.argv[4], '.update-journal');
let undoRecord;
const rename = fs.renameSync;
fs.renameSync = (source, target) => {
if (process.argv[3] === 'trial enrollment' && target.endsWith('/update-state.json') &&
JSON.parse(fs.readFileSync(source, 'utf8')).pending?.phase === 'starting') process.kill(process.pid, 'SIGKILL');
if (target === process.argv[2]) undoRecord = fs.readFileSync(journal, 'utf8');
if (process.argv[3] === 'replacement temporary' && target.endsWith('/new-directory/asset.txt')) {
assert.equal(fs.readFileSync(journal, 'utf8'), undoRecord, 'publication must not append to the durable undo journal');
assert.ok(undoRecord.includes(JSON.stringify(path.relative(process.cwd(), source))));
process.kill(process.pid, 'SIGKILL');
}
rename(source, target);
if (process.argv[3] === 'live rename' && target === process.argv[2]) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
};
require(process.argv[1]).launchPanel({ timeoutMs: 2000 }).catch(error => { console.error(error); process.exit(1); });
`, launcher, entry, boundary, id], { cwd: root, timeout: 8000, killSignal: "SIGKILL" }), err =>
err.signal === "SIGKILL" && (boundary !== "live rename" || /Stopping an unverified panel worker/.test(err.stderr)));
assert.equal(state.read().pending?.phase, "applying");
assert.match(fs.readFileSync(entry, "utf8"), /unverified source/);
assert.equal(readPanelInfoVersion(root), boundary === "trial enrollment" ? "v1.0.0" : "v0.9.0");
const previousBoot = await execFileAsync(process.execPath, [launcher], { cwd: root, timeout: 5000 });
assert.equal(previousBoot.stdout.trim(), "previous source");
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.equal(fs.existsSync(path.join(root, "new-directory")), false);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.restored, true);
});
test("reboot recovery discards a sealed but unpublished release without changing installed files", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
fs.writeFileSync(entry, "console.log('previous source');");
writePanelInfo(root, "v0.9.0");
const inode = fs.statSync(entry).ino;
const worker = require(`../${launcherPath}`).panelWorkerIdentity(process.pid);
assert.ok(worker?.bootId);
const oldBoot = { ...worker, bootId: `old-${worker.bootId}` };
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0", "v1.0.0", false, { appName: "adpanel", expected: 1, previous: [oldBoot], supervisor: oldBoot });
const stage = state.openStage(id);
stage.write("index.js", "throw new Error('the unverified source must not run');");
stage.seal();
const launcher = path.join(root, launcherPath);
const recovered = await execFileAsync(process.execPath, [launcher, "--recover-after-reboot"], { cwd: root, timeout: 5000 });
assert.equal(recovered.stdout, "", "the service preflight must not load application code");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().ignoredThrough, "v1.0.0");
assert.equal(state.read().failure?.reason, "interrupted");
assert.equal(state.read().failure?.restored, null);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.statSync(entry).ino, inode, "the previous source was never replaced");
assert.equal(fs.readdirSync(path.join(root, ".update-backups")).some(name => name.startsWith(".staged-")), false);
assert.equal((await execFileAsync(process.execPath, [launcher], { cwd: root, timeout: 5000 })).stdout.trim(), "previous source");
});
test("panel recovery journal can restore an interrupted install without consuming its backups", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const infoPath = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
const addedPath = path.join(root, "new.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, "previous");
const lastUpdate = new Date("2020-01-02T03:04:05Z");
fs.utimesSync(indexPath, lastUpdate, lastUpdate);
const installer = createPanelUpdateState(infoPath);
const id = beginFixtureUpdate(installer, "v1.0.0");
installer.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, "replacement");
installer.snapshot(id, "new.js", false);
writePanelUpdateFileNoFollow(addedPath, "new file");
writePanelUpdateFileNoFollow(infoPath, "new metadata");
const recovery = createPanelUpdateState(infoPath);
assert.equal(recovery.recover(id, "interrupted"), true);
assert.equal(fs.readFileSync(indexPath, "utf8"), "previous");
assert.equal(fs.statSync(indexPath).mtime.toISOString(), lastUpdate.toISOString());
assert.equal(fs.existsSync(addedPath), false);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(recovery.read().failure.restored, true);
assert.equal(recovery.read().pending, undefined);
const backup = path.join(root, ".update-backups", id, "index.js");
fs.writeFileSync(indexPath, "later in-place edit");
assert.equal(fs.readFileSync(backup, "utf8"), "previous");
});
test("replay removes a crashed restore temporary and reports emergency shared snapshots", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const state = createPanelUpdateState(info, { warn() {} });
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "candidate");
const backupDir = path.join(root, ".update-backups", id);
const scratch = path.join(backupDir, ".update-restore.tmp");
fs.writeFileSync(scratch, "interrupted restore");
const copy = fs.copyFileSync;
t.mock.method(fs, "copyFileSync", (source, target, flags) => {
if (target === scratch) throw Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
return copy(source, target, flags);
});
assert.equal(state.recover(id, "storage"), true);
assert.equal(fs.existsSync(scratch), false);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
assert.equal(state.read().failure.backupMayShareLiveFiles, true);
assert.ok(fs.existsSync(path.join(backupDir, ".backup-may-share-live-files")));
});
test("reboot replay frees reserved space when storage blocks the emergency restore", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const state = createPanelUpdateState(info, { warn() {}, error() {} });
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "candidate");
writePanelUpdateFileNoFollow(info, '[{"panel-version":"v1.0.0"}]');
const backupRoot = path.join(root, ".update-backups");
const reserve = path.join(backupRoot, ".preflight-space-reserve");
const scratch = path.join(backupRoot, id, ".update-restore.tmp");
assert.ok(fs.existsSync(reserve), "the updater reserved space before changing live files");
const full = () => Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
const copy = fs.copyFileSync;
const link = fs.linkSync;
t.mock.method(fs, "copyFileSync", (source, target, flags) => {
if (target === scratch) throw full();
return copy(source, target, flags);
});
t.mock.method(fs, "linkSync", (source, target) => {
if (target === scratch && fs.existsSync(reserve)) throw full();
return link(source, target);
});
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.backupMayShareLiveFiles, true);
});
test("a crash in the cross-device restore copy leaves a temporary that replay removes", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "candidate");
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const fs = require('node:fs');
const path = require('node:path');
const reserve = path.join(path.dirname(process.argv[2]), '.update-backups', '.preflight-space-reserve');
const open = fs.openSync;
fs.openSync = (file, flags, ...args) => {
if (flags === 'wx' && path.basename(file).startsWith('..update-restore-path.json.') && fs.existsSync(reserve)) {
throw Object.assign(new Error('fixture disk full before journaling the cross-device copy'), { code: 'ENOSPC' });
}
return open(file, flags, ...args);
};
const rename = fs.renameSync;
fs.renameSync = (source, target) => {
if (target === process.argv[3]) {
if (path.basename(source) === '.update-restore.tmp') {
throw Object.assign(new Error('fixture cross-device rename'), { code: 'EXDEV' });
}
process.kill(process.pid, 'SIGKILL');
}
return rename(source, target);
};
require(process.argv[1]).createPanelUpdateState(process.argv[2]).recover(process.argv[4], 'interrupted');
`, path.join(ROOT, launcherPath), info, entry, id], { timeout: 5000 }), { signal: "SIGKILL" });
const scratch = fs.readdirSync(root).find(name => /^\.update-restore-.*\.tmp$/.test(name));
assert.ok(scratch, "the interrupted copy reached the destination filesystem");
assert.equal(state.read().pending.phase, "restoring");
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(fs.existsSync(path.join(root, scratch)), false);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
});
test("panel recovery sweeper restores an abandoned install even when auto update is off", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const infoPath = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, "previous");
const state = createPanelUpdateState(infoPath);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, "candidate");
const { createPanelUpdateCoordinator, createPanelUpdateMutex } = require("../services/panel-update-coordinator");
const coordinator = createPanelUpdateCoordinator({ panelInfoFile: infoPath });
const release = createPanelUpdateMutex(infoPath).tryAcquire();
assert.ok(release);
try {
coordinator.recoverAbandonedPanelUpdate();
assert.equal(fs.readFileSync(indexPath, "utf8"), "candidate", "a live installer owns the journal");
} finally {
release();
}
coordinator.recoverAbandonedPanelUpdate();
assert.equal(fs.readFileSync(indexPath, "utf8"), "previous");
assert.equal(state.read().failure.reason, "interrupted");
assert.match(coordinator.getPanelUpdateStatus().updateError, /previous version was restored/);
});
test("panel recovery records an interrupted download without touching the live tree when storage stays full", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const infoPath = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, "previous");
const state = createPanelUpdateState(infoPath);
const id = state.prepare("v1.0.0");
t.mock.method(fs, "writeFileSync", () => { throw Object.assign(new Error("disk full"), { code: "ENOSPC" }); });
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().ignoredThrough, "v1.0.0");
assert.equal(state.read().failure.restored, null);
assert.equal(fs.readFileSync(indexPath, "utf8"), "previous");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
});
test("reboot recovery releases reserved space if discarding an abandoned stage hits ENOSPC", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const backupRoot = path.join(root, ".update-backups");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "candidate");
stage.seal();
const reserve = path.join(backupRoot, ".preflight-space-reserve");
const staged = path.join(backupRoot, `.staged-${id}`);
const remove = fs.rmSync;
const cleanup = t.mock.method(fs, "rmSync", (target, options) => {
if (target === staged && fs.existsSync(reserve)) throw Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
return remove(target, options);
});
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(cleanup.mock.calls.length, 3);
assert.equal(fs.existsSync(reserve), false);
assert.equal(fs.existsSync(staged), false);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().failure.restored, null);
assert.equal(state.read().pending, undefined);
});
test("panel recovery removes an abandoned replacement temp file before removing its new directory", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const infoPath = path.join(root, "panel-information.json");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(infoPath);
const id = beginFixtureUpdate(state, "v1.0.0");
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const fs = require("node:fs");
const path = require("node:path");
const { createPanelUpdateState, writePanelUpdateFileNoFollow } = require(process.argv[1]);
const root = process.argv[2];
const id = process.argv[3];
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const target = path.join(root, "new-dir", "asset.js");
state.snapshot(id, "new-dir", false, true);
fs.mkdirSync(path.dirname(target));
state.snapshot(id, "new-dir/asset.js", false);
fs.renameSync = () => process.kill(process.pid, "SIGKILL");
writePanelUpdateFileNoFollow(target, "candidate", { beforeOpen: temporary => state.snapshot(id, path.relative(root, temporary), false) });
`, path.join(ROOT, launcherPath), root, id], { timeout: 10_000 }), { signal: "SIGKILL" });
assert.match(fs.readdirSync(path.join(root, "new-dir"))[0], /^\.asset\.js\..*\.tmp$/);
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(fs.existsSync(path.join(root, "new-dir")), false);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
});
test("panel rollback retries the directory flush even when a candidate file is already absent", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const directory = path.join(root, "assets");
const state = createPanelUpdateState(info, { error() {} });
writePanelInfo(root, "v0.9.0");
fs.mkdirSync(directory);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "assets/new.js", false);
writePanelUpdateFileNoFollow(path.join(directory, "new.js"), "candidate");
const directoryInode = fs.statSync(directory).ino;
const fsync = fs.fsyncSync;
let attempts = 0;
t.mock.method(fs, "fsyncSync", fd => {
if (fs.fstatSync(fd).ino === directoryInode && ++attempts === 1) {
throw Object.assign(new Error("fixture fsync failed"), { code: "EIO" });
}
return fsync(fd);
});
assert.equal(state.recover(id, "interrupted"), false);
assert.equal(fs.existsSync(path.join(directory, "new.js")), false);
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(attempts, 2);
});
test("reboot recovery frees reserved space to flush a restored source directory", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const directory = path.join(root, "assets");
const target = path.join(directory, "source.js");
const reserve = path.join(root, ".update-backups", ".preflight-space-reserve");
const state = createPanelUpdateState(info, { error() {} });
writePanelInfo(root, "v0.9.0");
fs.mkdirSync(directory);
fs.writeFileSync(target, "previous source");
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "assets/source.js", true);
writePanelUpdateFileNoFollow(target, "candidate");
const directoryInode = fs.statSync(directory).ino;
const fsync = fs.fsyncSync;
let refused = 0;
t.mock.method(fs, "fsyncSync", fd => {
if (fs.fstatSync(fd).ino === directoryInode && fs.existsSync(reserve)) {
refused++;
throw Object.assign(new Error("fixture disk full while flushing a restored directory"), { code: "ENOSPC" });
}
return fsync(fd);
});
assert.equal(state.recover(id, "interrupted"), true);
assert.equal(refused, 1);
assert.equal(fs.existsSync(reserve), false);
assert.equal(fs.readFileSync(target, "utf8"), "previous source");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.restored, true);
});
test("attempts without live replacements do not evict usable backups", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const backupRoot = path.join(root, ".update-backups");
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const state = createPanelUpdateState(info, { warn() {} });
for (let revision = 0; revision < 7; revision++) {
const id = beginFixtureUpdate(state, `v1.0.${revision}`);
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "candidate");
assert.equal(state.recover(id, "interrupted"), true);
}
const backups = () => fs.readdirSync(backupRoot, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name).sort();
const retained = backups();
assert.equal(retained.length, 5);
const diskFull = Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
const copy = t.mock.method(fs, "copyFileSync", () => { throw diskFull; });
const setupFailed = state.prepare("v1.1.0");
assert.throws(() => state.begin(setupFailed), { code: "ENOSPC" });
assert.equal(state.recover(setupFailed, "storage"), true);
copy.mock.restore();
const snapshotFailed = beginFixtureUpdate(state, "v1.1.0");
const failSnapshot = t.mock.method(fs, "copyFileSync", () => { throw diskFull; });
assert.throws(() => state.snapshot(snapshotFailed, "index.js", true), { code: "ENOSPC" });
assert.equal(state.recover(snapshotFailed, "storage"), true);
failSnapshot.mock.restore();
const writeFailed = beginFixtureUpdate(state, "v1.1.0");
state.snapshot(writeFailed, "index.js", true);
state.snapshot(writeFailed, ".replacement.tmp", false, false, true);
fs.writeFileSync(path.join(root, ".replacement.tmp"), "partial replacement");
assert.equal(state.recover(writeFailed, "storage"), true);
assert.equal(fs.existsSync(path.join(root, ".replacement.tmp")), false);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
assert.deepEqual(backups(), retained);
const cleanupInterrupted = beginFixtureUpdate(state, "v1.1.0");
const discarded = path.join(backupRoot, `.discarded-${cleanupInterrupted}`);
const remove = fs.rmSync;
const failCleanup = t.mock.method(fs, "rmSync", (target, options) => {
if (target === discarded) {
fs.unlinkSync(path.join(discarded, ".snapshot-unused"));
throw new Error("fixture cleanup interrupted");
}
return remove(target, options);
});
assert.equal(state.recover(cleanupInterrupted, "storage"), true);
assert.equal(fs.existsSync(discarded), true);
failCleanup.mock.restore();
assert.equal(state.recover(beginFixtureUpdate(state, "v1.1.1"), "storage"), true);
assert.deepEqual(backups(), retained);
});
test("an existing backup root must be flushed before staging any update", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const backupRoot = path.join(root, ".update-backups");
fs.mkdirSync(backupRoot);
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const rootInode = fs.statSync(root).ino;
const fsync = fs.fsyncSync;
t.mock.method(fs, "fsyncSync", fd => {
if (fs.fstatSync(fd).ino === rootInode) throw Object.assign(new Error("fixture root flush failed"), { code: "EIO" });
return fsync(fd);
});
assert.throws(() => state.prepare("v1.0.0"), { code: "EIO" });
assert.deepEqual(fs.readdirSync(backupRoot), []);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
});
test("the launcher restores from its reserve when it cannot record the trial on a full disk", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
const oldInfo = [{ "panel-version": "v0.9.0", "panel-last-update-at": "2020-01-02T03:04:05.000Z" }];
fs.writeFileSync(info, JSON.stringify(oldInfo));
fs.writeFileSync(indexPath, "module.exports = 'previous build';");
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, "throw new Error('candidate must not run');");
writePanelUpdateFileNoFollow(info, JSON.stringify([{ "panel-version": "v1.0.0" }]));
state.setPhase(id, "restart");
const open = fs.openSync;
t.mock.method(fs, "openSync", (target, flags, ...args) => {
if (flags === "wx" && (target === `${info}.lock` || path.basename(target).startsWith(".update-state.json."))) {
throw Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
}
return open(target, flags, ...args);
});
const reserve = path.join(root, ".update-backups", ".preflight-space-reserve");
const rename = fs.renameSync;
let publishedReserve = false;
t.mock.method(fs, "renameSync", (source, target) => {
rename(source, target);
if (path.basename(source) === ".storage-restoring.json") publishedReserve = true;
});
const fsync = fs.fsyncSync;
const backupInode = fs.statSync(path.dirname(reserve)).ino;
let failedFlush = false;
t.mock.method(fs, "fsyncSync", fd => {
if (publishedReserve && !failedFlush && fs.fstatSync(fd).ino === backupInode) {
failedFlush = true;
assert.ok(fs.existsSync(reserve));
throw Object.assign(new Error("fixture disk full while flushing the reserved rollback record"), { code: "ENOSPC" });
}
return fsync(fd);
});
await require("../scripts/panel-update-recovery.cjs").launchPanel({ panelRoot: root });
assert.equal(failedFlush, true);
assert.equal(require(indexPath), "previous build");
assert.deepEqual(JSON.parse(fs.readFileSync(info, "utf8")), oldInfo);
assert.equal(state.read().failure.reason, "storage");
assert.equal(state.read().failure.restored, true);
assert.equal(state.read().pending, undefined);
});
test("the launcher recovers from a failed enrollment and never loads an expired restart", async (t) => {
const { launchPanel, RESTART_RECOVERY_MS } = require("../scripts/panel-update-recovery.cjs");
const rename = fs.renameSync;
t.mock.method(fs, "renameSync", (source, target) => {
if (path.basename(target) === "update-state.json" && JSON.parse(fs.readFileSync(source)).pending?.phase === "starting") {
throw Object.assign(new Error("fixture trial enrollment failed"), { code: "EIO" });
}
return rename(source, target);
});
for (const expired of [false, true]) {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const entry = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "module.exports = 'previous build';");
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "throw new Error('candidate must not run');");
state.setPhase(id, "restart");
if (expired) {
const staged = state.read();
staged.pending.phaseAt -= RESTART_RECOVERY_MS;
state.write(staged);
}
await launchPanel({ panelRoot: root });
assert.equal(require(entry), "previous build");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.reason, expired ? "restart" : "startup");
}
});
test("the launcher rolls back a staged release after a host reboot", { skip: process.platform !== "linux" }, async (t) => {
const { panelWorkerIdentity } = require("../scripts/panel-update-recovery.cjs");
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const previousInfo = [{ "panel-version": "v0.9.0", "panel-last-update-at": "2020-01-02T03:04:05.000Z" }];
const previous = `require('node:http').createServer().listen(0, '127.0.0.1', () => console.log('RECOVERED AFTER REBOOT ' + process.pid));`;
fs.writeFileSync(info, JSON.stringify(previousInfo));
fs.writeFileSync(entry, previous);
const worker = panelWorkerIdentity(process.pid);
assert.ok(worker?.bootId);
const previousBoot = { ...worker, bootId: `old-${worker.bootId}` };
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0", "v1.0.0", false, {
appName: "adpanel", expected: 1, previous: [previousBoot], slots: [0], supervisor: previousBoot,
});
state.begin(id);
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, `
console.log('CANDIDATE AFTER REBOOT');
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => require('./${launcherPath}').markPanelUpdateReady(server));`);
writePanelUpdateFileNoFollow(info, JSON.stringify([{ "panel-version": "v1.0.0", "panel-last-update-at": "2026-11-23T03:04:05.000Z" }]));
state.setPhase(id, "restart");
const cluster = await startClusterFixture(root);
try {
const output = await cluster.waitFor(text => new Set(text.match(/RECOVERED AFTER REBOOT \d+/g)).size === 2 && text);
assert.doesNotMatch(output, /CANDIDATE AFTER REBOOT/);
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.deepEqual(JSON.parse(fs.readFileSync(info, "utf8")), previousInfo);
const result = state.read();
assert.equal(result.pending, undefined);
assert.equal(result.failure?.reason, "interrupted");
assert.equal(result.failure?.restored, true);
assert.equal(result.ignoredThrough, "v1.0.0");
} finally {
await cluster.stop();
}
});
function prepareRecoveryServiceFixture(root) {
copyClusterFixture(root);
fs.unlinkSync(path.join(root, "node_modules"));
fs.mkdirSync(path.join(root, "node_modules", ".bin"), { recursive: true });
const runtime = "scripts/adpanel-runtime.sh";
fs.copyFileSync(path.join(ROOT, runtime), path.join(root, runtime));
for (const [relative, script] of [
["scripts/generate-ecosystem.sh", "#!/bin/sh\necho 'fixture configuration disk full' >&2\nexit 1\n"],
["scripts/adpanel-autoscale-monitor.sh", "#!/bin/sh\nexit 99\n"],
["node_modules/.bin/pm2-runtime", "#!/bin/sh\nexit 99\n"],
]) fs.writeFileSync(path.join(root, relative), script, { mode: 0o700 });
return () => assert.rejects(execFileAsync("bash", [path.join(root, runtime)], {
cwd: root, env: { PATH: process.env.PATH, PANEL_DIR: root }, timeout: 10_000,
}), err => err.code === 1 && /fixture configuration disk full/.test(err.stderr));
}
test("the service restores source after reboot before PM2 configuration needs disk space", { skip: process.platform !== "linux" }, async (t) => {
const { panelWorkerIdentity } = require("../scripts/panel-update-recovery.cjs");
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const runRuntime = prepareRecoveryServiceFixture(root);
const entry = path.join(root, "index.js");
const previous = "throw new Error('the recovery-only command must not start the panel');";
fs.writeFileSync(entry, previous);
writePanelInfo(root, "v0.9.0");
const worker = panelWorkerIdentity(process.pid);
assert.ok(worker?.bootId);
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = state.prepare("v1.0.0", "v1.0.0", false, {
appName: "adpanel", expected: 1, previous: [worker], slots: [0], supervisor: worker,
});
state.begin(id);
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "module.exports = 'candidate';");
state.setPhase(id, "restart");
await runRuntime();
assert.equal(state.read().pending?.id, id, "a same-boot service restart must leave the release eligible for trial");
const staged = state.read();
staged.pending.cohort.supervisor.bootId = `old-${worker.bootId}`;
staged.pending.cohort.previous[0].bootId = staged.pending.cohort.supervisor.bootId;
state.write(staged);
await runRuntime();
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure?.restored, true);
});
test("the service restores a killed publisher before PM2 configuration on the same boot", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const runRuntime = prepareRecoveryServiceFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const previous = "throw new Error('recovery must not load application code');";
const previousInfo = JSON.stringify([{ "panel-version": "v0.9.0", "panel-last-update-at": "2020-01-02T03:04:05.000Z" }]);
fs.writeFileSync(info, previousInfo);
fs.writeFileSync(entry, previous);
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
const stage = state.openStage(id);
stage.write("index.js", "throw new Error('the candidate must not run');");
stage.write("new-directory/nested/asset.txt", "candidate asset");
stage.seal();
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const fs = require('node:fs');
const rename = fs.renameSync;
fs.renameSync = (source, target) => {
rename(source, target);
if (target === process.argv[2]) process.kill(process.pid, 'SIGKILL');
};
require(process.argv[1]).launchPanel().catch(err => { console.error(err); process.exitCode = 1; });
`, path.join(root, launcherPath), info], { cwd: root, timeout: 10_000 }), { signal: "SIGKILL" });
assert.equal(state.read().pending.phase, "applying");
assert.equal(readPanelInfoVersion(root), "v1.0.0");
assert.equal(fs.readFileSync(path.join(root, ".update-backups", id, "index.js"), "utf8"), previous);
await runRuntime();
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
assert.equal(fs.existsSync(path.join(root, "new-directory")), false);
const result = state.read();
assert.equal(result.pending, undefined);
assert.equal(result.failure?.reason, "interrupted");
assert.equal(result.failure?.restored, true);
});
test("an update cannot record a new journal before flushing the previous completion receipt", { skip: process.platform !== "linux" }, (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
writePanelInfo(root, "v1.0.0");
const state = createPanelUpdateState(info);
const first = beginFixtureUpdate(state, "v1.0.0");
state.setPhase(first, "restart");
const worker = require(`../${launcherPath}`).panelWorkerIdentity(process.pid);
assert.equal(state.joinTrial(first, worker, 10_000), true);
assert.equal(state.readyTrial(first, worker), true);
const directory = path.join(root, ".update-backups", first);
const inode = fs.statSync(directory).ino;
const fsync = fs.fsyncSync;
const failingFlush = t.mock.method(fs, "fsyncSync", fd => {
if (fs.fstatSync(fd).ino === inode) throw Object.assign(new Error("fixture completion flush failed"), { code: "EIO" });
return fsync(fd);
});
assert.throws(() => state.prepare("v2.0.0"), { code: "EIO" });
assert.equal(state.read().pending, undefined);
assert.equal(state.read().verified.id, first);
assert.equal(readPanelInfoVersion(root), "v1.0.0");
failingFlush.mock.restore();
assert.equal(state.read().pending, undefined);
const second = state.prepare("v2.0.0");
assert.equal(state.read().pending.id, second);
});
test("the launcher rolls back if the final confirmation rename is visible but its fsync failed", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const launcher = path.join(ROOT, launcherPath);
const info = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
const previous = 'console.log("previous build");';
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, previous);
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, `
const fs = require('node:fs');
const root = __dirname + '/.update-backups';
const inode = fs.statSync(root).ino;
const fsync = fs.fsyncSync;
fs.fsyncSync = fd => {
if (fs.fstatSync(fd).ino === inode && !JSON.parse(fs.readFileSync(root + '/update-state.json')).pending) {
throw Object.assign(new Error('fixture commit fsync failed'), { code: 'EIO' });
}
return fsync(fd);
};
const { markPanelUpdateReady } = require(${JSON.stringify(launcher)});
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => markPanelUpdateReady(server));`);
state.setPhase(id, "restart");
const boot = () => execFileAsync(process.execPath, ["-e", `
require(process.argv[1]).launchPanel({ panelRoot: process.argv[2], timeoutMs: 1500, settleMs: 25 })
.catch(error => { console.error(error); process.exit(1); });`, launcher, root], { timeout: 10_000 });
await assert.rejects(boot(), err => err.code === 1 && /fixture commit fsync failed/.test(err.stderr));
assert.equal(state.read().pending.phase, "committing");
assert.equal(state.read().verified, undefined);
assert.equal((await boot()).stdout.trim(), "previous build");
assert.equal(state.read().failure.reason, "commit");
assert.equal(state.read().failure.restored, true);
assert.equal(state.read().pending, undefined);
});
test("confirmation does not succeed if retiring its recovery record cannot be flushed", (t) => {
const { createPanelUpdateCoordinator, createPanelUpdateMutex, panelWorkerIdentity } = require("../services/panel-update-coordinator");
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const backupRoot = path.join(root, ".update-backups");
const marker = path.join(backupRoot, ".confirm-pending.json");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const coordinator = createPanelUpdateCoordinator({ panelInfoFile: info });
const id = beginFixtureUpdate(state, "v1.0.0");
state.setPhase(id, "restart");
const worker = panelWorkerIdentity(process.pid);
assert.equal(state.joinTrial(id, worker, 10000), true);
const fsync = fs.fsyncSync;
const backupDir = path.join(backupRoot, id);
const backupInode = fs.statSync(backupDir).ino;
const archived = path.join(backupDir, ".confirm-pending.json");
const flush = t.mock.method(fs, "fsyncSync", fd => {
if (fs.fstatSync(fd).ino === backupInode && fs.existsSync(archived)) {
assert.equal(fs.existsSync(marker), true);
const duringFlush = coordinator.getPanelUpdateStatus();
assert.equal(duringFlush.restartPending, true);
assert.equal(duringFlush.verifiedUpdate, undefined);
throw Object.assign(new Error("fixture marker retirement flush failed"), { code: "EIO" });
}
return fsync(fd);
});
const release = createPanelUpdateMutex(info).tryAcquire();
try {
assert.throws(() => state.readyTrial(id, worker), { code: "EIO" });
} finally {
release();
}
flush.mock.restore();
const reopened = createPanelUpdateState(info).read();
assert.equal(reopened.verified, undefined);
assert.equal(reopened.pending.phase, "committing");
assert.equal(reopened.pending.id, id);
assert.equal(fs.existsSync(marker), true);
});
for (const boundary of ["verified state fsync", "archive directory fsync", "guard directory fsync", "guard directory fsync crash", "receipt directory fsync crash", "marker retirement"]) {
test(`startup recovery covers a stopped confirmer at ${boundary}`, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const launcher = path.join(ROOT, launcherPath);
const previous = 'console.log("previous build");';
const previousInfo = JSON.stringify([{ "panel-version": "v0.9.0", "panel-last-update-at": "2025-01-02T03:04:05.000Z" }]);
fs.writeFileSync(info, previousInfo);
fs.writeFileSync(entry, previous);
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, `
const fs = require('node:fs');
const root = __dirname + '/.update-backups';
const backup = root + '/${id}';
const inode = fs.statSync(${boundary === "archive directory fsync" || boundary.startsWith("receipt ") ? "backup" : "root"}).ino;
const fsync = fs.fsyncSync;
const unlink = fs.unlinkSync;
const blockConfirmation = () => {
fs.writeFileSync(__dirname + '/confirmation-blocked', '');
if (${boundary.endsWith(" crash")}) process.kill(process.pid, 'SIGKILL');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
};
fs.fsyncSync = fd => {
const blocked = ${boundary === "verified state fsync"
? `JSON.parse(fs.readFileSync(root + '/update-state.json')).verified?.id === '${id}'`
: boundary === "archive directory fsync" ? "fs.existsSync(backup + '/.confirm-pending.json')"
: boundary.startsWith("receipt ") ? "fs.existsSync(backup + '/.confirm-provisional.json') || fs.existsSync(backup + '/.confirm-complete.json')"
: boundary.startsWith("guard directory fsync") ? "fs.existsSync(backup + '/.confirm-pending.json') && !fs.existsSync(root + '/.confirm-pending.json')" : "false"};
if (fs.fstatSync(fd).ino === inode && blocked) blockConfirmation();
return fsync(fd);
};
if (${boundary === "marker retirement"}) {
fs.unlinkSync = file => {
if (file === root + '/.confirm-pending.json') blockConfirmation();
return unlink(file);
};
}
const { markPanelUpdateReady } = require(${JSON.stringify(launcher)});
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => markPanelUpdateReady(server));`);
writePanelUpdateFileNoFollow(info, JSON.stringify([{ "panel-version": "v1.0.0", "panel-last-update-at": "2026-01-02T03:04:05.000Z" }]));
state.setPhase(id, "restart");
const boot = () => execFileAsync(process.execPath, ["-e", `
require(process.argv[1]).launchPanel({ panelRoot: process.argv[2], timeoutMs: 1500, settleMs: 25 })
.catch(err => { console.error(err); process.exit(1); });`, launcher, root], { timeout: 5000, killSignal: "SIGKILL" });
await assert.rejects(boot(), err => err.signal === "SIGKILL" && !err.killed);
assert.equal(fs.existsSync(path.join(root, "confirmation-blocked")), true);
assert.equal(state.read().pending.phase, "committing");
assert.equal(state.read().verified, undefined);
assert.equal((await boot()).stdout.trim(), "previous build");
assert.equal(state.read().failure.reason, "commit");
assert.equal(state.read().failure.restored, true);
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
});
}
test("a late startup watchdog leaves the verified worker alone during unrelated update work", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const launcher = path.join(ROOT, launcherPath);
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.setPhase(id, "restart");
const { stdout } = await execFileAsync(process.execPath, ["-e", `
const assert = require('node:assert/strict');
const { fork } = require('node:child_process');
const [launcher, info, id] = process.argv.slice(1);
const recovery = require(launcher);
const state = recovery.createPanelUpdateState(info);
const worker = recovery.panelWorkerIdentity(process.pid);
assert.equal(state.joinTrial(id, worker, 10000), true);
assert.equal(state.readyTrial(id, worker), true);
const release = recovery.createPanelUpdateMutex(info).tryAcquire();
assert.ok(release);
const deadlineAt = Date.now() + 1000;
const watchdog = fork(launcher, ['--watch-panel-startup', info, id, String(deadlineAt)]);
watchdog.once('message', message => {
assert.equal(message, 'armed');
setTimeout(() => {
release();
watchdog.disconnect();
console.log('Verified worker was not stopped');
}, Math.max(0, deadlineAt - Date.now()) + 400);
});`, launcher, info, id], { timeout: 5000, killSignal: "SIGKILL" });
assert.match(stdout, /Verified worker was not stopped/);
assert.equal(state.read().verified.id, id);
});
test("unrelated update lock holders do not hide an already verified release or its next offer", (t) => {
const { createPanelUpdateCoordinator, createPanelUpdateMutex, panelWorkerIdentity } = require("../services/panel-update-coordinator");
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const panelInfoFile = path.join(root, "panel-information.json");
const state = createPanelUpdateState(panelInfoFile);
writePanelInfo(root, "v1.0.0");
const id = beginFixtureUpdate(state, "v1.0.0");
state.setPhase(id, "restart");
const worker = panelWorkerIdentity(process.pid);
assert.equal(state.joinTrial(id, worker, 10000), true);
assert.equal(state.readyTrial(id, worker), true);
const coordinator = createPanelUpdateCoordinator({ panelInfoFile, compareVersions });
const release = createPanelUpdateMutex(panelInfoFile).tryAcquire();
assert.ok(release);
try {
const status = coordinator.getPanelUpdateStatus("v1.1.0", "v1.0.0");
assert.equal(status.restartPending, false);
assert.equal(status.updateBlocked, false);
assert.equal(status.offerUnavailable, false);
assert.deepEqual(status.verifiedUpdate, { id, version: "v1.0.0" });
} finally {
release();
}
});
test("a trial can only commit when every replacement has a fresh readiness report", { skip: process.platform !== "linux" }, (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const { panelWorkerIdentity } = require("../scripts/panel-update-recovery.cjs");
const first = panelWorkerIdentity(process.pid);
const second = panelWorkerIdentity(process.ppid);
assert.ok(first && second);
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = state.prepare("v1.0.0", "v1.0.0", false, { expected: 2, previous: [] });
state.begin(id);
state.setPhase(id, "restart");
let now = Date.now();
t.mock.method(Date, "now", () => now);
assert.equal(state.joinTrial(id, first, 10_000), true);
assert.equal(state.joinTrial(id, second, 10_000), true);
assert.equal(state.readyTrial(id, first), false);
now += 4000;
assert.equal(state.readyTrial(id, second), false);
assert.equal(state.read().pending.phase, "starting");
assert.equal(state.readyTrial(id, first), true);
assert.equal(state.read().verified.id, id);
});
test("the recovery launcher restores interrupted and failed starts before loading the previous build", async (t) => {
const launcher = path.join(ROOT, launcherPath);
const previous = 'console.log("previous build");';
const ready = `
const { markPanelUpdateReady } = require(${JSON.stringify(launcher)});
const server = require("node:http").createServer((req, res) => res.end("ready"));
server.listen(0, "127.0.0.1", () => {
markPanelUpdateReady(server);
setTimeout(() => { console.log("new build ready"); server.close(); }, 300);
});`;
const cases = [
{ phase: "applying", source: 'throw new Error("must not start");', reason: "interrupted" },
{ phase: "restart", source: "function {", reason: "startup" },
{ phase: "restart", source: "Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);", reason: "startup" },
{ phase: "restart", source: ready.replace("markPanelUpdateReady(server)", "markPanelUpdateReady(server, { listening: false })"), reason: "startup" },
{ phase: "restart", source: ready },
];
for (const { phase, source, reason } of cases) {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const infoPath = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, previous);
const state = createPanelUpdateState(infoPath);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, source);
writePanelUpdateFileNoFollow(infoPath, JSON.stringify([{ "panel-version": "v1.0.0" }]));
if (phase === "restart") state.setPhase(id, phase);
const boot = () => execFileAsync(process.execPath, ["-e", `
require(process.argv[1]).launchPanel({ panelRoot: process.argv[2], timeoutMs: 1500, settleMs: 25 })
.catch(error => { console.error(error); process.exit(1); });`, launcher, root], { timeout: 15_000 });
if (phase === "restart" && reason) {
await assert.rejects(boot(), (err) => err.code === 1 || (err.signal === "SIGKILL" && !err.killed));
assert.equal(state.read().pending.phase, "starting");
}
const { stdout } = await boot();
assert.equal(state.read().pending, undefined);
if (reason) {
assert.equal(stdout.trim(), "previous build");
assert.equal(fs.readFileSync(indexPath, "utf8"), previous);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().failure.reason, reason);
assert.equal(state.read().ignoredThrough, "v1.0.0");
} else {
assert.equal(stdout.trim(), "new build ready");
assert.equal(readPanelInfoVersion(root), "v1.0.0");
assert.equal(state.read().failure, undefined);
}
}
});
test("the startup watchdog bounds a hung replacement-worker enrollment", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const launcher = path.join(ROOT, launcherPath);
const info = path.join(root, "panel-information.json");
const { createPanelUpdateMutex, panelWorkerIdentity } = require(launcher);
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(path.join(root, "index.js"), "throw new Error('candidate must not run before enrollment');");
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0", "v1.0.0", false, { expected: 2, previous: [] });
state.begin(id);
state.setPhase(id, "restart");
assert.equal(state.joinTrial(id, panelWorkerIdentity(process.pid), 2000), true);
await assert.rejects(execFileAsync(process.execPath, ["-e", `
const fs = require('node:fs');
const rename = fs.renameSync;
fs.renameSync = (source, target) => {
if (target.endsWith('/update-state.json') && JSON.parse(fs.readFileSync(source)).pending?.workers?.length === 2) {
fs.writeFileSync(process.argv[2] + '/enrollment-blocked', '');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);
}
return rename(source, target);
};
require(process.argv[1]).launchPanel({ panelRoot: process.argv[2] })
.catch(err => { console.error(err); process.exit(1); });
`, launcher, root], { timeout: 5000, killSignal: "SIGKILL" }), err => err.signal === "SIGKILL" && !err.killed);
assert.equal(fs.existsSync(path.join(root, "enrollment-blocked")), true);
assert.equal(state.read().pending.workers.length, 1);
const release = createPanelUpdateMutex(info).tryAcquire();
assert.ok(release, "the watchdog-killed process must not hold the recovery lock");
release();
});
test("the launcher never runs a candidate when its startup watchdog cannot arm", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const launcher = path.join(ROOT, launcherPath);
const entry = path.join(root, "index.js");
const marker = path.join(root, "candidate-ran");
const previous = 'console.log("previous build");';
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, previous);
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, `require('node:fs').writeFileSync(${JSON.stringify(marker)}, 'ran');
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0);`);
state.setPhase(id, "restart");
const boot = (prefix = "") => execFileAsync(process.execPath, ["-e", `${prefix}
require(process.argv[1]).launchPanel({ panelRoot: process.argv[2], timeoutMs: 1500 })
.catch(err => { console.error(err); process.exit(1); });`, launcher, root], { timeout: 5000, killSignal: "SIGKILL" });
const { stdout, stderr } = await boot(`
require('node:child_process').fork = () => {
const child = new (require('node:events').EventEmitter)();
process.nextTick(() => child.emit('error', new Error('fixture watchdog fork failed')));
return child;
};`);
assert.match(stderr, /fixture watchdog fork failed/);
assert.equal(stdout.trim(), "previous build");
assert.equal(fs.existsSync(marker), false);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.restored, true);
});
function copyClusterFixture(root) {
for (const relative of [launcherPath, "utils/atomic-file.js", "utils/cross-process-mutex.js", "utils/panel-metrics.js",
"services/panel-update-coordinator.js", "ecosystem.config.template.js"]) {
fs.mkdirSync(path.dirname(path.join(root, relative)), { recursive: true });
fs.copyFileSync(path.join(ROOT, relative), path.join(root, relative));
}
fs.symlinkSync(path.join(ROOT, "node_modules"), path.join(root, "node_modules"), "dir");
}
function runClusterFixtureCommand(root, args) {
return execFileAsync(process.execPath, [require.resolve("pm2/bin/pm2"), ...args], {
cwd: root, env: { PATH: process.env.PATH, HOME: root, PM2_HOME: path.join(root, ".pm2") }, timeout: 15_000,
});
}
async function startClusterFixture(root, instances = 2, appOptions = {}) {
await execFileAsync("bash", [path.join(ROOT, "scripts/generate-ecosystem.sh"), "--panel-dir", root, "--quiet"], { timeout: 10_000 });
const generated = require(path.join(root, "ecosystem.config.js")).apps[0];
assert.equal(generated.script, path.join(root, launcherPath));
assert.equal(generated.exec_mode, "cluster");
const config = path.join(root, "fixture.config.js");
fs.writeFileSync(config, `module.exports = ${JSON.stringify({ apps: [{ ...generated, instances, restart_delay: 50, kill_timeout: 750, ...appOptions }] })};`);
const child = spawn(process.execPath, [require.resolve("pm2/bin/pm2-runtime"), "start", config], {
cwd: root,
env: { PATH: process.env.PATH, HOME: root, PM2_HOME: path.join(root, ".pm2") },
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
child.stdout.on("data", chunk => { output += chunk; });
child.stderr.on("data", chunk => { output += chunk; });
const closed = new Promise(resolve => child.once("close", resolve));
return {
async waitFor(check) {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline && child.exitCode === null && child.signalCode === null) {
const result = await check(output);
if (result) return result;
await new Promise(resolve => setTimeout(resolve, 25));
}
throw new Error(`PM2 fixture did not reach the expected state: ${output}`);
},
async stop() {
child.kill("SIGINT");
const timer = setTimeout(() => child.kill("SIGKILL"), 5000);
await closed;
clearTimeout(timer);
},
};
}
test("online updates refuse a legacy Agent unit or a process still running under it", async () => {
const { verifyAgentUpdateLauncher } = require("../services/panel-update-coordinator");
const root = "/fixture/panel";
const launcher = `${root}/scripts/panel-update-recovery.cjs`;
const legacy = `${root}/AgentWorker/worker.js`;
const args = ["/usr/bin/node", "--max-old-space-size=288", launcher, "--agent"];
const unit = ({ start = args, condition = "", preStart = "", reload = "no", pid = 42 } = {}) =>
`LoadState=loaded\nWorkingDirectory=${root}\nExecStart={ path=/usr/bin/node ; argv[]=${start.join(" ")} ; ignore_errors=no ; }\n` +
`ExecCondition=${condition}\nExecStartPre=${preStart}\nNeedDaemonReload=${reload}\nMainPID=${pid}\n`;
await verifyAgentUpdateLauncher(root, { readUnit: () => null });
await verifyAgentUpdateLauncher(root, { readUnit: () => "LoadState=not-found\nMainPID=0\n" });
await verifyAgentUpdateLauncher(root, { readUnit: unit, readArgs: pid => { assert.equal(pid, 42); return args; } });
for (const options of [
{ readUnit: () => unit({ start: [args[0], args[1], legacy, launcher, "--agent"] }) },
{ readUnit: () => unit({ condition: `${root}/AgentWorker/feature-config.js` }) },
{ readUnit: () => unit({ preStart: legacy }) },
{ readUnit: () => unit({ reload: "yes" }) },
{ readUnit: unit, readArgs: () => [args[0], args[1], legacy] },
]) await assert.rejects(verifyAgentUpdateLauncher(root, options), { statusCode: 409 });
});
test("PM2 policies that could strand recovery prevent update staging", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
writePanelInfo(root, "v0.9.0");
const info = path.join(root, "panel-information.json");
fs.writeFileSync(path.join(root, "index.js"), `
const { createPanelUpdateCoordinator } = require('./services/panel-update-coordinator');
const coordinator = createPanelUpdateCoordinator({
panelInfoFile: ${JSON.stringify(info)},
installUpdate: version => coordinator.applyPanelRelease(version, () => { throw new Error('unexpected staging'); }),
});
require('node:http').createServer().listen(0, '127.0.0.1', async () => {
try { await coordinator.installPanelUpdate('v1.0.0'); }
catch (err) { console.log('UPDATE REFUSED ' + err.statusCode + ': ' + err.message); }
});`);
for (const [config, message] of [
[{ stop_exit_codes: [1] }, /automatic restarts without stop exit codes/],
[{ max_restarts: 2 }, /unstable restart limit of at least three/],
]) {
const cluster = await startClusterFixture(root, 1, config);
try {
const output = await cluster.waitFor(text => /UPDATE REFUSED/.test(text) && text);
assert.match(output, /UPDATE REFUSED 409: Panel updates require/);
assert.match(output, message);
assert.deepEqual(createPanelUpdateState(info).read(), {});
assert.equal(readPanelInfoVersion(root), "v0.9.0");
} finally {
await cluster.stop();
}
}
});
test("PM2 can restart into recovery after counting both a planned stop and a candidate crash", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const candidate = "console.log('CANDIDATE CRASH'); process.exit(1);";
const previous = `
const fs = require('node:fs');
const { createPanelUpdateCoordinator } = require('./services/panel-update-coordinator');
const coordinator = createPanelUpdateCoordinator({
panelInfoFile: ${JSON.stringify(info)}, verifyAgentLauncher: () => {},
installUpdate: version => coordinator.applyPanelRelease(version, begin => {
begin()('index.js', ${JSON.stringify(candidate)});
return { version };
}),
});
require('node:http').createServer().listen(0, '127.0.0.1', () => {
const marker = __dirname + '/update-requested';
if (fs.existsSync(marker)) return console.log('RESTORED ' + process.pid);
fs.writeFileSync(marker, '');
coordinator.installPanelUpdate('v1.0.0').catch(console.error);
});`;
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, previous);
const cluster = await startClusterFixture(root, 1, { min_uptime: 60_000, max_restarts: 3 });
try {
await cluster.waitFor(output => /CANDIDATE CRASH/.test(output) && /RESTORED \d+/.test(output));
const { stdout } = await runClusterFixtureCommand(root, ["jlist"]);
assert.equal(JSON.parse(stdout)[0].pm2_env.unstable_restarts, 2);
assert.equal(createPanelUpdateState(info).read().failure?.restored, true);
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
} finally {
await cluster.stop();
}
});
test("generated PM2 cluster startup recovers a failed staged release before serving the previous build", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const infoPath = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
const previous = `
if (!require("./scripts/panel-update-recovery.cjs").isManagedRecoveryLauncher()) process.exit(2);
require("node:http").createServer((req, res) => res.end("previous"))
.listen(0, "127.0.0.1", () => console.log("RECOVERED WORKER " + process.pid));`;
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, previous);
const state = createPanelUpdateState(infoPath);
const id = state.prepare("v1.0.0", "v1.0.0", false, { expected: 2, previous: [] });
const stage = state.openStage(id);
stage.write("index.js", 'throw new Error("Synthetic release cannot start");');
stage.seal();
const cluster = await startClusterFixture(root);
try {
await cluster.waitFor(output => new Set(output.match(/RECOVERED WORKER \d+/g)).size >= 2);
assert.equal(fs.readFileSync(indexPath, "utf8"), previous);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.reason, "startup");
assert.equal(state.read().ignoredThrough, "v1.0.0");
} finally {
await cluster.stop();
}
});
test("the managed launcher restores a legacy pending update rather than verifying it without a cohort", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
writePanelInfo(root, "v0.9.0");
const entry = path.join(root, "index.js");
const previous = `require('node:http').createServer().listen(0, '127.0.0.1', () => console.log('PREVIOUS ' + process.pid));`;
fs.writeFileSync(entry, previous);
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, `throw new Error('legacy candidate must not load');`);
state.setPhase(id, "restart");
const cluster = await startClusterFixture(root, 1);
try {
const output = await cluster.waitFor(text => /PREVIOUS \d+/.test(text) && text);
assert.doesNotMatch(output, /legacy candidate must not load/);
assert.equal(state.read().failure.reason, "interrupted");
assert.equal(state.read().failure.restored, true);
assert.equal(state.read().pending, undefined);
} finally {
await cluster.stop();
}
});
test("PM2 restores the previous release when a confirmer dies after renaming the verified state", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const previous = `require('node:http').createServer().listen(0, '127.0.0.1', () => console.log('RESTORED ' + process.pid));`;
const previousInfo = JSON.stringify([{ "panel-version": "v0.9.0", "panel-last-update-at": "2025-01-02T03:04:05.000Z" }]);
fs.writeFileSync(info, previousInfo);
fs.writeFileSync(entry, previous);
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0", "v1.0.0", false, { expected: 2, previous: [] });
state.begin(id);
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, `
const fs = require('node:fs');
const root = __dirname + '/.update-backups';
const inode = fs.statSync(root).ino;
const fsync = fs.fsyncSync;
fs.fsyncSync = fd => {
if (fs.fstatSync(fd).ino === inode && JSON.parse(fs.readFileSync(root + '/update-state.json')).verified?.id === '${id}') {
fs.writeFileSync(__dirname + '/confirmer-killed', String(process.pid));
process.kill(process.pid, 'SIGKILL');
}
return fsync(fd);
};
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => require('./${launcherPath}').markPanelUpdateReady(server));`);
writePanelUpdateFileNoFollow(info, JSON.stringify([{ "panel-version": "v1.0.0", "panel-last-update-at": "2026-01-02T03:04:05.000Z" }]));
state.setPhase(id, "restart");
const cluster = await startClusterFixture(root);
try {
await cluster.waitFor(output => new Set(output.match(/RESTORED \d+/g)).size === 2);
assert.match(fs.readFileSync(path.join(root, "confirmer-killed"), "utf8"), /^\d+$/);
assert.equal(fs.readFileSync(entry, "utf8"), previous);
assert.equal(fs.readFileSync(info, "utf8"), previousInfo);
const result = state.read();
assert.equal(result.pending, undefined);
assert.equal(result.verified, undefined);
assert.equal(result.failure.reason, "commit");
assert.equal(result.failure.restored, true);
assert.equal(result.ignoredThrough, "v1.0.0");
} finally {
await cluster.stop();
}
});
test("panel verification keeps rollback pending through both confirmation flushes", { skip: process.platform !== "linux" }, t => {
const { panelWorkerIdentity } = require("../scripts/panel-update-recovery.cjs");
for (const failure of [null, "guard flush", "receipt flush", "readiness"]) {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
const id = beginFixtureUpdate(state, "v1.0.0");
const worker = panelWorkerIdentity(process.pid);
state.setPhase(id, "restart");
assert.equal(state.joinTrial(id, worker, 10_000), true);
const backupRoot = path.join(root, ".update-backups");
const inode = fs.statSync(backupRoot).ino;
const guard = path.join(backupRoot, ".confirm-pending.json");
const directory = path.join(backupRoot, id);
const archive = path.join(directory, ".confirm-pending.json");
const receipt = path.join(directory, ".confirm-provisional.json");
const receiptInode = fs.statSync(directory).ino;
const originalFsync = fs.fsyncSync;
const originalNow = Date.now;
let guardFlushed = false;
let receiptFlushed = false;
fs.fsyncSync = fd => {
const currentInode = fs.fstatSync(fd).ino;
if (currentInode === inode && fs.existsSync(archive) && !fs.existsSync(guard)) {
guardFlushed = true;
assert.equal(state.read().pending?.id, id);
assert.equal(state.read().verified, undefined);
if (failure === "guard flush") throw new Error("fixture guard flush failed");
}
if (currentInode === receiptInode && fs.existsSync(receipt)) {
receiptFlushed = true;
assert.equal(state.read().pending?.id, id);
assert.equal(state.read().verified, undefined);
if (failure === "receipt flush") throw new Error("fixture receipt flush failed");
if (failure === "readiness") Date.now = () => originalNow() + 4000;
}
return originalFsync(fd);
};
try {
if (failure) {
assert.throws(() => state.readyTrial(id, worker), /fixture .* flush failed|worker set did not stay ready/);
assert.equal(state.read().pending?.phase, "committing");
assert.equal(state.read().verified, undefined);
} else {
assert.equal(state.readyTrial(id, worker), true);
assert.equal(state.read().verified?.id, id);
assert.equal(fs.existsSync(guard), false);
assert.equal(fs.existsSync(receipt), false);
assert.equal(fs.existsSync(path.join(directory, ".confirm-complete.json")), true);
}
assert.equal(guardFlushed, true);
assert.equal(receiptFlushed, failure !== "guard flush");
} finally {
fs.fsyncSync = originalFsync;
Date.now = originalNow;
}
}
});
test("PM2 publishes only after old web and Agent readers exit and confirms both replacements", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const infoPath = path.join(root, "panel-information.json");
const candidate = `
const fs = require('node:fs');
const { markPanelUpdateReady } = require('./scripts/panel-update-recovery.cjs');
const server = require('node:http').createServer((_req, res) => res.end('candidate'));
console.log('CANDIDATE ' + process.pid);
server.listen(0, '127.0.0.1', () => {
const timer = setInterval(() => {
if (!fs.existsSync(__dirname + '/ready-' + process.pid)) return;
clearInterval(timer);
markPanelUpdateReady(server);
}, 25);
});`;
const previous = `
const fs = require('node:fs');
const { createPanelUpdateCoordinator } = require('./services/panel-update-coordinator');
const info = __dirname + '/panel-information.json';
const coordinator = createPanelUpdateCoordinator({
panelInfoFile: info, compareVersions: () => 0,
verifyAgentLauncher: () => {},
launchRestart: () => ({ on() {}, unref() {} }),
installUpdate: version => coordinator.applyPanelRelease(version, async begin => {
const write = begin();
write('index.js', ${JSON.stringify(candidate)});
write('lazy-helper.js', "module.exports = 'candidate';");
return { version };
}),
});
const server = require('node:http').createServer((_req, res) => res.end('previous'));
server.listen(0, '127.0.0.1', () => console.log('PREVIOUS ' + process.pid));
setInterval(() => {
if (fs.existsSync(__dirname + '/exit-' + process.pid)) process.exit(1);
if (fs.existsSync(__dirname + '/read-' + process.pid)) {
fs.unlinkSync(__dirname + '/read-' + process.pid);
console.log('OLD WEB READ ' + require('./lazy-helper'));
}
const request = __dirname + '/stage-' + process.pid;
if (!fs.existsSync(request)) return;
fs.unlinkSync(request);
coordinator.installPanelUpdate('v1.0.0').catch(err => console.error(err));
}, 25);`;
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(path.join(root, "index.js"), previous);
fs.writeFileSync(path.join(root, "lazy-helper.js"), "module.exports = 'previous';");
fs.mkdirSync(path.join(root, "AgentWorker"));
fs.writeFileSync(path.join(root, "AgentWorker/feature-config.js"), "exports.readAgentFeatureConfig = () => ({ enabled: true });");
fs.writeFileSync(path.join(root, "AgentWorker/worker.js"), `
const fs = require('node:fs');
exports.main = ({ updateSignal }) => {
console.log('AGENT LOAD ' + require('../lazy-helper'));
updateSignal.addEventListener('abort', () => {
delete require.cache[require.resolve('../lazy-helper')];
console.log('OLD AGENT READ ' + require('../lazy-helper'));
const timer = setInterval(() => {
if (!fs.existsSync(__dirname + '/../agent-may-exit')) return;
clearInterval(timer);
process.exit(1);
}, 25);
}, { once: true });
setInterval(() => {}, 500);
};`);
const state = createPanelUpdateState(infoPath);
const cluster = await startClusterFixture(root);
let agentOutput = "";
const agents = [];
const startAgent = () => {
const agent = spawn(process.execPath, [path.join(root, launcherPath), "--agent"], { cwd: root });
for (const stream of [agent.stdout, agent.stderr]) stream.on("data", chunk => { agentOutput += chunk; });
const closed = new Promise(resolve => agent.once("close", resolve));
agents.push({ agent, closed });
return closed;
};
try {
const workers = await cluster.waitFor(output => {
const pids = [...new Set([...output.matchAll(/PREVIOUS (\d+)/g)].map(match => Number(match[1])))];
return pids.length === 2 && pids;
});
const originalAgentClosed = startAgent();
await cluster.waitFor(() => /AGENT LOAD previous/.test(agentOutput));
fs.writeFileSync(path.join(root, `stage-${workers[0]}`), "");
const pending = await cluster.waitFor(() => {
const current = state.read().pending;
return current?.phase === "restart" && current;
});
assert.equal(pending.cohort.expected, 2);
assert.deepEqual(pending.cohort.previous.map(worker => worker.pid).sort(), [...workers].sort());
assert.equal(pending.staged, true);
fs.writeFileSync(path.join(root, `read-${workers[1]}`), "");
await cluster.waitFor(output => /OLD WEB READ previous/.test(output) && /OLD AGENT READ previous/.test(agentOutput));
fs.writeFileSync(path.join(root, `exit-${workers[0]}`), "");
const { execFileSync } = require("node:child_process");
await cluster.waitFor(output => {
assert.doesNotMatch(output, /CANDIDATE/);
const listing = JSON.parse(execFileSync(process.execPath, [require.resolve("pm2/bin/pm2"), "jlist"], {
env: { ...process.env, PM2_HOME: path.join(root, ".pm2") }, timeout: 5000,
}));
return listing.some(worker => worker.pid > 0 && !workers.includes(worker.pid));
});
assert.equal(state.read().pending.phase, "restart");
fs.writeFileSync(path.join(root, `exit-${workers[1]}`), "");
await cluster.waitFor(() => workers.every(pid => !require(`../${launcherPath}`).panelWorkerIdentity(pid)));
assert.equal(readPanelInfoVersion(root), "v0.9.0", "a still-running Agent holds the old generation");
fs.writeFileSync(path.join(root, "agent-may-exit"), "");
await originalAgentClosed;
startAgent();
const replacements = await cluster.waitFor(output => {
const pids = [...new Set([...output.matchAll(/CANDIDATE (\d+)/g)].map(match => Number(match[1])))];
return pids.length === 2 && pids;
});
fs.writeFileSync(path.join(root, `ready-${replacements[0]}`), "");
await cluster.waitFor(() => state.read().pending?.workers?.some(worker => worker.pid === replacements[0] && worker.readyAt));
assert.equal(state.read().pending.phase, "starting");
assert.equal(state.read().verified, undefined);
assert.doesNotMatch(agentOutput, /AGENT LOAD candidate/);
fs.writeFileSync(path.join(root, `ready-${replacements[1]}`), "");
await cluster.waitFor(() => state.read().verified?.id === pending.id);
assert.equal(state.read().pending, undefined);
await cluster.waitFor(() => /AGENT LOAD candidate/.test(agentOutput));
} finally {
for (const { agent } of agents) agent.kill();
await Promise.all(agents.map(({ closed }) => closed));
await cluster.stop();
}
});
for (const holdReload of [false, true]) {
test(holdReload ? "an old worker omitted by PM2 cannot overlap candidate startup" : "the daemon restarts the whole PM2 panel group after the requester exits", {
skip: process.platform !== "linux",
}, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const state = createPanelUpdateState(info);
const candidate = `
console.log('CANDIDATE ' + process.pid);
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => require('./${launcherPath}').markPanelUpdateReady(server));`;
const previous = `
const fs = require('node:fs');
const { createPanelUpdateCoordinator } = require('./services/panel-update-coordinator');
const coordinator = createPanelUpdateCoordinator({
panelInfoFile: ${JSON.stringify(info)}, compareVersions: () => 0, verifyAgentLauncher: () => {},
${holdReload ? "launchRestart: () => {}," : ""}
installUpdate: version => coordinator.applyPanelRelease(version, async begin => {
begin()('index.js', ${JSON.stringify(candidate)});
return { version };
}),
});
if (fs.existsSync(__dirname + '/hold-reload')) console.log('REPLACEMENT WAITING ' + process.pid);
else require('node:http').createServer().listen(0, '127.0.0.1', () => console.log('PREVIOUS ' + process.pid));
process.on('SIGINT', () => {
if (fs.existsSync(__dirname + '/ignore-stop-' + process.pid)) {
console.log('IGNORED STOP ' + process.pid);
return;
}
process.exit(0);
});
setInterval(() => {
const trigger = __dirname + '/stage-' + process.pid;
if (fs.existsSync(trigger)) {
fs.unlinkSync(trigger);
coordinator.installPanelUpdate('v1.0.0').catch(console.error);
}
if (fs.existsSync(__dirname + '/exit-' + process.pid)) process.exit(1);
}, 25);`;
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, previous);
const cluster = await startClusterFixture(root);
const pidsIn = (output, label) => [...new Set([...output.matchAll(new RegExp(`${label} (\\d+)`, "g"))].map(match => Number(match[1])))];
let reload;
try {
const workers = await cluster.waitFor(output => {
const initial = pidsIn(output, "PREVIOUS");
return initial.length === 2 && initial;
});
if (holdReload) {
const { stdout } = await runClusterFixtureCommand(root, ["jlist"]);
const slot = JSON.parse(stdout).find(worker => worker.pid === workers[0]).pm_id;
fs.writeFileSync(path.join(root, "hold-reload"), "");
reload = runClusterFixtureCommand(root, ["reload", String(slot)]).catch(() => {});
await cluster.waitFor(output => /REPLACEMENT WAITING \d+/.test(output));
} else {
fs.writeFileSync(path.join(root, `ignore-stop-${workers[1]}`), "");
}
fs.writeFileSync(path.join(root, `stage-${workers[holdReload ? 1 : 0]}`), "");
const pending = await cluster.waitFor(() => {
const current = state.read().pending;
return current?.phase === "restart" && current;
});
if (holdReload) {
assert.ok(!pending.cohort.previous.some(worker => worker.pid === workers[0]), "PM2 must omit the parked worker in this fixture");
for (const worker of pending.cohort.previous) fs.writeFileSync(path.join(root, `exit-${worker.pid}`), "");
await cluster.waitFor(async output => {
assert.doesNotMatch(output, /CANDIDATE \d+/);
const { stdout } = await runClusterFixtureCommand(root, ["jlist"]);
return JSON.parse(stdout).filter(worker => worker.pid > 0 && !pending.cohort.previous.some(prior => prior.pid === worker.pid)).length === 2;
});
assert.equal(state.read().pending.phase, "restart");
assert.doesNotThrow(() => process.kill(workers[0], 0), "the omitted worker is still alive");
fs.writeFileSync(path.join(root, `exit-${workers[0]}`), "");
}
const verified = await cluster.waitFor(output => pidsIn(output, "CANDIDATE").length === 2 && state.read().verified?.id === pending.id && output);
if (!holdReload) assert.match(verified, new RegExp(`IGNORED STOP ${workers[1]}`));
assert.doesNotMatch(verified, /Could not publish or enroll a panel trial worker/);
assert.equal(state.read().pending, undefined);
for (const pid of workers) assert.throws(() => process.kill(pid, 0), { code: "ESRCH" });
} finally {
await cluster.stop();
await reload;
}
});
}
test("a new PM2 supervisor verifies the replacement count in its own config", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
copyClusterFixture(root);
const { panelWorkerIdentity } = require("../scripts/panel-update-recovery.cjs");
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
writePanelInfo(root, "v0.9.0");
const id = state.prepare("v1.0.0", "v1.0.0", false, {
appName: "adpanel", expected: 2, previous: [], supervisor: panelWorkerIdentity(process.pid),
});
state.begin(id);
fs.writeFileSync(path.join(root, "index.js"), `
const { markPanelUpdateReady } = require('./scripts/panel-update-recovery.cjs');
const server = require('node:http').createServer();
server.listen(0, '127.0.0.1', () => markPanelUpdateReady(server));`);
state.setPhase(id, "restart");
const cluster = await startClusterFixture(root, 1);
try {
const pending = await cluster.waitFor(() => {
const current = state.read().pending;
return current?.phase === "starting" && current;
});
assert.equal(pending.expectedWorkers, 1);
await cluster.waitFor(() => state.read().verified?.id === id);
} finally {
await cluster.stop();
}
});
test("writePanelUpdateFileNoFollow preserves permissions and refuses to write through symlinks", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-nofollow-"));
try {
const target = path.join(dir, "regular.txt");
fs.writeFileSync(target, "old", { mode: 0o751 });
const mode = fs.statSync(target).mode & 0o777;
writePanelUpdateFileNoFollow(target, Buffer.from("hello"));
assert.equal(fs.readFileSync(target, "utf8"), "hello");
assert.equal(fs.statSync(target).mode & 0o777, mode);
const outside = path.join(dir, "outside.txt");
fs.writeFileSync(outside, "OUTSIDE");
const link = path.join(dir, "link.txt");
fs.symlinkSync(outside, link);
assert.throws(
() => writePanelUpdateFileNoFollow(link, Buffer.from("replacement")),
(err) => err.code === "EUPDATEFILETYPE",
"an existing symlink target must be refused"
);
assert.equal(fs.lstatSync(link).isSymbolicLink(), true);
assert.equal(fs.readFileSync(outside, "utf8"), "OUTSIDE", "the symlink target must be untouched");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("rollbackPanelUpdateFiles restores overwritten files and removes created ones", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-rollback-"));
try {
const backupDir = path.join(dir, "backup");
fs.mkdirSync(backupDir, { recursive: true });
const existing = path.join(dir, "index.js");
const created = path.join(dir, "new.js");
fs.writeFileSync(path.join(backupDir, "index.js"), "OLD");
fs.writeFileSync(existing, "NEW");
fs.writeFileSync(created, "CREATED");
rollbackPanelUpdateFiles([
{ relative: "index.js", target: existing, existedBefore: true },
{ relative: "new.js", target: created, existedBefore: false },
], backupDir, { warn() {}, error() {} });
assert.equal(fs.readFileSync(existing, "utf8"), "OLD", "the overwritten file must be restored from the snapshot");
assert.equal(fs.existsSync(created), false, "a file the update created must be removed");
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
// ---------------------------------------------------------------------------
// installPanelUpdateInternal end-to-end over a real temp panel root
// ---------------------------------------------------------------------------
const PANEL_UPDATE_REGION_START = 'const PANEL_INFO_FILE = path.join(__dirname, "panel-information.json");';
const PANEL_UPDATE_REGION_END = "async function fetchNodeReleases() {";
function buildPanelUpdateContext(options = {}) {
const root = options.root || makeTempPanelRoot();
const warnings = [];
const errors = [];
const logs = [];
const testState = {
releases: options.releases || [{ tag_name: "v1.0.0", zipball_url: "https://example/zip", body: options.releaseBody || "" }],
zipBuffer: options.zipBuffer || null,
restarts: 0,
spawnError: null,
timers: [],
now: options.now ?? Date.now(),
AdmZip,
};
let region = sliceBetween(indexSource, PANEL_UPDATE_REGION_START, PANEL_UPDATE_REGION_END);
if (Number.isFinite(options.maxTotal)) {
region = region.replace(
"const PANEL_UPDATE_MAX_TOTAL_UNCOMPRESSED = 512 * 1024 * 1024;",
`const PANEL_UPDATE_MAX_TOTAL_UNCOMPRESSED = ${options.maxTotal};`
);
}
if (Number.isFinite(options.maxEntry)) {
region = region.replace(
"const PANEL_UPDATE_MAX_ENTRY_UNCOMPRESSED = 64 * 1024 * 1024;",
`const PANEL_UPDATE_MAX_ENTRY_UNCOMPRESSED = ${options.maxEntry};`
);
}
const prelude = `
const { GENERATED_LOGO_FILENAME_RE, GENERATED_LOGIN_BG_FILENAME_RE } = __test.branding;
function readJson(file, fallback) {
try {
if (!fs.existsSync(file)) return fallback;
const raw = fs.readFileSync(file, "utf8").trim();
if (!raw) return fallback;
return JSON.parse(raw);
} catch { return fallback; }
}
function safeWriteJson(file, obj) {
try { fs.writeFileSync(file, JSON.stringify(obj, null, 2), "utf8"); return true; } catch { return false; }
}
function httpRequestJson(url) {
__test.releaseChecks = (__test.releaseChecks || 0) + 1;
if (__test.onReleaseRequest) return __test.onReleaseRequest(url);
if (url.includes("/tags/") && !__test.feedStatus) {
const tag = decodeURIComponent(url.split("/tags/")[1]);
const release = __test.releases.find(entry => entry?.tag_name === tag);
return release ? { status: 200, json: release } : { status: 404 };
}
return { status: __test.feedStatus || 200, json: __test.releases };
}
function httpGetRaw(url) {
if (__test.onDownload) return __test.onDownload(url);
if (__test.httpError) return Promise.reject(new Error(__test.httpError));
return Promise.resolve(__test.zipBuffer);
}
function require(mod) {
if (mod === "adm-zip") return __test.AdmZip;
if (mod === "./services/panel-update-coordinator") return {
createPanelUpdateCoordinator: (options) => __test.createPanelUpdateCoordinator({
...options, logger: console, recoveryAvailable: () => true, captureWorkers: () => undefined, acquireScaleLock: () => () => {},
launchRestart: spawn, armTimer: setTimeout, isStopping: () => false,
now: () => __test.now, getLoadedUpdateId: () => __test.loadedUpdateId,
}),
writePanelUpdateFileNoFollow: __test.writePanelUpdateFileNoFollow,
checkPanelUpdateParent: __test.checkPanelUpdateParent,
};
if (mod === "./services/panel-update-dependencies") return __test.panelUpdateDependencies;
if (mod === "./services/panel-update-releases") return __test.panelReleaseLookup;
if (mod === "./utils/update-version") return __test.updateVersion;
throw new Error("module not allowed in test sandbox: " + mod);
}
function spawn() {
if (__test.spawnError) throw __test.spawnError;
__test.restarts += 1;
return { unref() { }, on() { } };
}
// Deterministic fake timers: the restart watchdog is armed by the panel
// and fired manually by tests (the real restart would kill the process).
function setTimeout(fn, ms) { const t = { fn, ms }; __test.timers.push(t); return t; }
function clearTimeout(t) { const i = __test.timers.indexOf(t); if (i >= 0) __test.timers.splice(i, 1); }
function rateLimit() { return function middleware() { }; }
// adpanel:per-limiter-redis-stores — the update region's swept limiters
// reference the boot-time Redis client and store factory; the harness
// has no Redis, so a null client yields a undefined store (MemoryStore
// fallback), the same shape a Redis-less boot takes.
const redisClient = null;
function buildSharedRateLimitRedisStore() { return undefined; }
function sessionRevoke2faRateLimiter(req, res, next) { next(); }
function isAdmin() { return Promise.resolve(true); }
function findUserByEmail() { return Promise.resolve({ email: "admin@example.com", admin: true }); }
function issueActionToken() { return "token"; }
function requireActionTokenOr403() { return true; }
function requireDestructiveActionStepUp() { return { ok: true }; }
const app = {
get(route, handler) {
if (route === "/api/settings/panel-info") __test.infoRoute = handler;
},
post(route, ...handlers) {
if (route === "/api/settings/panel-update/check") __test.checkRoute = handlers.at(-1);
if (route === "/api/settings/panel-update/install") __test.installRoute = handlers.at(-1);
},
delete() { },
};
`;
const sandbox = {
fs,
path,
os,
crypto,
zlib,
Buffer,
Date,
performance: { timeOrigin: options.processStartedAt ?? Date.now() - 1000 },
atomicWriteFileSync,
// schedulePanelRestart reads process.env when building the restart script.
process: { env: {} },
console: {
log: (...a) => logs.push(a.join(" ")),
warn: (...a) => warnings.push(a.join(" ")),
error: (...a) => errors.push(a.join(" ")),
},
__dirname: root,
__test: Object.assign(testState, require("../services/panel-update-coordinator"), {
branding: require("../utils/branding"),
panelUpdateDependencies: require("../services/panel-update-dependencies"),
panelReleaseLookup: require("../services/panel-update-releases"),
updateVersion: require("../utils/update-version"),
loadedUpdateId: options.loadedUpdateId,
}),
};
vm.createContext(sandbox);
vm.runInContext(prelude + "\n" + region, sandbox);
return { sandbox, testState, root, warnings, errors, logs };
}
function writePanelInfo(root, version) {
fs.writeFileSync(
path.join(root, "panel-information.json"),
JSON.stringify([{ "panel-version": version, "panel-architecture": "test", "panel-auto-update": false }], null, 2)
);
}
function readPanelInfoVersion(root) {
return JSON.parse(fs.readFileSync(path.join(root, "panel-information.json"), "utf8"))[0]["panel-version"];
}
function publishFixtureRelease(root, expectedId) {
const state = createPanelUpdateState(path.join(root, "panel-information.json"), { error() {}, warn() {} });
const pending = state.read().pending;
assert.equal(pending?.staged, true);
if (expectedId) assert.equal(pending.id, expectedId);
state.publishStagedRelease(pending.id, require(`../${launcherPath}`).panelWorkerIdentity(process.pid), Date.now() + 10000);
}
function buildReleaseZip(entries) {
const zip = new AdmZip();
for (const [name, content] of entries) {
zip.addFile(name, Buffer.from(content));
}
return zip.toBuffer();
}
test("panel install: full success path — updatable files replaced, protected files skipped, backup kept, version bumped", async () => {
const root = makeTempPanelRoot();
fs.mkdirSync(path.join(root, "data"), { recursive: true });
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
fs.writeFileSync(path.join(root, "db.js"), "OLD-DB");
fs.writeFileSync(path.join(root, "package.json"), "{}");
fs.writeFileSync(path.join(root, ".env"), "ADPANEL_AGENT_ENABLED=OFF\n");
fs.writeFileSync(path.join(root, "start.sh"), "echo hi");
fs.mkdirSync(path.join(root, "public", "js"), { recursive: true });
fs.mkdirSync(path.join(root, "scripts"), { recursive: true });
const runtimeFiles = ["AgentWorker/node_modules/fixture/index.js", "AgentWorker/.env", "scripts/.venv/runtime",
"public/images/favicon.ico", "public/uploads/avatars/user.png",
"public/images/logo-0123456789abcdef.webp", "public/images/login-background-0123456789abcdef.webm",
"public/images/login-background-remote-fedcba9876543210.avif",
launcherPath, "scripts/adpanel-runtime.sh", "scripts/generate-ecosystem.sh", "scripts/adpanel-autoscale-monitor.sh",
"utils/atomic-file.js", "utils/cross-process-mutex.js", "utils/package.json"];
for (const relative of runtimeFiles) {
const runtimePath = path.join(root, relative);
fs.mkdirSync(path.dirname(runtimePath), { recursive: true });
fs.writeFileSync(runtimePath, "previous runtime content");
}
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
["ADPanel-v1.0.0/db.js", "NEW-DB"],
["ADPanel-v1.0.0/public/js/new-file.js", "console.log(1);"],
["ADPanel-v1.0.0/scripts/new.sh", "echo new"],
["ADPanel-v1.0.0/AgentWorker/worker.js", "WORKER"],
["ADPanel-v1.0.0/services/server-agent-queue.js", "QUEUE"],
["ADPanel-v1.0.0/ecosystem.config.template.js", "NEW-TEMPLATE"],
["ADPanel-v1.0.0/.env", "ADPANEL_AGENT_ENABLED=ON"],
["ADPanel-v1.0.0/privileged/adpanel-priv", "NOT UPDATABLE"],
["ADPanel-v1.0.0/initialize.sh", "NOT UPDATABLE"],
["ADPanel-v1.0.0/panel-information.json", "EVIL-VERSION-BOOKKEEPING"],
["ADPanel-v1.0.0/data/evil.txt", "EVIL"],
["ADPanel-v1.0.0/node_modules/evil.js", "EVIL"],
["ADPanel-v1.0.0/public/uploads", "NOT UPDATABLE"],
...runtimeFiles.map(relative => [`ADPanel-v1.0.0/${relative}`, "NOT UPDATABLE"]),
["ADPanel-v1.0.0/random.txt", "not updatable"],
]);
const { sandbox, testState, logs } = buildPanelUpdateContext({ root, zipBuffer });
const result = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
assert.equal(result.ok, true);
assert.equal(result.version, "v1.0.0");
assert.match(result.sha256, /^[a-f0-9]{64}$/);
assert.equal(result.sha256, sha256Hex(zipBuffer));
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
publishFixtureRelease(root, result.updateId);
for (const relative of runtimeFiles) {
assert.equal(fs.readFileSync(path.join(root, relative), "utf8"), "previous runtime content");
assert.equal(fs.existsSync(path.join(root, ".update-backups", result.updateId, relative)), false);
}
assert.equal(result.filesUpdated, 6);
assert.equal(result.filesSkipped, 24);
assert.equal(testState.restarts, 1, "a successful install schedules exactly one restart");
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "NEW-INDEX");
assert.equal(fs.readFileSync(path.join(root, "db.js"), "utf8"), "NEW-DB");
assert.equal(fs.readFileSync(path.join(root, "public/js/new-file.js"), "utf8"), "console.log(1);");
assert.equal(fs.readFileSync(path.join(root, "scripts/new.sh"), "utf8"), "echo new");
assert.equal(fs.readFileSync(path.join(root, "AgentWorker/worker.js"), "utf8"), "WORKER");
assert.equal(fs.readFileSync(path.join(root, "services/server-agent-queue.js"), "utf8"), "QUEUE");
assert.equal(fs.existsSync(path.join(root, "ecosystem.config.template.js")), false, "an inline update must not replace the recovery launcher configuration");
assert.equal(fs.readFileSync(path.join(root, "start.sh"), "utf8"), "echo hi", "files not in the archive are untouched");
assert.equal(readPanelInfoVersion(root), "v1.0.0", "the panel writes its own bookkeeping, never the archive's copy");
assert.ok(
!fs.readFileSync(path.join(root, "panel-information.json"), "utf8").includes("EVIL"),
"the archive's version-bookkeeping payload must not land in the file"
);
const [panelInfo] = JSON.parse(fs.readFileSync(path.join(root, "panel-information.json"), "utf8"));
const { "panel-last-update-at": installedAt, ...infoFields } = panelInfo;
assert.ok(Number.isFinite(Date.parse(installedAt)), "a successful install records its commit time");
assert.deepEqual([infoFields], [
{ "panel-version": "v1.0.0", "panel-architecture": "test", "panel-auto-update": false },
], "the rewrite preserves fields the panel does not own (auto-update, architecture)");
assert.equal(fs.existsSync(path.join(root, "data/evil.txt")), false, "protected directories must never be extracted");
assert.equal(fs.existsSync(path.join(root, "node_modules/evil.js")), false, "node_modules must never be extracted");
assert.equal(fs.readFileSync(path.join(root, ".env"), "utf8"), "ADPANEL_AGENT_ENABLED=OFF\n", "the update must preserve the operator's Agent flag");
assert.equal(fs.existsSync(path.join(root, "privileged/adpanel-priv")), false, "the helper remains installer-owned");
assert.equal(fs.existsSync(path.join(root, "initialize.sh")), false, "the root installer is not web-updatable");
const backups = fs.readdirSync(path.join(root, ".update-backups"), { withFileTypes: true })
.filter(entry => entry.isDirectory()).map(entry => entry.name);
assert.equal(backups.length, 1);
assert.equal(fs.readFileSync(path.join(root, ".update-backups", backups[0], "index.js"), "utf8"), "OLD-INDEX");
assert.equal(fs.readFileSync(path.join(root, ".update-backups", backups[0], "db.js"), "utf8"), "OLD-DB");
assert.ok(logs.join("\n").includes(sha256Hex(zipBuffer)), "the audit trail must carry the artifact hash");
fs.rmSync(root, { recursive: true, force: true });
});
test("panel install: downgrades are refused with 409 and nothing is touched", async () => {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v2.0.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.9.9/index.js", "DOWNGRADED"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.9.9', 'manual')", sandbox),
(err) => err.statusCode === 409 && /downgrade refused/.test(err.message)
);
assert.equal(testState.restarts, 0, "a refused install must not restart the panel");
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(readPanelInfoVersion(root), "v2.0.0");
fs.rmSync(root, { recursive: true, force: true });
});
test("panel install: same-version repair installs stay allowed; unknown versions are never treated as downgrades", async () => {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v1.0.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "REPAIRED"]]);
const { sandbox } = buildPanelUpdateContext({ root, zipBuffer });
const result = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
assert.equal(result.ok, true);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
publishFixtureRelease(root, result.updateId);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "REPAIRED");
fs.rmSync(root, { recursive: true, force: true });
const root2 = makeTempPanelRoot();
fs.writeFileSync(path.join(root2, "index.js"), "OLD-INDEX");
const ctx2 = buildPanelUpdateContext({
root: root2,
zipBuffer,
releases: [{ tag_name: "v0.0.1", zipball_url: "https://example/zip", body: "" }],
});
const result2 = await vm.runInContext("installPanelUpdateInternal('v0.0.1', 'manual')", ctx2.sandbox);
assert.equal(result2.ok, true, "an unknown current version must not be read as newer than everything");
fs.rmSync(root2, { recursive: true, force: true });
});
test("panel install: an explicit version matches either tag spelling and prefers an exact release", async (t) => {
const prefixed = { tag_name: "v1.0.0", zipball_url: "https://example/prefixed.zip" };
const bare = { tag_name: "1.0.0", zipball_url: "https://example/bare.zip" };
for (const [version, releases, expected] of [
["v1.0.0", [bare], bare],
["V1.0.0", [bare], bare],
["1.0.0", [prefixed], prefixed],
["v1.0.0", [bare, prefixed], prefixed],
["1.0.0", [prefixed, bare], bare],
]) {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-release/index.js", "UPDATED"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, releases });
testState.onDownload = (url) => {
assert.equal(url, expected.zipball_url);
return zipBuffer;
};
const response = await testState.installRoute({ session: { user: "admin@example.com" }, body: { version } }, {
status() { return this; }, json: (body) => body,
});
assert.equal(response.ok, true, response.error);
publishFixtureRelease(root, response.updateId);
assert.equal(readPanelInfoVersion(root), "v1.0.0");
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "UPDATED");
assert.equal(testState.restarts, 1);
}
});
test("panel install: version strings that carry shell/garbage tails are rejected by the strict validator", async () => {
for (const bad of ["1.2.3-$(id)", "1.2.3;rm -rf", "1.2.3.4", "1.2.3-evil/../../x", "abc", ""]) {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
const { sandbox } = buildPanelUpdateContext({ root });
await assert.rejects(
vm.runInContext(`installPanelUpdateInternal(${JSON.stringify(bad)}, 'manual')`, sandbox),
(err) => err.statusCode === 400 && /invalid version format/.test(err.message),
`version ${JSON.stringify(bad)} must be rejected`
);
fs.rmSync(root, { recursive: true, force: true });
}
});
test("panel install: a release the GitHub API does not list is a 404", async () => {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const { sandbox } = buildPanelUpdateContext({
root,
releases: [{ tag_name: "v1.0.0", zipball_url: "https://example/zip", body: "" }],
zipBuffer: Buffer.from("x"),
});
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v9.9.9', 'manual')", sandbox),
(err) => err.statusCode === 404
);
fs.rmSync(root, { recursive: true, force: true });
});
test("panel release checks find stable tags beyond the first GitHub page and refuse a truncated feed", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const { sandbox, testState } = buildPanelUpdateContext({ root });
const previews = Array.from({ length: 100 }, (_, index) => ({ tag_name: `v2.0.0-rc.${index}` }));
const stable = { tag_name: "v1.2.0" };
testState.onReleaseRequest = url => {
const params = new URL(url).searchParams;
assert.equal(params.get("per_page"), "100");
return { status: 200, json: params.get("page") === "1" ? previews : [stable, { tag_name: "v9.0.0", draft: true }] };
};
const check = await vm.runInContext("checkPanelUpdateInternal()", sandbox);
assert.equal(check.latestRelease, stable);
assert.equal(check.updateAvailable, true);
assert.equal(testState.releaseChecks, 2);
testState.releaseChecks = 0;
testState.onReleaseRequest = () => ({ status: 200, json: [stable, ...previews.slice(1)] });
await assert.rejects(vm.runInContext("checkPanelUpdateInternal()", sandbox), /supported page limit/);
assert.equal(testState.releaseChecks, 5);
assert.deepEqual(createPanelUpdateState(path.join(root, "panel-information.json")).read(), {});
});
test("panel install: blocked destinations reject and roll back the release without following symlinks", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
fs.mkdirSync(path.join(root, "public", "js"), { recursive: true });
const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-outside-"));
t.after(() => fs.rmSync(outsideDir, { recursive: true, force: true }));
const outsideFile = path.join(outsideDir, "outside.txt");
fs.writeFileSync(outsideFile, "OUTSIDE");
fs.symlinkSync(outsideFile, path.join(root, "public", "js", "x.js"));
fs.symlinkSync(outsideDir, path.join(root, "public", "sub"));
for (const [relative, expectedError] of [
["public/js/x.js", /target is not a regular file/i],
["public/sub/nested/blocked.js", /symlink or non-directory parent/],
]) {
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
[`ADPanel-v1.0.0/${relative}`, "REPLACEMENT"],
]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), (err) =>
err.statusCode === 409 && expectedError.test(err.message));
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
}
assert.equal(fs.readFileSync(outsideFile, "utf8"), "OUTSIDE", "a pre-planted symlink must not redirect the write");
assert.equal(fs.existsSync(path.join(outsideDir, "nested")), false, "a symlinked directory must not become an escape hatch");
assert.ok(fs.lstatSync(path.join(root, "public", "js", "x.js")).isSymbolicLink(), "the symlink itself is left alone");
});
test("panel install: an archive without any updatable files cannot commit a version", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/README.md", "Release notes only"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), /no panel files to update/);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
});
test("panel install: a release cannot change how Node loads the recovery launcher", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const indexPath = path.join(root, "index.js");
fs.writeFileSync(indexPath, "previous");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([
["ADPanel-release/index.js", "candidate"],
["ADPanel-release/package.json", JSON.stringify({ type: "module" })],
]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), /startup format/);
assert.equal(fs.readFileSync(indexPath, "utf8"), "previous");
assert.equal(testState.restarts, 0);
assert.equal(createPanelUpdateState(path.join(root, "panel-information.json")).read().failure.reason, "startupFormat");
});
test("panel install: a mid-extraction failure discards staged files without changing the live tree", async () => {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
fs.mkdirSync(path.join(root, "public"), { recursive: true });
fs.writeFileSync(path.join(root, "public", "x"), "I am a file, not a directory");
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
["ADPanel-v1.0.0/public/newdir/ok.js", "OK"],
["ADPanel-v1.0.0/public/x/y.js", "Y"],
]);
const { sandbox } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox),
(err) => err && err.code === "ENOTDIR",
"writing under a file-parent must fail the extraction"
);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX", "the live file must not be replaced");
assert.equal(fs.existsSync(path.join(root, "public/newdir")), false, "the directory must exist only in the private stage");
assert.equal(fs.readdirSync(path.join(root, ".update-backups")).some(name => name.startsWith(".staged-")), false);
assert.equal(readPanelInfoVersion(root), "v0.9.0", "the version bookkeeping must not move on a failed install");
fs.rmSync(root, { recursive: true, force: true });
});
test("panel install: a partial staging write leaves the installed source unchanged", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "NEW-INDEX"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
const writeFileSync = fs.writeFileSync;
const failure = Object.assign(new Error("disk full during update"), { code: "ENOSPC" });
t.mock.method(fs, "writeFileSync", (target, data, ...options) => {
if (typeof target === "number" && Buffer.isBuffer(data) && data.toString() === "NEW-INDEX") {
writeFileSync(target, data.subarray(0, 3));
throw failure;
}
return writeFileSync(target, data, ...options);
});
await assert.rejects(vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox), { code: "ENOSPC" });
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
});
test("panel publish: persistent disk-full errors restore already replaced files", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const indexPath = path.join(root, "index.js");
fs.writeFileSync(indexPath, "OLD-INDEX", { mode: 0o640 });
fs.writeFileSync(path.join(root, "nodes.js"), "OLD-NODES");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
["ADPanel-v1.0.0/nodes.js", "NEW-NODES"],
]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
const { updateId } = await vm.runInContext("installPanelUpdate('v1.0.0')", sandbox);
const state = createPanelUpdateState(path.join(root, "panel-information.json"), { error() {}, warn() {} });
const writeFileSync = fs.writeFileSync;
const failure = Object.assign(new Error("disk remains full"), { code: "ENOSPC" });
let diskFull = false;
t.mock.method(fs, "writeFileSync", (target, data, ...options) => {
if (typeof target === "number" && Buffer.isBuffer(data) && data.toString() === "NEW-NODES") {
assert.equal(fs.readFileSync(indexPath, "utf8"), "NEW-INDEX");
diskFull = true;
}
if (diskFull) throw failure;
return writeFileSync(target, data, ...options);
});
assert.throws(() => publishFixtureRelease(root, updateId), { code: "ENOSPC" });
assert.equal(state.recover(updateId, "storage"), true);
assert.equal(fs.readFileSync(indexPath, "utf8"), "OLD-INDEX");
assert.equal(fs.statSync(indexPath).mode & 0o777, 0o640);
assert.equal(fs.readFileSync(path.join(root, "nodes.js"), "utf8"), "OLD-NODES");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 1);
});
test("panel publish: an incomplete rollback leaves the backup and reports that recovery is required", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const indexPath = path.join(root, "index.js");
const infoPath = path.join(root, "panel-information.json");
fs.writeFileSync(indexPath, "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "NEW-INDEX"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
const { updateId } = await vm.runInContext("installPanelUpdate('v1.0.0')", sandbox);
const renameSync = fs.renameSync;
t.mock.method(fs, "renameSync", (source, target) => {
if (target === infoPath || (target === indexPath && /^\.update-restore(?:-|\.)/.test(path.basename(source)))) {
throw Object.assign(new Error("storage write failed"), { code: "EIO" });
}
return renameSync(source, target);
});
assert.throws(() => publishFixtureRelease(root, updateId), { code: "EIO" });
const state = createPanelUpdateState(infoPath, { error() {} });
assert.equal(state.recover(updateId, "install"), false);
const status = await testState.infoRoute({ query: { status: "1" } }, { set() {}, json: body => body });
assert.match(status.updateError, /Automatic recovery could not finish.*before restarting/);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 1);
const backupRoot = path.join(root, ".update-backups");
const { pending } = createPanelUpdateState(infoPath).read();
assert.equal(pending.phase, "restoring");
assert.equal(fs.readFileSync(path.join(backupRoot, pending.id, "index.js"), "utf8"), "OLD-INDEX");
});
test("status reports operator action when an abandoned install cannot save its rollback phase", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const info = path.join(root, "panel-information.json");
const indexPath = path.join(root, "index.js");
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(indexPath, "previous");
const state = createPanelUpdateState(info);
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(indexPath, "candidate");
const { createPanelUpdateCoordinator, createPanelUpdateMutex } = require("../services/panel-update-coordinator");
const coordinator = createPanelUpdateCoordinator({ panelInfoFile: info, logger: { error() {} } });
const release = createPanelUpdateMutex(info).tryAcquire();
try {
assert.equal(coordinator.getPanelUpdateStatus().restartPending, true);
} finally {
release();
}
const abandoned = coordinator.getPanelUpdateStatus();
assert.equal(abandoned.recoveryPending, true);
assert.equal(abandoned.updateBlocked, true);
assert.equal(abandoned.updateError, "", "operator action must not be reported before a recovery attempt fails");
const rename = fs.renameSync;
t.mock.method(fs, "renameSync", (source, target) => {
if (path.basename(target) === "update-state.json") throw Object.assign(new Error("fixture journal write failed"), { code: "EIO" });
return rename(source, target);
});
coordinator.recoverAbandonedPanelUpdate();
const status = createPanelUpdateCoordinator({ panelInfoFile: info }).getPanelUpdateStatus();
assert.equal(state.read().pending.phase, "applying");
assert.equal(status.restartPending, false);
assert.equal(status.updateBlocked, true);
assert.equal(status.failedUpdate.restored, false);
assert.match(status.updateError, /restore from backup/i);
});
test("all workers report incomplete recovery when storage cannot allocate a status file", (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const panelInfoFile = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
const logger = { error() {}, warn() {} };
const { createPanelUpdateCoordinator } = require("../services/panel-update-coordinator");
const state = createPanelUpdateState(panelInfoFile, logger);
writePanelInfo(root, "v0.9.0");
fs.writeFileSync(entry, "previous");
const id = beginFixtureUpdate(state, "v1.0.0");
state.snapshot(id, "index.js", true);
writePanelUpdateFileNoFollow(entry, "candidate");
const diskFull = Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
const open = fs.openSync;
const preventNewFiles = t.mock.method(fs, "openSync", (file, flags, ...args) => {
if (flags === "wx" && file.startsWith(root)) throw diskFull;
return open(file, flags, ...args);
});
const preventCopy = t.mock.method(fs, "copyFileSync", () => { throw diskFull; });
const preventLink = t.mock.method(fs, "linkSync", () => { throw diskFull; });
createPanelUpdateCoordinator({ panelInfoFile, logger }).recoverAbandonedPanelUpdate();
const observer = createPanelUpdateCoordinator({ panelInfoFile, logger });
const status = observer.getPanelUpdateStatus();
assert.equal(status.updateBlocked, true);
assert.equal(status.restartPending, false);
assert.deepEqual(status.failedUpdate, { version: "v1.0.0", reason: "storage", restored: false });
assert.match(status.updateError, /Automatic recovery could not finish/);
assert.equal(state.read().pending.id, id);
assert.equal(fs.readFileSync(entry, "utf8"), "candidate");
for (const mock of [preventNewFiles, preventCopy, preventLink]) mock.mock.restore();
observer.recoverAbandonedPanelUpdate();
assert.equal(observer.getPanelUpdateStatus().failedUpdate.restored, true);
assert.equal(fs.readFileSync(entry, "utf8"), "previous");
});
test("panel publish: a failed version record write rolls back files before candidate startup", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
["ADPanel-v1.0.0/public/js/new-file.js", "NEW-FILE"],
]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
const infoPath = path.join(root, "panel-information.json");
const { updateId } = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
const renameSync = fs.renameSync;
const failure = Object.assign(new Error("version record could not be written"), { code: "ENOSPC" });
t.mock.method(fs, "renameSync", (source, target) => {
if (target === infoPath) throw failure;
return renameSync(source, target);
});
assert.throws(() => publishFixtureRelease(root, updateId), /version record/);
assert.equal(createPanelUpdateState(infoPath).recover(updateId, "storage"), true);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(fs.existsSync(path.join(root, "public/js/new-file.js")), false);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 1);
});
test("panel install: automatic and manual workers cannot write the same installation concurrently", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "NEW-INDEX"]]);
const automatic = buildPanelUpdateContext({ root, zipBuffer });
const manual = buildPanelUpdateContext({ root, zipBuffer });
vm.runInContext("setPanelAutoUpdateEnabled(true)", automatic.sandbox);
let finishDownload;
const downloadStarted = new Promise((resolve) => {
automatic.testState.onDownload = () => new Promise((finish) => {
finishDownload = finish;
resolve();
});
});
const automaticInstall = vm.runInContext("runPanelAutoUpdateCycle('interval')", automatic.sandbox);
try {
await downloadStarted;
const response = {
statusCode: 200,
status(code) { this.statusCode = code; return this; },
json(body) { this.body = body; return this; },
};
await manual.testState.installRoute({ session: { user: "admin@example.com" }, body: { version: "v1.0.0" } }, response);
assert.equal(response.statusCode, 409);
assert.match(response.body.error, /update is already in progress/);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(manual.testState.restarts, 0);
} finally {
finishDownload?.(zipBuffer);
await automaticInstall;
}
assert.equal(readPanelInfoVersion(root), "v0.9.0", "staging must not change the live version");
const { pending } = createPanelUpdateState(path.join(root, "panel-information.json")).read();
assert.equal(pending?.version, "v1.0.0");
assert.equal(pending?.staged, true);
assert.equal(automatic.testState.restarts, 1);
});
test("panel check and automatic update distinguish an unavailable stable release from an up-to-date panel", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v1.0.0");
const { sandbox, testState, errors, logs } = buildPanelUpdateContext({ root, releases: [] });
vm.runInContext("setPanelAutoUpdateEnabled(true)", sandbox);
const check = async () => {
const response = {
statusCode: 200,
status(code) { this.statusCode = code; return this; },
json(body) { this.body = body; return this; },
};
await testState.checkRoute({}, response);
return response;
};
for (const releases of [[], [{ tag_name: "v1.1.0-rc.1", prerelease: true }]]) {
testState.releases = releases;
const response = await check();
assert.equal(response.statusCode, 503);
assert.match(response.body.error, /no stable panel release/i);
assert.equal(response.body.updateAvailable, undefined);
}
await vm.runInContext("runPanelAutoUpdateCycle('interval')", sandbox);
assert.match(errors.at(-1), /Cycle failed: No stable panel release/);
assert.equal(testState.restarts, 0);
assert.equal(readPanelInfoVersion(root), "v1.0.0");
testState.releases = [{ tag_name: "v1.0.0" }];
const response = await check();
assert.equal(response.statusCode, 200);
assert.equal(response.body.updateAvailable, false);
assert.equal(response.body.latestVersion, "v1.0.0");
await vm.runInContext("runPanelAutoUpdateCycle('interval')", sandbox);
assert.match(logs.at(-1), /No update available/);
});
test("panel auto update skips a failed release across workers and tries a newer stable version", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const first = buildPanelUpdateContext({ root });
first.testState.httpError = "download interrupted";
vm.runInContext("setPanelAutoUpdateEnabled(true)", first.sandbox);
await vm.runInContext("runPanelAutoUpdateCycle('interval')", first.sandbox);
assert.match(first.errors.at(-1), /failed to download/);
assert.equal(first.testState.releaseChecks, 1, "automatic install uses the exact release it checked");
const zipBuffer = buildReleaseZip([["ADPanel-next/index.js", "UPDATED"]]);
const next = buildPanelUpdateContext({ root, zipBuffer });
await vm.runInContext("runPanelAutoUpdateCycle('startup')", next.sandbox);
assert.equal(next.testState.restarts, 0);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
const info = await next.testState.infoRoute({ query: { status: "1" } }, { set() {}, json: (body) => body });
assert.match(info.updateError, /Update to v1\.0\.0 failed.*could not be downloaded.*No panel files were changed/);
assert.equal(info.actionTokens, undefined);
const check = await next.testState.checkRoute({}, { json: (body) => body });
assert.equal(check.updateDeferred, true);
assert.equal(check.actionTokens, undefined);
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0', true)", next.sandbox), { statusCode: 409 });
assert.equal(next.testState.restarts, 0);
next.testState.releases = [{ tag_name: "v1.0.1", zipball_url: "https://example/next" }];
await vm.runInContext("runPanelAutoUpdateCycle('interval')", next.sandbox);
assert.equal(next.testState.restarts, 1);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
publishFixtureRelease(root);
assert.equal(readPanelInfoVersion(root), "v1.0.1");
});
test("an invalid manual request or failed feed does not suppress a release", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v1.0.0");
const info = path.join(root, "panel-information.json");
const state = createPanelUpdateState(info);
const { sandbox, testState } = buildPanelUpdateContext({ root,
zipBuffer: buildReleaseZip([["ADPanel-release/index.js", "candidate"]]),
releases: [{ tag_name: "v1.1.0", zipball_url: "https://example/next" }],
});
vm.runInContext("setPanelAutoUpdateEnabled(true)", sandbox);
for (const [version, statusCode] of [["v9.0.0-preview_name", 400], ["v0.9.0", 409], ["v2.0.0", 404]]) {
await assert.rejects(vm.runInContext(`installPanelUpdate(${JSON.stringify(version)})`, sandbox), { statusCode });
assert.deepEqual(state.read(), {});
}
testState.feedStatus = 502;
await assert.rejects(vm.runInContext("installPanelUpdate('v1.1.0')", sandbox), { statusCode: 502 });
assert.deepEqual(state.read(), {});
await vm.runInContext("runPanelAutoUpdateCycle('interval')", sandbox);
assert.deepEqual(state.read(), { checkFailed: true });
assert.equal(testState.restarts, 0);
testState.feedStatus = 200;
await vm.runInContext("runPanelAutoUpdateCycle('interval')", sandbox);
assert.equal(state.read().checkFailed, undefined);
assert.equal(state.read().pending.version, "v1.1.0");
assert.equal(testState.restarts, 1);
});
test("a healthy automatic check clears the feed error even when install prerequisites block the release", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const panelInfoFile = path.join(root, "panel-information.json");
const state = createPanelUpdateState(panelInfoFile);
const { createPanelUpdateCoordinator } = require("../services/panel-update-coordinator");
const checkUpdate = t.mock.fn(async () => { throw new Error("feed offline"); });
const installUpdate = t.mock.fn();
const coordinator = createPanelUpdateCoordinator({
panelInfoFile, readPanelInfo: () => ({ autoUpdate: true, version: "v1.0.0" }), checkUpdate, installUpdate,
recoveryAvailable: () => false, logger: { log() {}, error() {} },
});
await coordinator.runPanelAutoUpdateCycle();
assert.match(coordinator.getPanelUpdateStatus().updateError, /could not verify a stable GitHub release/);
checkUpdate.mock.mockImplementation(async () => ({ updateAvailable: true, currentVersion: "v1.0.0", latestVersion: "v1.1.0" }));
await coordinator.runPanelAutoUpdateCycle();
assert.equal(coordinator.getPanelUpdateStatus().updateError, "");
assert.deepEqual(state.read(), {});
assert.equal(installUpdate.mock.callCount(), 0);
});
test("a selected release is deferred if the initial journal write exhausts storage after reservation", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const { sandbox, testState } = buildPanelUpdateContext({ root });
const open = fs.openSync;
t.mock.method(fs, "openSync", (target, flags, ...args) => {
if (flags === "wx" && path.basename(target).startsWith(".update-state.json.")) {
throw Object.assign(new Error("fixture disk full"), { code: "ENOSPC" });
}
return open(target, flags, ...args);
});
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), err =>
err.code === "ENOSPC" && /No panel files were changed/.test(err.panelUpdateMessage));
const saved = createPanelUpdateState(path.join(root, "panel-information.json")).read();
assert.equal(saved.pending, undefined);
assert.equal(saved.ignoredThrough, "v1.0.0");
assert.equal(saved.failure.reason, "storage");
assert.equal(saved.failure.restored, null);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
});
test("startup's space reserve saves the failed release when the initial preflight file cannot be allocated", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const info = path.join(root, "panel-information.json");
const entry = path.join(root, "index.js");
fs.writeFileSync(entry, "previous source");
const installer = buildPanelUpdateContext({ root });
vm.runInContext("setPanelAutoUpdateEnabled(true)", installer.sandbox);
const state = createPanelUpdateState(info);
state.write({ checkFailed: true });
state.reservePreflightSpace();
const backupRoot = path.join(root, ".update-backups");
const reserve = path.join(backupRoot, ".preflight-space-reserve");
assert.ok(fs.statSync(reserve).blocks > 0, "the reserve must allocate disk blocks");
const open = fs.openSync;
const diskFull = t.mock.method(fs, "openSync", (target, flags, ...args) => {
if (flags === "wx" && path.dirname(target) === backupRoot && fs.existsSync(reserve)) {
throw Object.assign(new Error("fixture disk full before staging"), { code: "ENOSPC" });
}
return open(target, flags, ...args);
});
await vm.runInContext("runPanelAutoUpdateCycle('startup')", installer.sandbox);
diskFull.mock.restore();
assert.equal(fs.existsSync(reserve), false);
assert.equal(state.read().pending, undefined);
assert.equal(state.read().ignoredThrough, "v1.0.0");
assert.equal(state.read().failure?.reason, "storage");
assert.equal(state.read().checkFailed, undefined);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.readFileSync(entry, "utf8"), "previous source");
const observer = buildPanelUpdateContext({ root });
const status = await observer.testState.infoRoute({ query: { status: "1" } }, { set() {}, json: body => body });
assert.match(status.updateError, /ran out of storage space.*No panel files were changed/);
observer.testState.onDownload = () => assert.fail("the failed release must not be downloaded again");
await vm.runInContext("runPanelAutoUpdateCycle('startup')", observer.sandbox);
assert.equal(observer.testState.restarts, 0);
});
test("panel info: a different worker reports the installed build still needs to be loaded", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "NEW-INDEX"]]);
const installer = buildPanelUpdateContext({ root, zipBuffer });
const otherWorker = buildPanelUpdateContext({ root, zipBuffer, loadedUpdateId: null });
const readInfo = (worker) => worker.testState.infoRoute({}, { set() { }, json: (body) => body });
const result = await vm.runInContext("installPanelUpdate('v1.0.0')", installer.sandbox);
assert.equal(result.restartScheduled, true);
const staged = await readInfo(otherWorker);
assert.equal(staged.version, "v0.9.0");
assert.equal(staged.restartPending, true);
publishFixtureRelease(root, result.updateId);
const info = await readInfo(otherWorker);
assert.equal(info.version, "v1.0.0");
assert.equal(info.restartRequired, true);
const restarted = buildPanelUpdateContext({ root, processStartedAt: 1, loadedUpdateId: result.updateId });
const restartedInfo = await readInfo(restarted);
assert.equal(restartedInfo.version, "v1.0.0");
assert.equal(restartedInfo.restartRequired, false);
fs.utimesSync(path.join(root, "index.js"), new Date(0), new Date(0));
assert.equal((await readInfo(restarted)).lastUpdate, restartedInfo.lastUpdate, "last update is not the source file's mtime");
});
test("panel info reports an unreadable recovery record and blocks new installs", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const backupRoot = path.join(root, ".update-backups");
fs.mkdirSync(backupRoot);
fs.writeFileSync(path.join(backupRoot, "update-state.json"), "{");
const { sandbox, testState } = buildPanelUpdateContext({ root });
const info = await testState.infoRoute({}, { set() {}, json: body => body });
assert.equal(info.version, "v0.9.0");
assert.equal(info.updateBlocked, true);
assert.match(info.updateError, /cannot read its update recovery record/);
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), { name: "SyntaxError" });
assert.equal(testState.releaseChecks, undefined);
assert.equal(testState.restarts, 0);
});
test("panel install: the declared uncompressed budget aborts the install before anything is decompressed", async () => {
const root = makeTempPanelRoot();
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const big = "a".repeat(1024 * 1024);
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/public/js/a.js", big],
["ADPanel-v1.0.0/public/js/b.js", big],
]);
const { sandbox } = buildPanelUpdateContext({ root, zipBuffer, maxTotal: 1.5 * 1024 * 1024 });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox),
(err) => err.statusCode === 502 && /size budget/.test(err.message)
);
assert.equal(fs.existsSync(path.join(root, "public/js/a.js")), false, "no extraction may happen once the budget is blown");
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
fs.rmSync(root, { recursive: true, force: true });
});
test("panel install: integrity pins are enforced end-to-end through the real pins file", async () => {
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "PINNED"]]);
const hash = sha256Hex(zipBuffer);
// requirePinned without a pin: refused.
const root1 = makeTempPanelRoot();
fs.mkdirSync(path.join(root1, "data"), { recursive: true });
fs.writeFileSync(path.join(root1, "index.js"), "OLD-INDEX");
writePanelInfo(root1, "v0.9.0");
fs.writeFileSync(path.join(root1, "data", "update-checksums.json"), JSON.stringify({ requirePinned: true, panel: {} }));
const ctx1 = buildPanelUpdateContext({ root: root1, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", ctx1.sandbox),
(err) => err.statusCode === 502 && /no pinned sha256/.test(err.message)
);
fs.rmSync(root1, { recursive: true, force: true });
// Pin mismatch: refused before extraction.
const root2 = makeTempPanelRoot();
fs.mkdirSync(path.join(root2, "data"), { recursive: true });
fs.writeFileSync(path.join(root2, "index.js"), "OLD-INDEX");
writePanelInfo(root2, "v0.9.0");
fs.writeFileSync(path.join(root2, "data", "update-checksums.json"), JSON.stringify({ panel: { "v1.0.0": "0".repeat(64) } }));
const ctx2 = buildPanelUpdateContext({ root: root2, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", ctx2.sandbox),
(err) => err.statusCode === 502 && /pinned sha256 mismatch/.test(err.message)
);
assert.equal(fs.readFileSync(path.join(root2, "index.js"), "utf8"), "OLD-INDEX");
fs.rmSync(root2, { recursive: true, force: true });
// Matching pin: installs and reports the verified hash.
const root3 = makeTempPanelRoot();
fs.writeFileSync(path.join(root3, "index.js"), "OLD-INDEX");
writePanelInfo(root3, "v0.9.0");
fs.mkdirSync(path.join(root3, "data"), { recursive: true });
fs.writeFileSync(path.join(root3, "data", "update-checksums.json"), JSON.stringify({ panel: { "v1.0.0": hash } }));
const ctx3 = buildPanelUpdateContext({ root: root3, zipBuffer });
const result = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", ctx3.sandbox);
assert.equal(result.ok, true);
assert.equal(result.sha256, hash);
assert.ok(ctx3.logs.join("\n").includes("verified against pinned checksum"));
publishFixtureRelease(root3, result.updateId);
assert.equal(fs.readFileSync(path.join(root3, "index.js"), "utf8"), "PINNED");
fs.rmSync(root3, { recursive: true, force: true });
});
test("panel install: an invalid checksum policy fails closed without changing files", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
fs.mkdirSync(path.join(root, "data"));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/index.js", "NEW-INDEX"]]);
for (const invalidPolicy of ['{"requirePinned": true,', '{"requirePinned": "true"}']) {
fs.writeFileSync(path.join(root, "data", "update-checksums.json"), invalidPolicy);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox),
(err) => err.statusCode === 502 && /invalid update checksum policy/.test(err.message)
);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
}
const pins = path.join(root, "data", "update-checksums.json");
fs.unlinkSync(pins);
fs.symlinkSync(path.join(root, "missing-policy.json"), pins);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox),
err => err.statusCode === 502 && /invalid update checksum policy/.test(err.message));
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(testState.restarts, 0);
});
test("dependency preflight rejects a release that requires a different Node engine", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const { verifyPanelUpdateDependencies } = require("../services/panel-update-dependencies");
const version = Number(process.versions.node.split(".")[0]) + 1;
const manifest = Buffer.from(JSON.stringify({ engines: { node: `>=${version}` } }));
await assert.rejects(verifyPanelUpdateDependencies(root, manifest), {
code: "PANEL_UPDATE_DEPENDENCIES", statusCode: 409,
});
assert.deepEqual(fs.readdirSync(root), []);
});
test("panel install: a release cannot commit with incompatible installed dependencies", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const manifest = (version) => JSON.stringify({ name: "panel-fixture", version: "1.0.0", dependencies: { "fixture-package": version } });
const dependency = path.join(root, "node_modules", "fixture-package");
fs.mkdirSync(dependency, { recursive: true });
fs.writeFileSync(path.join(dependency, "package.json"), JSON.stringify({ name: "fixture-package", version: "1.0.0" }));
fs.writeFileSync(path.join(root, "package.json"), manifest("^1.0.0"));
fs.writeFileSync(path.join(root, "index.js"), "OLD-INDEX");
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([
["ADPanel-v1.0.0/index.js", "NEW-INDEX"],
["ADPanel-v1.0.0/package.json", manifest("^2.0.0")],
]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await assert.rejects(
vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox),
(err) => err.statusCode === 409 && /runtime dependencies/.test(err.message)
);
assert.equal(fs.readFileSync(path.join(root, "index.js"), "utf8"), "OLD-INDEX");
assert.equal(fs.readFileSync(path.join(root, "package.json"), "utf8"), manifest("^1.0.0"));
assert.equal(fs.readdirSync(path.join(root, ".update-backups"), { withFileTypes: true }).some(entry => entry.isDirectory()), false);
const update = createPanelUpdateState(path.join(root, "panel-information.json")).read();
assert.equal(update.failure.reason, "dependencies");
assert.equal(update.pending, undefined);
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(testState.restarts, 0);
fs.writeFileSync(path.join(dependency, "package.json"), JSON.stringify({ name: "fixture-package", version: "2.0.0" }));
const result = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
assert.equal(result.ok, true);
publishFixtureRelease(root, result.updateId);
assert.equal(readPanelInfoVersion(root), "v1.0.0");
});
// ---------------------------------------------------------------------------
// installNodeUpdateInternal: downgrade gate in front of the payload prep
// ---------------------------------------------------------------------------
function buildNodeInstallSandbox() {
const source = extractBlock(indexSource, 'async function installNodeUpdateInternal(node, targetVersion, source = "manual") {');
const state = { prepared: [], calls: [], runtime: { version: "v1.0.0" }, runtimeError: null };
const sandbox = {
normalizeUpdateVersionTag, compareVersions, isUpdateDowngrade,
console: { log() { }, warn() { }, error() { } },
fetchNodeRuntimeInfo: async () => {
if (state.runtimeError) throw state.runtimeError;
return state.runtime;
},
prepareNodeUpdatePayload: async (version) => {
state.prepared.push(version);
return { version, files: [], filesSkipped: 0 };
},
callNodeUpdateApi: async (node, suffix, opts) => {
state.calls.push({ node, suffix, opts });
return { status: 200, json: { ok: true, filesUpdated: 3 } };
},
// The install body now runs under the per-node keyed mutex; pass through
// so the extracted block resolves it (the assertions below are
// single-invocation and order-based, which pass-through preserves).
withKeyedLock: (key, task) => task(),
};
vm.createContext(sandbox);
vm.runInContext(source, sandbox);
return { sandbox, state };
}
test("node install: a downgrade is refused before the payload is prepared", async () => {
const { sandbox, state } = buildNodeInstallSandbox();
state.runtime = { version: "v2.0.0" };
await assert.rejects(
vm.runInContext("installNodeUpdateInternal({ id: 'n1', name: 'node-1' }, 'v1.9.0', 'manual')", sandbox),
(err) => err.statusCode === 409 && /downgrade refused/.test(err.message)
);
assert.equal(state.prepared.length, 0, "no archive may be downloaded once the downgrade is detected");
assert.equal(state.calls.length, 0, "nothing may be sent to the node");
});
test("node install: upgrades proceed, unknown/unreachable versions fall through permissively", async () => {
const { sandbox, state } = buildNodeInstallSandbox();
state.runtime = { version: "v1.0.0" };
const result = await vm.runInContext("installNodeUpdateInternal({ id: 'n1', name: 'node-1' }, 'v2.0.0', 'manual')", sandbox);
assert.equal(result.ok, true);
assert.equal(result.version, "v2.0.0");
assert.deepEqual(state.prepared, ["v2.0.0"]);
assert.equal(state.calls.length, 1);
assert.equal(state.calls[0].opts.action, "node-update-install");
state.prepared.length = 0;
state.calls.length = 0;
state.runtime = { version: "vunknown" };
await vm.runInContext("installNodeUpdateInternal({ id: 'n1', name: 'node-1' }, 'v0.0.1', 'manual')", sandbox);
assert.equal(state.prepared.length, 1, "an unorderable node version must not trigger the downgrade refusal");
state.prepared.length = 0;
state.runtimeError = new Error("node is unreachable");
await vm.runInContext("installNodeUpdateInternal({ id: 'n1', name: 'node-1' }, 'v0.0.1', 'manual')", sandbox);
assert.equal(state.prepared.length, 1, "an unreachable node falls through and fails at the install call instead");
});
// ---------------------------------------------------------------------------
// Client contracts (settings.js / settings.ejs)
// ---------------------------------------------------------------------------
test("panel info client renders a saved rollback below the tables and clears the stale restart notice", async () => {
const source = extractBlock(settingsSource, "function clearPanelUpdateOffer() {") + "\n" +
extractBlock(settingsSource, "async function loadPanelInfo({ quiet = false, offer = _latestVersionFound } = {}) {");
const version = { textContent: "v1.0.0" };
const warning = { textContent: "", style: { display: "none" } };
const status = { textContent: "Restarting...", style: {}, dataset: { panelRestart: "attempt-one" } };
const latestUpdateBox = { style: { display: "flex" } };
const upToDateTag = { style: { display: "none" } };
const elements = { panelInfoVersion: version, panelRestartWarning: warning, panelUpdateStatus: status };
const error = "Update to v1.0.0 failed. The previous version was restored.";
let payload = { version: "v0.9.0", updateError: error, offeredVersion: "v1.0.0", offerUnavailable: true };
const sandbox = vm.createContext({
document: { getElementById: id => elements[id] },
AbortSignal, console,
panelInfoRequest: 0, panelInfoRendered: 0, panelInfoTokensReceived: 0,
initializePanelInfoCopyButtons() {}, renderAutoUpdateButton() {},
_cachedVersion: "", _cachedLastUpdate: "", _cachedArchitecture: "",
_panelInfoTokens: { installUpdate: "unchanged" }, _latestVersionFound: "v1.0.0",
latestUpdateBox, upToDateTag,
fetch: async (url) => {
assert.match(url, /^\/api\/settings\/panel-info\?status=1(?:&offer=v1\.0\.0)?$/);
return { ok: true, json: async () => payload };
},
});
vm.runInContext(source, sandbox);
const rollbackPayload = payload;
payload = { version: "v1.0.0", restartPending: true, recoveryPending: true, updateBlocked: true };
await vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
assert.match(warning.textContent, /waiting to restore/);
assert.equal(warning.className, "panelinfo-update-status info");
payload = rollbackPayload;
sandbox._latestVersionFound = "v1.0.0";
latestUpdateBox.style.display = "flex";
await vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
assert.equal(version.textContent, "v0.9.0");
assert.equal(warning.textContent, error);
assert.equal(warning.className, "panelinfo-update-status error");
assert.equal(warning.style.display, "");
assert.equal(status.style.display, "none");
assert.equal(latestUpdateBox.style.display, "none");
assert.equal(sandbox._panelInfoTokens.installUpdate, "unchanged");
let finishStalePoll;
const fetchStatus = sandbox.fetch;
sandbox.fetch = () => new Promise(resolve => { finishStalePoll = resolve; });
const stalePoll = vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
status.dataset.panelRestart = "attempt-two";
status.textContent = "Restarting to verify...";
status.style.display = "";
finishStalePoll({ ok: true, json: async () => rollbackPayload });
await stalePoll;
assert.equal(status.dataset.panelRestart, "attempt-two", "an earlier poll cannot clear a newer install's restart notice");
assert.equal(status.textContent, "Restarting to verify...");
sandbox.fetch = fetchStatus;
payload = { version: "v0.9.1", updateError: error, verifiedUpdate: { id: "attempt-two", version: "v0.9.1" } };
await vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
assert.equal(warning.textContent, error, "an unrelated deferred release still has a warning");
assert.equal(status.textContent, "Update to v0.9.1 verified.");
assert.equal(status.style.display, "");
sandbox._latestVersionFound = "v1.0.0";
latestUpdateBox.style.display = "flex";
status.dataset.panelCheck = "available";
status.textContent = "New version available: v1.0.0";
status.style.display = "";
payload = rollbackPayload;
await vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
assert.equal(latestUpdateBox.style.display, "none");
assert.equal(status.style.display, "none", "the withdrawn offer no longer has a success message");
assert.equal(warning.textContent, error, "the saved rollback is still visible");
upToDateTag.style.display = 'inline-flex';
status.dataset.panelCheck = 'current';
status.textContent = 'You are running the latest version (v0.9.0)';
status.style.display = '';
payload = { version: 'v1.0.1' };
await vm.runInContext("loadPanelInfo({ quiet: true })", sandbox);
assert.equal(version.textContent, 'v1.0.1');
assert.equal(status.style.display, 'none', 'a version change invalidates the old check result');
assert.equal(upToDateTag.style.display, 'none');
});
test("panel check client clears prior update results on a failed recheck", async () => {
const source = extractBlock(settingsSource, "function clearPanelUpdateOffer() {") + "\n" +
extractRoute(settingsSource, " const checkBtn = document.getElementById('checkForUpdatesBtn');", " if (panelUpdateBtn) {");
const status = { style: {}, dataset: {} };
const upToDateTag = { style: {} };
const latestUpdateBox = { style: {} };
let onCheck;
let nextResponse;
let current = { version: "v1.0.0" };
const checkButton = { addEventListener(event, handler) { if (event === "click") onCheck = handler; } };
const elements = {
checkForUpdatesBtn: checkButton,
panelUpToDateTag: upToDateTag,
latestUpdateBox,
panelUpdateStatus: status,
};
const sandbox = vm.createContext({
document: { getElementById: (id) => elements[id] },
_panelInfoTokens: { checkUpdate: "token" },
_latestVersionFound: null,
loadPanelInfo: async ({ quiet, offer } = {}) => {
if (offer) {
assert.equal(quiet, true);
assert.equal(offer, "v1.1.0");
}
return current;
},
fetch: async () => nextResponse(),
console: { error() {} },
});
vm.runInContext(source, sandbox);
nextResponse = () => ({ ok: true, json: async () => ({ updateAvailable: true, currentVersion: "v1.0.0", latestVersion: "v1.1.0" }) });
await onCheck();
assert.equal(latestUpdateBox.style.display, "flex");
assert.equal(sandbox._latestVersionFound, "v1.1.0");
assert.equal(status.dataset.panelCheck, "available");
current = { version: "v1.0.0", offerUnavailable: true, updateError: "The candidate failed." };
await onCheck();
assert.equal(status.textContent, "The candidate failed.");
assert.equal(latestUpdateBox.style.display, "none", "a delayed check cannot reoffer a deferred release");
assert.equal(sandbox._latestVersionFound, null);
const unavailable = "No stable panel release is available from the update source.";
nextResponse = () => ({ ok: false, json: async () => ({ error: unavailable }) });
await onCheck();
assert.equal(status.textContent, unavailable);
assert.equal(latestUpdateBox.style.display, "none");
assert.equal(sandbox._latestVersionFound, null);
current = { version: "v1.0.0" };
nextResponse = () => ({ ok: true, json: async () => ({ updateAvailable: false, currentVersion: "v1.0.0" }) });
await onCheck();
assert.equal(upToDateTag.style.display, "inline-flex");
current = { version: "v1.1.0" };
await onCheck();
assert.equal(upToDateTag.style.display, "none", "a delayed check cannot report a different version as current");
assert.match(status.textContent, /status changed/);
nextResponse = () => { throw new Error("network unavailable"); };
await onCheck();
assert.equal(status.textContent, "Network error while checking for updates");
assert.equal(upToDateTag.style.display, "none");
assert.equal(checkButton.disabled, false);
});
test("panel install client rides the guarded step-up flow and re-stashes the re-minted one-time token", () => {
const block = extractBlock(settingsSource, "async function doInstall(version, source) {");
assert.match(block, /sendGuardedRequestWithStepUp\('\/api\/settings\/panel-update\/install'/);
assert.match(block, /onStepUpChallenge/, "the one-time install token must be renewed from the challenge body");
assert.match(block, /headers\['x-action-token'\] = fresh;/, "the fresh token must reach the retry headers");
assert.match(block, /cancelledMessage/, "a cancelled verification must surface as a status message, not silence");
});
test("panel install client refreshes a stale token and clears the completed install state", async () => {
const source = extractBlock(settingsSource, "async function doInstall(version, source) {");
const status = { style: {}, dataset: {} };
const panelUpdateBtn = {};
const latestUpdateBox = { style: { display: "flex" } };
const attempted = [];
const sandbox = vm.createContext({
document: { getElementById: () => status },
window: {},
console,
confirm: () => true,
panelUpdateBtn,
latestUpdateBox,
_latestVersionFound: "v1.0.0",
_panelInfoTokens: { installUpdate: "expired" },
loadPanelInfo: async ({ quiet } = {}) => {
if (!quiet) sandbox._panelInfoTokens = { installUpdate: "fresh" };
return { version: "v0.9.0" };
},
setTimeout() { },
sendGuardedRequestWithStepUp: async (url, method, payload, { headers }) => {
assert.equal(payload.checkedOffer, true);
const sent = headers["x-action-token"];
attempted.push(sent);
return sent === "fresh"
? { res: { ok: true }, data: { message: "Installed", updateId: "attempt-two" } }
: { res: { ok: false, status: 403 }, data: { code: "ACTION_TOKEN_INVALID", error: "invalid or missing action token" } };
},
});
vm.runInContext(source, sandbox);
await vm.runInContext("doInstall('v1.0.0', 'auto')", sandbox);
assert.deepEqual(attempted, ["fresh"]);
assert.equal(status.textContent, "Installed");
assert.equal(status.dataset.panelRestart, "attempt-two");
assert.equal(panelUpdateBtn.disabled, false);
assert.equal(panelUpdateBtn.textContent, "Update");
assert.equal(latestUpdateBox.style.display, "none");
assert.equal(sandbox._latestVersionFound, null);
});
test("panel auto toggle client rides the guarded flow (challenge only ever comes when disabling)", () => {
const block = extractRoute(settingsSource, " if (autoUpdateBtn) {", " async function doInstall(version, source) {");
assert.match(block, /sendGuardedRequestWithStepUp\('\/api\/settings\/panel-update\/auto'/);
});
test("node install client rides the guarded flow with the anchored version regex", () => {
const block = extractBlock(settingsSource, "async function doNodeInstall(version, source) {");
assert.match(block, /sendGuardedRequestWithStepUp\('\/api\/settings\/node-update\/install'/);
assert.match(block, /onStepUpChallenge/);
assert.ok(
block.includes("/^v?\\d+\\.\\d+\\.\\d+([\\-+][A-Za-z0-9_.-]+)?$/"),
"the client-side version check must be anchored like the server's validator"
);
});
test("node auto toggle client rides the guarded flow", () => {
const block = extractRoute(settingsSource, " if (autoBtn) {", " if (manualBtn && manualInput) {");
assert.match(block, /sendGuardedRequestWithStepUp\('\/api\/settings\/node-update\/auto'/);
});
test("the shared step-up helper fires the challenge hook on the first challenge and on every rejected retry", () => {
const block = extractBlock(settingsSource, "async function sendGuardedRequestWithStepUp(url, method, payload, copy = {}) {");
assert.match(block, /handleChallenge\(result\.data\);/, "the first challenge must renew consumed one-time artifacts");
assert.match(block, /handleChallenge\(retry\.data\);/, "a rejected in-modal retry must renew them again");
});
test("settings.js no longer carries the hardcoded 2026-08-10 fallback", () => {
assert.doesNotMatch(settingsSource, /2026-08-10/);
assert.match(settingsSource, /data\.lastUpdate \|\| 'unknown'/);
});
test("settings.ejs serves the hardened settings.js bundle", () => {
const ejs = fs.readFileSync(SETTINGS_EJS, "utf8");
assert.match(ejs, /settings\.js\?v=20261117-account-identity1/, "the cache-buster must be bumped so browsers pick up the hardened bundle");
assert.doesNotMatch(ejs, /settings\.js\?v=20260927-adminstepup1/, "the pre-identity bundle cache-buster must not remain");
assert.doesNotMatch(ejs, /settings\.js\?v=20260919-webhooktokenretry1/, "the stale cache-buster must not remain");
});
test("the checksum pins template exists and is shape-valid", () => {
const pins = JSON.parse(fs.readFileSync(CHECKSUMS_FILE, "utf8"));
assert.equal(typeof pins.requirePinned, "boolean", "requirePinned must default to false (opt-in strict mode)");
assert.equal(typeof pins.panel, "object");
assert.equal(typeof pins.node, "object");
});
// ---------------------------------------------------------------------------
// Restart verification, bounded retry, and rollback
// ---------------------------------------------------------------------------
// Fire armed watchdog timers in FIFO order. `times` caps how many fire; a
// retried attempt arms its own timer, so draining without a cap runs the whole
// retry budget to exhaustion.
function fireTimers(testState, times = Infinity) {
let fired = 0;
while (fired < times && testState.timers.length > 0) {
const timer = testState.timers.shift();
fired += 1;
testState.now += timer.ms;
timer.fn();
}
}
test("panel install: the restart is scheduled exactly once and arms one liveness watchdog", async () => {
const root = makeTempPanelRoot();
try {
fs.mkdirSync(path.join(root, "public", "js"), { recursive: true });
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/public/js/new.js", "console.log(1);"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
const result = await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
assert.equal(result.ok, true);
assert.equal(result.restartScheduled, true, "a scheduled restart must be reported as scheduled");
assert.match(result.message, /restarting.*verify/i);
assert.equal(testState.restarts, 1);
assert.equal(testState.timers.length, 1, "exactly one liveness watchdog is armed per attempt");
assert.equal(testState.timers[0].ms, 30000, "the watchdog grace period is 30s");
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), /awaiting recovery or restart/);
assert.equal(testState.restarts, 1, "no second restart script while one is pending");
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("panel install: exhausting restart retries discards the stage and records the failure", async () => {
const root = makeTempPanelRoot();
try {
fs.mkdirSync(path.join(root, "public", "js"), { recursive: true });
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/public/js/new.js", "console.log(1);"]]);
const { sandbox, testState } = buildPanelUpdateContext({ root, zipBuffer });
await vm.runInContext("installPanelUpdateInternal('v1.0.0', 'manual')", sandbox);
assert.equal(testState.restarts, 1);
// The mocked restart script never kills the sandboxed process, so every
// watchdog firing is a "still alive" verdict — the exact failure shape the
// swallowed `|| true` script used to hide.
fireTimers(testState, 1);
assert.equal(testState.restarts, 2, "the watchdog retries the restart");
fireTimers(testState, 1);
assert.equal(testState.restarts, 3, "the retry budget is bounded (3 attempts total)");
fireTimers(testState, 1);
assert.equal(testState.restarts, 3, "no further attempts after the budget is spent");
assert.equal(testState.timers.length, 0, "the watchdog disarms itself after the final attempt");
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.existsSync(path.join(root, "public/js/new.js")), false);
const update = createPanelUpdateState(path.join(root, "panel-information.json")).read();
assert.equal(update.pending, undefined);
assert.equal(update.failure.reason, "restart");
assert.equal(update.failure.restored, null);
assert.equal(fs.readdirSync(path.join(root, ".update-backups")).some(name => name.startsWith(".staged-")), false);
assert.equal(update.ignoredThrough, "v1.0.0");
await vm.runInContext("installPanelUpdate('v1.0.0')", sandbox);
assert.equal(testState.restarts, 4);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("panel install: a restart that cannot be scheduled immediately discards the stage", async () => {
const root = makeTempPanelRoot();
try {
fs.mkdirSync(path.join(root, "public", "js"), { recursive: true });
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/public/js/new.js", "console.log(1);"]]);
const { sandbox, testState, errors } = buildPanelUpdateContext({ root, zipBuffer });
testState.spawnError = new Error("spawn bash ENOENT");
await assert.rejects(vm.runInContext("installPanelUpdate('v1.0.0')", sandbox), /restart could not be scheduled/);
assert.equal(testState.restarts, 0);
assert.ok(errors.some(line => /Could not schedule the restart/.test(line)));
assert.equal(readPanelInfoVersion(root), "v0.9.0");
assert.equal(fs.existsSync(path.join(root, "public/js/new.js")), false);
assert.equal(createPanelUpdateState(path.join(root, "panel-information.json")).read().failure.restored, null);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("panel-info exposes the restart state and the settings UI surfaces restart failures", () => {
const routeBlock = sliceBetween(
indexSource,
'app.get("/api/settings/panel-info"',
'app.post("/api/settings/panel-update/check"'
);
assert.match(routeBlock, /\.\.\.getPanelUpdateStatus\(req\.query\?\.offer, info\.version\)/);
assert.match(settingsSource, /panelRestartWarning/, "the settings UI must render a restart-failure warning");
assert.match(settingsSource, /if \(data\.updateError\)/, "loadPanelInfo must render a saved update failure");
assert.match(settingsSource, /if \(data\.restartRequired\)/, "an older worker must show the on-disk build still needs a restart");
const settingsEjs = fs.readFileSync(SETTINGS_EJS, "utf8");
assert.match(settingsEjs, /id="panelRestartWarning"/, "settings.ejs must carry the restart warning element");
});
test("a different worker can resume the durable restart budget without reviving a stale timer", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
writePanelInfo(root, "v0.9.0");
const zipBuffer = buildReleaseZip([["ADPanel-v1.0.0/public/js/new.js", "console.log(1);"]]);
const installer = buildPanelUpdateContext({ root, zipBuffer });
const state = createPanelUpdateState(path.join(root, "panel-information.json"));
await vm.runInContext("installPanelUpdate('v1.0.0')", installer.sandbox);
assert.equal(state.read().pending.restartAttempts, 1);
let survivorNow = state.read().pending.restartNextAt;
const { createPanelUpdateCoordinator } = require("../services/panel-update-coordinator");
let takenOver = 0;
const coordinator = createPanelUpdateCoordinator({
panelInfoFile: path.join(root, "panel-information.json"), now: () => survivorNow,
launchRestart: () => { takenOver += 1; }, armTimer: () => undefined,
});
coordinator.recoverAbandonedPanelUpdate();
assert.equal(takenOver, 1);
assert.equal(state.read().pending.restartAttempts, 2);
fireTimers(installer.testState);
assert.equal(installer.testState.restarts, 1, "the former owner's callback cannot spend a claimed retry");
survivorNow = state.read().pending.restartNextAt;
coordinator.recoverAbandonedPanelUpdate();
assert.equal(takenOver, 2);
survivorNow = state.read().pending.restartNextAt;
coordinator.recoverAbandonedPanelUpdate();
assert.equal(state.read().pending, undefined);
assert.equal(state.read().failure.restored, null);
});
test("a queued restart survives a short lock hold but drops a superseded dispatch", async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const { createPanelUpdateCoordinator, createPanelUpdateMutex } = require("../services/panel-update-coordinator");
const panelInfoFile = path.join(root, "panel-information.json");
writePanelInfo(root, "v0.9.0");
const state = createPanelUpdateState(panelInfoFile);
const id = beginFixtureUpdate(state, "v1.0.0");
state.setPhase(id, "restart");
let dispatch;
let sent = 0;
const coordinator = createPanelUpdateCoordinator({
panelInfoFile, launchRestart: (_cohort, send) => { dispatch = send; }, armTimer: () => undefined,
});
coordinator.recoverAbandonedPanelUpdate();
assert.equal(typeof dispatch, "function");
const mutex = createPanelUpdateMutex(panelInfoFile);
const firstRelease = mutex.tryAcquire();
assert.ok(firstRelease);
const first = dispatch(() => { sent += 1; });
assert.equal(sent, 0);
firstRelease();
assert.equal(await first, true);
assert.equal(sent, 1);
const secondRelease = mutex.tryAcquire();
assert.ok(secondRelease);
const second = dispatch(() => { sent += 1; });
try {
assert.equal(state.recover(id, "restart"), true);
} finally {
secondRelease();
}
assert.equal(await second, false);
assert.equal(sent, 1);
});
test("the built-in autoscaler defers without changing its config while an update is pending", { skip: process.platform !== "linux" }, async (t) => {
const root = makeTempPanelRoot();
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
for (const relative of [launcherPath, "utils/atomic-file.js", "utils/cross-process-mutex.js"]) {
const target = path.join(root, relative);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(path.join(ROOT, relative), target);
}
const generated = path.join(root, "generator-ran");
fs.writeFileSync(path.join(root, "scripts", "generate-ecosystem.sh"), '#!/bin/sh\ntouch "$PANEL_DIR/generator-ran"\nprintf "CHANGED=0\\n"\n', { mode: 0o700 });
fs.mkdirSync(path.join(root, "node_modules", ".bin"), { recursive: true });
fs.writeFileSync(path.join(root, "node_modules", ".bin", "pm2"), "#!/bin/sh\nexit 1\n", { mode: 0o700 });
const monitor = () => execFileAsync("bash", [path.join(ROOT, "scripts", "adpanel-autoscale-monitor.sh"), "--once"], {
env: { PATH: path.dirname(process.execPath) + ":/usr/bin:/bin", HOME: root, PANEL_DIR: root, PM2_HOME: path.join(root, ".pm2") }, timeout: 5000,
});
const info = path.join(root, "panel-information.json");
const { createPanelScaleMutex } = require("../scripts/panel-update-recovery.cjs");
const release = createPanelScaleMutex(info).tryAcquire();
assert.ok(release);
try {
await monitor();
assert.equal(fs.existsSync(generated), false);
} finally {
release();
}
const state = createPanelUpdateState(info);
const id = state.prepare("v1.0.0");
await monitor();
assert.equal(fs.existsSync(generated), false);
assert.equal(state.recover(id, "interrupted"), true);
await monitor();
assert.equal(fs.existsSync(generated), true);
});
test("the restart watchdog is bound to the active journal and does not restart-fight a shutdown", () => {
assert.match(coordinatorSource, /RESTART_MAX_ATTEMPTS = 3/);
assert.match(coordinatorSource, /current\?\.id !== id \|\| current\.phase !== "restart"/);
assert.match(coordinatorSource, /if \(isStopping\(\)\) return/);
assert.match(indexSource, /isStopping: \(\) => isShuttingDown/);
assert.match(coordinatorSource, /await delay\(2000,/, "the restart request leaves time for the HTTP response");
});