feat: add verified console self-update for release packages

Check official GitHub Releases, require SHA256SUMS, safely extract and swap release-package code, roll back on failed health checks, and persist task state across restarts. Docker and source deployments stay check-only. Add updater tests, route security tests and five-language admin copy.
This commit is contained in:
OddTurtleHead committed 2026-11-24 01:44:24 +08:00
1 parent ae6788a796
commit 2de2e23fd3
32 files changed
+3573 -16

No files matched your search

+72
View File
@@ -12,6 +12,7 @@ import { createPluginAdminRouter } from "../plugins/admin-router.js";
import type { PluginRegistry } from "../plugins/registry.js";
import type { PluginStore } from "../plugins/store.js";
import type { PluginRuntime } from "../plugins/runtime.js";
import { UpdateError, type UpdateService } from "../updater/update-service.js";
export interface AdminConnectionRecord {
id: string;
@@ -45,6 +46,9 @@ export interface AdminRouterOptions {
pluginRegistry?: PluginRegistry;
pluginStore?: PluginStore;
pluginRuntime?: PluginRuntime;
updateService?: UpdateService;
/** Stops the current process after the update response has been flushed. */
restartAfterUpdate?: () => void;
startedAt: number;
clientIp?: (request: Request) => string;
}
@@ -414,6 +418,62 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
}
});
router.get("/update", (_request, response) => {
if (!options.updateService) {
response.json({
currentVersion: options.version ?? "0.0.0",
deployment: {
mode: "source",
platform: process.platform,
architecture: process.arch,
applyAllowed: false,
reasonCode: "UPDATE_UNAVAILABLE",
upgradePath: "source",
},
task: null,
});
return;
}
response.json(options.updateService.getStatus());
});
router.post("/update/check", requireSameOrigin, requireCsrf(options.sessions), async (_request, response) => {
if (!options.updateService) {
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
return;
}
try {
response.json(await options.updateService.checkForUpdates());
} catch (error: unknown) {
sendUpdateError(response, error);
}
});
router.post("/update/apply", requireSameOrigin, requireCsrf(options.sessions), async (request, response) => {
if (!options.updateService) {
response.status(503).json({ ok: false, code: "UPDATE_UNAVAILABLE" });
return;
}
if (!options.restartAfterUpdate) {
response.status(503).json({ ok: false, code: "UPDATE_RESTART_UNAVAILABLE" });
return;
}
try {
const body = asRecord(request.body);
const version = readString(body, "version", 32);
const confirmVersion = readString(body, "confirmVersion", 32);
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
const task = await options.updateService.applyUpdate(version, confirmVersion);
options.service.database.addAudit("ADMIN_UPDATE_STARTED", { version });
response.once("finish", () => {
setTimeout(() => options.restartAfterUpdate?.(), 250).unref();
});
response.status(202).json({ ok: true, task });
} catch (error: unknown) {
sendUpdateError(response, error);
}
});
router.put("/server", requireSameOrigin, requireCsrf(options.sessions), (request, response) => {
try {
options.service.updateSettings(readSettingsInput(asRecord(request.body)));
@@ -814,3 +874,15 @@ function sendAdminError(response: Response, error: unknown): void {
}
response.status(500).json({ ok: false, code: "INTERNAL_ERROR" });
}
function sendUpdateError(response: Response, error: unknown): void {
if (error instanceof UpdateError) {
response.status(error.statusCode).json({ ok: false, code: error.code, message: error.message });
return;
}
if (error instanceof AdminInputError) {
response.status(400).json({ ok: false, code: error.code });
return;
}
response.status(500).json({ ok: false, code: "UPDATE_FAILED" });
}
+177
View File
@@ -0,0 +1,177 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import express from "express";
import type { Logger } from "../logger.js";
import { AdminService } from "./admin-service.js";
import { AdminSessionStore } from "./admin-session.js";
import { createAdminRouter } from "./admin-router.js";
import { WebSpeakDatabase } from "../persistence/database.js";
import { UpdateError, type UpdateService } from "../updater/update-service.js";
import type { UpdateCheckView, UpdateStatusView, UpdateTaskView } from "../shared/update.js";
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const statusView: UpdateStatusView = {
currentVersion: "0.3.2",
deployment: {
mode: "release-package", platform: "linux", architecture: "x64",
applyAllowed: true, reasonCode: null, upgradePath: "release-package",
},
task: null,
};
const taskView: UpdateTaskView = {
id: "upd_route_test", status: "restarting", fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
};
const checkView: UpdateCheckView = {
currentVersion: "0.3.2",
releases: [{
version: "0.4.0", tag: "v0.4.0", publishedAt: "2026-01-01T00:00:00.000Z",
releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0",
assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 10,
assetAvailable: true, hasChecksums: true, digest: null, canApply: true, blockedReason: null,
}],
};
interface Fixture {
origin: string;
service: AdminService;
database: WebSpeakDatabase;
applyCalls: Array<[string, string]>;
restarted: () => boolean;
login(): Promise<{ cookie: string; csrf: string }>;
post(route: string, body: unknown, headers?: Record<string, string>): Promise<Response>;
}
async function fixture(t: TestContext, options: { updateService?: boolean } = {}): Promise<Fixture> {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-routes-"));
const database = new WebSpeakDatabase(path.join(directory, "test.db"));
const service = new AdminService(database, Buffer.alloc(32, 3), logger, path.join(directory, "absent.json"), undefined, "0.3.2");
await service.initialize();
await service.changePassword("test-only-admin-password");
const applyCalls: Array<[string, string]> = [];
let restarted = false;
const updateService = {
getStatus: () => statusView,
checkForUpdates: async () => checkView,
applyUpdate: async (version: string, confirmVersion: string) => {
applyCalls.push([version, confirmVersion]);
if (version !== confirmVersion) throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "confirmation mismatch");
return taskView;
},
} as unknown as UpdateService;
const app = express();
app.use(express.json());
app.use("/api/admin", createAdminRouter({
service, sessions: new AdminSessionStore(), logger,
getActiveSessions: () => 0, getPeakSessions: () => 0, startedAt: Date.now(), version: "0.3.2",
...(options.updateService === false ? {} : { updateService, restartAfterUpdate: () => { restarted = true; } }),
}));
const server = app.listen(0, "127.0.0.1");
await new Promise<void>((resolve) => server.once("listening", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
const origin = `http://127.0.0.1:${address.port}`;
t.after(async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
database.close();
rmSync(directory, { recursive: true, force: true });
});
const post = (route: string, body: unknown, headers: Record<string, string> = {}) => fetch(`${origin}/api/admin${route}`, {
method: "POST", headers: { origin, "content-type": "application/json", ...headers }, body: JSON.stringify(body),
});
const login = async () => {
const response = await post("/login", { username: "admin", password: "test-only-admin-password" });
assert.equal(response.status, 200);
const body = await response.json() as { csrfToken: string };
return { cookie: response.headers.get("set-cookie")!.split(";", 1)[0]!, csrf: body.csrfToken };
};
return { origin, service, database, applyCalls, restarted: () => restarted, login, post };
}
test("update routes require an authenticated session", async t => {
const f = await fixture(t);
assert.equal((await fetch(`${f.origin}/api/admin/update`)).status, 401);
assert.equal((await f.post("/update/check", {})).status, 401);
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" })).status, 401);
});
test("update routes reject missing CSRF tokens and cross-origin requests", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const noCsrf = await f.post("/update/check", {}, { cookie });
assert.equal(noCsrf.status, 403);
assert.equal((await noCsrf.json() as { code: string }).code, "CSRF_REJECTED");
const crossOrigin = await fetch(`${f.origin}/api/admin/update/apply`, {
method: "POST",
headers: { origin: "https://evil.example", cookie, "x-csrf-token": csrf, "content-type": "application/json" },
body: JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" }),
});
assert.equal(crossOrigin.status, 403);
assert.equal((await crossOrigin.json() as { code: string }).code, "ORIGIN_REJECTED");
const wrongType = await fetch(`${f.origin}/api/admin/update/check`, {
method: "POST",
headers: { origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "text/plain" },
body: "{}",
});
assert.equal(wrongType.status, 415);
assert.equal((await wrongType.json() as { code: string }).code, "JSON_REQUIRED");
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 200);
});
test("apply requires version and confirmVersion to match before touching the service", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.1" }, { cookie, "x-csrf-token": csrf });
assert.equal(response.status, 400);
assert.equal((await response.json() as { code: string }).code, "UPDATE_CONFIRMATION_REQUIRED");
assert.deepEqual(f.applyCalls, []);
const missing = await f.post("/update/apply", { version: "0.4.0" }, { cookie, "x-csrf-token": csrf });
assert.equal(missing.status, 400);
assert.deepEqual(f.applyCalls, []);
});
test("a confirmed apply returns the task and stops the process after the response", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const response = await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf });
assert.equal(response.status, 202);
const body = await response.json() as { ok: boolean; task: UpdateTaskView };
assert.equal(body.ok, true);
assert.equal(body.task.id, "upd_route_test");
assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
assert.ok(f.database.recentAudit(10).some((event) => event.event === "ADMIN_UPDATE_STARTED"));
await new Promise<void>((resolve) => setTimeout(resolve, 400));
assert.equal(f.restarted(), true);
});
test("update status and check return the service projections", async t => {
const f = await fixture(t);
const { cookie, csrf } = await f.login();
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
assert.equal(status.status, 200);
assert.deepEqual(await status.json(), statusView);
const check = await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf });
assert.equal(check.status, 200);
assert.deepEqual(await check.json(), checkView);
});
test("deployments without an update service expose a read-only source status", async t => {
const f = await fixture(t, { updateService: false });
const { cookie, csrf } = await f.login();
const status = await fetch(`${f.origin}/api/admin/update`, { headers: { cookie } });
assert.equal(status.status, 200);
const body = await status.json() as UpdateStatusView;
assert.equal(body.deployment.mode, "source");
assert.equal(body.deployment.applyAllowed, false);
assert.equal(body.deployment.reasonCode, "UPDATE_UNAVAILABLE");
assert.equal((await f.post("/update/check", {}, { cookie, "x-csrf-token": csrf })).status, 503);
assert.equal((await f.post("/update/apply", { version: "0.4.0", confirmVersion: "0.4.0" }, { cookie, "x-csrf-token": csrf })).status, 503);
});
+22 -1
View File
@@ -5,6 +5,7 @@ import { createAccelerationRelayServer } from "./server/acceleration-relay.js";
import { normalizeScreenShareIceServers, type ScreenShareIceServer } from "./server/screen-share.js";
import { SkinRegistry } from "./admin/skin-registry.js";
import { PluginRegistry } from "./plugins/registry.js";
import { UpdateService } from "./updater/update-service.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT_DIR = path.resolve(__dirname, "..");
@@ -52,13 +53,33 @@ async function main() {
logger.info({ dataDir: DATA_DIR }, "Starting WebSpeak server");
const hasCert = existsSync(path.join(CERT_DIR, "cert.pem"));
const updateService = new UpdateService({
rootDir: ROOT_DIR,
dataDir: DATA_DIR,
currentVersion: APP_VERSION,
logger,
port: APP_PORT,
https: hasCert,
});
updateService.initialize();
const webServer = createWebServer({
let webServer: ReturnType<typeof createWebServer> | undefined;
webServer = createWebServer({
port: APP_PORT,
version: APP_VERSION,
logFile: path.join(LOG_DIR, "webspeak.log"),
staticDir: STATIC_DIR,
certDir: hasCert ? CERT_DIR : undefined,
updateService,
restartAfterUpdate: () => {
void (async () => {
logger.info("Stopping for scheduled update");
try { await webServer?.stop(); }
catch (error) { logger.warn({ err: error instanceof Error ? error.message : String(error) }, "Web server did not stop cleanly for update"); }
database.close();
process.exit(0);
})();
},
voiceBridgeOptions: {
joinTickets,
trustedProxies: readTrustedProxies(process.env.WEBSPEAK_TRUSTED_PROXIES),
+5
View File
@@ -22,6 +22,7 @@ import type { PluginRegistry } from "../plugins/registry.js";
import { PluginRuntime } from "../plugins/runtime.js";
import { createPluginRuntimeRouter } from "../plugins/runtime-router.js";
import { parseHiddenHostParts } from "../shared/skin-chrome.js";
import type { UpdateService } from "../updater/update-service.js";
export interface WebServerOptions {
port: number;
@@ -37,6 +38,8 @@ export interface WebServerOptions {
logger: Logger;
nextVisitorNumber?: () => number;
visitorCount?: () => number;
updateService?: UpdateService;
restartAfterUpdate?: () => void;
}
export interface WebServer {
@@ -301,6 +304,8 @@ export function createWebServer(options: WebServerOptions): WebServer {
skinRegistry: options.skinRegistry,
pluginRegistry: options.pluginRegistry,
pluginRuntime,
updateService: options.updateService,
restartAfterUpdate: options.restartAfterUpdate,
version: options.version,
logFile: options.logFile,
startedAt,
+53
View File
@@ -93,6 +93,52 @@ const tsAdminOverview = object({
});
const savedTsAdminSettings = object({ ok: choice(true), settings: tsAdminSettings });
const sessionStatus = object({ authenticated: boolean, mustChangePassword: optional(boolean), csrfToken: optional(text) });
const updateStep = object({
name: text,
status: choice("running", "succeeded", "failed"),
at: text,
detail: optional(text),
});
const updateTask = object({
id: text,
status: choice("downloading", "verifying", "extracting", "staging", "restarting", "succeeded", "failed"),
fromVersion: text,
targetVersion: text,
startedAt: text,
updatedAt: text,
finishedAt: nullable(text),
errorCode: nullable(text),
errorMessage: nullable(text),
rolledBack: boolean,
steps: array(updateStep),
});
const updateDeployment = object({
mode: choice("docker", "release-package", "source"),
platform: text,
architecture: text,
applyAllowed: boolean,
reasonCode: nullable(text),
upgradePath: choice("docker-compose", "release-package", "source"),
});
const updateStatus = object({
currentVersion: text,
deployment: updateDeployment,
task: nullable(updateTask),
});
const updateRelease = object({
version: text,
tag: text,
publishedAt: text,
releaseUrl: text,
assetName: text,
assetSize: number,
assetAvailable: boolean,
hasChecksums: boolean,
digest: nullable(text),
canApply: boolean,
blockedReason: nullable(text),
});
const updateCheck = object({ currentVersion: text, releases: array(updateRelease) });
export const adminResponses = {
session(value: unknown) {
@@ -127,6 +173,9 @@ export const adminResponses = {
latencyMs: number, serverName: nullable(text), requiresPassword: boolean,
packetLossPercent: optional(number), attempts: optional(number), successfulAttempts: optional(number), errorCode: optional(text),
}),
updateStatus,
updateCheck,
updateApplied: object({ ok: choice(true), task: updateTask }),
};
export type AdminSettings = ReturnType<typeof settings>;
@@ -135,3 +184,7 @@ export type AdminSession = ReturnType<typeof session>;
export type ManagedInvite = ReturnType<typeof invite>;
export type AdminLog = ReturnType<typeof logEntry>;
export type AdminConnectionRecord = ReturnType<typeof connection>;
export type AdminUpdateTask = ReturnType<typeof updateTask>;
export type AdminUpdateStatus = ReturnType<typeof updateStatus>;
export type AdminUpdateCheck = ReturnType<typeof updateCheck>;
export type AdminUpdateRelease = ReturnType<typeof updateRelease>;
+78
View File
@@ -0,0 +1,78 @@
/**
* Browser-safe projections of the administrator update API.
*
* The console never receives download URLs or local paths. It selects a
* version, and the server re-resolves the official GitHub release asset
* before doing any work.
*/
export type UpdateDeploymentMode = "docker" | "release-package" | "source";
export type UpdateUpgradePath = "docker-compose" | "release-package" | "source";
export type UpdateTaskStatus =
| "downloading"
| "verifying"
| "extracting"
| "staging"
| "restarting"
| "succeeded"
| "failed";
export type UpdateStepStatus = "running" | "succeeded" | "failed";
export interface UpdateStepView {
name: string;
status: UpdateStepStatus;
at: string;
detail?: string;
}
export interface UpdateTaskView {
id: string;
status: UpdateTaskStatus;
fromVersion: string;
targetVersion: string;
startedAt: string;
updatedAt: string;
finishedAt: string | null;
errorCode: string | null;
errorMessage: string | null;
rolledBack: boolean;
steps: UpdateStepView[];
}
export interface UpdateDeploymentView {
mode: UpdateDeploymentMode;
platform: string;
architecture: string;
applyAllowed: boolean;
reasonCode: string | null;
upgradePath: UpdateUpgradePath;
}
export interface UpdateStatusView {
currentVersion: string;
deployment: UpdateDeploymentView;
task: UpdateTaskView | null;
}
export interface UpdateReleaseView {
version: string;
tag: string;
publishedAt: string;
releaseUrl: string;
assetName: string;
assetSize: number;
assetAvailable: boolean;
hasChecksums: boolean;
digest: string | null;
canApply: boolean;
blockedReason: string | null;
}
export interface UpdateCheckView {
currentVersion: string;
releases: UpdateReleaseView[];
}
export interface UpdateApplyInput {
version: string;
confirmVersion: string;
}
+95
View File
@@ -0,0 +1,95 @@
import assert from "node:assert/strict";
import test from "node:test";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { createTarGz, createZip } from "./test-support.js";
function fixture(t: test.TestContext, name: string, data: Buffer): { directory: string; archive: string; destination: string } {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-archive-"));
const archive = path.join(directory, name);
writeFileSync(archive, data);
t.after(() => rmSync(directory, { recursive: true, force: true }));
return { directory, archive, destination: path.join(directory, "out") };
}
function rejectsWith(code: string) {
return (error: unknown) => error instanceof ArchiveError && error.code === code;
}
test("tar.gz release archives extract files and directories", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "webspeak/", type: "directory", mode: 0o755 },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/dist/index.js", data: "console.log('ok');\n", mode: 0o755 },
]));
await extractReleaseArchive(archive, destination, "release.tar.gz");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/dist/index.js"), "utf8"), "console.log('ok');\n");
});
test("zip release archives extract stored entries", async t => {
const { archive, destination } = fixture(t, "release.zip", createZip([
{ name: "webspeak/", directory: true },
{ name: "webspeak/package.json", data: JSON.stringify({ version: "0.4.0" }) },
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>" },
]));
await extractReleaseArchive(archive, destination, "release.zip");
assert.equal(JSON.parse(readFileSync(path.join(destination, "webspeak/package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(destination, "webspeak/web/dist/index.html"), "utf8"), "<!doctype html>");
});
test("tar entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:/escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.tar.gz", createTarGz([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("zip entries that traverse or use absolute paths are rejected before writing", async t => {
for (const name of ["../escape.txt", "/etc/escape.txt", "a/../../escape.txt", "C:\\escape.txt"]) {
const { directory, archive, destination } = fixture(t, "release.zip", createZip([{ name, data: "owned" }]));
await assert.rejects(extractReleaseArchive(archive, destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(existsSync(path.join(directory, "out", "escape.txt")), false);
assert.equal(existsSync(path.join(directory, "escape.txt")), false);
}
});
test("symbolic and hard links are refused for both archive formats", async t => {
const tarSymlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "/etc/passwd" }]));
await assert.rejects(extractReleaseArchive(tarSymlink.archive, tarSymlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const tarHardlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "hardlink", linkname: "target" }]));
await assert.rejects(extractReleaseArchive(tarHardlink.archive, tarHardlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
const zipSymlink = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
await assert.rejects(extractReleaseArchive(zipSymlink.archive, zipSymlink.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("unsupported archive formats and malformed archives are rejected", async t => {
const unsupported = fixture(t, "release.rar", Buffer.from("not an archive"));
await assert.rejects(extractReleaseArchive(unsupported.archive, unsupported.destination, "release.rar"), rejectsWith("UPDATE_ARCHIVE_UNSUPPORTED"));
const truncated = fixture(t, "release.tar.gz", Buffer.from("short"));
await assert.rejects(extractReleaseArchive(truncated.archive, truncated.destination, "release.tar.gz"));
const brokenZip = fixture(t, "release.zip", Buffer.alloc(64));
await assert.rejects(extractReleaseArchive(brokenZip.archive, brokenZip.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_INVALID"));
const invalidName = fixture(t, "release.tar.gz", createTarGz([{ name: "", data: "x" }]));
await assert.rejects(extractReleaseArchive(invalidName.archive, invalidName.destination, "release.tar.gz"));
});
test("declared extraction limits stop archive bombs", async t => {
const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
{ name: "one.txt", data: "one" },
{ name: "two.txt", data: "two" },
]));
await assert.rejects(
extractReleaseArchive(archive, destination, "release.tar.gz", { maxEntries: 1 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
const fileLimit = fixture(t, "release.zip", createZip([{ name: "big.txt", data: "1234567890" }]));
await assert.rejects(
extractReleaseArchive(fileLimit.archive, fileLimit.destination, "release.zip", { maxFileBytes: 4 }),
rejectsWith("UPDATE_ARCHIVE_LIMIT"),
);
});
+365
View File
@@ -0,0 +1,365 @@
import { createReadStream, createWriteStream, type Stats } from "node:fs";
import { chmod, mkdir, open, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { createGunzip, createInflateRaw } from "node:zlib";
import { Transform as StreamTransform } from "node:stream";
import { pipeline } from "node:stream/promises";
export type ArchiveErrorCode =
| "UPDATE_ARCHIVE_INVALID"
| "UPDATE_ARCHIVE_UNSAFE"
| "UPDATE_ARCHIVE_LIMIT"
| "UPDATE_ARCHIVE_UNSUPPORTED";
export class ArchiveError extends Error {
constructor(readonly code: ArchiveErrorCode, message: string) {
super(message);
this.name = "ArchiveError";
}
}
export interface ExtractLimits {
maxEntries: number;
maxTotalBytes: number;
maxFileBytes: number;
}
const DEFAULT_LIMITS: ExtractLimits = {
maxEntries: 50_000,
maxTotalBytes: 4 * 1024 ** 3,
maxFileBytes: 2 * 1024 ** 3,
};
export async function extractReleaseArchive(
archivePath: string,
destination: string,
archiveName: string,
limits: Partial<ExtractLimits> = {},
): Promise<void> {
const effective = { ...DEFAULT_LIMITS, ...limits };
await mkdir(destination, { recursive: true });
if (/\.zip$/i.test(archiveName)) {
await extractZip(archivePath, destination, effective);
return;
}
if (/\.(?:tar\.gz|tgz)$/i.test(archiveName)) {
await extractTarGz(archivePath, destination, effective);
return;
}
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "Only .tar.gz and .zip release packages are supported.");
}
function unsafe(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_UNSAFE", message);
}
function invalid(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_INVALID", message);
}
function limitExceeded(message: string): never {
throw new ArchiveError("UPDATE_ARCHIVE_LIMIT", message);
}
/** Reject absolute paths, drive letters, parent traversal and NUL bytes. */
export function safeArchivePath(raw: string): string {
if (!raw || raw.includes("\0")) unsafe("Archive entry has an invalid name.");
const normalized = raw.replaceAll("\\", "/");
if (normalized.startsWith("/")) unsafe("Archive entry uses an absolute path.");
if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive entry uses a drive-qualified path.");
const parts = normalized.split("/").filter((part) => part !== "" && part !== ".");
if (parts.some((part) => part === "..")) unsafe("Archive entry escapes the extraction directory.");
return parts.join("/");
}
function resolveEntry(destination: string, relative: string): string {
const target = path.resolve(destination, relative);
const root = path.resolve(destination);
if (target !== root && !target.startsWith(root + path.sep)) unsafe("Archive entry escapes the extraction directory.");
return target;
}
function isZeroBlock(buffer: Buffer): boolean {
for (const byte of buffer) if (byte !== 0) return false;
return true;
}
function readCString(buffer: Buffer): string {
const end = buffer.indexOf(0);
return (end >= 0 ? buffer.subarray(0, end) : buffer).toString("utf8");
}
function readOctal(buffer: Buffer): number {
const text = readCString(buffer).trim();
if (!text) return 0;
if (!/^[0-7]+$/.test(text)) invalid("Archive header has an invalid numeric field.");
return Number.parseInt(text, 8);
}
function verifyTarChecksum(header: Buffer): void {
const expected = readOctal(header.subarray(148, 156));
if (!expected) return;
let sum = 0;
for (let index = 0; index < header.length; index++) {
sum += index >= 148 && index < 156 ? 0x20 : header[index];
}
if (sum !== expected) invalid("Archive header checksum does not match.");
}
interface PaxFields {
path?: string;
linkpath?: string;
}
function parsePax(buffer: Buffer): PaxFields {
const fields: PaxFields = {};
let offset = 0;
while (offset < buffer.length) {
const space = buffer.indexOf(0x20, offset);
if (space < 0) break;
const length = Number.parseInt(buffer.subarray(offset, space).toString("ascii"), 10);
if (!Number.isFinite(length) || length <= 0 || offset + length > buffer.length) break;
const record = buffer.subarray(space + 1, offset + length - 1).toString("utf8");
const equals = record.indexOf("=");
if (equals > 0) {
const key = record.slice(0, equals);
const value = record.slice(equals + 1);
if (key === "path") fields.path = value;
else if (key === "linkpath") fields.linkpath = value;
}
offset += length;
}
return fields;
}
class TarReader {
private buffer: Buffer = Buffer.alloc(0);
private readonly iterator: AsyncIterator<Buffer>;
constructor(stream: NodeJS.ReadableStream) {
this.iterator = (stream as AsyncIterable<Buffer>)[Symbol.asyncIterator]();
}
async readExact(size: number): Promise<Buffer> {
while (this.buffer.length < size) {
const next = await this.iterator.next();
if (next.done) invalid("Release archive ended unexpectedly.");
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, next.value]) : next.value;
}
const result = this.buffer.subarray(0, size);
this.buffer = this.buffer.subarray(size);
return result;
}
async skip(size: number): Promise<void> {
let remaining = size;
while (remaining > 0) {
const current = this.buffer.length ? this.buffer : undefined;
if (current) {
const take = Math.min(current.length, remaining);
this.buffer = current.subarray(take);
remaining -= take;
} else {
const next = await this.iterator.next();
if (next.done) invalid("Release archive ended unexpectedly.");
this.buffer = next.value;
}
}
}
}
async function writeAll(stream: ReturnType<typeof createWriteStream>, chunk: Buffer): Promise<void> {
if (!stream.write(chunk)) await once(stream, "drain");
}
async function extractTarGz(file: string, destination: string, limits: ExtractLimits): Promise<void> {
const reader = new TarReader(createReadStream(file).pipe(createGunzip()));
let entries = 0;
let total = 0;
let longName: string | undefined;
let pax: PaxFields = {};
for (;;) {
const header = await reader.readExact(512);
if (isZeroBlock(header)) break;
verifyTarChecksum(header);
let name = readCString(header.subarray(0, 100));
const prefix = readCString(header.subarray(345, 500));
if (prefix) name = `${prefix}/${name}`;
const size = readOctal(header.subarray(124, 136));
if (size > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
const mode = readOctal(header.subarray(100, 108)) & 0o777;
const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
const padded = Math.ceil(size / 512) * 512;
if (type === "L") {
if (size > 1024 * 1024) limitExceeded("Archive long-name header is too large.");
longName = (await reader.readExact(size)).toString("utf8").replace(/\0+$/, "");
await reader.skip(padded - size);
continue;
}
if (type === "x" || type === "X") {
if (size > 1024 * 1024) limitExceeded("Archive extended header is too large.");
pax = { ...pax, ...parsePax(await reader.readExact(size)) };
await reader.skip(padded - size);
continue;
}
if (type === "g") {
await reader.skip(padded);
continue;
}
const entryName = pax.path ?? longName ?? name;
longName = undefined;
pax = {};
if (!entryName) invalid("Archive entry has no name.");
if (type === "1" || type === "2") {
unsafe(`Archive entry ${entryName} is a ${type === "1" ? "hard link" : "symbolic link"}; links are not accepted.`);
}
if (type !== "0" && type !== "7" && type !== "5") {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `Archive entry ${entryName} has unsupported type ${type}.`);
}
entries++;
if (entries > limits.maxEntries) limitExceeded("Archive contains too many entries.");
total += size;
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
const relative = safeArchivePath(entryName);
const target = resolveEntry(destination, relative);
if (type === "5") {
await mkdir(target, { recursive: true, mode: mode || 0o755 });
await reader.skip(padded);
continue;
}
await mkdir(path.dirname(target), { recursive: true });
const stream = createWriteStream(target, { mode: mode || 0o644, flags: "wx" });
try {
let remaining = size;
while (remaining > 0) {
const chunk = await reader.readExact(Math.min(remaining, 64 * 1024));
remaining -= chunk.length;
await writeAll(stream, chunk);
}
stream.end();
await once(stream, "finish");
} catch (error) {
stream.destroy();
throw error;
}
await reader.skip(padded - size);
}
}
interface ZipEntry {
name: string;
flags: number;
method: number;
compressedSize: number;
uncompressedSize: number;
localOffset: number;
mode: number;
directory: boolean;
}
const EOCD_SIGNATURE = 0x06054b50;
const CENTRAL_SIGNATURE = 0x02014b50;
const LOCAL_SIGNATURE = 0x04034b50;
async function extractZip(file: string, destination: string, limits: ExtractLimits): Promise<void> {
const handle = await open(file, "r");
try {
const info: Stats = await handle.stat();
if (info.size < 22) invalid("ZIP archive is truncated.");
const tailSize = Math.min(info.size, 65_557);
const tail = Buffer.alloc(tailSize);
await handle.read(tail, 0, tailSize, info.size - tailSize);
let eocd = -1;
for (let index = tail.length - 22; index >= 0; index--) {
if (tail.readUInt32LE(index) === EOCD_SIGNATURE) {
const commentLength = tail.readUInt16LE(index + 20);
if (index + 22 + commentLength === tail.length) { eocd = index; break; }
}
}
if (eocd < 0) invalid("ZIP end-of-directory record was not found.");
const entryCount = tail.readUInt16LE(eocd + 10);
const directorySize = tail.readUInt32LE(eocd + 12);
const directoryOffset = tail.readUInt32LE(eocd + 16);
if (entryCount === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
}
if (entryCount > limits.maxEntries) limitExceeded("Archive contains too many entries.");
if (directoryOffset + directorySize > info.size) invalid("ZIP central directory is outside the archive.");
const directory = Buffer.alloc(directorySize);
await handle.read(directory, 0, directorySize, directoryOffset);
const entries: ZipEntry[] = [];
let offset = 0;
let total = 0;
for (let index = 0; index < entryCount; index++) {
if (offset + 46 > directory.length || directory.readUInt32LE(offset) !== CENTRAL_SIGNATURE) {
invalid("ZIP central directory is malformed.");
}
const versionMadeBy = directory.readUInt16LE(offset + 4);
const flags = directory.readUInt16LE(offset + 8);
const method = directory.readUInt16LE(offset + 10);
const compressedSize = directory.readUInt32LE(offset + 20);
const uncompressedSize = directory.readUInt32LE(offset + 24);
const nameLength = directory.readUInt16LE(offset + 28);
const extraLength = directory.readUInt16LE(offset + 30);
const commentLength = directory.readUInt16LE(offset + 32);
const externalAttributes = directory.readUInt32LE(offset + 38);
const localOffset = directory.readUInt32LE(offset + 42);
const nameStart = offset + 46;
if (nameStart + nameLength > directory.length) invalid("ZIP entry name is truncated.");
const name = directory.subarray(nameStart, nameStart + nameLength).toString("utf8");
offset = nameStart + nameLength + extraLength + commentLength;
if (flags & 0x1) unsafe(`ZIP entry ${name} is encrypted.`);
if (method !== 0 && method !== 8) throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `ZIP entry ${name} uses unsupported compression.`);
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localOffset === 0xffffffff) {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", "ZIP64 release packages are not supported.");
}
const unixMode = versionMadeBy >> 8 === 3 ? externalAttributes >>> 16 : 0;
const fileType = unixMode & 0o170000;
if (fileType === 0o120000) unsafe(`ZIP entry ${name} is a symbolic link.`);
if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000) {
unsafe(`ZIP entry ${name} has an unsupported file type.`);
}
const directoryEntry = name.endsWith("/") || fileType === 0o040000;
if (!directoryEntry && uncompressedSize > limits.maxFileBytes) limitExceeded("Archive entry exceeds the file size limit.");
total += directoryEntry ? 0 : uncompressedSize;
if (total > limits.maxTotalBytes) limitExceeded("Archive expands beyond the size limit.");
entries.push({ name, flags, method, compressedSize, uncompressedSize, localOffset, mode: unixMode & 0o777, directory: directoryEntry });
}
for (const entry of entries) {
const relative = safeArchivePath(entry.name);
if (!relative) invalid("ZIP entry has an empty path.");
const target = resolveEntry(destination, relative);
if (entry.directory) {
await mkdir(target, { recursive: true, mode: entry.mode || 0o755 });
continue;
}
await mkdir(path.dirname(target), { recursive: true });
if (entry.compressedSize === 0) {
await writeFile(target, Buffer.alloc(0), { mode: entry.mode || 0o644, flag: "wx" });
continue;
}
const header = Buffer.alloc(30);
await handle.read(header, 0, 30, entry.localOffset);
if (header.readUInt32LE(0) !== LOCAL_SIGNATURE) invalid(`ZIP entry ${entry.name} has an invalid local header.`);
const nameLength = header.readUInt16LE(26);
const extraLength = header.readUInt16LE(28);
const dataStart = entry.localOffset + 30 + nameLength + extraLength;
if (dataStart + entry.compressedSize > info.size) invalid(`ZIP entry ${entry.name} is truncated.`);
const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
let writtenBytes = 0;
const limiter = new StreamTransform({
transform(chunk: Buffer, _encoding, callback) {
writtenBytes += chunk.length;
if (writtenBytes > entry.uncompressedSize) callback(new ArchiveError("UPDATE_ARCHIVE_INVALID", `ZIP entry ${entry.name} exceeds its declared size.`));
else callback(null, chunk);
},
});
const sink = createWriteStream(target, { mode: entry.mode || 0o644, flags: "wx" });
if (entry.method === 8) await pipeline(source, createInflateRaw(), limiter, sink);
else await pipeline(source, limiter, sink);
const written = await stat(target);
if (written.size !== entry.uncompressedSize) invalid(`ZIP entry ${entry.name} has an unexpected size.`);
if (entry.mode) await chmod(target, entry.mode);
}
} finally {
await handle.close();
}
}
+104
View File
@@ -0,0 +1,104 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
CodeSwapError, locatePackageRoot, restoreCode, swapCode, validateStagedPackage,
} from "./code-swap.js";
import { createPackageFiles } from "./test-support.js";
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-swap-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function packageInvalid(error: unknown): boolean {
return error instanceof CodeSwapError && error.code === "UPDATE_PACKAGE_INVALID";
}
function persistentState(root: string): void {
writeFileSync(path.join(root, "config.json"), JSON.stringify({ siteName: "kept" }));
for (const [directory, file] of [["data", "webspeak.db"], ["certs", "cert.pem"], ["skins", "skin.json"], ["plugins", "plugin.json"]]) {
mkdirSync(path.join(root, directory), { recursive: true });
writeFileSync(path.join(root, directory, file), `${directory}-content`);
}
}
test("staged packages must be complete, regular files and version-matched", t => {
const root = workspace(t);
createPackageFiles(root, "0.4.0");
assert.doesNotThrow(() => validateStagedPackage(root, { version: "0.4.0", platform: "linux" }));
assert.throws(() => validateStagedPackage(root, { version: "0.4.1", platform: "linux" }), packageInvalid);
const missing = workspace(t);
createPackageFiles(missing, "0.4.0");
rmSync(path.join(missing, "runtime", "node"));
assert.throws(() => validateStagedPackage(missing, { version: "0.4.0", platform: "linux" }), packageInvalid);
const linked = workspace(t);
createPackageFiles(linked, "0.4.0");
rmSync(path.join(linked, "runtime", "node"));
symlinkSync(process.execPath, path.join(linked, "runtime", "node"));
assert.throws(() => validateStagedPackage(linked, { version: "0.4.0", platform: "linux" }), packageInvalid);
});
test("locatePackageRoot accepts both bare and single-wrapper layouts", t => {
const bare = workspace(t);
createPackageFiles(bare, "0.4.0");
assert.equal(locatePackageRoot(bare, "0.4.0", "linux"), bare);
const wrapped = workspace(t);
createPackageFiles(path.join(wrapped, "webspeak"), "0.4.0");
assert.equal(locatePackageRoot(wrapped, "0.4.0", "linux"), path.join(wrapped, "webspeak"));
const missing = workspace(t);
assert.throws(() => locatePackageRoot(missing, "0.4.0", "linux"), packageInvalid);
});
test("code swap replaces only code and preserves data, config, certs, skins and plugins", t => {
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
mkdirSync(path.join(root, "dist"), { recursive: true });
mkdirSync(path.join(root, "node_modules"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
writeFileSync(path.join(root, "node_modules", "old.txt"), "old dependency");
persistentState(root);
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
swapCode(root, staged, backup);
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "new code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.4.0");
assert.equal(readFileSync(path.join(root, "node_modules", "new.txt"), "utf8"), "new dependency");
assert.equal(readFileSync(path.join(backup, "dist", "index.js"), "utf8"), "old code");
assert.equal(readFileSync(path.join(backup, "node_modules", "old.txt"), "utf8"), "old dependency");
for (const [directory, file, contents] of [
["data", "webspeak.db", "data-content"], ["certs", "cert.pem", "certs-content"],
["skins", "skin.json", "skins-content"], ["plugins", "plugin.json", "plugins-content"],
]) {
assert.equal(readFileSync(path.join(root, directory, file), "utf8"), contents);
assert.equal(existsSync(path.join(backup, directory)), false);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(root, "config.json"), "utf8")), { siteName: "kept" });
assert.equal(existsSync(path.join(backup, "config.json")), false);
});
test("restoreCode returns the previous code and keeps rejected code for inspection", t => {
const root = workspace(t), staged = path.join(workspace(t), "staged"), backup = path.join(workspace(t), "backup");
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "dist", "index.js"), "old code");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "0.3.2" }));
persistentState(root);
createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code" });
swapCode(root, staged, backup);
restoreCode(root, backup);
assert.equal(readFileSync(path.join(root, "dist", "index.js"), "utf8"), "old code");
assert.equal(JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")).version, "0.3.2");
assert.equal(readFileSync(path.join(backup, "rejected", "dist", "index.js"), "utf8"), "new code");
assert.equal(readFileSync(path.join(root, "data", "webspeak.db"), "utf8"), "data-content");
assert.throws(() => restoreCode(root, path.join(root, "absent-backup")), (error: unknown) =>
error instanceof CodeSwapError && error.code === "UPDATE_ROLLBACK_FAILED");
});
+125
View File
@@ -0,0 +1,125 @@
import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
import path from "node:path";
import { parseStableVersion } from "./version.js";
/**
* Only package code is ever moved. Persistent state (data/, config.json,
* certs/) is deliberately absent from this list.
*/
export const CODE_ENTRIES = [
"dist",
"web/dist",
"node_modules",
"runtime",
"package.json",
"package-lock.json",
"README.md",
"LICENSE",
"config.example.json",
"start-webspeak.sh",
"start-webspeak.cmd",
] as const;
export type CodeSwapErrorCode = "UPDATE_PACKAGE_INVALID" | "UPDATE_SWAP_FAILED" | "UPDATE_ROLLBACK_FAILED";
export class CodeSwapError extends Error {
constructor(readonly code: CodeSwapErrorCode, message: string) {
super(message);
this.name = "CodeSwapError";
}
}
export interface StagedPackageOptions {
version: string;
platform?: NodeJS.Platform;
}
function requireEntry(root: string, relative: string, kind: "file" | "directory"): void {
const target = path.join(root, relative);
let stats;
try { stats = lstatSync(target); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package is missing ${relative}.`); }
if (stats.isSymbolicLink()) throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} is a symbolic link.`);
if (kind === "file" ? !stats.isFile() : !stats.isDirectory()) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", `Release package entry ${relative} has the wrong type.`);
}
}
/** The extracted package must be a complete runnable release for this platform. */
export function validateStagedPackage(root: string, options: StagedPackageOptions): void {
requireEntry(root, "dist/index.js", "file");
requireEntry(root, "web/dist/index.html", "file");
requireEntry(root, "node_modules", "directory");
requireEntry(root, "package.json", "file");
requireEntry(root, options.platform === "win32" ? "runtime/node.exe" : "runtime/node", "file");
let manifest: unknown;
try { manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); }
catch { throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package manifest is not valid JSON."); }
const version = manifest && typeof manifest === "object" && !Array.isArray(manifest)
? (manifest as Record<string, unknown>).version
: undefined;
if (!parseStableVersion(version) || version !== options.version) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package version does not match the selected release.");
}
}
/** Archives usually contain one wrapper directory; accept both layouts. */
export function locatePackageRoot(extractedDir: string, version: string, platform?: NodeJS.Platform): string {
const entries = readdirSync(extractedDir, { withFileTypes: true });
const root = entries.length === 1 && entries[0].isDirectory()
? path.join(extractedDir, entries[0].name)
: extractedDir;
if (!existsSync(path.join(root, "package.json"))) {
throw new CodeSwapError("UPDATE_PACKAGE_INVALID", "Release package root was not found after extraction.");
}
validateStagedPackage(root, { version, platform });
return root;
}
function moveIfPresent(from: string, to: string): void {
if (!existsSync(from)) return;
mkdirSync(path.dirname(to), { recursive: true });
renameSync(from, to);
}
/**
* Move the previous code aside, then move the verified side-by-side package
* into place. `data/`, `config.json` and `certs/` are never in CODE_ENTRIES.
*/
export function swapCode(rootDir: string, stagedRoot: string, backupDir: string): void {
try {
if (existsSync(backupDir)) throw new Error("Backup directory already exists.");
mkdirSync(backupDir, { recursive: true });
for (const entry of CODE_ENTRIES) moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
for (const entry of CODE_ENTRIES) moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
} catch (error) {
try { restoreCode(rootDir, backupDir); }
catch { /* Report the original swap error; rollback failure is handled by the caller. */ }
if (error instanceof CodeSwapError) throw error;
throw new CodeSwapError("UPDATE_SWAP_FAILED", error instanceof Error ? error.message : "Release package swap failed.");
}
}
/**
* Restore the previous code. New code is moved aside instead of deleted so it
* remains available for diagnostics.
*/
export function restoreCode(rootDir: string, backupDir: string): void {
if (!existsSync(backupDir)) throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", "Code backup directory is missing.");
const rejected = path.join(backupDir, "rejected");
try {
for (const entry of CODE_ENTRIES) {
const current = path.join(rootDir, entry);
if (existsSync(current) && existsSync(path.join(backupDir, entry))) {
moveIfPresent(current, path.join(rejected, entry));
}
}
for (const entry of CODE_ENTRIES) moveIfPresent(path.join(backupDir, entry), path.join(rootDir, entry));
} catch (error) {
throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", error instanceof Error ? error.message : "Code rollback failed.");
}
}
export function removeStagingDirectory(directory: string): void {
try { rmSync(directory, { recursive: true, force: true }); } catch { /* Best-effort cleanup. */ }
}
+90
View File
@@ -0,0 +1,90 @@
import assert from "node:assert/strict";
import test from "node:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
assetKindFor, detectDeployment, isReleasePackageRoot, releaseAssetName, upgradePathFor,
} from "./deployment.js";
function temporary(t: test.TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-deployment-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function releasePackageRoot(t: test.TestContext, platform: "linux" | "win32" = "linux"): string {
const root = temporary(t);
const runtime = platform === "win32" ? "node.exe" : "node";
for (const directory of ["runtime", "dist", "web/dist"]) mkdirSync(path.join(root, directory), { recursive: true });
writeFileSync(path.join(root, "runtime", runtime), "");
writeFileSync(path.join(root, "dist", "index.js"), "");
writeFileSync(path.join(root, "web", "dist", "index.html"), "");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version: "1.0.0" }));
return root;
}
test("deployment mode honours the explicit environment override", () => {
const env = { WEBSPEAK_DEPLOYMENT_MODE: "release-package" };
const info = detectDeployment({ rootDir: "/does/not/exist", env, isDocker: true, platform: "linux", architecture: "x64" });
assert.equal(info.mode, "release-package");
assert.equal(info.applyAllowed, true);
assert.equal(info.reasonCode, null);
assert.equal(info.upgradePath, "release-package");
});
test("docker and source deployments never allow an in-console apply", () => {
const docker = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: true, platform: "linux", architecture: "x64" });
assert.deepEqual(
{ mode: docker.mode, applyAllowed: docker.applyAllowed, reasonCode: docker.reasonCode, upgradePath: docker.upgradePath },
{ mode: "docker", applyAllowed: false, reasonCode: "DEPLOYMENT_DOCKER", upgradePath: "docker-compose" },
);
const source = detectDeployment({ rootDir: "/does/not/exist", env: {}, isDocker: false, platform: "linux", architecture: "x64" });
assert.deepEqual(
{ mode: source.mode, applyAllowed: source.applyAllowed, reasonCode: source.reasonCode, upgradePath: source.upgradePath },
{ mode: "source", applyAllowed: false, reasonCode: "DEPLOYMENT_SOURCE", upgradePath: "source" },
);
});
test("a complete packaged tree is detected as a release package", t => {
const root = releasePackageRoot(t);
assert.equal(isReleasePackageRoot(root, "linux"), true);
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "arm64" });
assert.equal(info.mode, "release-package");
assert.equal(info.assetKind, "linux-arm64");
assert.equal(info.applyAllowed, true);
assert.equal(detectDeployment({ rootDir: root, env: { WEBSPEAK_DEPLOYMENT_MODE: "docker" }, isDocker: false, platform: "linux" }).mode, "docker");
});
test("incomplete trees stay in source mode", t => {
const root = temporary(t);
assert.equal(isReleasePackageRoot(root, "linux"), false);
mkdirSync(path.join(root, "runtime"), { recursive: true });
writeFileSync(path.join(root, "runtime", "node"), "");
assert.equal(isReleasePackageRoot(root, "linux"), false);
});
test("asset names and platform support are pinned to official release shapes", () => {
assert.equal(assetKindFor("linux", "x64"), "linux-x64");
assert.equal(assetKindFor("linux", "arm64"), "linux-arm64");
assert.equal(assetKindFor("win32", "x64"), "windows-x64");
assert.equal(assetKindFor("linux", "riscv64"), null);
assert.equal(assetKindFor("darwin", "arm64"), null);
assert.equal(releaseAssetName("0.4.0", "linux-x64"), "webspeak-webclient-v0.4.0-linux-x64.tar.gz");
assert.equal(releaseAssetName("0.4.0", "linux-arm64"), "webspeak-webclient-v0.4.0-linux-arm64.tar.gz");
assert.equal(releaseAssetName("0.4.0", "windows-x64"), "webspeak-webclient-v0.4.0-windows-x64.zip");
assert.equal(upgradePathFor("docker"), "docker-compose");
assert.equal(upgradePathFor("release-package"), "release-package");
assert.equal(upgradePathFor("source"), "source");
});
test("unsupported platforms are visible but cannot apply", t => {
const root = releasePackageRoot(t);
const info = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "linux", architecture: "s390x" });
assert.equal(info.mode, "release-package");
assert.equal(info.applyAllowed, false);
assert.equal(info.reasonCode, "ARCH_UNSUPPORTED");
const darwin = detectDeployment({ rootDir: root, env: {}, isDocker: false, platform: "darwin", architecture: "arm64" });
assert.equal(darwin.applyAllowed, false);
assert.equal(darwin.reasonCode, "PLATFORM_UNSUPPORTED");
});
+85
View File
@@ -0,0 +1,85 @@
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import type { UpdateDeploymentMode, UpdateDeploymentView, UpdateUpgradePath } from "../shared/update.js";
export interface DeploymentDetectionOptions {
rootDir: string;
platform?: NodeJS.Platform;
architecture?: string;
env?: NodeJS.ProcessEnv;
/** Test seam; omitted means inspect the real container markers. */
isDocker?: boolean;
}
export interface DeploymentInfo extends UpdateDeploymentView {
platform: NodeJS.Platform;
assetKind: "linux-x64" | "linux-arm64" | "windows-x64" | null;
}
const EXPLICIT_MODES: UpdateDeploymentMode[] = ["docker", "release-package", "source"];
export function detectDeployment(options: DeploymentDetectionOptions): DeploymentInfo {
const platform = options.platform ?? process.platform;
const architecture = options.architecture ?? process.arch;
const env = options.env ?? process.env;
const explicit = env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase();
let mode: UpdateDeploymentMode;
if (explicit && (EXPLICIT_MODES as string[]).includes(explicit)) {
mode = explicit as UpdateDeploymentMode;
} else if (options.isDocker ?? runningInContainer(env)) {
mode = "docker";
} else {
mode = isReleasePackageRoot(options.rootDir, platform) ? "release-package" : "source";
}
const assetKind = mode === "release-package" ? assetKindFor(platform, architecture) : null;
let reasonCode: string | null = null;
if (mode === "docker") reasonCode = "DEPLOYMENT_DOCKER";
else if (mode === "source") reasonCode = "DEPLOYMENT_SOURCE";
else if (!assetKind) reasonCode = platform !== "linux" && platform !== "win32" ? "PLATFORM_UNSUPPORTED" : "ARCH_UNSUPPORTED";
return {
mode,
platform,
architecture,
applyAllowed: mode === "release-package" && assetKind !== null,
reasonCode,
upgradePath: upgradePathFor(mode),
assetKind,
};
}
export function runningInContainer(env: NodeJS.ProcessEnv = process.env): boolean {
if (env.WEBSPEAK_DEPLOYMENT_MODE?.trim().toLowerCase() === "docker") return true;
if (existsSync("/.dockerenv")) return true;
if (env.container) return true;
try {
const cgroup = readFileSync("/proc/1/cgroup", "utf8");
return /(?:docker|kubepods|containerd|libpod|podman)/i.test(cgroup);
} catch {
return false;
}
}
export function isReleasePackageRoot(rootDir: string, platform: NodeJS.Platform = process.platform): boolean {
const runtime = platform === "win32" ? path.join(rootDir, "runtime", "node.exe") : path.join(rootDir, "runtime", "node");
return existsSync(runtime)
&& existsSync(path.join(rootDir, "dist", "index.js"))
&& existsSync(path.join(rootDir, "web", "dist", "index.html"))
&& existsSync(path.join(rootDir, "package.json"));
}
export function assetKindFor(platform: NodeJS.Platform, architecture: string): DeploymentInfo["assetKind"] {
if (platform === "win32" && architecture === "x64") return "windows-x64";
if (platform === "linux" && architecture === "x64") return "linux-x64";
if (platform === "linux" && architecture === "arm64") return "linux-arm64";
return null;
}
export function releaseAssetName(version: string, assetKind: NonNullable<DeploymentInfo["assetKind"]>): string {
return assetKind === "windows-x64"
? `webspeak-webclient-v${version}-windows-x64.zip`
: `webspeak-webclient-v${version}-${assetKind}.tar.gz`;
}
export function upgradePathFor(mode: UpdateDeploymentMode): UpdateUpgradePath {
return mode === "docker" ? "docker-compose" : mode === "release-package" ? "release-package" : "source";
}
+161
View File
@@ -0,0 +1,161 @@
import { compareVersions, parseReleaseTag } from "./version.js";
export const OFFICIAL_REPOSITORY = "EchoSixHIYA/WebSpeak-client-for-TeamSpeak";
export const CHECKSUM_ASSET_NAME = "SHA256SUMS.txt";
export interface ReleaseAsset {
name: string;
size: number;
url: string;
digest: string | null;
}
export interface OfficialRelease {
version: string;
tag: string;
publishedAt: string;
releaseUrl: string;
assets: ReleaseAsset[];
}
export type ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
export class ReleaseSourceError extends Error {
readonly code: ReleaseSourceErrorCode = "UPDATE_RELEASE_UNAVAILABLE";
constructor(message: string) {
super(message);
this.name = "ReleaseSourceError";
}
}
export interface ReleaseSourceOptions {
fetch?: typeof fetch;
apiBaseUrl?: string;
repository?: string;
userAgent?: string;
timeoutMs?: number;
}
const ALLOWED_DOWNLOAD_HOSTS = new Set([
"github.com",
"api.github.com",
"objects.githubusercontent.com",
"release-assets.githubusercontent.com",
]);
export class GitHubReleaseSource {
private readonly fetcher: typeof fetch;
private readonly apiBaseUrl: string;
private readonly repository: string;
private readonly userAgent: string;
private readonly timeoutMs: number;
constructor(options: ReleaseSourceOptions = {}) {
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
this.apiBaseUrl = (options.apiBaseUrl ?? "https://api.github.com").replace(/\/+$/, "");
this.repository = options.repository ?? OFFICIAL_REPOSITORY;
this.userAgent = options.userAgent ?? "WebSpeak-Console-Updater";
this.timeoutMs = options.timeoutMs ?? 12_000;
}
private get owner(): string {
return this.repository.split("/")[0];
}
private get repo(): string {
return this.repository.split("/")[1];
}
async listStableReleases(): Promise<OfficialRelease[]> {
let response: Response;
try {
response = await this.fetcher(`${this.apiBaseUrl}/repos/${this.repository}/releases?per_page=30`, {
headers: {
accept: "application/vnd.github+json",
"user-agent": this.userAgent,
"x-github-api-version": "2022-11-28",
},
signal: AbortSignal.timeout(this.timeoutMs),
redirect: "error",
});
} catch {
throw new ReleaseSourceError("The official release list could not be reached.");
}
if (!response.ok) throw new ReleaseSourceError(`The official release list returned HTTP ${response.status}.`);
let value: unknown;
try { value = await response.json(); }
catch { throw new ReleaseSourceError("The official release list is not valid JSON."); }
if (!Array.isArray(value)) throw new ReleaseSourceError("The official release list is not an array.");
const releases: OfficialRelease[] = [];
const seen = new Set<string>();
for (const entry of value) {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
const record = entry as Record<string, unknown>;
if (record.draft === true || record.prerelease === true) continue;
const tag = typeof record.tag_name === "string" ? record.tag_name : "";
const version = parseReleaseTag(tag)?.text;
if (!version || seen.has(version)) continue;
const releaseUrl = typeof record.html_url === "string" ? record.html_url : "";
if (!isOfficialReleasePage(releaseUrl, this.owner, this.repo)) continue;
const assets: ReleaseAsset[] = [];
if (Array.isArray(record.assets)) {
for (const asset of record.assets) {
if (!asset || typeof asset !== "object" || Array.isArray(asset)) continue;
const item = asset as Record<string, unknown>;
const name = typeof item.name === "string" ? item.name : "";
const url = typeof item.browser_download_url === "string" ? item.browser_download_url : "";
if (!name || !url) continue;
try { assertOfficialDownloadUrl(url, this.owner, this.repo); }
catch { continue; }
assets.push({
name,
size: typeof item.size === "number" && Number.isFinite(item.size) ? item.size : 0,
url,
digest: typeof item.digest === "string" && item.digest ? item.digest : null,
});
}
}
seen.add(version);
releases.push({
version,
tag,
publishedAt: typeof record.published_at === "string" ? record.published_at : "",
releaseUrl,
assets,
});
}
return releases.sort((left, right) => compareVersions(right.version, left.version));
}
async findRelease(version: string): Promise<OfficialRelease | null> {
const releases = await this.listStableReleases();
return releases.find((release) => release.version === version) ?? null;
}
}
export function isOfficialReleasePage(value: string, owner: string, repo: string): boolean {
try {
const url = new URL(value);
return url.protocol === "https:"
&& !url.username && !url.password
&& url.hostname === "github.com"
&& url.pathname.startsWith(`/${owner}/${repo}/releases/`);
} catch {
return false;
}
}
/**
* Only GitHub-owned hosts are accepted. For the release download path the
* repository prefix is pinned so a tampered asset URL cannot point elsewhere.
*/
export function assertOfficialDownloadUrl(value: string, owner: string, repo: string): void {
let url: URL;
try { url = new URL(value); }
catch { throw new ReleaseSourceError("The release asset URL is invalid."); }
if (url.protocol !== "https:" || url.username || url.password || !ALLOWED_DOWNLOAD_HOSTS.has(url.hostname)) {
throw new ReleaseSourceError("The release asset is not hosted on an official GitHub domain.");
}
if (url.hostname === "github.com" && !url.pathname.startsWith(`/${owner}/${repo}/releases/download/`)) {
throw new ReleaseSourceError("The release asset is not part of the official repository.");
}
}
+174
View File
@@ -0,0 +1,174 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { spawn, type ChildProcess } from "node:child_process";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { runRestartPlan } from "./restart-runner.js";
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
async function availablePort(): Promise<number> {
const server = createServer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
assert.ok(address && typeof address !== "string");
const port = address.port;
await new Promise<void>((resolve) => server.close(() => resolve()));
return port;
}
async function waitFor(check: () => boolean, timeoutMs = 5_000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!check()) {
if (Date.now() > deadline) throw new Error("timed out waiting for condition");
await sleep(50);
}
}
function appScript(version: string, port: number, pidFile: string): string {
return `const http = require("node:http");
const { writeFileSync } = require("node:fs");
const server = http.createServer((request, response) => {
if (request.url === "/api/health") {
response.setHeader("content-type", "application/json");
response.end(JSON.stringify({ status: "ok", version: ${JSON.stringify(version)} }));
return;
}
response.statusCode = 404;
response.end();
});
server.listen(${port}, "127.0.0.1", () => writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)));
process.on("SIGTERM", () => { server.close(() => process.exit(0)); setTimeout(() => process.exit(0), 1000).unref(); });
`;
}
interface RunnerFixture {
directory: string;
rootDir: string;
stagedRoot: string;
backupDir: string;
planPath: string;
statePath: string;
lockPath: string;
pidFile: string;
taskId: string;
}
function runnerFixture(t: TestContext): RunnerFixture {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-runner-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
const rootDir = path.join(directory, "app");
const stagedRoot = path.join(directory, "staged");
const backupDir = path.join(directory, "backup");
const statePath = path.join(directory, "data", "updates", "state.json");
const lockPath = path.join(directory, "data", "updates", "update.lock");
const taskId = "upd_runner_test";
for (const directoryName of ["data", "config.json", "certs", "skins", "plugins"]) {
const target = path.join(rootDir, directoryName);
if (directoryName === "config.json") writeFileSync(target, JSON.stringify({ kept: true }));
else {
mkdirSync(target, { recursive: true });
writeFileSync(path.join(target, "marker.txt"), `${directoryName} preserved`);
}
}
for (const [root, version] of [[rootDir, "1.0.0"], [stagedRoot, "2.0.0"]] as const) {
mkdirSync(path.join(root, "dist"), { recursive: true });
writeFileSync(path.join(root, "package.json"), JSON.stringify({ version }));
writeFileSync(path.join(root, "dist", "index.js"), `// version marker ${version}\n`);
}
return {
directory, rootDir, stagedRoot, backupDir, statePath, lockPath, taskId,
pidFile: path.join(directory, "app.pid"),
planPath: path.join(directory, "plan.json"),
};
}
function writePlan(fixture: RunnerFixture, port: number, pidFile: string, options: { targetVersion: string; reportedVersion: string; healthTimeoutMs?: number }) {
mkdirSync(path.dirname(fixture.statePath), { recursive: true });
writeFileSync(fixture.lockPath, JSON.stringify({ pid: process.pid, taskId: fixture.taskId, createdAt: new Date().toISOString() }));
writeFileSync(path.join(fixture.stagedRoot, "dist", "index.js"), appScript(options.reportedVersion, port, pidFile));
writeFileSync(fixture.planPath, JSON.stringify({
schemaVersion: 1,
taskId: fixture.taskId,
rootDir: fixture.rootDir,
statePath: fixture.statePath,
lockPath: fixture.lockPath,
stagedRoot: fixture.stagedRoot,
backupDir: fixture.backupDir,
fromVersion: "1.0.0",
targetVersion: options.targetVersion,
nodePath: process.execPath,
appEntry: path.join(fixture.rootDir, "dist", "index.js"),
health: { protocol: "http", port, path: "/api/health" },
waitForPid: null,
parentTimeoutMs: 2_000,
healthTimeoutMs: options.healthTimeoutMs ?? 1_500,
pollIntervalMs: 50,
appLogPath: path.join(fixture.directory, "app.log"),
}, null, 2));
}
async function stopPidFile(pidFile: string): Promise<void> {
if (!existsSync(pidFile)) return;
const pid = Number(readFileSync(pidFile, "utf8"));
if (Number.isInteger(pid) && pid > 0) {
try { process.kill(pid, "SIGTERM"); } catch { /* Already gone. */ }
for (let attempt = 0; attempt < 40; attempt++) {
try { process.kill(pid, 0); await sleep(50); }
catch { return; }
}
try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
}
}
test("a healthy target version completes the swap and leaves persistent state alone", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "2.0.0" });
t.after(() => stopPidFile(fixture.pidFile));
assert.equal(await runRestartPlan(fixture.planPath), 0);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "succeeded");
assert.equal(state.task.finishedAt === null, false);
assert.deepEqual(state.task.steps.map((step: { name: string; status: string }) => [step.name, step.status]), [
["restart", "succeeded"],
["swap", "succeeded"],
]);
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "2\.0\.0"/);
assert.match(readFileSync(path.join(fixture.backupDir, "dist", "index.js"), "utf8"), /version marker 1\.0\.0/);
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
assert.equal(existsSync(fixture.lockPath), false);
assert.equal(existsSync(fixture.stagedRoot), false);
await waitFor(() => existsSync(fixture.pidFile));
});
test("a failed health check rolls back to the previous code and reports the failure", { timeout: 20_000 }, async t => {
const fixture = runnerFixture(t);
const port = await availablePort();
writePlan(fixture, port, fixture.pidFile, { targetVersion: "2.0.0", reportedVersion: "9.9.9", healthTimeoutMs: 800 });
writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), appScript("1.0.0", port, fixture.pidFile));
// Simulate the previous process still serving while the runner takes over.
const previous = spawn(process.execPath, [path.join(fixture.rootDir, "dist", "index.js")], { stdio: "ignore", detached: true });
previous.unref();
t.after(async () => { await stopPidFile(fixture.pidFile); try { previous.kill("SIGKILL"); } catch { /* Exited. */ } });
await waitFor(() => existsSync(fixture.pidFile) && Number(readFileSync(fixture.pidFile, "utf8")) === previous.pid);
assert.equal(await runRestartPlan(fixture.planPath), 1);
const state = JSON.parse(readFileSync(fixture.statePath, "utf8"));
assert.equal(state.task.status, "failed");
assert.equal(state.task.rolledBack, true);
assert.equal(state.task.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
assert.match(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), /version: "1\.0\.0"/);
assert.match(readFileSync(path.join(fixture.backupDir, "rejected", "dist", "index.js"), "utf8"), /version: "9\.9\.9"/);
for (const directoryName of ["data", "certs", "skins", "plugins"]) {
assert.equal(readFileSync(path.join(fixture.rootDir, directoryName, "marker.txt"), "utf8"), `${directoryName} preserved`);
}
assert.deepEqual(JSON.parse(readFileSync(path.join(fixture.rootDir, "config.json"), "utf8")), { kept: true });
assert.equal(existsSync(fixture.lockPath), false);
});
+347
View File
@@ -0,0 +1,347 @@
import { spawn, type ChildProcess } from "node:child_process";
import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import http from "node:http";
import https from "node:https";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { CodeSwapError, restoreCode, swapCode } from "./code-swap.js";
import type { PersistedUpdateState } from "./update-state.js";
import type { UpdateTaskView } from "../shared/update.js";
export interface RestartPlan {
schemaVersion: 1;
taskId: string;
rootDir: string;
statePath: string;
lockPath: string;
stagedRoot: string;
backupDir: string;
fromVersion: string;
targetVersion: string;
/** Absolute path to the runtime bundled with the package (or a test stub). */
nodePath: string;
/** Absolute path to dist/index.js after the swap. */
appEntry: string;
health: { protocol: "http" | "https"; port: number; path: string };
waitForPid: number | null;
parentTimeoutMs: number;
healthTimeoutMs: number;
pollIntervalMs: number;
appLogPath: string;
}
class RunnerError extends Error {
constructor(readonly code: string, message: string) {
super(message);
this.name = "RunnerError";
}
}
const sleep = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
function readPlan(planPath: string): RestartPlan {
const parsed: unknown = JSON.parse(readFileSync(planPath, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is invalid.");
const plan = parsed as Record<string, unknown>;
if (plan.schemaVersion !== 1
|| typeof plan.taskId !== "string"
|| typeof plan.rootDir !== "string"
|| typeof plan.statePath !== "string"
|| typeof plan.lockPath !== "string"
|| typeof plan.stagedRoot !== "string"
|| typeof plan.backupDir !== "string"
|| typeof plan.fromVersion !== "string"
|| typeof plan.targetVersion !== "string"
|| typeof plan.nodePath !== "string"
|| typeof plan.appEntry !== "string"
|| !plan.health || typeof plan.health !== "object") {
throw new RunnerError("UPDATE_PLAN_INVALID", "Restart plan is incomplete.");
}
const health = plan.health as Record<string, unknown>;
return {
schemaVersion: 1,
taskId: plan.taskId,
rootDir: plan.rootDir,
statePath: plan.statePath,
lockPath: plan.lockPath,
stagedRoot: plan.stagedRoot,
backupDir: plan.backupDir,
fromVersion: plan.fromVersion,
targetVersion: plan.targetVersion,
nodePath: plan.nodePath,
appEntry: plan.appEntry,
health: {
protocol: health.protocol === "https" ? "https" : "http",
port: typeof health.port === "number" ? health.port : 3040,
path: typeof health.path === "string" ? health.path : "/api/health",
},
waitForPid: typeof plan.waitForPid === "number" && Number.isFinite(plan.waitForPid) ? plan.waitForPid : null,
parentTimeoutMs: typeof plan.parentTimeoutMs === "number" ? plan.parentTimeoutMs : 60_000,
healthTimeoutMs: typeof plan.healthTimeoutMs === "number" ? plan.healthTimeoutMs : 90_000,
pollIntervalMs: typeof plan.pollIntervalMs === "number" ? plan.pollIntervalMs : 500,
appLogPath: typeof plan.appLogPath === "string" ? plan.appLogPath : path.join(path.dirname(plan.statePath), "app.log"),
};
}
function loadState(plan: RestartPlan): PersistedUpdateState {
try {
const parsed: unknown = JSON.parse(readFileSync(plan.statePath, "utf8"));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)
&& (parsed as Record<string, unknown>).schemaVersion === 1
&& (parsed as Record<string, unknown>).task
&& typeof (parsed as Record<string, unknown>).task === "object"
&& ((parsed as { task: { id?: unknown } }).task.id === plan.taskId)) {
return parsed as PersistedUpdateState;
}
} catch { /* Build a task below. */ }
return {
schemaVersion: 1,
task: {
id: plan.taskId,
status: "restarting",
fromVersion: plan.fromVersion,
targetVersion: plan.targetVersion,
startedAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [],
},
};
}
class StateWriter {
private state: PersistedUpdateState;
constructor(private readonly plan: RestartPlan) {
this.state = loadState(plan);
}
private write(): void {
const task = this.state.task!;
task.updatedAt = new Date().toISOString();
mkdirSync(path.dirname(this.plan.statePath), { recursive: true });
const temporary = `${this.plan.statePath}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(this.state, null, 2), "utf8");
renameSync(temporary, this.plan.statePath);
}
get task(): UpdateTaskView {
return this.state.task!;
}
step(name: string, status: UpdateTaskView["steps"][number]["status"], detail?: string): void {
const task = this.state.task!;
const existing = task.steps.find((step) => step.name === name);
const at = new Date().toISOString();
if (existing) {
existing.status = status;
existing.at = at;
if (detail) existing.detail = detail;
} else {
task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
}
this.write();
}
status(status: UpdateTaskView["status"], error?: { code: string; message: string }): void {
const task = this.state.task!;
task.status = status;
if (error) {
task.errorCode = error.code;
task.errorMessage = error.message;
}
if (status === "succeeded" || status === "failed") task.finishedAt = new Date().toISOString();
this.write();
}
rolledBack(value: boolean): void {
this.state.task!.rolledBack = value;
this.write();
}
}
function processAlive(pid: number | null): boolean {
if (!pid || !Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
async function waitForParent(pid: number | null, timeoutMs: number): Promise<void> {
if (!pid) return;
const deadline = Date.now() + timeoutMs;
while (processAlive(pid)) {
if (Date.now() > deadline) throw new RunnerError("UPDATE_RESTART_TIMEOUT", "The previous process did not stop in time.");
await sleep(100);
}
}
interface HealthResponse {
status?: string;
version?: string;
}
function probeHealth(plan: RestartPlan): Promise<HealthResponse | null> {
return new Promise((resolve) => {
const client = plan.health.protocol === "https" ? https : http;
const request = client.get({
hostname: "127.0.0.1",
port: plan.health.port,
path: plan.health.path,
timeout: 2_000,
...(plan.health.protocol === "https" ? { rejectUnauthorized: false } : {}),
}, (response) => {
if (response.statusCode !== 200) { response.resume(); resolve(null); return; }
let body = "";
response.setEncoding("utf8");
response.on("data", (chunk: string) => { if (body.length < 64 * 1024) body += chunk; });
response.on("end", () => {
try {
const parsed: unknown = JSON.parse(body);
resolve(parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as HealthResponse : null);
} catch { resolve(null); }
});
response.on("error", () => resolve(null));
});
request.on("timeout", () => request.destroy());
request.on("error", () => resolve(null));
});
}
async function waitForVersion(plan: RestartPlan, version: string, timeoutMs: number): Promise<HealthResponse | null> {
const deadline = Date.now() + timeoutMs;
let last: HealthResponse | null = null;
while (Date.now() < deadline) {
last = await probeHealth(plan);
if (last?.status === "ok" && last.version === version) return last;
await sleep(plan.pollIntervalMs);
}
return last?.version === version ? last : null;
}
function startApp(plan: RestartPlan): ChildProcess {
mkdirSync(path.dirname(plan.appLogPath), { recursive: true });
const log = openSync(plan.appLogPath, "a");
try {
const child = spawn(plan.nodePath, [plan.appEntry], {
cwd: plan.rootDir,
env: process.env,
detached: true,
windowsHide: true,
stdio: ["ignore", log, log],
});
child.unref();
return child;
} finally {
closeSync(log);
}
}
async function ensureApp(plan: RestartPlan, expectedVersion: string): Promise<boolean> {
let healthy = await waitForVersion(plan, expectedVersion, Math.min(5_000, plan.healthTimeoutMs));
if (healthy) return true;
let child: ChildProcess | undefined;
try {
child = startApp(plan);
healthy = await waitForVersion(plan, expectedVersion, plan.healthTimeoutMs);
if (healthy) return true;
await stopApp(child);
return false;
} finally {
child?.unref();
}
}
function exited(child: ChildProcess): boolean {
return child.exitCode !== null || child.signalCode !== null;
}
async function stopApp(child: ChildProcess | undefined): Promise<void> {
if (!child || exited(child)) return;
try { child.kill("SIGTERM"); } catch { /* Already gone. */ }
const deadline = Date.now() + 6_000;
while (!exited(child) && Date.now() < deadline) await sleep(100);
if (exited(child)) return;
try { child.kill("SIGKILL"); } catch { /* Already gone. */ }
const hardDeadline = Date.now() + 2_000;
while (!exited(child) && Date.now() < hardDeadline) await sleep(100);
}
function removeLock(plan: RestartPlan): void {
try {
const parsed = JSON.parse(readFileSync(plan.lockPath, "utf8")) as { taskId?: string };
if (parsed.taskId === plan.taskId) rmSync(plan.lockPath, { force: true });
} catch { /* Lock already reclaimed. */ }
}
export async function runRestartPlan(planPath: string): Promise<number> {
const plan = readPlan(planPath);
const state = new StateWriter(plan);
let swapped = false;
let newApp: ChildProcess | undefined;
state.status("restarting");
state.step("restart", "running");
try {
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
state.step("swap", "running");
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
swapped = true;
state.step("swap", "succeeded");
let healthy = await waitForVersion(plan, plan.targetVersion, Math.min(5_000, plan.healthTimeoutMs));
if (!healthy) {
newApp = startApp(plan);
healthy = await waitForVersion(plan, plan.targetVersion, plan.healthTimeoutMs);
}
if (!healthy) throw new RunnerError("UPDATE_HEALTH_CHECK_FAILED", `The updated version did not report ${plan.targetVersion} on /api/health.`);
state.step("restart", "succeeded");
state.status("succeeded");
removeLock(plan);
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
return 0;
} catch (error) {
await stopApp(newApp);
const code = error instanceof RunnerError || error instanceof CodeSwapError
? error.code
: "UPDATE_RESTART_FAILED";
const message = error instanceof Error ? error.message : "The update could not be completed.";
state.step("restart", "failed", message);
let rolledBack = !swapped;
if (swapped) {
state.step("rollback", "running");
try {
restoreCode(plan.rootDir, plan.backupDir);
state.step("rollback", "succeeded");
rolledBack = true;
} catch (rollbackError) {
state.step("rollback", "failed", rollbackError instanceof Error ? rollbackError.message : "Code rollback failed.");
state.rolledBack(false);
state.status("failed", { code: "UPDATE_ROLLBACK_FAILED", message: `${message} Code rollback also failed.` });
removeLock(plan);
return 1;
}
}
const healthy = await ensureApp(plan, plan.fromVersion);
state.rolledBack(rolledBack);
if (!healthy) {
state.status("failed", { code: "UPDATE_ROLLBACK_HEALTH_FAILED", message: `${message} The previous version did not become healthy.` });
} else {
state.status("failed", { code, message });
}
removeLock(plan);
return 1;
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const planPath = process.argv[2];
if (!planPath) {
console.error("Usage: restart-runner <plan.json>");
process.exit(2);
}
runRestartPlan(planPath)
.then((code) => process.exit(code))
.catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
}
+151
View File
@@ -0,0 +1,151 @@
import { createHash } from "node:crypto";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
import { gzipSync } from "node:zlib";
/** Test-only archive builders. Not imported by production code. */
export interface TarFixtureEntry {
name: string;
data?: Buffer | string;
type?: "file" | "directory" | "symlink" | "hardlink";
linkname?: string;
mode?: number;
}
function octal(value: number, width: number): string {
return value.toString(8).padStart(width, "0");
}
function tarHeader(entry: TarFixtureEntry): Buffer {
const buffer = Buffer.alloc(512);
const directory = entry.type === "directory";
const link = entry.type === "symlink" || entry.type === "hardlink";
const data = entry.data === undefined ? Buffer.alloc(0) : Buffer.from(entry.data);
const size = directory || link ? 0 : data.length;
buffer.write(entry.name, 0, 100, "utf8");
buffer.write(`${octal(entry.mode ?? (directory ? 0o755 : 0o644), 7)}\0`, 100, 8, "ascii");
buffer.write("0000000\0", 108, 8, "ascii");
buffer.write("0000000\0", 116, 8, "ascii");
buffer.write(`${octal(size, 11)}\0`, 124, 12, "ascii");
buffer.write("00000000000\0", 136, 12, "ascii");
buffer.write(" ", 148, 8, "ascii");
buffer.write(entry.type === "directory" ? "5" : entry.type === "symlink" ? "2" : entry.type === "hardlink" ? "1" : "0", 156, 1, "ascii");
if (entry.linkname) buffer.write(entry.linkname, 157, 100, "utf8");
buffer.write("ustar\0", 257, 6, "ascii");
buffer.write("00", 263, 2, "ascii");
buffer.write("root", 265, 32, "ascii");
buffer.write("root", 297, 32, "ascii");
buffer.write("0000000\0", 329, 8, "ascii");
buffer.write("0000000\0", 337, 8, "ascii");
let checksum = 0;
for (const byte of buffer) checksum += byte;
buffer.write(`${octal(checksum, 6)}\0 `, 148, 8, "ascii");
return buffer;
}
export function createTarGz(entries: TarFixtureEntry[]): Buffer {
const chunks: Buffer[] = [];
for (const entry of entries) {
const data = entry.type === "directory" || entry.type === "symlink" || entry.type === "hardlink"
? Buffer.alloc(0)
: Buffer.from(entry.data ?? "");
chunks.push(tarHeader(entry));
if (data.length) {
chunks.push(data, Buffer.alloc((512 - (data.length % 512)) % 512));
}
}
chunks.push(Buffer.alloc(1024));
return gzipSync(Buffer.concat(chunks));
}
export interface ZipFixtureEntry {
name: string;
data?: Buffer | string;
mode?: number;
directory?: boolean;
}
function crc32(buffer: Buffer): number {
let crc = 0xffffffff;
for (const byte of buffer) {
crc ^= byte;
for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0xedb88320 : crc >>> 1;
}
return (crc ^ 0xffffffff) >>> 0;
}
export function createZip(entries: ZipFixtureEntry[]): Buffer {
const locals: Buffer[] = [];
const central: Buffer[] = [];
let offset = 0;
for (const entry of entries) {
const directory = entry.directory === true || entry.name.endsWith("/");
const data = directory ? Buffer.alloc(0) : Buffer.from(entry.data ?? "");
const name = Buffer.from(entry.name, "utf8");
const mode = entry.mode ?? (directory ? 0o040755 : 0o100644);
const crc = crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0, 6);
local.writeUInt16LE(0, 8);
local.writeUInt32LE(0, 10);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(data.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
locals.push(local, name, data);
const entryCentral = Buffer.alloc(46);
entryCentral.writeUInt32LE(0x02014b50, 0);
entryCentral.writeUInt16LE(0x0314, 4);
entryCentral.writeUInt16LE(20, 6);
entryCentral.writeUInt16LE(0, 8);
entryCentral.writeUInt16LE(0, 10);
entryCentral.writeUInt32LE(0, 12);
entryCentral.writeUInt32LE(crc, 16);
entryCentral.writeUInt32LE(data.length, 20);
entryCentral.writeUInt32LE(data.length, 24);
entryCentral.writeUInt16LE(name.length, 28);
entryCentral.writeUInt16LE(0, 30);
entryCentral.writeUInt16LE(0, 32);
entryCentral.writeUInt16LE(0, 34);
entryCentral.writeUInt16LE(0, 36);
entryCentral.writeUInt32LE((mode << 16) >>> 0, 38);
entryCentral.writeUInt32LE(offset, 42);
central.push(entryCentral, name);
offset += 30 + name.length + data.length;
}
const directory = Buffer.concat(central);
const eocd = Buffer.alloc(22);
eocd.writeUInt32LE(0x06054b50, 0);
eocd.writeUInt16LE(0, 4);
eocd.writeUInt16LE(0, 6);
eocd.writeUInt16LE(entries.length, 8);
eocd.writeUInt16LE(entries.length, 10);
eocd.writeUInt32LE(directory.length, 12);
eocd.writeUInt32LE(offset, 16);
eocd.writeUInt16LE(0, 20);
return Buffer.concat([...locals, directory, eocd]);
}
export function sha256Hex(value: Buffer): string {
return createHash("sha256").update(value).digest("hex");
}
/** Minimal runnable release-package layout accepted by validateStagedPackage. */
export function createPackageFiles(root: string, version: string, extra: Record<string, string> = {}): void {
for (const directory of ["dist", "web/dist", "node_modules", "runtime"]) {
mkdirSync(path.join(root, directory), { recursive: true });
}
writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "webspeak-webclient", version }), "utf8");
writeFileSync(path.join(root, "dist", "index.js"), "// package entry\n", "utf8");
writeFileSync(path.join(root, "web", "dist", "index.html"), "<!doctype html>\n", "utf8");
writeFileSync(path.join(root, "runtime", "node"), "#!/bin/sh\nexit 0\n", { encoding: "utf8", mode: 0o755 });
for (const [relative, contents] of Object.entries(extra)) {
const target = path.join(root, relative);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, contents, "utf8");
}
}
+369
View File
@@ -0,0 +1,369 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Logger } from "../logger.js";
import { CHECKSUM_ASSET_NAME, OFFICIAL_REPOSITORY } from "./releases.js";
import { UpdateError, UpdateService, type UpdateErrorCode, type UpdateServiceOptions } from "./update-service.js";
import { createPackageFiles, createTarGz, sha256Hex, type TarFixtureEntry } from "./test-support.js";
import { readUpdateState } from "./update-state.js";
const logger: Logger = { debug() {}, info() {}, warn() {}, error() {}, child() { return this; } };
const ASSET_NAME = "webspeak-webclient-v0.4.0-linux-x64.tar.gz";
const RELEASE_LIST_URL = `https://api.github.com/repos/${OFFICIAL_REPOSITORY}/releases?per_page=30`;
interface AssetFixture { name: string; data: Buffer; digest?: string | null; url?: string }
interface ReleaseFixture {
version: string;
assets: AssetFixture[];
prerelease?: boolean;
draft?: boolean;
releaseUrl?: string;
}
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-update-service-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function releaseJson(fixture: ReleaseFixture) {
return {
tag_name: `v${fixture.version}`,
draft: fixture.draft === true,
prerelease: fixture.prerelease === true,
html_url: fixture.releaseUrl ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/tag/v${fixture.version}`,
published_at: "2026-01-01T00:00:00.000Z",
assets: fixture.assets.map((asset) => ({
name: asset.name,
size: asset.data.length,
browser_download_url: asset.url ?? `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v${fixture.version}/${asset.name}`,
digest: asset.digest ?? null,
})),
};
}
function fakeFetch(releases: ReleaseFixture[], downloads: Map<string, Buffer>) {
return (async (input: string | URL | Request) => {
const url = String(input);
if (url === RELEASE_LIST_URL) {
return new Response(JSON.stringify(releases.map(releaseJson)), { status: 200, headers: { "content-type": "application/json" } });
}
const body = downloads.get(url);
if (body) return new Response(body as unknown as BodyInit, { status: 200, headers: { "content-type": "application/octet-stream" } });
return new Response("not found", { status: 404 });
}) as typeof fetch;
}
function packageArchive(version: string, extra: TarFixtureEntry[] = []): Buffer {
return createTarGz([
{ name: "webspeak/", type: "directory" },
{ name: "webspeak/package.json", data: JSON.stringify({ name: "webspeak-webclient", version }) },
{ name: "webspeak/dist/index.js", data: "// package entry\n" },
{ name: "webspeak/web/dist/index.html", data: "<!doctype html>\n" },
{ name: "webspeak/node_modules/.keep", data: "" },
{ name: "webspeak/runtime/node", data: "#!/bin/sh\nexit 0\n", mode: 0o755 },
...extra,
]);
}
function checksumText(assetName: string, archive: Buffer): string {
return `${sha256Hex(archive)} ${assetName}\n`;
}
interface ServiceFixture {
service: UpdateService;
launched: string[];
dataDir: string;
rootDir: string;
}
function createService(
t: TestContext,
releases: ReleaseFixture[],
downloads: Map<string, Buffer>,
options: Partial<UpdateServiceOptions> = {},
): ServiceFixture {
const directory = workspace(t);
const rootDir = options.rootDir ?? path.join(directory, "app");
if (!options.rootDir) createPackageFiles(rootDir, "0.3.2");
const dataDir = path.join(directory, "data");
const launched: string[] = [];
const service = new UpdateService({
rootDir,
dataDir,
currentVersion: "0.3.2",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
fetch: fakeFetch(releases, downloads),
now: () => new Date("2026-01-01T00:00:00.000Z"),
launchRunner: async (planPath) => { launched.push(planPath); },
healthTimeoutMs: 100,
downloadTimeoutMs: 2_000,
...options,
});
service.initialize();
return { service, launched, dataDir, rootDir };
}
function updateErrorCode(code: UpdateErrorCode) {
return (error: unknown) => error instanceof UpdateError && error.code === code;
}
function digest(archive: Buffer): string {
return `sha256:${sha256Hex(archive)}`;
}
test("release checks list only official stable versions and expose blocked reasons", async t => {
const archive = packageArchive("0.4.0");
const downloads = new Map<string, Buffer>();
const assetUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
downloads.set(assetUrl, archive);
downloads.set(checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive)));
const { service } = createService(t, [
{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)), digest: digest(Buffer.from(checksumText(ASSET_NAME, archive))) },
],
},
{ version: "0.4.1", assets: [{ name: "webspeak-webclient-v0.4.1-linux-x64.tar.gz", data: archive }] },
{
version: "0.4.2",
assets: [{ name: ASSET_NAME, data: archive }],
releaseUrl: "https://evil.example/releases/tag/v0.4.2",
},
{
version: "0.4.3",
assets: [{ name: "webspeak-webclient-v0.4.3-linux-x64.tar.gz", data: archive, url: "https://evil.example/package.tar.gz" }],
},
{ version: "0.5.0", assets: [], prerelease: true },
{ version: "0.6.0", assets: [], draft: true },
{ version: "0.3.2", assets: [] },
], downloads);
const check = await service.checkForUpdates();
assert.deepEqual(check.releases.map((release) => release.version), ["0.4.3", "0.4.1", "0.4.0"]);
const ready = check.releases.find((release) => release.version === "0.4.0")!;
assert.equal(ready.assetName, ASSET_NAME);
assert.equal(ready.assetAvailable, true);
assert.equal(ready.hasChecksums, true);
assert.equal(ready.canApply, true);
assert.equal(ready.blockedReason, null);
assert.equal(ready.digest, digest(archive));
const noChecksum = check.releases.find((release) => release.version === "0.4.1")!;
assert.equal(noChecksum.canApply, false);
assert.equal(noChecksum.blockedReason, "UPDATE_CHECKSUM_MISSING");
const maliciousAsset = check.releases.find((release) => release.version === "0.4.3")!;
assert.equal(maliciousAsset.assetAvailable, false);
assert.equal(maliciousAsset.canApply, false);
assert.equal(maliciousAsset.blockedReason, "UPDATE_ASSET_UNAVAILABLE");
});
test("apply requires a matching confirmation and a supported deployment", async t => {
const archive = packageArchive("0.4.0");
const { service, launched } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map());
await assert.rejects(service.applyUpdate("0.4.0", "0.4.1"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
await assert.rejects((service.applyUpdate as unknown as (version: string) => Promise<unknown>)("0.4.0"), updateErrorCode("UPDATE_CONFIRMATION_REQUIRED"));
await assert.rejects(service.applyUpdate("not-a-version", "not-a-version"), updateErrorCode("UPDATE_VERSION_INVALID"));
await assert.rejects(service.applyUpdate("0.3.2", "0.3.2"), updateErrorCode("UPDATE_VERSION_NOT_NEWER"));
assert.equal(launched.length, 0);
const sourceDirectory = workspace(t);
const source = createService(t, [], new Map(), { rootDir: sourceDirectory });
assert.equal(source.service.getStatus().deployment.mode, "source");
await assert.rejects(source.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
assert.equal(source.launched.length, 0);
const docker = createService(t, [], new Map(), { isDocker: true });
assert.equal(docker.service.getStatus().deployment.mode, "docker");
await assert.rejects(docker.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_NOT_SUPPORTED"));
assert.equal(docker.launched.length, 0);
});
test("a missing SHA256SUMS entry refuses the update and persists a failed task", async t => {
const archive = packageArchive("0.4.0");
const assetName = "webspeak-webclient-v0.4.1-linux-x64.tar.gz";
const { service, launched, dataDir } = createService(t, [{
version: "0.4.1",
assets: [{ name: assetName, data: archive }],
}], new Map([[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.1/${assetName}`, archive]]));
const check = await service.checkForUpdates();
assert.equal(check.releases[0].blockedReason, "UPDATE_CHECKSUM_MISSING");
await assert.rejects(service.applyUpdate("0.4.1", "0.4.1"), updateErrorCode("UPDATE_CHECKSUM_MISSING"));
assert.equal(launched.length, 0);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.status, "failed");
assert.equal(state.task?.errorCode, "UPDATE_CHECKSUM_MISSING");
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), false);
assert.equal(existsSync(path.join(dataDir, "updates", "tasks", state.task!.id)), false);
});
test("a wrong checksum, digest mismatch or unsupported digest refuses the package", async t => {
const archive = packageArchive("0.4.0");
const baseRelease = (digestValue: string | null): ReleaseFixture => ({
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digestValue },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
});
const archiveUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`;
const checksumUrl = `https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`;
const downloads = new Map<string, Buffer>([
[archiveUrl, archive],
[checksumUrl, Buffer.from(checksumText(ASSET_NAME, archive))],
]);
const badChecksum = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`) },
],
}], new Map([[archiveUrl, archive], [checksumUrl, Buffer.from(`${"0".repeat(64)} ${ASSET_NAME}\n`)]]));
await assert.rejects(badChecksum.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_CHECKSUM_MISMATCH"));
assert.equal(badChecksum.launched.length, 0);
const wrongDigest = createService(t, [baseRelease(`sha256:${"0".repeat(64)}`)], new Map(downloads));
await assert.rejects(wrongDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_MISMATCH"));
const unsupportedDigest = createService(t, [baseRelease("md5:abc")], new Map(downloads));
await assert.rejects(unsupportedDigest.service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_DIGEST_UNSUPPORTED"));
});
test("unsafe archives are refused before any code is staged", async t => {
const archive = packageArchive("0.4.0", [{ name: "webspeak/../../escape.txt", data: "owned" }]);
const { service, launched, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map([
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, Buffer.from(checksumText(ASSET_NAME, archive))],
]));
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_ARCHIVE_UNSAFE"));
assert.equal(launched.length, 0);
assert.equal(existsSync(path.join(dataDir, "..", "escape.txt")), false);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.errorCode, "UPDATE_ARCHIVE_UNSAFE");
});
test("a verified package is staged, persisted and handed to the restart runner", async t => {
const archive = packageArchive("0.4.0");
const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
const { service, launched, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive, digest: digest(archive) },
{ name: CHECKSUM_ASSET_NAME, data: checksums, digest: digest(checksums) },
],
}], new Map([
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${ASSET_NAME}`, archive],
[`https://github.com/${OFFICIAL_REPOSITORY}/releases/download/v0.4.0/${CHECKSUM_ASSET_NAME}`, checksums],
]));
const task = await service.applyUpdate("0.4.0", "0.4.0");
assert.equal(task.status, "restarting");
assert.equal(task.targetVersion, "0.4.0");
assert.deepEqual(task.steps.map((step) => [step.name, step.status]), [
["download", "succeeded"],
["checksum", "succeeded"],
["extract", "succeeded"],
["stage", "succeeded"],
["restart", "running"],
]);
const state = readUpdateState(path.join(dataDir, "updates", "state.json"));
assert.equal(state.task?.id, task.id);
assert.equal(state.task?.status, "restarting");
assert.equal(launched.length, 1);
const plan = JSON.parse(readFileSync(launched[0], "utf8"));
assert.equal(plan.taskId, task.id);
assert.equal(plan.targetVersion, "0.4.0");
assert.equal(plan.fromVersion, "0.3.2");
assert.equal(JSON.parse(readFileSync(path.join(plan.stagedRoot, "package.json"), "utf8")).version, "0.4.0");
assert.equal(existsSync(path.join(dataDir, "updates", "update.lock")), true);
// The old process is gone once the restarted instance reads the state.
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: 0, taskId: task.id, createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: path.dirname(plan.rootDir),
dataDir,
currentVersion: "0.4.0",
logger,
platform: "linux",
architecture: "x64",
env: {},
isDocker: false,
fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:00:00.000Z"),
});
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "succeeded");
assert.equal(restarted.getStatus().task?.finishedAt, "2026-01-01T00:00:00.000Z");
});
test("a concurrent lock leaves the running task state untouched", async t => {
const archive = packageArchive("0.4.0");
const { service, dataDir } = createService(t, [{
version: "0.4.0",
assets: [
{ name: ASSET_NAME, data: archive },
{ name: CHECKSUM_ASSET_NAME, data: Buffer.from(checksumText(ASSET_NAME, archive)) },
],
}], new Map());
mkdirSync(path.join(dataDir, "updates"), { recursive: true });
writeFileSync(path.join(dataDir, "updates", "update.lock"), JSON.stringify({ pid: process.pid, taskId: "upd_running", createdAt: "2026-01-01T00:00:00.000Z" }));
writeFileSync(path.join(dataDir, "updates", "state.json"), JSON.stringify({ schemaVersion: 1, task: null }));
service.initialize();
await assert.rejects(service.applyUpdate("0.4.0", "0.4.0"), updateErrorCode("UPDATE_IN_PROGRESS"));
assert.equal(readUpdateState(path.join(dataDir, "updates", "state.json")).task, null);
assert.equal(service.getStatus().task, null);
});
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
const fixture = createService(t, [], new Map());
const running = {
schemaVersion: 1 as const,
task: {
id: "upd_live", status: "downloading" as const, fromVersion: "0.3.2", targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z", updatedAt: "2026-01-01T00:00:00.000Z", finishedAt: null,
errorCode: null, errorMessage: null, rolledBack: false, steps: [],
},
};
const statePath = path.join(fixture.dataDir, "updates", "state.json");
const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
mkdirSync(path.dirname(statePath), { recursive: true });
writeFileSync(statePath, JSON.stringify(running));
writeFileSync(lockPath, JSON.stringify({ pid: process.pid, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
const restarted = new UpdateService({
rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.3.2", logger,
platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
now: () => new Date("2026-01-01T00:00:00.000Z"),
});
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "downloading");
writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId: "upd_live", createdAt: "2026-01-01T00:00:00.000Z" }));
restarted.initialize();
assert.equal(restarted.getStatus().task?.status, "failed");
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
});
+491
View File
@@ -0,0 +1,491 @@
import { createHash, randomBytes } from "node:crypto";
import { spawn, type ChildProcess } from "node:child_process";
import {
closeSync, copyFileSync, createWriteStream, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync,
} from "node:fs";
import { rename, rm } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { Logger } from "../logger.js";
import type { UpdateCheckView, UpdateReleaseView, UpdateStatusView, UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
import { CodeSwapError, locatePackageRoot } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
type OfficialRelease, type ReleaseAsset,
} from "./releases.js";
import {
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
reconcileInterruptedState, updateLockIsHeld, UpdateLockedError, writeUpdateState, type PersistedUpdateState,
} from "./update-state.js";
import { compareVersions, isNewerVersion, isValidVersion } from "./version.js";
export type UpdateErrorCode =
| "UPDATE_IN_PROGRESS"
| "UPDATE_NOT_SUPPORTED"
| "UPDATE_VERSION_INVALID"
| "UPDATE_VERSION_NOT_NEWER"
| "UPDATE_VERSION_NOT_FOUND"
| "UPDATE_CONFIRMATION_REQUIRED"
| "UPDATE_ASSET_UNAVAILABLE"
| "UPDATE_CHECKSUM_MISSING"
| "UPDATE_CHECKSUM_MISMATCH"
| "UPDATE_DIGEST_MISMATCH"
| "UPDATE_DIGEST_UNSUPPORTED"
| "UPDATE_DOWNLOAD_FAILED"
| "UPDATE_DOWNLOAD_TOO_LARGE"
| "UPDATE_ARCHIVE_UNSAFE"
| "UPDATE_ARCHIVE_INVALID"
| "UPDATE_ARCHIVE_LIMIT"
| "UPDATE_ARCHIVE_UNSUPPORTED"
| "UPDATE_PACKAGE_INVALID"
| "UPDATE_RELEASE_UNAVAILABLE"
| "UPDATE_RUNNER_MISSING"
| "UPDATE_RUNNER_FAILED"
| "UPDATE_FAILED";
export class UpdateError extends Error {
constructor(readonly code: UpdateErrorCode, message: string, readonly statusCode = 400) {
super(message);
this.name = "UpdateError";
}
}
export interface UpdateServiceOptions {
rootDir: string;
dataDir: string;
currentVersion: string;
logger: Logger;
port?: number;
https?: boolean;
platform?: NodeJS.Platform;
architecture?: string;
env?: NodeJS.ProcessEnv;
isDocker?: boolean;
fetch?: typeof fetch;
apiBaseUrl?: string;
repository?: string;
now?: () => Date;
/** Compiled directory containing restart-runner.js and code-swap.js. */
runnerSourceDir?: string;
/** Test seam replacing the detached runner spawn. */
launchRunner?: (planPath: string, runnerDir: string) => Promise<void>;
healthTimeoutMs?: number;
downloadTimeoutMs?: number;
}
const CHECKSUM_LIMIT = 1024 * 1024;
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
interface DownloadResult {
sha256: string;
bytes: number;
}
export class UpdateService {
readonly deployment: DeploymentInfo;
private readonly source: GitHubReleaseSource;
private readonly updatesDir: string;
private readonly statePath: string;
private readonly lockPath: string;
private readonly tasksDir: string;
private readonly backupsDir: string;
private readonly fetcher: typeof fetch;
private readonly now: () => Date;
private state: PersistedUpdateState = emptyUpdateState();
private applying = false;
private releaseLock: (() => void) | null = null;
constructor(private readonly options: UpdateServiceOptions) {
this.deployment = detectDeployment({
rootDir: options.rootDir,
platform: options.platform,
architecture: options.architecture,
env: options.env,
isDocker: options.isDocker,
});
this.source = new GitHubReleaseSource({
fetch: options.fetch,
apiBaseUrl: options.apiBaseUrl,
repository: options.repository,
});
this.fetcher = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
this.now = options.now ?? (() => new Date());
this.updatesDir = path.join(options.dataDir, "updates");
this.statePath = path.join(this.updatesDir, "state.json");
this.lockPath = path.join(this.updatesDir, "update.lock");
this.tasksDir = path.join(this.updatesDir, "tasks");
this.backupsDir = path.join(this.updatesDir, "backups");
}
initialize(): void {
mkdirSync(this.updatesDir, { recursive: true });
this.state = readUpdateState(this.statePath);
const task = this.state.task;
// A live lock owner (for example a second process starting by mistake)
// must not have its in-flight task reconciled as interrupted.
if (!task || !isActiveTaskStatus(task.status) || !updateLockIsHeld(this.lockPath, task.id)) {
const changed = reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
if (changed) writeUpdateState(this.statePath, this.state);
}
clearStaleUpdateLock(this.lockPath);
this.options.logger.info({
deployment: this.deployment.mode,
version: this.options.currentVersion,
task: this.state.task?.status ?? "idle",
}, "Update service initialized");
}
getStatus(): UpdateStatusView {
return {
currentVersion: this.options.currentVersion,
deployment: {
mode: this.deployment.mode,
platform: this.deployment.platform,
architecture: this.deployment.architecture,
applyAllowed: this.deployment.applyAllowed,
reasonCode: this.deployment.reasonCode,
upgradePath: this.deployment.upgradePath,
},
task: this.state.task,
};
}
async checkForUpdates(): Promise<UpdateCheckView> {
let releases: OfficialRelease[];
try { releases = await this.source.listStableReleases(); }
catch (error) { throw mapError(error); }
const newer = releases
.filter((release) => isNewerVersion(release.version, this.options.currentVersion))
.sort((left, right) => compareVersions(right.version, left.version));
return {
currentVersion: this.options.currentVersion,
releases: newer.map((release) => this.toReleaseView(release)),
};
}
private toReleaseView(release: OfficialRelease): UpdateReleaseView {
const assetName = this.deployment.assetKind ? releaseAssetName(release.version, this.deployment.assetKind) : "";
const asset = assetName ? release.assets.find((item) => item.name === assetName) ?? null : null;
const checksums = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME) ?? null;
let blockedReason: string | null = null;
if (!this.deployment.applyAllowed) blockedReason = this.deployment.reasonCode ?? "DEPLOYMENT_SOURCE";
else if (!asset) blockedReason = "UPDATE_ASSET_UNAVAILABLE";
else if (!checksums) blockedReason = "UPDATE_CHECKSUM_MISSING";
return {
version: release.version,
tag: release.tag,
publishedAt: release.publishedAt,
releaseUrl: release.releaseUrl,
assetName,
assetSize: asset?.size ?? 0,
assetAvailable: Boolean(asset),
hasChecksums: Boolean(checksums),
digest: asset?.digest ?? null,
canApply: blockedReason === null,
blockedReason,
};
}
async applyUpdate(version: string, confirmVersion: string): Promise<UpdateTaskView> {
if (version !== confirmVersion) {
throw new UpdateError("UPDATE_CONFIRMATION_REQUIRED", "The confirmation does not match the selected version.");
}
if (!this.deployment.applyAllowed) {
throw new UpdateError("UPDATE_NOT_SUPPORTED", this.deployment.reasonCode ?? "Updates cannot be applied from this deployment.", 409);
}
if (!isValidVersion(version)) throw new UpdateError("UPDATE_VERSION_INVALID", "The selected version is invalid.");
if (!isNewerVersion(version, this.options.currentVersion)) {
throw new UpdateError("UPDATE_VERSION_NOT_NEWER", "The selected version is not newer than the running version.", 409);
}
if (this.applying || (this.state.task && isActiveTaskStatus(this.state.task.status))) {
throw new UpdateError("UPDATE_IN_PROGRESS", "Another update task is already running.", 409);
}
this.applying = true;
const taskId = `upd_${Date.now().toString(36)}_${randomBytes(6).toString("hex")}`;
const startedAt = this.now().toISOString();
const task: UpdateTaskView = {
id: taskId,
status: "downloading",
fromVersion: this.options.currentVersion,
targetVersion: version,
startedAt,
updatedAt: startedAt,
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [],
};
const taskDirectory = path.join(this.tasksDir, taskId);
try {
this.releaseLock = acquireUpdateLock(this.lockPath, taskId);
this.state = { schemaVersion: 1, task };
writeUpdateState(this.statePath, this.state);
mkdirSync(taskDirectory, { recursive: true });
const release = await this.source.findRelease(version);
if (!release) throw new UpdateError("UPDATE_VERSION_NOT_FOUND", "The selected stable release is no longer published.", 404);
if (!this.deployment.assetKind) throw new UpdateError("UPDATE_NOT_SUPPORTED", "This platform has no release package.", 409);
const assetName = releaseAssetName(version, this.deployment.assetKind);
const asset = release.assets.find((item) => item.name === assetName);
if (!asset) throw new UpdateError("UPDATE_ASSET_UNAVAILABLE", "The official release has no package for this platform.", 404);
const checksumAsset = release.assets.find((item) => item.name === CHECKSUM_ASSET_NAME);
if (!checksumAsset) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "The official release has no SHA256SUMS.txt; updates are refused.", 409);
const downloadDirectory = path.join(taskDirectory, "download");
mkdirSync(downloadDirectory, { recursive: true });
const archivePath = path.join(downloadDirectory, assetName);
const checksumPath = path.join(downloadDirectory, CHECKSUM_ASSET_NAME);
this.startStep(task, "download");
const [archive, checksumFile] = await Promise.all([
this.downloadAsset(asset, archivePath, DOWNLOAD_LIMIT),
this.downloadAsset(checksumAsset, checksumPath, CHECKSUM_LIMIT),
]);
this.finishStep(task, "download", "succeeded");
this.updateTaskStatus(task, "verifying");
this.startStep(task, "checksum");
this.verifyChecksums(checksumPath, assetName, archive.sha256, checksumFile.sha256, asset, checksumAsset);
this.finishStep(task, "checksum", "succeeded");
this.updateTaskStatus(task, "extracting");
this.startStep(task, "extract");
const extractedDirectory = path.join(taskDirectory, "extracted");
try {
await extractReleaseArchive(archivePath, extractedDirectory, assetName);
} catch (error) {
if (error instanceof ArchiveError) throw new UpdateError(error.code, error.message, 422);
throw error;
}
this.finishStep(task, "extract", "succeeded");
this.updateTaskStatus(task, "staging");
this.startStep(task, "stage");
let stagedRoot: string;
try {
if (!existsSync(archivePath)) throw new Error("Downloaded release package is missing.");
stagedRoot = locatePackageRoot(extractedDirectory, version, this.deployment.platform);
} catch (error) {
if (error instanceof CodeSwapError) throw new UpdateError("UPDATE_PACKAGE_INVALID", error.message, 422);
throw error;
}
this.finishStep(task, "stage", "succeeded");
const planPath = path.join(taskDirectory, "plan.json");
const runnerDirectory = path.join(taskDirectory, "runner");
const plan = {
schemaVersion: 1,
taskId,
rootDir: this.options.rootDir,
statePath: this.statePath,
lockPath: this.lockPath,
stagedRoot,
backupDir: path.join(this.backupsDir, taskId),
fromVersion: this.options.currentVersion,
targetVersion: version,
nodePath: path.join(this.options.rootDir, this.deployment.platform === "win32" ? "runtime/node.exe" : "runtime/node"),
appEntry: path.join(this.options.rootDir, "dist", "index.js"),
health: {
protocol: this.options.https ? "https" : "http",
port: this.options.port ?? 3040,
path: "/api/health",
},
waitForPid: process.pid,
parentTimeoutMs: 60_000,
healthTimeoutMs: this.options.healthTimeoutMs ?? 90_000,
pollIntervalMs: 500,
appLogPath: path.join(taskDirectory, "app.log"),
};
writeFileSync(planPath, JSON.stringify(plan, null, 2), { encoding: "utf8", mode: 0o600 });
this.updateTaskStatus(task, "restarting");
this.startStep(task, "restart");
writeUpdateState(this.statePath, this.state);
try {
if (this.options.launchRunner) await this.options.launchRunner(planPath, runnerDirectory);
else await this.launchRunner(planPath, runnerDirectory);
} catch (error) {
if (error instanceof UpdateError) throw error;
throw new UpdateError("UPDATE_RUNNER_FAILED", error instanceof Error ? error.message : "The restart runner could not be started.");
}
this.releaseLock = null;
this.options.logger.info({ taskId, from: task.fromVersion, to: version }, "Update prepared; restart runner started");
return task;
} catch (error) {
const updateError = mapError(error);
// A lock conflict belongs to another task. Never overwrite its persisted
// state just because this request was rejected.
const ownsTask = this.releaseLock !== null || this.state.task?.id === taskId;
task.status = "failed";
task.updatedAt = this.now().toISOString();
task.finishedAt = task.updatedAt;
task.errorCode = updateError.code;
task.errorMessage = updateError.message;
const runningStep = [...task.steps].reverse().find((step) => step.status === "running");
this.finishStep(task, runningStep?.name ?? "prepare", "failed", updateError.message);
if (ownsTask) {
this.state = { schemaVersion: 1, task };
try { writeUpdateState(this.statePath, this.state); } catch { /* Preserve the original error. */ }
}
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
this.releaseLock?.();
this.releaseLock = null;
throw updateError;
} finally {
this.applying = false;
}
}
private updateTaskStatus(task: UpdateTaskView, status: UpdateTaskStatus): void {
task.status = status;
task.updatedAt = this.now().toISOString();
writeUpdateState(this.statePath, this.state);
}
private startStep(task: UpdateTaskView, name: string, detail?: string): void {
const at = this.now().toISOString();
const existing = task.steps.find((step) => step.name === name);
if (existing) { existing.status = "running"; existing.at = at; if (detail) existing.detail = detail; }
else task.steps.push({ name, status: "running", at, ...(detail ? { detail } : {}) });
task.updatedAt = at;
}
private finishStep(task: UpdateTaskView, name: string, status: "succeeded" | "failed", detail?: string): void {
const at = this.now().toISOString();
const existing = task.steps.find((step) => step.name === name);
if (existing) { existing.status = status; existing.at = at; if (detail) existing.detail = detail; }
else task.steps.push({ name, status, at, ...(detail ? { detail } : {}) });
task.updatedAt = at;
}
private verifyChecksums(
checksumPath: string,
assetName: string,
archiveSha256: string,
checksumSha256: string,
asset: ReleaseAsset,
checksumAsset: ReleaseAsset,
): void {
const text = readFileSync(checksumPath, "utf8");
const expected = parseChecksumFile(text).get(assetName);
if (!expected) throw new UpdateError("UPDATE_CHECKSUM_MISSING", "SHA256SUMS.txt has no entry for the selected package; the update is refused.", 409);
if (expected !== archiveSha256) throw new UpdateError("UPDATE_CHECKSUM_MISMATCH", "The downloaded package does not match SHA256SUMS.txt.", 422);
this.crossCheckDigest(asset, archiveSha256);
this.crossCheckDigest(checksumAsset, checksumSha256);
}
private crossCheckDigest(asset: ReleaseAsset, actual: string): void {
if (!asset.digest) return;
const [algorithm, value] = asset.digest.split(":", 2);
if (algorithm?.toLowerCase() !== "sha256" || !/^[a-f0-9]{64}$/i.test(value ?? "")) {
throw new UpdateError("UPDATE_DIGEST_UNSUPPORTED", "GitHub supplied an unsupported asset digest.", 409);
}
if (value.toLowerCase() !== actual) throw new UpdateError("UPDATE_DIGEST_MISMATCH", "The package does not match the GitHub asset digest.", 422);
}
private async downloadAsset(asset: ReleaseAsset, destination: string, limit: number): Promise<DownloadResult> {
try { assertOfficialDownloadUrl(asset.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
let response: Response;
try {
response = await this.fetcher(asset.url, {
headers: { "user-agent": "WebSpeak-Console-Updater", accept: "application/octet-stream" },
signal: AbortSignal.timeout(this.options.downloadTimeoutMs ?? 300_000),
});
} catch (error) {
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be downloaded.", 502);
}
if (response.url) {
try { assertOfficialDownloadUrl(response.url, ...repositoryParts(this.options.repository)); }
catch (error) { throw mapError(error); }
}
if (!response.ok || !response.body) throw new UpdateError("UPDATE_DOWNLOAD_FAILED", `The release asset returned HTTP ${response.status}.`, 502);
const declared = Number(response.headers.get("content-length") ?? "");
if (Number.isFinite(declared) && declared > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
const temporary = `${destination}.${process.pid}.tmp`;
const hash = createHash("sha256");
const stream = createWriteStream(temporary, { mode: 0o600, flags: "wx" });
let bytes = 0;
try {
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
const buffer = Buffer.from(chunk);
bytes += buffer.length;
if (bytes > limit) throw new UpdateError("UPDATE_DOWNLOAD_TOO_LARGE", "The release asset exceeds the download limit.", 422);
hash.update(buffer);
if (!stream.write(buffer)) await new Promise<void>((resolve) => stream.once("drain", resolve));
}
stream.end();
await new Promise<void>((resolve, reject) => {
stream.once("finish", resolve);
stream.once("error", reject);
});
await rename(temporary, destination);
} catch (error) {
stream.destroy();
await rm(temporary, { force: true }).catch(() => undefined);
if (error instanceof UpdateError) throw error;
throw new UpdateError("UPDATE_DOWNLOAD_FAILED", error instanceof Error ? error.message : "The release asset could not be saved.", 502);
}
return { sha256: hash.digest("hex"), bytes };
}
private async launchRunner(planPath: string, runnerDirectory: string): Promise<void> {
const sourceDirectory = this.options.runnerSourceDir ?? path.dirname(fileURLToPath(import.meta.url));
const runnerSource = path.join(sourceDirectory, "restart-runner.js");
const swapSource = path.join(sourceDirectory, "code-swap.js");
if (!existsSync(runnerSource) || !existsSync(swapSource)) {
throw new UpdateError("UPDATE_RUNNER_MISSING", "The compiled restart runner is missing; rebuild the application before updating.", 500);
}
mkdirSync(runnerDirectory, { recursive: true });
copyFileSync(runnerSource, path.join(runnerDirectory, "restart-runner.js"));
copyFileSync(swapSource, path.join(runnerDirectory, "code-swap.js"));
writeFileSync(path.join(runnerDirectory, "package.json"), JSON.stringify({ type: "module" }), "utf8");
let nodePath: string;
if (this.deployment.platform === "win32") {
nodePath = path.join(runnerDirectory, "node.exe");
copyFileSync(process.execPath, nodePath);
} else {
nodePath = process.execPath;
}
const log = path.join(path.dirname(planPath), "runner.log");
await new Promise<void>((resolve, reject) => {
let child: ChildProcess;
try {
const fd = openSync(log, "a");
child = spawn(nodePath, [path.join(runnerDirectory, "restart-runner.js"), planPath], {
cwd: this.options.rootDir,
env: process.env,
detached: true,
windowsHide: true,
stdio: ["ignore", fd, fd],
});
closeSync(fd);
} catch (error) {
reject(error);
return;
}
child.once("error", reject);
child.once("spawn", () => { child.unref(); resolve(); });
});
}
}
function repositoryParts(repository: string | undefined): [string, string] {
const [owner, repo] = (repository ?? "EchoSixHIYA/WebSpeak-client-for-TeamSpeak").split("/");
return [owner, repo];
}
export function parseChecksumFile(text: string): Map<string, string> {
const entries = new Map<string, string>();
for (const line of text.split(/\r?\n/)) {
const match = /^([a-fA-F0-9]{64})\s+\*?(.+?)\s*$/.exec(line.trim());
if (!match) continue;
const name = match[2].replace(/^\.\//, "");
if (!entries.has(name)) entries.set(name, match[1].toLowerCase());
}
return entries;
}
function mapError(error: unknown): UpdateError {
if (error instanceof UpdateError) return error;
if (error instanceof UpdateLockedError) return new UpdateError("UPDATE_IN_PROGRESS", error.message, 409);
if (error instanceof ReleaseSourceError) return new UpdateError("UPDATE_RELEASE_UNAVAILABLE", error.message, 502);
if (error instanceof ArchiveError) return new UpdateError(error.code, error.message, 422);
if (error instanceof CodeSwapError) return new UpdateError(error.code === "UPDATE_ROLLBACK_FAILED" ? "UPDATE_FAILED" : "UPDATE_PACKAGE_INVALID", error.message, 422);
return new UpdateError("UPDATE_FAILED", error instanceof Error ? error.message : "The update failed.", 500);
}
+98
View File
@@ -0,0 +1,98 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { UpdateTaskView } from "../shared/update.js";
import {
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
reconcileInterruptedState, UpdateLockedError, writeUpdateState,
} from "./update-state.js";
function workspace(t: TestContext): string {
const directory = mkdtempSync(path.join(tmpdir(), "webspeak-state-"));
t.after(() => rmSync(directory, { recursive: true, force: true }));
return directory;
}
function task(overrides: Partial<UpdateTaskView> = {}): UpdateTaskView {
return {
id: "upd_test",
status: "restarting",
fromVersion: "0.3.2",
targetVersion: "0.4.0",
startedAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
finishedAt: null,
errorCode: null,
errorMessage: null,
rolledBack: false,
steps: [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }],
...overrides,
};
}
test("state files round-trip and malformed files fall back to idle", t => {
const directory = workspace(t), filename = path.join(directory, "state.json");
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
writeUpdateState(filename, { schemaVersion: 1, task: task() });
const loaded = readUpdateState(filename);
assert.equal(loaded.task?.id, "upd_test");
assert.deepEqual(loaded.task?.steps, [{ name: "swap", status: "running", at: "2026-01-01T00:00:00.000Z" }]);
for (const contents of ["not json", "{}", JSON.stringify({ schemaVersion: 2, task: task() }), JSON.stringify({ schemaVersion: 1, task: { id: 42 } })]) {
writeFileSync(filename, contents);
assert.deepEqual(readUpdateState(filename), emptyUpdateState());
}
});
test("interrupted tasks reconcile against the version that is actually running", () => {
const completed = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
assert.equal(reconcileInterruptedState(completed, "0.4.0", "2026-01-01T01:00:00.000Z"), true);
assert.equal(completed.task?.status, "succeeded");
assert.equal(completed.task?.finishedAt, "2026-01-01T01:00:00.000Z");
const interrupted = { schemaVersion: 1 as const, task: task({ targetVersion: "0.4.0" }) };
assert.equal(reconcileInterruptedState(interrupted, "0.3.2", "2026-01-01T01:00:00.000Z"), true);
assert.equal(interrupted.task?.status, "failed");
assert.equal(interrupted.task?.errorCode, "UPDATE_INTERRUPTED");
const finished = { schemaVersion: 1 as const, task: task({ status: "succeeded" as const }) };
assert.equal(reconcileInterruptedState(finished, "0.3.2", "2026-01-01T01:00:00.000Z"), false);
assert.equal(isActiveTaskStatus("downloading"), true);
assert.equal(isActiveTaskStatus("failed"), false);
});
test("the update lock is exclusive and safe to release", t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
const release = acquireUpdateLock(lock, "task-one");
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-one");
assert.throws(() => acquireUpdateLock(lock, "task-two"), (error: unknown) => error instanceof UpdateLockedError);
release();
assert.equal(existsSync(lock), false);
const second = acquireUpdateLock(lock, "task-two");
second();
assert.equal(existsSync(lock), false);
});
test("locks left by dead processes are reclaimed while live locks are preserved", t => {
const directory = workspace(t), lock = path.join(directory, "update.lock");
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
const release = acquireUpdateLock(lock, "new-task");
assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
release();
writeFileSync(lock, JSON.stringify({ pid: process.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), true);
writeFileSync(lock, JSON.stringify({ pid: 0, taskId: "dead-task", createdAt: "2026-01-01T00:00:00.000Z" }));
clearStaleUpdateLock(lock);
assert.equal(existsSync(lock), false);
});
test("state writes replace the destination atomically", t => {
const directory = workspace(t), filename = path.join(directory, "nested", "state.json");
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "first" }) });
writeUpdateState(filename, { schemaVersion: 1, task: task({ id: "second" }) });
assert.equal(readUpdateState(filename).task?.id, "second");
assert.equal(existsSync(`${filename}.${process.pid}.tmp`), false);
});
+168
View File
@@ -0,0 +1,168 @@
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
export interface PersistedUpdateState {
schemaVersion: 1;
task: UpdateTaskView | null;
}
export interface UpdateLockRecord {
pid: number;
taskId: string;
createdAt: string;
}
export class UpdateLockedError extends Error {
readonly code = "UPDATE_IN_PROGRESS";
constructor(message = "Another update task is already running.") {
super(message);
this.name = "UpdateLockedError";
}
}
const ACTIVE_STATUSES: UpdateTaskStatus[] = ["downloading", "verifying", "extracting", "staging", "restarting"];
export function isActiveTaskStatus(status: UpdateTaskStatus | string): boolean {
return (ACTIVE_STATUSES as string[]).includes(status);
}
export function emptyUpdateState(): PersistedUpdateState {
return { schemaVersion: 1, task: null };
}
export function readUpdateState(filename: string): PersistedUpdateState {
try {
const parsed: unknown = JSON.parse(readFileSync(filename, "utf8"));
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return emptyUpdateState();
const record = parsed as Record<string, unknown>;
if (record.schemaVersion !== 1) return emptyUpdateState();
return { schemaVersion: 1, task: parseTask(record.task) };
} catch {
return emptyUpdateState();
}
}
function parseTask(value: unknown): UpdateTaskView | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const task = value as Record<string, unknown>;
if (typeof task.id !== "string" || !task.id
|| typeof task.status !== "string"
|| typeof task.fromVersion !== "string"
|| typeof task.targetVersion !== "string"
|| typeof task.startedAt !== "string"
|| typeof task.updatedAt !== "string") return null;
return {
id: task.id,
status: task.status as UpdateTaskStatus,
fromVersion: task.fromVersion,
targetVersion: task.targetVersion,
startedAt: task.startedAt,
updatedAt: task.updatedAt,
finishedAt: typeof task.finishedAt === "string" ? task.finishedAt : null,
errorCode: typeof task.errorCode === "string" ? task.errorCode : null,
errorMessage: typeof task.errorMessage === "string" ? task.errorMessage : null,
rolledBack: task.rolledBack === true,
steps: Array.isArray(task.steps)
? task.steps.filter((step): step is UpdateTaskView["steps"][number] => Boolean(step)
&& typeof step === "object"
&& !Array.isArray(step)
&& typeof (step as Record<string, unknown>).name === "string"
&& typeof (step as Record<string, unknown>).status === "string"
&& typeof (step as Record<string, unknown>).at === "string")
.map((step) => ({
name: step.name,
status: step.status,
at: step.at,
...(typeof step.detail === "string" ? { detail: step.detail } : {}),
}))
: [],
};
}
export function writeUpdateState(filename: string, state: PersistedUpdateState): void {
mkdirSync(path.dirname(filename), { recursive: true });
const temporary = `${filename}.${process.pid}.tmp`;
writeFileSync(temporary, JSON.stringify(state, null, 2), { encoding: "utf8", mode: 0o600 });
renameSync(temporary, filename);
}
/**
* Reconcile a task that was active when the previous process stopped. If the
* running version already matches the target the update completed; otherwise
* it failed and is reported as interrupted.
*/
export function reconcileInterruptedState(state: PersistedUpdateState, currentVersion: string, now: string): boolean {
const task = state.task;
if (!task || !isActiveTaskStatus(task.status)) return false;
if (task.targetVersion === currentVersion) {
task.status = "succeeded";
task.finishedAt = now;
task.updatedAt = now;
return true;
}
task.status = "failed";
task.finishedAt = now;
task.updatedAt = now;
task.errorCode = "UPDATE_INTERRUPTED";
task.errorMessage = "The process stopped before the update completed. The previous version is still running.";
return true;
}
function processIsAlive(pid: number): boolean {
if (!Number.isInteger(pid) || pid <= 0) return false;
try {
process.kill(pid, 0);
return true;
} catch (error) {
return (error as NodeJS.ErrnoException).code === "EPERM";
}
}
/**
* Cross-process mutex. Lock files written by a dead process are reclaimed so
* a crash cannot permanently block the maintenance page.
*/
export function acquireUpdateLock(lockPath: string, taskId: string): () => void {
mkdirSync(path.dirname(lockPath), { recursive: true });
const payload = JSON.stringify({ pid: process.pid, taskId, createdAt: new Date().toISOString() } satisfies UpdateLockRecord);
for (let attempt = 0; attempt < 2; attempt++) {
try {
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
return () => {
try {
const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial<UpdateLockRecord>;
if (current.taskId === taskId) unlinkSync(lockPath);
} catch { /* The lock may already have been reclaimed. */ }
};
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
let current: Partial<UpdateLockRecord> = {};
try { current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial<UpdateLockRecord>; } catch { /* Treat as stale. */ }
const alive = processIsAlive(Number(current.pid));
if (alive && current.taskId !== taskId) throw new UpdateLockedError();
try { unlinkSync(lockPath); } catch { /* Another process reclaimed it first. */ }
}
}
throw new UpdateLockedError();
}
export function clearStaleUpdateLock(lockPath: string): void {
try {
const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial<UpdateLockRecord>;
if (!processIsAlive(Number(current.pid))) unlinkSync(lockPath);
} catch {
try { if (existsSync(lockPath)) unlinkSync(lockPath); } catch { /* Best effort. */ }
}
}
/** True when a live process still owns the lock, optionally for a specific task. */
export function updateLockIsHeld(lockPath: string, taskId?: string): boolean {
try {
const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial<UpdateLockRecord>;
if (!processIsAlive(Number(current.pid))) return false;
return taskId === undefined || current.taskId === taskId;
} catch {
return false;
}
}
+28
View File
@@ -0,0 +1,28 @@
import assert from "node:assert/strict";
import test from "node:test";
import { compareVersions, isNewerVersion, isValidVersion, parseReleaseTag, parseStableVersion } from "./version.js";
test("stable versions require exactly three numeric segments", () => {
assert.deepEqual(parseStableVersion(" 01.002.0003 "), { major: 1, minor: 2, patch: 3, text: "1.2.3" });
for (const value of ["1.2", "1.2.3-beta", "v1.2.3", "1.2.3.4", "", null, 1.2]) {
assert.equal(parseStableVersion(value), null);
}
});
test("release tags accept only the v-prefixed stable shape", () => {
assert.equal(parseReleaseTag("v0.3.2")?.text, "0.3.2");
assert.equal(parseReleaseTag("0.3.2"), null);
assert.equal(parseReleaseTag("v0.3.2-rc.1"), null);
assert.equal(parseReleaseTag("vv0.3.2"), null);
});
test("version comparison and newer checks are numeric", () => {
assert.ok(compareVersions("0.10.0", "0.9.9") > 0);
assert.ok(compareVersions("1.0.0", "1.0.0") === 0);
assert.ok(compareVersions("1.0.0", "1.0.1") < 0);
assert.equal(isNewerVersion("0.3.3", "0.3.2"), true);
assert.equal(isNewerVersion("0.3.2", "0.3.2"), false);
assert.equal(isNewerVersion("not-a-version", "0.3.2"), false);
assert.equal(isValidVersion("2.0.0"), true);
assert.equal(isValidVersion("2.0"), false);
});
+38
View File
@@ -0,0 +1,38 @@
/** Stable semantic versions only. Pre-release/rolling channels are deliberate non-goals. */
export interface StableVersion {
major: number;
minor: number;
patch: number;
text: string;
}
const STABLE = /^(\d{1,6})\.(\d{1,6})\.(\d{1,6})$/;
export function parseStableVersion(value: unknown): StableVersion | null {
if (typeof value !== "string") return null;
const match = STABLE.exec(value.trim());
if (!match) return null;
const [, major, minor, patch] = match;
return { major: Number(major), minor: Number(minor), patch: Number(patch), text: `${Number(major)}.${Number(minor)}.${Number(patch)}` };
}
/** `v1.2.3` is the only accepted release tag shape. */
export function parseReleaseTag(value: unknown): StableVersion | null {
if (typeof value !== "string" || !value.startsWith("v")) return null;
return parseStableVersion(value.slice(1));
}
export function isValidVersion(value: unknown): value is string {
return parseStableVersion(value) !== null;
}
export function compareVersions(left: string, right: string): number {
const a = parseStableVersion(left);
const b = parseStableVersion(right);
if (!a || !b) return 0;
return a.major - b.major || a.minor - b.minor || a.patch - b.patch;
}
export function isNewerVersion(candidate: string, current: string): boolean {
return compareVersions(candidate, current) > 0;
}