+
+
@@ -288,13 +331,51 @@ import type { AdminConnectionRecord } from "../../../../src/shared/admin-respons
const props = defineProps<{
model: ReturnType;
initialSection?: string;
- i18n: Pick, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText">;
+ i18n: Pick, "tr" | "formatDate" | "formatAge" | "sessionStateLabel" | "connectionStatusLabel" | "inviteStatusLabel" | "eventName" | "connectionFailureText" | "errorText">;
}>();
// Request ownership, cancellation and drafts remain in the page's controller.
const { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
- loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup } = props.model;
-const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText } = props.i18n;
+ loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup,
+ updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion, checkForUpdates, applyUpdate } = props.model;
+const { tr, formatDate, formatAge, sessionStateLabel, connectionStatusLabel, inviteStatusLabel, eventName, connectionFailureText, errorText } = props.i18n;
type OperationsSection = 'sessions' | 'invites' | 'logs' | 'audit' | 'maintenance';
+const canApplyUpdates = computed(() => operations.update.deployment.applyAllowed);
+const deploymentLabel = computed(() => {
+ const mode = operations.update.deployment.mode;
+ return mode === 'docker' ? tr('updateModeDocker') : mode === 'release-package' ? tr('updateModeReleasePackage') : tr('updateModeSource');
+});
+function blockedReasonText(code: string | null) {
+ switch (code) {
+ case 'DEPLOYMENT_DOCKER': return tr('updateBlockedDocker');
+ case 'DEPLOYMENT_SOURCE': return tr('updateBlockedSource');
+ case 'PLATFORM_UNSUPPORTED': return tr('updateBlockedPlatform');
+ case 'ARCH_UNSUPPORTED': return tr('updateBlockedArch');
+ case 'UPDATE_ASSET_UNAVAILABLE': return tr('updateAssetMissing');
+ case 'UPDATE_CHECKSUM_MISSING': return tr('updateChecksumMissing');
+ default: return tr('updateBlockedUnavailable');
+ }
+}
+const blockedUpdateText = computed(() => blockedReasonText(operations.update.deployment.reasonCode));
+const releaseBlockedText = (release: { blockedReason: string | null }) => blockedReasonText(release.blockedReason);
+function updateStatusText(status: string | undefined) {
+ switch (status) {
+ case 'downloading': return tr('updateStatusDownloading');
+ case 'verifying': return tr('updateStatusVerifying');
+ case 'extracting': return tr('updateStatusExtracting');
+ case 'staging': return tr('updateStatusStaging');
+ case 'restarting': return tr('updateStatusRestarting');
+ case 'succeeded': return tr('updateStatusSucceeded');
+ case 'failed': return tr('updateStatusFailed');
+ default: return '';
+ }
+}
+const updateTaskStatusLabel = computed(() => updateStatusText(operations.update.task?.status));
+const updateTaskErrorText = computed(() => operations.update.task?.errorCode ? errorText(operations.update.task.errorCode) : '');
+const selectedRelease = computed(() => availableUpdates.value.find(release => release.version === selectedVersion.value && release.canApply) ?? null);
+function applySelectedUpdate() {
+ const release = selectedRelease.value;
+ if (release) void applyUpdate(release);
+}
const normalizeSection = (value?: string): OperationsSection => value === 'invites' || value === 'logs' || value === 'audit' || value === 'maintenance' ? value : 'sessions';
const activeSection = ref(normalizeSection(props.initialSection));
watch(() => props.initialSection, value => { activeSection.value = normalizeSection(value); });
diff --git a/web/src/composables/useAdminI18n.ts b/web/src/composables/useAdminI18n.ts
index 173cbe3..e02be08 100644
--- a/web/src/composables/useAdminI18n.ts
+++ b/web/src/composables/useAdminI18n.ts
@@ -27,6 +27,7 @@ const eventLabels: Record = {
ADMIN_SKIN_INSTALLED: "skinInstalledEvent", ADMIN_SKIN_REMOVED: "skinRemovedEvent",
ADMIN_SKIN_ENABLED: "skinEnabledEvent", ADMIN_SKIN_DISABLED: "skinDisabledEvent",
INVITE_CREATED: "inviteCreatedEvent", INVITE_REVOKED: "inviteRevokedEvent", INVITE_CONSUMED: "inviteConsumedEvent",
+ ADMIN_UPDATE_STARTED: "updateStartedEvent",
TS_ADMIN_SETTINGS_UPDATED: "tsAdminSaved",
TS_ADMIN_OVERVIEW_READ: "tsAdminReadEvent",
TS_ADMIN_OVERVIEW_FAILED: "tsAdminReadFailedEvent",
@@ -51,6 +52,16 @@ const errorLabels: Record = {
TS_ADMIN_CLIENT_CHANGED: "tsAdminClientChanged", TS_ADMIN_CONFIG_CHANGED: "tsAdminConfigChanged", TS_ADMIN_PARTIAL_SUCCESS: "tsAdminPartialError",
TS_ADMIN_RATE_LIMITED: "tsAdminRateError", TS_ADMIN_TLS_FAILED: "tsAdminTlsError",
TS_ADMIN_READ_FAILED: "tsAdminReadError", TS_ADMIN_TIMEOUT: "tsAdminTimeoutError",
+ UPDATE_IN_PROGRESS: "updateErrorInProgress", UPDATE_CHECKSUM_MISSING: "updateErrorChecksum",
+ UPDATE_CHECKSUM_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_UNSUPPORTED: "updateErrorChecksum",
+ UPDATE_ARCHIVE_UNSAFE: "updateErrorArchive", UPDATE_ARCHIVE_INVALID: "updateErrorArchive", UPDATE_ARCHIVE_LIMIT: "updateErrorArchive", UPDATE_ARCHIVE_UNSUPPORTED: "updateErrorArchive",
+ UPDATE_PACKAGE_INVALID: "updateErrorPackage", UPDATE_DOWNLOAD_FAILED: "updateErrorDownload", UPDATE_DOWNLOAD_TOO_LARGE: "updateErrorDownload",
+ UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorApply", UPDATE_INTERRUPTED: "updateErrorInterrupted",
+ UPDATE_HEALTH_CHECK_FAILED: "updateErrorApply", UPDATE_ROLLBACK_HEALTH_FAILED: "updateErrorGeneric",
+ UPDATE_RESTART_FAILED: "updateErrorGeneric", UPDATE_RESTART_TIMEOUT: "updateErrorGeneric", UPDATE_PLAN_INVALID: "updateErrorGeneric",
+ UPDATE_NOT_SUPPORTED: "updateErrorGeneric", UPDATE_RELEASE_UNAVAILABLE: "updateErrorGeneric", UPDATE_ASSET_UNAVAILABLE: "updateErrorGeneric",
+ UPDATE_CONFIRMATION_REQUIRED: "updateErrorGeneric", UPDATE_VERSION_INVALID: "updateErrorGeneric", UPDATE_VERSION_NOT_NEWER: "updateErrorGeneric",
+ UPDATE_VERSION_NOT_FOUND: "updateErrorGeneric", UPDATE_RUNNER_MISSING: "updateErrorGeneric", UPDATE_RUNNER_FAILED: "updateErrorGeneric",
};
const connectionErrors: Record = {
PASSWORD_REQUIRED: "serverPasswordRequiredError", SERVER_PASSWORD_REQUIRED: "serverPasswordRequiredError",
diff --git a/web/src/composables/useAdminOperations.ts b/web/src/composables/useAdminOperations.ts
index 852ee1d..a7c5a89 100644
--- a/web/src/composables/useAdminOperations.ts
+++ b/web/src/composables/useAdminOperations.ts
@@ -1,5 +1,5 @@
import { onScopeDispose, reactive, ref, type Ref } from "vue";
-import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord } from "../../../src/shared/admin-responses.js";
+import type { AdminSession, ManagedInvite, AdminLog, AdminConnectionRecord, AdminUpdateRelease, AdminUpdateStatus } from "../../../src/shared/admin-responses.js";
import type { copy } from "../i18n/admin.js";
import { isAdminRequestCancelled, type AdminApi } from "../services/admin-api.js";
import { createAdminRequests } from "../services/admin-requests.js";
@@ -12,19 +12,31 @@ interface Options {
refreshOverview(): Promise;
}
+function emptyUpdateStatus(): AdminUpdateStatus {
+ return {
+ currentVersion: "",
+ deployment: { mode: "source", platform: "", architecture: "", applyAllowed: false, reasonCode: "UPDATE_UNAVAILABLE", upgradePath: "source" },
+ task: null,
+ };
+}
+
export function useAdminOperations(options: Options) {
const requests = createAdminRequests();
const operationsLoading = ref(false), terminatingSession = ref(""), inviteSubmitting = ref(false);
+ const updateChecking = ref(false), updateApplying = ref(false), updateChecked = ref(false);
+ const availableUpdates = ref([]), selectedVersion = ref("");
const revokingInvites = reactive(new Set());
const inviteForm = reactive({ channel: "", expiresInHours: 24, maxUses: 0 });
const createdInvite = ref<{ token: string; link: string } | null>(null);
const operations = reactive({ sessions: [] as AdminSession[], invites: [] as ManagedInvite[],
diagnostics: { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 },
+ update: emptyUpdateStatus(),
logs: { available: false, entries: [] as AdminLog[], sessions: [] as AdminConnectionRecord[] }, audit: [] as Array<{ event: string; createdAt: string }> });
let noticeTimer: number | undefined;
function cancelRequests() {
requests.reset();
operationsLoading.value = false; terminatingSession.value = ""; inviteSubmitting.value = false;
+ updateChecking.value = false; updateApplying.value = false;
revokingInvites.clear();
if (noticeTimer !== undefined) window.clearTimeout(noticeTimer);
noticeTimer = undefined;
@@ -35,6 +47,8 @@ export function useAdminOperations(options: Options) {
operations.sessions = []; operations.invites = []; operations.audit = [];
operations.logs = { available: false, entries: [], sessions: [] };
operations.diagnostics = { version: "", node: "", platform: "", arch: "", schemaVersion: 0, createdSessions: 0 };
+ operations.update = emptyUpdateStatus();
+ availableUpdates.value = []; selectedVersion.value = ""; updateChecked.value = false;
Object.assign(inviteForm, { channel: "", expiresInHours: 24, maxUses: 0 });
}
onScopeDispose(reset);
@@ -45,13 +59,15 @@ export function useAdminOperations(options: Options) {
const request = requests.begin("load");
operationsLoading.value = true;
try {
- const [sessions, invites, diagnostics, logs, audit] = await Promise.all([
- options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
+ const [sessions, invites, diagnostics, update, logs, audit] = await Promise.all([
+ options.api.sessions(request.signal), options.api.invites(request.signal), options.api.diagnostics(request.signal),
+ options.api.updateStatus(request.signal), options.api.logs(request.signal), options.api.audit(request.signal),
]);
if (!request.isCurrent()) return;
operations.sessions = sessions.sessions;
operations.invites = invites.invites;
operations.diagnostics = { ...diagnostics.gateway, schemaVersion: diagnostics.database.schemaVersion, createdSessions: diagnostics.sessions.created };
+ operations.update = update;
operations.logs = logs;
operations.audit = audit.events;
} catch (error) { if (request.isCurrent()) report(error); }
@@ -103,6 +119,31 @@ export function useAdminOperations(options: Options) {
} catch (error) { if (request.isCurrent()) report(error); }
finally { request.finish(); }
}
+ async function checkForUpdates() {
+ if (updateChecking.value) return;
+ const request = requests.begin("update-check");
+ updateChecking.value = true; updateChecked.value = false; availableUpdates.value = []; options.errorMessage.value = "";
+ try {
+ const result = await options.api.checkUpdates(request.signal);
+ if (!request.isCurrent()) return;
+ availableUpdates.value = result.releases;
+ selectedVersion.value = result.releases.find(release => release.canApply)?.version ?? "";
+ updateChecked.value = true;
+ } catch (error) { if (request.isCurrent()) report(error); }
+ finally { if (request.isCurrent()) updateChecking.value = false; request.finish(); }
+ }
+ async function applyUpdate(release: AdminUpdateRelease) {
+ if (updateApplying.value) return;
+ if (!window.confirm(options.tr("updateConfirmApply", { version: release.version }))) return;
+ const request = requests.begin("update-apply");
+ updateApplying.value = true; options.errorMessage.value = "";
+ try {
+ const result = await options.api.applyUpdate({ version: release.version, confirmVersion: release.version }, request.signal);
+ if (!request.isCurrent()) return;
+ operations.update = { ...operations.update, task: result.task, deployment: { ...operations.update.deployment, applyAllowed: false } };
+ } catch (error) { if (request.isCurrent()) report(error); }
+ finally { if (request.isCurrent()) updateApplying.value = false; request.finish(); }
+ }
async function downloadBackup() {
const request = requests.begin("backup");
try {
@@ -118,5 +159,7 @@ export function useAdminOperations(options: Options) {
finally { request.finish(); }
}
return { operations, operationsLoading, terminatingSession, inviteSubmitting, revokingInvites, inviteForm, createdInvite,
- loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, cancelRequests, reset };
+ updateChecking, updateApplying, updateChecked, availableUpdates, selectedVersion,
+ loadOperations, terminateSession, createInvite, revokeInvite, copyInviteLink, downloadBackup, checkForUpdates, applyUpdate,
+ cancelRequests, reset };
}
diff --git a/web/src/i18n/admin-organization.ts b/web/src/i18n/admin-organization.ts
index 148c24e..aaeb167 100644
--- a/web/src/i18n/admin-organization.ts
+++ b/web/src/i18n/admin-organization.ts
@@ -10,6 +10,27 @@ const zh = {
adminBrowserSessions: "浏览器会话", adminBrowserSessionsLead: "这里只显示通过此 WebSpeak 实例连接的用户;结束会话会断开对应浏览器。完整 TS 成员列表见 TeamSpeak 服务管理。",
adminInviteScope: "这些邀请链接由当前 WebSpeak 实例生成和管理。",
adminLogsSection: "连接与日志", adminMaintenanceSection: "诊断与备份",
+ updateTitle: "版本更新", updateLead: "检查官方 GitHub Releases 中的正式版本。发布包安装可在控制台校验并切换版本;Docker 和源码运行只显示检查结果。",
+ updateCurrentVersion: "当前版本", updateDeploymentMode: "部署模式", updateArchitecture: "平台与架构",
+ updateModeDocker: "Docker Compose", updateModeReleasePackage: "发布包", updateModeSource: "源码运行",
+ updateCanApply: "可在此控制台更新", updateCannotApply: "此部署不能在此应用更新",
+ updateCheckAction: "检查正式版", updateChecking: "正在检查…", updateUpToDate: "没有比当前版本更新的正式版。",
+ updateSelectRelease: "选择目标版本", updateApplyAction: "应用更新", updateApplying: "正在准备更新…",
+ updateConfirmApply: "将把 WebSpeak 更新到 v{{version}}。更新前建议先导出备份;进程会重启,页面会短暂断开。继续吗?",
+ updateBackupHint: "建议先使用上方的“导出备份”。控制台只替换程序代码,不会改动 data/、config.json 或 certs/。",
+ updateChecksumMissing: "该版本缺少 SHA256SUMS.txt,已拒绝更新。", updateAssetMissing: "该版本没有适用于当前平台和架构的发布包。",
+ updateBlockedDocker: "容器内不能替换镜像。请保留 webspeak-data volume,在宿主机执行 docker compose pull && docker compose up -d;不要执行 docker compose down -v。",
+ updateBlockedSource: "源码运行没有捆绑运行时,控制台无法安全切换版本。请拉取源码后自行构建(npm ci && npm run build && npm run web:build),或改用发布包/Docker Compose。",
+ updateBlockedPlatform: "当前平台没有官方发布包,只能检查版本。", updateBlockedArch: "当前架构没有官方发布包,只能检查版本。",
+ updateBlockedUnavailable: "此实例未启用控制台更新。", updateTaskTitle: "更新任务",
+ updateStatusDownloading: "正在下载", updateStatusVerifying: "正在校验", updateStatusExtracting: "正在解包", updateStatusStaging: "正在暂存",
+ updateStatusRestarting: "正在重启", updateStatusSucceeded: "更新成功", updateStatusFailed: "更新失败",
+ updateRolledBack: "已恢复上一版本。", updateRestartHint: "更新成功后进程会自动重启;页面断开时请稍后刷新。",
+ updateReleaseNotes: "发行说明",
+ updateErrorChecksum: "校验和缺失或不匹配,已拒绝安装该发布包。", updateErrorArchive: "发布包未通过安全解包检查。",
+ updateErrorDownload: "无法从官方 Release 下载或保存资源。", updateErrorPackage: "发布包内容与所选正式版不匹配。",
+ updateErrorApply: "更新失败,已恢复上一版本。", updateErrorInterrupted: "更新被中断,未确认完成。",
+ updateErrorInProgress: "已有更新任务正在进行。", updateErrorGeneric: "更新未能完成,请查看日志。", updateStartedEvent: "已开始更新",
adminWsOverviewTitle: "WebSpeak 管理服务已就绪", adminWsOverviewLead: "先管理实例接入与访客体验;需要管理 TS 服务时,再按需配置独立连接。",
adminWsManageLead: "接入策略、站点公告、语音传输、皮肤商店和浏览器会话。",
adminTsManageLead: "服务器设置、频道、在线成员、服务器组和封禁。需单独配置 Query 凭据,常规语音连接不需要。",
@@ -32,6 +53,27 @@ const en = {
adminBrowserSessions: "Browser sessions", adminBrowserSessionsLead: "Only users connected through this WebSpeak instance are listed here. Ending a session disconnects that browser. Use TeamSpeak service management for the full TS client list.",
adminInviteScope: "These invite links are created and managed by this WebSpeak instance.",
adminLogsSection: "Connections & logs", adminMaintenanceSection: "Diagnostics & backups",
+ updateTitle: "Version update", updateLead: "Check stable versions in the official GitHub Releases. Release-package installs can verify and switch versions here; Docker and source installs only show check results.",
+ updateCurrentVersion: "Current version", updateDeploymentMode: "Deployment", updateArchitecture: "Platform & architecture",
+ updateModeDocker: "Docker Compose", updateModeReleasePackage: "Release package", updateModeSource: "From source",
+ updateCanApply: "Update from this console", updateCannotApply: "This deployment cannot apply updates here",
+ updateCheckAction: "Check stable releases", updateChecking: "Checking…", updateUpToDate: "No stable release is newer than the running version.",
+ updateSelectRelease: "Select target version", updateApplyAction: "Apply update", updateApplying: "Preparing update…",
+ updateConfirmApply: "WebSpeak will be updated to v{{version}}. Export a backup first; the process restarts and this page disconnects briefly. Continue?",
+ updateBackupHint: "Export a backup above first. The console replaces application code only and never touches data/, config.json or certs/.",
+ updateChecksumMissing: "This release has no SHA256SUMS.txt; the update is refused.", updateAssetMissing: "This release has no package for the current platform and architecture.",
+ updateBlockedDocker: "An image cannot be replaced from inside the container. Keep the webspeak-data volume and run docker compose pull && docker compose up -d on the host. Never run docker compose down -v.",
+ updateBlockedSource: "Source installs have no bundled runtime, so the console cannot switch versions safely. Pull the source and rebuild (npm ci && npm run build && npm run web:build), or use a release package/Docker Compose.",
+ updateBlockedPlatform: "No official package exists for this platform; only version checks are available.", updateBlockedArch: "No official package exists for this architecture; only version checks are available.",
+ updateBlockedUnavailable: "Console updates are not enabled for this instance.", updateTaskTitle: "Update task",
+ updateStatusDownloading: "Downloading", updateStatusVerifying: "Verifying", updateStatusExtracting: "Extracting", updateStatusStaging: "Staging",
+ updateStatusRestarting: "Restarting", updateStatusSucceeded: "Update succeeded", updateStatusFailed: "Update failed",
+ updateRolledBack: "The previous version was restored.", updateRestartHint: "The process restarts after a successful update; refresh shortly if this page disconnects.",
+ updateReleaseNotes: "Release notes",
+ updateErrorChecksum: "The checksum is missing or does not match; the package was refused.", updateErrorArchive: "The package failed the safe-extraction checks.",
+ updateErrorDownload: "The official release asset could not be downloaded or saved.", updateErrorPackage: "The package does not match the selected stable release.",
+ updateErrorApply: "The update failed and the previous version was restored.", updateErrorInterrupted: "The update was interrupted before completion was confirmed.",
+ updateErrorInProgress: "Another update task is already running.", updateErrorGeneric: "The update could not be completed; check the logs.", updateStartedEvent: "Update started",
adminWsOverviewTitle: "WebSpeak management is ready", adminWsOverviewLead: "Manage instance access and the guest experience first. Configure an independent TS management connection when you need it.",
adminWsManageLead: "Access policy, site announcements, voice transport, the skin store and browser sessions.",
adminTsManageLead: "Server settings, channels, clients, server groups and bans. Separate Query credentials are required; ordinary voice connections do not need them.",
@@ -53,6 +95,27 @@ const de = {
adminBrowserSessions: "Browsersitzungen", adminBrowserSessionsLead: "Hier stehen nur Nutzer dieser WebSpeak-Instanz. Beenden trennt den jeweiligen Browser. Die vollständige TS-Mitgliederliste befindet sich in der TeamSpeak-Verwaltung.",
adminInviteScope: "Diese Einladungslinks werden von dieser WebSpeak-Instanz erstellt und verwaltet.",
adminLogsSection: "Verbindungen & Protokolle", adminMaintenanceSection: "Diagnose & Sicherungen",
+ updateTitle: "Versionsaktualisierung", updateLead: "Stabile Versionen aus den offiziellen GitHub Releases prüfen. Release-Pakete können hier geprüft und gewechselt werden; Docker- und Quellinstallationen zeigen nur Prüfergebnisse.",
+ updateCurrentVersion: "Aktuelle Version", updateDeploymentMode: "Bereitstellung", updateArchitecture: "Plattform & Architektur",
+ updateModeDocker: "Docker Compose", updateModeReleasePackage: "Release-Paket", updateModeSource: "Aus Quellen",
+ updateCanApply: "In dieser Konsole aktualisieren", updateCannotApply: "Diese Bereitstellung kann hier nicht aktualisiert werden",
+ updateCheckAction: "Stabile Versionen prüfen", updateChecking: "Wird geprüft…", updateUpToDate: "Keine stabile Version ist neuer als die laufende.",
+ updateSelectRelease: "Zielversion wählen", updateApplyAction: "Update anwenden", updateApplying: "Update wird vorbereitet…",
+ updateConfirmApply: "WebSpeak wird auf v{{version}} aktualisiert. Vorher eine Sicherung exportieren; der Prozess startet neu und die Seite trennt kurz. Fortfahren?",
+ updateBackupHint: "Zuerst oben eine Sicherung exportieren. Die Konsole ersetzt nur Anwendungscode und ändert data/, config.json oder certs/ nicht.",
+ updateChecksumMissing: "Diesem Release fehlt SHA256SUMS.txt; das Update wird abgelehnt.", updateAssetMissing: "Dieses Release hat kein Paket für Plattform und Architektur.",
+ updateBlockedDocker: "Ein Image kann nicht im Container ersetzt werden. Das Volume webspeak-data behalten und auf dem Host docker compose pull && docker compose up -d ausführen. Niemals docker compose down -v verwenden.",
+ updateBlockedSource: "Quellinstallationen haben keine mitgelieferte Laufzeit; die Konsole kann Versionen nicht sicher wechseln. Quellen aktualisieren und neu bauen (npm ci && npm run build && npm run web:build) oder Release-Paket/Docker Compose verwenden.",
+ updateBlockedPlatform: "Für diese Plattform gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.", updateBlockedArch: "Für diese Architektur gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.",
+ updateBlockedUnavailable: "Konsolen-Updates sind für diese Instanz nicht aktiviert.", updateTaskTitle: "Update-Aufgabe",
+ updateStatusDownloading: "Wird heruntergeladen", updateStatusVerifying: "Wird geprüft", updateStatusExtracting: "Wird entpackt", updateStatusStaging: "Wird bereitgestellt",
+ updateStatusRestarting: "Neustart", updateStatusSucceeded: "Update erfolgreich", updateStatusFailed: "Update fehlgeschlagen",
+ updateRolledBack: "Die vorherige Version wurde wiederhergestellt.", updateRestartHint: "Nach erfolgreichem Update startet der Prozess neu; die Seite bei Trennung später neu laden.",
+ updateReleaseNotes: "Release-Notizen",
+ updateErrorChecksum: "Prüfsumme fehlt oder stimmt nicht; das Paket wurde abgelehnt.", updateErrorArchive: "Das Paket hat die sichere Entpackprüfung nicht bestanden.",
+ updateErrorDownload: "Das offizielle Release-Artefakt konnte nicht geladen oder gespeichert werden.", updateErrorPackage: "Das Paket passt nicht zum gewählten stabilen Release.",
+ updateErrorApply: "Das Update ist fehlgeschlagen; die vorherige Version wurde wiederhergestellt.", updateErrorInterrupted: "Das Update wurde vor der Bestätigung unterbrochen.",
+ updateErrorInProgress: "Eine andere Update-Aufgabe läuft bereits.", updateErrorGeneric: "Das Update konnte nicht abgeschlossen werden; Protokolle prüfen.", updateStartedEvent: "Update gestartet",
adminWsOverviewTitle: "WebSpeak-Verwaltung ist bereit", adminWsOverviewLead: "Zuerst Instanzzugang und Gastoberfläche verwalten. Eine separate TS-Verbindung nur bei Bedarf einrichten.",
adminWsManageLead: "Zugriffsregeln, Website-Ankündigungen, Sprachtransport, Skin-Store und Browsersitzungen.",
adminTsManageLead: "Servereinstellungen, Kanäle, Mitglieder, Servergruppen und Sperren. Separate Query-Zugangsdaten sind nötig; normale Sprachverbindungen benötigen sie nicht.",
@@ -74,6 +137,27 @@ const ru = {
adminBrowserSessions: "Сеансы браузеров", adminBrowserSessionsLead: "Здесь только пользователи этого экземпляра WebSpeak. Завершение сеанса отключает соответствующий браузер. Полный список участников TS доступен в управлении TeamSpeak.",
adminInviteScope: "Эти ссылки-приглашения создаются и управляются текущим экземпляром WebSpeak.",
adminLogsSection: "Подключения и журналы", adminMaintenanceSection: "Диагностика и копии",
+ updateTitle: "Обновление версии", updateLead: "Проверка стабильных версий в официальных GitHub Releases. Установки из пакета могут проверить и сменить версию здесь; Docker и исходники показывают только результат проверки.",
+ updateCurrentVersion: "Текущая версия", updateDeploymentMode: "Развёртывание", updateArchitecture: "Платформа и архитектура",
+ updateModeDocker: "Docker Compose", updateModeReleasePackage: "Пакет релиза", updateModeSource: "Из исходников",
+ updateCanApply: "Можно обновить из консоли", updateCannotApply: "Это развёртывание нельзя обновить здесь",
+ updateCheckAction: "Проверить стабильные версии", updateChecking: "Проверка…", updateUpToDate: "Нет стабильной версии новее текущей.",
+ updateSelectRelease: "Выберите целевую версию", updateApplyAction: "Применить обновление", updateApplying: "Подготовка обновления…",
+ updateConfirmApply: "WebSpeak будет обновлён до v{{version}}. Сначала экспортируйте резервную копию; процесс перезапустится, страница кратко отключится. Продолжить?",
+ updateBackupHint: "Сначала используйте «Экспорт резервной копии» выше. Консоль заменяет только код приложения и не изменяет data/, config.json или certs/.",
+ updateChecksumMissing: "В релизе нет SHA256SUMS.txt; обновление отклонено.", updateAssetMissing: "В релизе нет пакета для текущей платформы и архитектуры.",
+ updateBlockedDocker: "Образ нельзя заменить изнутри контейнера. Сохраните том webspeak-data и выполните на хосте docker compose pull && docker compose up -d. Никогда не запускайте docker compose down -v.",
+ updateBlockedSource: "В установке из исходников нет встроенной среды выполнения, поэтому консоль не может безопасно сменить версию. Обновите исходники и пересоберите (npm ci && npm run build && npm run web:build) или используйте пакет релиза/Docker Compose.",
+ updateBlockedPlatform: "Для этой платформы нет официального пакета; доступна только проверка версий.", updateBlockedArch: "Для этой архитектуры нет официального пакета; доступна только проверка версий.",
+ updateBlockedUnavailable: "Обновление из консоли для этого экземпляра не включено.", updateTaskTitle: "Задача обновления",
+ updateStatusDownloading: "Скачивание", updateStatusVerifying: "Проверка", updateStatusExtracting: "Распаковка", updateStatusStaging: "Подготовка",
+ updateStatusRestarting: "Перезапуск", updateStatusSucceeded: "Обновление выполнено", updateStatusFailed: "Обновление не удалось",
+ updateRolledBack: "Предыдущая версия восстановлена.", updateRestartHint: "После успешного обновления процесс перезапустится; обновите страницу позже, если она отключилась.",
+ updateReleaseNotes: "Примечания к релизу",
+ updateErrorChecksum: "Контрольная сумма отсутствует или не совпадает; пакет отклонён.", updateErrorArchive: "Пакет не прошёл проверку безопасной распаковки.",
+ updateErrorDownload: "Не удалось скачать или сохранить официальный ресурс релиза.", updateErrorPackage: "Пакет не соответствует выбранному стабильному релизу.",
+ updateErrorApply: "Обновление не удалось; предыдущая версия восстановлена.", updateErrorInterrupted: "Обновление прервано до подтверждения завершения.",
+ updateErrorInProgress: "Другая задача обновления уже выполняется.", updateErrorGeneric: "Не удалось завершить обновление; проверьте журналы.", updateStartedEvent: "Обновление начато",
adminWsOverviewTitle: "Управление WebSpeak готово", adminWsOverviewLead: "Настройте доступ и гостевой интерфейс. Отдельное управление TS подключайте по мере необходимости.",
adminWsManageLead: "Политика доступа, объявления сайта, голосовой транспорт, магазин тем и сеансы браузеров.",
adminTsManageLead: "Настройки сервера, каналы, участники, серверные группы и блокировки. Нужны отдельные данные Query; для обычного голосового подключения они не требуются.",
@@ -95,6 +179,27 @@ const ja = {
adminBrowserSessions: "ブラウザーセッション", adminBrowserSessionsLead: "この WebSpeak 経由の利用者だけを表示します。終了すると該当のブラウザーが切断されます。TS の全メンバーは TeamSpeak サービス管理で確認できます。",
adminInviteScope: "この招待リンクは現在の WebSpeak インスタンスが発行・管理します。",
adminLogsSection: "接続とログ", adminMaintenanceSection: "診断とバックアップ",
+ updateTitle: "バージョン更新", updateLead: "公式 GitHub Releases の安定版を確認します。リリースパッケージではここで検証して切り替えられます。Docker とソース実行は確認結果のみ表示します。",
+ updateCurrentVersion: "現在のバージョン", updateDeploymentMode: "デプロイ", updateArchitecture: "プラットフォームとアーキテクチャ",
+ updateModeDocker: "Docker Compose", updateModeReleasePackage: "リリースパッケージ", updateModeSource: "ソース実行",
+ updateCanApply: "このコンソールから更新できます", updateCannotApply: "このデプロイではここから更新できません",
+ updateCheckAction: "安定版を確認", updateChecking: "確認中…", updateUpToDate: "現在より新しい安定版はありません。",
+ updateSelectRelease: "対象バージョンを選択", updateApplyAction: "更新を適用", updateApplying: "更新を準備中…",
+ updateConfirmApply: "WebSpeak を v{{version}} に更新します。先にバックアップを書き出してください。プロセスが再起動し、ページが一時的に切断されます。続行しますか?",
+ updateBackupHint: "先に上の「バックアップを書き出す」を使用してください。コンソールはプログラムコードのみを置き換え、data/、config.json、certs/ は変更しません。",
+ updateChecksumMissing: "このリリースには SHA256SUMS.txt がないため、更新を拒否しました。", updateAssetMissing: "このリリースには現在のプラットフォームとアーキテクチャ向けのパッケージがありません。",
+ updateBlockedDocker: "コンテナ内からイメージは置き換えられません。webspeak-data ボリュームを保持し、ホストで docker compose pull && docker compose up -d を実行してください。docker compose down -v は実行しないでください。",
+ updateBlockedSource: "ソース実行には同梱ランタイムがないため、安全にバージョンを切り替えられません。ソースを取得して再ビルドする(npm ci && npm run build && npm run web:build)か、リリースパッケージ/Docker Compose を使用してください。",
+ updateBlockedPlatform: "このプラットフォーム向けの公式パッケージがないため、バージョン確認のみ可能です。", updateBlockedArch: "このアーキテクチャ向けの公式パッケージがないため、バージョン確認のみ可能です。",
+ updateBlockedUnavailable: "このインスタンスではコンソール更新が有効になっていません。", updateTaskTitle: "更新タスク",
+ updateStatusDownloading: "ダウンロード中", updateStatusVerifying: "検証中", updateStatusExtracting: "展開中", updateStatusStaging: "ステージング中",
+ updateStatusRestarting: "再起動中", updateStatusSucceeded: "更新成功", updateStatusFailed: "更新失敗",
+ updateRolledBack: "以前のバージョンに戻しました。", updateRestartHint: "更新成功後にプロセスが再起動します。ページが切断された場合はしばらくしてから再読み込みしてください。",
+ updateReleaseNotes: "リリースノート",
+ updateErrorChecksum: "チェックサムがないか一致しないため、パッケージを拒否しました。", updateErrorArchive: "パッケージは安全な展開チェックに合格しませんでした。",
+ updateErrorDownload: "公式リリースの資産をダウンロードまたは保存できませんでした。", updateErrorPackage: "パッケージが選択した安定版と一致しません。",
+ updateErrorApply: "更新に失敗し、以前のバージョンに戻しました。", updateErrorInterrupted: "完了確認前に更新が中断されました。",
+ updateErrorInProgress: "別の更新タスクが実行中です。", updateErrorGeneric: "更新を完了できませんでした。ログを確認してください。", updateStartedEvent: "更新を開始",
adminWsOverviewTitle: "WebSpeak 管理を利用できます", adminWsOverviewLead: "まず接続方針と訪問者向け画面を管理します。必要な場合だけ、独立した TS 管理接続を設定します。",
adminWsManageLead: "アクセス方針、サイトのお知らせ、音声転送、スキンストア、ブラウザー接続。",
adminTsManageLead: "サーバー設定、チャンネル、メンバー、サーバーグループ、禁止リスト。専用 Query 認証情報が必要ですが、通常の音声接続には不要です。",
diff --git a/web/src/services/admin-api.ts b/web/src/services/admin-api.ts
index 868893a..c250740 100644
--- a/web/src/services/admin-api.ts
+++ b/web/src/services/admin-api.ts
@@ -1,6 +1,7 @@
import { adminResponses, type AdminResponseReader } from "../../../src/shared/admin-responses.js";
import type { AdminSettingsInput, ManagedInviteInput, TsAdminSettingsInput, TsAdminActionRequest } from "../../../src/shared/admin-inputs.js";
import type { SkinStoreInstallInput } from "../../../src/shared/skin-store.js";
+import type { UpdateApplyInput } from "../../../src/shared/update.js";
import { pluginResponses, type PluginPackage, type PluginSettingsInput } from "../../../src/shared/plugins.js";
export class AdminApiError extends Error {
@@ -128,6 +129,9 @@ export function createAdminApi(options: AdminApiOptions) {
createInvite: (body: ManagedInviteInput, signal?: AbortSignal) => request("/invites", adminResponses.createdInvite, "POST", body, true, signal),
revokeInvite: (id: string, signal?: AbortSignal) => request(`/invites/${encodeURIComponent(id)}/revoke`, adminResponses.ok, "POST", {}, true, signal),
diagnostics: (signal?: AbortSignal) => request("/diagnostics", adminResponses.diagnostics, "GET", undefined, true, signal),
+ updateStatus: (signal?: AbortSignal) => request("/update", adminResponses.updateStatus, "GET", undefined, true, signal),
+ checkUpdates: (signal?: AbortSignal) => request("/update/check", adminResponses.updateCheck, "POST", {}, true, signal),
+ applyUpdate: (body: UpdateApplyInput, signal?: AbortSignal) => request("/update/apply", adminResponses.updateApplied, "POST", body, true, signal),
logs: (signal?: AbortSignal) => request("/logs?limit=100", adminResponses.logs, "GET", undefined, true, signal),
audit: (signal?: AbortSignal) => request("/audit?limit=50", adminResponses.audit, "GET", undefined, true, signal),
skins: (signal?: AbortSignal) => request("/skins", adminResponses.skins, "GET", undefined, true, signal),
diff --git a/web/test/admin-view.test.mjs b/web/test/admin-view.test.mjs
index c3bb612..4094789 100644
--- a/web/test/admin-view.test.mjs
+++ b/web/test/admin-view.test.mjs
@@ -45,6 +45,7 @@ const defaults = path => ({
"/session": { authenticated: true, mustChangePassword: false, csrfToken: "test-csrf" },
"/server": settings(), "/overview": overview, "/sessions": { sessions: [] }, "/invites": { invites: [] },
"/diagnostics": { gateway: { version: "test", node: "test", platform: "test", arch: "test" }, database: { schemaVersion: 1 }, sessions: { created: 0 } },
+ "/update": { currentVersion: "test", deployment: { mode: "source", platform: "test", architecture: "test", applyAllowed: false, reasonCode: "DEPLOYMENT_SOURCE", upgradePath: "source" }, task: null },
"/logs?limit=100": { available: false, entries: [], sessions: [] }, "/audit?limit=50": { events: [] },
"/skins": { skins: [], defaultSkinId: "builtin.light" },
"/ts-admin/settings": tsSettings(), "/ts-admin/overview": tsOverview(),
@@ -453,6 +454,15 @@ test("store install submits the reviewed revision once and reloads the instance
});
function manifestForStoreTest() { return { id: "store-test", name: "Fixture", version: "1.0.0", author: "Fixture", license: "MIT", minAppVersion: "0.2.8", installedAt: 1 }; }
+test("all update maintenance copy is explicit in each supported language", async () => {
+ const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
+ const keys = Object.keys(adminOrganizationCopy.zh).filter(key => key.startsWith("update")).sort();
+ assert.ok(keys.length >= 30);
+ for (const language of ["zh", "en", "de", "ru", "ja"]) {
+ for (const key of keys) assert.ok(adminOrganizationCopy[language][key]?.trim(), `${language}.${key}`);
+ }
+});
+
test("all store translations are explicit in each supported language", async () => {
const { skinStoreCopy } = await vite.ssrLoadModule("/src/i18n/skin-store.ts");
const keys = Object.keys(skinStoreCopy.zh).sort();
From eb6c4ba85703eddebaba5664f0e8225c400b0cc7 Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Tue, 24 Nov 2026 02:06:26 +0800
Subject: [PATCH 2/5] fix: harden console self-update rollback and deployment
checks
Recovered after the original 04bd82e object was lost from the worktree history; the working tree still contained the same ten-file fix (249 insertions).
---
src/admin/admin-router.ts | 7 +--
src/admin/update-routes.test.ts | 25 ++++++++++
src/updater/code-swap.test.ts | 32 ++++++++++++-
src/updater/code-swap.ts | 17 ++++++-
src/updater/deployment.test.ts | 35 ++++++++++++--
src/updater/deployment.ts | 15 +++---
src/updater/update-service.test.ts | 74 ++++++++++++++++++++++++++++-
src/updater/update-service.ts | 49 +++++++++++++++++--
web/src/composables/useAdminI18n.ts | 3 +-
web/src/i18n/admin-organization.ts | 20 ++++++--
10 files changed, 249 insertions(+), 28 deletions(-)
diff --git a/src/admin/admin-router.ts b/src/admin/admin-router.ts
index 9dd24ba..c5a91dd 100644
--- a/src/admin/admin-router.ts
+++ b/src/admin/admin-router.ts
@@ -465,10 +465,11 @@ export function createAdminRouter(options: AdminRouterOptions): Router {
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 });
+ // Do not wait for the response to finish: a reverse proxy or a client
+ // that disconnects early must not leave the restart runner waiting for
+ // this process until its timeout expires.
+ setTimeout(() => options.restartAfterUpdate?.(), 250).unref();
} catch (error: unknown) {
sendUpdateError(response, error);
}
diff --git a/src/admin/update-routes.test.ts b/src/admin/update-routes.test.ts
index 8f411c5..90f273e 100644
--- a/src/admin/update-routes.test.ts
+++ b/src/admin/update-routes.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
import { mkdtempSync, rmSync } from "node:fs";
+import http from "node:http";
import { tmpdir } from "node:os";
import path from "node:path";
import express from "express";
@@ -152,6 +153,30 @@ test("a confirmed apply returns the task and stops the process after the respons
assert.equal(f.restarted(), true);
});
+test("a client that disconnects before the response still schedules the restart", async t => {
+ const f = await fixture(t);
+ const { cookie, csrf } = await f.login();
+ const body = JSON.stringify({ version: "0.4.0", confirmVersion: "0.4.0" });
+ const url = new URL(`${f.origin}/api/admin/update/apply`);
+ const request = http.request({
+ hostname: url.hostname, port: url.port, path: url.pathname, method: "POST",
+ headers: {
+ origin: f.origin, cookie, "x-csrf-token": csrf, "content-type": "application/json",
+ "content-length": Buffer.byteLength(body),
+ },
+ });
+ request.on("error", () => { /* Expected once the socket is destroyed. */ });
+ request.end(body);
+ const deadline = Date.now() + 2_000;
+ while (f.applyCalls.length === 0 && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20));
+ assert.deepEqual(f.applyCalls, [["0.4.0", "0.4.0"]]);
+ // Close the connection without consuming the response. The restart must not
+ // depend on the response finish event.
+ request.destroy();
+ await new Promise((resolve) => setTimeout(resolve, 700));
+ 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();
diff --git a/src/updater/code-swap.test.ts b/src/updater/code-swap.test.ts
index 301e5f9..f44224c 100644
--- a/src/updater/code-swap.test.ts
+++ b/src/updater/code-swap.test.ts
@@ -1,6 +1,6 @@
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 { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
@@ -84,6 +84,36 @@ test("code swap replaces only code and preserves data, config, certs, skins and
assert.equal(existsSync(path.join(backup, "config.json")), false);
});
+test("code swap copies across filesystems when rename reports EXDEV", t => {
+ const shared = "/dev/shm";
+ if (!existsSync(shared)) {
+ t.skip("no separate filesystem available for the EXDEV test");
+ return;
+ }
+ const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
+ const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-xdev-"));
+ t.after(() => rmSync(stagedBase, { recursive: true, force: true }));
+ const staged = path.join(stagedBase, "staged");
+
+ 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" }));
+ createPackageFiles(staged, "0.4.0", { "dist/index.js": "new code", "node_modules/new.txt": "new dependency" });
+ if (statSync(root).dev === statSync(staged).dev) {
+ t.skip("tmp and /dev/shm share a device on this system");
+ return;
+ }
+
+ 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");
+ // The copy fallback removes the source only after a successful copy.
+ assert.equal(existsSync(path.join(staged, "dist")), false);
+ assert.equal(existsSync(path.join(staged, "package.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 });
diff --git a/src/updater/code-swap.ts b/src/updater/code-swap.ts
index 62e1bb2..c99aa7a 100644
--- a/src/updater/code-swap.ts
+++ b/src/updater/code-swap.ts
@@ -1,4 +1,4 @@
-import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
+import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
import path from "node:path";
import { parseStableVersion } from "./version.js";
@@ -76,10 +76,23 @@ export function locatePackageRoot(extractedDir: string, version: string, platfor
return root;
}
+function moveEntry(from: string, to: string): void {
+ try {
+ renameSync(from, to);
+ } catch (error) {
+ // Staging and backups may live on another filesystem than the install
+ // directory. A rename cannot cross devices, so fall back to a copy that
+ // only removes the source once the copy has completed.
+ if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
+ cpSync(from, to, { recursive: true, force: false, errorOnExist: true, preserveTimestamps: true });
+ rmSync(from, { recursive: true, force: true });
+ }
+}
+
function moveIfPresent(from: string, to: string): void {
if (!existsSync(from)) return;
mkdirSync(path.dirname(to), { recursive: true });
- renameSync(from, to);
+ moveEntry(from, to);
}
/**
diff --git a/src/updater/deployment.test.ts b/src/updater/deployment.test.ts
index efd0cfa..4a00841 100644
--- a/src/updater/deployment.test.ts
+++ b/src/updater/deployment.test.ts
@@ -24,13 +24,38 @@ function releasePackageRoot(t: test.TestContext, platform: "linux" | "win32" = "
return root;
}
-test("deployment mode honours the explicit environment override", () => {
+test("an explicit release-package override cannot bypass container detection", () => {
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");
+ assert.equal(info.mode, "docker");
+ assert.equal(info.applyAllowed, false);
+ assert.equal(info.reasonCode, "DEPLOYMENT_DOCKER");
+ assert.equal(info.upgradePath, "docker-compose");
+});
+
+test("an explicit release-package override requires a complete package tree", t => {
+ const missing = detectDeployment({
+ rootDir: "/does/not/exist",
+ env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
+ isDocker: false,
+ platform: "linux",
+ architecture: "x64",
+ });
+ assert.equal(missing.mode, "source");
+ assert.equal(missing.applyAllowed, false);
+ assert.equal(missing.reasonCode, "DEPLOYMENT_SOURCE");
+
+ const root = releasePackageRoot(t);
+ const complete = detectDeployment({
+ rootDir: root,
+ env: { WEBSPEAK_DEPLOYMENT_MODE: "release-package" },
+ isDocker: false,
+ platform: "linux",
+ architecture: "x64",
+ });
+ assert.equal(complete.mode, "release-package");
+ assert.equal(complete.applyAllowed, true);
+ assert.equal(complete.reasonCode, null);
});
test("docker and source deployments never allow an in-console apply", () => {
diff --git a/src/updater/deployment.ts b/src/updater/deployment.ts
index 7d70891..5e982de 100644
--- a/src/updater/deployment.ts
+++ b/src/updater/deployment.ts
@@ -16,20 +16,23 @@ export interface DeploymentInfo extends UpdateDeploymentView {
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();
+ const packaged = isReleasePackageRoot(options.rootDir, platform);
let mode: UpdateDeploymentMode;
- if (explicit && (EXPLICIT_MODES as string[]).includes(explicit)) {
- mode = explicit as UpdateDeploymentMode;
- } else if (options.isDocker ?? runningInContainer(env)) {
+ // Container detection always wins: an explicit "release-package" override
+ // must never make an image replaceable from inside the container.
+ if (explicit === "docker" || (options.isDocker ?? runningInContainer(env))) {
mode = "docker";
+ } else if (explicit === "source") {
+ mode = "source";
} else {
- mode = isReleasePackageRoot(options.rootDir, platform) ? "release-package" : "source";
+ // An explicit "release-package" only counts when the tree really is a
+ // complete release package; otherwise applying would be unsafe.
+ mode = packaged ? "release-package" : "source";
}
const assetKind = mode === "release-package" ? assetKindFor(platform, architecture) : null;
let reasonCode: string | null = null;
diff --git a/src/updater/update-service.test.ts b/src/updater/update-service.test.ts
index 2722b26..96faf82 100644
--- a/src/updater/update-service.test.ts
+++ b/src/updater/update-service.test.ts
@@ -7,7 +7,7 @@ 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";
+import { readUpdateState, writeUpdateState } 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";
@@ -339,6 +339,78 @@ test("a concurrent lock leaves the running task state untouched", async t => {
assert.equal(service.getStatus().task, null);
});
+test("getStatus reports the task the restart runner persisted, not stale memory", async t => {
+ const archive = packageArchive("0.4.0");
+ const checksums = Buffer.from(checksumText(ASSET_NAME, archive));
+ const { service, dataDir } = createService(t, [{
+ version: "0.4.0",
+ assets: [
+ { name: ASSET_NAME, data: archive },
+ { name: CHECKSUM_ASSET_NAME, data: 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(service.getStatus().task?.status, "restarting");
+ // The runner rolls the task back in another process, after this one
+ // already returned the prepared task.
+ writeUpdateState(path.join(dataDir, "updates", "state.json"), {
+ schemaVersion: 1,
+ task: {
+ ...task, status: "failed", finishedAt: "2026-01-01T00:05:00.000Z", updatedAt: "2026-01-01T00:05:00.000Z",
+ errorCode: "UPDATE_HEALTH_CHECK_FAILED", errorMessage: "health check failed", rolledBack: true,
+ },
+ });
+ const status = service.getStatus();
+ assert.equal(status.task?.status, "failed");
+ assert.equal(status.task?.rolledBack, true);
+ assert.equal(status.task?.errorCode, "UPDATE_HEALTH_CHECK_FAILED");
+});
+
+test("initialization restores the previous code from an interrupted swap backup", t => {
+ const fixture = createService(t, [], new Map());
+ const taskId = "upd_interrupted_swap";
+ const statePath = path.join(fixture.dataDir, "updates", "state.json");
+ const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
+ const backupDir = path.join(fixture.dataDir, "updates", "backups", taskId);
+
+ // The process died after moving the previous code aside and only part of
+ // the new package had been moved in.
+ mkdirSync(path.join(backupDir, "dist"), { recursive: true });
+ writeFileSync(path.join(backupDir, "dist", "index.js"), "// old code\n");
+ writeFileSync(path.join(backupDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.3.2" }));
+ writeFileSync(path.join(fixture.rootDir, "dist", "index.js"), "// new code\n");
+ writeFileSync(path.join(fixture.rootDir, "package.json"), JSON.stringify({ name: "webspeak-webclient", version: "0.4.0" }));
+
+ writeUpdateState(statePath, {
+ schemaVersion: 1,
+ task: {
+ id: taskId, 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: [],
+ },
+ });
+ writeFileSync(lockPath, JSON.stringify({ pid: 0, taskId, createdAt: "2026-01-01T00:00:00.000Z" }));
+
+ const restarted = new UpdateService({
+ rootDir: fixture.rootDir, dataDir: fixture.dataDir, currentVersion: "0.4.0", logger,
+ platform: "linux", architecture: "x64", env: {}, isDocker: false, fetch: fakeFetch([], new Map()),
+ now: () => new Date("2026-01-01T00:10:00.000Z"),
+ });
+ restarted.initialize();
+
+ assert.equal(readFileSync(path.join(fixture.rootDir, "dist", "index.js"), "utf8"), "// old code\n");
+ assert.equal(JSON.parse(readFileSync(path.join(fixture.rootDir, "package.json"), "utf8")).version, "0.3.2");
+ const status = restarted.getStatus();
+ assert.equal(status.task?.status, "failed");
+ assert.equal(status.task?.rolledBack, true);
+ assert.equal(status.task?.errorCode, "UPDATE_INTERRUPTED");
+ assert.equal(existsSync(lockPath), false);
+});
+
test("initialization keeps a live task but reconciles it once its process is gone", async t => {
const fixture = createService(t, [], new Map());
const running = {
diff --git a/src/updater/update-service.ts b/src/updater/update-service.ts
index 6820f71..a1a90fd 100644
--- a/src/updater/update-service.ts
+++ b/src/updater/update-service.ts
@@ -9,7 +9,7 @@ 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 { CodeSwapError, locatePackageRoot, restoreCode } from "./code-swap.js";
import { detectDeployment, releaseAssetName, type DeploymentInfo } from "./deployment.js";
import {
assertOfficialDownloadUrl, CHECKSUM_ASSET_NAME, GitHubReleaseSource, ReleaseSourceError,
@@ -40,6 +40,8 @@ export type UpdateErrorCode =
| "UPDATE_ARCHIVE_LIMIT"
| "UPDATE_ARCHIVE_UNSUPPORTED"
| "UPDATE_PACKAGE_INVALID"
+ | "UPDATE_SWAP_FAILED"
+ | "UPDATE_ROLLBACK_FAILED"
| "UPDATE_RELEASE_UNAVAILABLE"
| "UPDATE_RUNNER_MISSING"
| "UPDATE_RUNNER_FAILED"
@@ -126,7 +128,8 @@ export class UpdateService {
// 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());
+ const recovered = task && isActiveTaskStatus(task.status) ? this.recoverInterruptedSwap(task) : null;
+ const changed = recovered !== null || reconcileInterruptedState(this.state, this.options.currentVersion, this.now().toISOString());
if (changed) writeUpdateState(this.statePath, this.state);
}
clearStaleUpdateLock(this.lockPath);
@@ -137,7 +140,45 @@ export class UpdateService {
}, "Update service initialized");
}
+ /**
+ * A crash during the swap leaves the previous code in the backup directory
+ * and possibly only partial new code in the install directory. Restore the
+ * previous code before reporting the task, rather than trusting a version
+ * whose files may be incomplete.
+ */
+ private recoverInterruptedSwap(task: NonNullable): boolean | null {
+ const backupDir = path.join(this.backupsDir, task.id);
+ if (!existsSync(backupDir)) return null;
+ const now = this.now().toISOString();
+ let restored = false;
+ try {
+ restoreCode(this.options.rootDir, backupDir);
+ restored = true;
+ } catch (error) {
+ this.options.logger.warn({
+ taskId: task.id,
+ err: error instanceof Error ? error.message : String(error),
+ }, "Interrupted update code could not be restored from backup");
+ }
+ task.status = "failed";
+ task.finishedAt = now;
+ task.updatedAt = now;
+ task.rolledBack = restored;
+ if (restored) {
+ task.errorCode = "UPDATE_INTERRUPTED";
+ task.errorMessage = "The process stopped during the update. The previous version was restored from the backup.";
+ } else {
+ task.errorCode = "UPDATE_ROLLBACK_FAILED";
+ task.errorMessage = "The process stopped during the update and the code could not be restored automatically. Restore the previous version from the backup.";
+ }
+ return true;
+ }
+
getStatus(): UpdateStatusView {
+ // The restart runner updates the persisted task after this process has
+ // already returned a response, so always report the on-disk state. Do not
+ // replace the in-memory state: an apply in progress still writes to it.
+ const state = readUpdateState(this.statePath);
return {
currentVersion: this.options.currentVersion,
deployment: {
@@ -148,7 +189,7 @@ export class UpdateService {
reasonCode: this.deployment.reasonCode,
upgradePath: this.deployment.upgradePath,
},
- task: this.state.task,
+ task: state.task,
};
}
@@ -486,6 +527,6 @@ function mapError(error: unknown): UpdateError {
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);
+ if (error instanceof CodeSwapError) return new UpdateError(error.code, error.message, 422);
return new UpdateError("UPDATE_FAILED", error instanceof Error ? error.message : "The update failed.", 500);
}
diff --git a/web/src/composables/useAdminI18n.ts b/web/src/composables/useAdminI18n.ts
index e02be08..ba9e90e 100644
--- a/web/src/composables/useAdminI18n.ts
+++ b/web/src/composables/useAdminI18n.ts
@@ -56,7 +56,8 @@ const errorLabels: Record = {
UPDATE_CHECKSUM_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_MISMATCH: "updateErrorChecksum", UPDATE_DIGEST_UNSUPPORTED: "updateErrorChecksum",
UPDATE_ARCHIVE_UNSAFE: "updateErrorArchive", UPDATE_ARCHIVE_INVALID: "updateErrorArchive", UPDATE_ARCHIVE_LIMIT: "updateErrorArchive", UPDATE_ARCHIVE_UNSUPPORTED: "updateErrorArchive",
UPDATE_PACKAGE_INVALID: "updateErrorPackage", UPDATE_DOWNLOAD_FAILED: "updateErrorDownload", UPDATE_DOWNLOAD_TOO_LARGE: "updateErrorDownload",
- UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorApply", UPDATE_INTERRUPTED: "updateErrorInterrupted",
+ UPDATE_FAILED: "updateErrorApply", UPDATE_ROLLBACK_FAILED: "updateErrorRollbackFailed", UPDATE_INTERRUPTED: "updateErrorInterrupted",
+ UPDATE_SWAP_FAILED: "updateErrorSwap",
UPDATE_HEALTH_CHECK_FAILED: "updateErrorApply", UPDATE_ROLLBACK_HEALTH_FAILED: "updateErrorGeneric",
UPDATE_RESTART_FAILED: "updateErrorGeneric", UPDATE_RESTART_TIMEOUT: "updateErrorGeneric", UPDATE_PLAN_INVALID: "updateErrorGeneric",
UPDATE_NOT_SUPPORTED: "updateErrorGeneric", UPDATE_RELEASE_UNAVAILABLE: "updateErrorGeneric", UPDATE_ASSET_UNAVAILABLE: "updateErrorGeneric",
diff --git a/web/src/i18n/admin-organization.ts b/web/src/i18n/admin-organization.ts
index aaeb167..c409394 100644
--- a/web/src/i18n/admin-organization.ts
+++ b/web/src/i18n/admin-organization.ts
@@ -29,7 +29,9 @@ const zh = {
updateReleaseNotes: "发行说明",
updateErrorChecksum: "校验和缺失或不匹配,已拒绝安装该发布包。", updateErrorArchive: "发布包未通过安全解包检查。",
updateErrorDownload: "无法从官方 Release 下载或保存资源。", updateErrorPackage: "发布包内容与所选正式版不匹配。",
- updateErrorApply: "更新失败,已恢复上一版本。", updateErrorInterrupted: "更新被中断,未确认完成。",
+ updateErrorApply: "更新失败,请查看日志。", updateErrorInterrupted: "更新被中断,未确认完成。",
+ updateErrorRollbackFailed: "更新失败且自动回滚也失败。请按备份手动恢复上一版本。",
+ updateErrorSwap: "替换程序文件失败,已尝试恢复上一版本;请查看日志。",
updateErrorInProgress: "已有更新任务正在进行。", updateErrorGeneric: "更新未能完成,请查看日志。", updateStartedEvent: "已开始更新",
adminWsOverviewTitle: "WebSpeak 管理服务已就绪", adminWsOverviewLead: "先管理实例接入与访客体验;需要管理 TS 服务时,再按需配置独立连接。",
adminWsManageLead: "接入策略、站点公告、语音传输、皮肤商店和浏览器会话。",
@@ -72,7 +74,9 @@ const en = {
updateReleaseNotes: "Release notes",
updateErrorChecksum: "The checksum is missing or does not match; the package was refused.", updateErrorArchive: "The package failed the safe-extraction checks.",
updateErrorDownload: "The official release asset could not be downloaded or saved.", updateErrorPackage: "The package does not match the selected stable release.",
- updateErrorApply: "The update failed and the previous version was restored.", updateErrorInterrupted: "The update was interrupted before completion was confirmed.",
+ updateErrorApply: "The update failed; check the logs.", updateErrorInterrupted: "The update was interrupted before completion was confirmed.",
+ updateErrorRollbackFailed: "The update failed and automatic rollback also failed. Restore the previous version manually from the backup.",
+ updateErrorSwap: "Replacing application files failed; the previous version was restored where possible. Check the logs.",
updateErrorInProgress: "Another update task is already running.", updateErrorGeneric: "The update could not be completed; check the logs.", updateStartedEvent: "Update started",
adminWsOverviewTitle: "WebSpeak management is ready", adminWsOverviewLead: "Manage instance access and the guest experience first. Configure an independent TS management connection when you need it.",
adminWsManageLead: "Access policy, site announcements, voice transport, the skin store and browser sessions.",
@@ -114,7 +118,9 @@ const de = {
updateReleaseNotes: "Release-Notizen",
updateErrorChecksum: "Prüfsumme fehlt oder stimmt nicht; das Paket wurde abgelehnt.", updateErrorArchive: "Das Paket hat die sichere Entpackprüfung nicht bestanden.",
updateErrorDownload: "Das offizielle Release-Artefakt konnte nicht geladen oder gespeichert werden.", updateErrorPackage: "Das Paket passt nicht zum gewählten stabilen Release.",
- updateErrorApply: "Das Update ist fehlgeschlagen; die vorherige Version wurde wiederhergestellt.", updateErrorInterrupted: "Das Update wurde vor der Bestätigung unterbrochen.",
+ updateErrorApply: "Das Update ist fehlgeschlagen; Protokolle prüfen.", updateErrorInterrupted: "Das Update wurde vor der Bestätigung unterbrochen.",
+ updateErrorRollbackFailed: "Das Update ist fehlgeschlagen und auch die automatische Wiederherstellung. Stellen Sie die vorherige Version manuell aus der Sicherung wieder her.",
+ updateErrorSwap: "Das Ersetzen der Anwendungsdateien ist fehlgeschlagen; die vorherige Version wurde nach Möglichkeit wiederhergestellt. Protokolle prüfen.",
updateErrorInProgress: "Eine andere Update-Aufgabe läuft bereits.", updateErrorGeneric: "Das Update konnte nicht abgeschlossen werden; Protokolle prüfen.", updateStartedEvent: "Update gestartet",
adminWsOverviewTitle: "WebSpeak-Verwaltung ist bereit", adminWsOverviewLead: "Zuerst Instanzzugang und Gastoberfläche verwalten. Eine separate TS-Verbindung nur bei Bedarf einrichten.",
adminWsManageLead: "Zugriffsregeln, Website-Ankündigungen, Sprachtransport, Skin-Store und Browsersitzungen.",
@@ -156,7 +162,9 @@ const ru = {
updateReleaseNotes: "Примечания к релизу",
updateErrorChecksum: "Контрольная сумма отсутствует или не совпадает; пакет отклонён.", updateErrorArchive: "Пакет не прошёл проверку безопасной распаковки.",
updateErrorDownload: "Не удалось скачать или сохранить официальный ресурс релиза.", updateErrorPackage: "Пакет не соответствует выбранному стабильному релизу.",
- updateErrorApply: "Обновление не удалось; предыдущая версия восстановлена.", updateErrorInterrupted: "Обновление прервано до подтверждения завершения.",
+ updateErrorApply: "Обновление не удалось; проверьте журналы.", updateErrorInterrupted: "Обновление прервано до подтверждения завершения.",
+ updateErrorRollbackFailed: "Обновление не удалось, и автоматический откат тоже не удался. Восстановите предыдущую версию вручную из резервной копии.",
+ updateErrorSwap: "Не удалось заменить файлы приложения; предыдущая версия восстановлена по возможности. Проверьте журналы.",
updateErrorInProgress: "Другая задача обновления уже выполняется.", updateErrorGeneric: "Не удалось завершить обновление; проверьте журналы.", updateStartedEvent: "Обновление начато",
adminWsOverviewTitle: "Управление WebSpeak готово", adminWsOverviewLead: "Настройте доступ и гостевой интерфейс. Отдельное управление TS подключайте по мере необходимости.",
adminWsManageLead: "Политика доступа, объявления сайта, голосовой транспорт, магазин тем и сеансы браузеров.",
@@ -198,7 +206,9 @@ const ja = {
updateReleaseNotes: "リリースノート",
updateErrorChecksum: "チェックサムがないか一致しないため、パッケージを拒否しました。", updateErrorArchive: "パッケージは安全な展開チェックに合格しませんでした。",
updateErrorDownload: "公式リリースの資産をダウンロードまたは保存できませんでした。", updateErrorPackage: "パッケージが選択した安定版と一致しません。",
- updateErrorApply: "更新に失敗し、以前のバージョンに戻しました。", updateErrorInterrupted: "完了確認前に更新が中断されました。",
+ updateErrorApply: "更新に失敗しました。ログを確認してください。", updateErrorInterrupted: "完了確認前に更新が中断されました。",
+ updateErrorRollbackFailed: "更新に失敗し、自動ロールバックも失敗しました。バックアップから以前のバージョンを手動で復元してください。",
+ updateErrorSwap: "アプリケーションのファイル置き換えに失敗しました。可能な範囲で以前のバージョンに戻しました。ログを確認してください。",
updateErrorInProgress: "別の更新タスクが実行中です。", updateErrorGeneric: "更新を完了できませんでした。ログを確認してください。", updateStartedEvent: "更新を開始",
adminWsOverviewTitle: "WebSpeak 管理を利用できます", adminWsOverviewLead: "まず接続方針と訪問者向け画面を管理します。必要な場合だけ、独立した TS 管理接続を設定します。",
adminWsManageLead: "アクセス方針、サイトのお知らせ、音声転送、スキンストア、ブラウザー接続。",
From 699e606da53c05e2a74ea15d4dd5b609d99a0ddf Mon Sep 17 00:00:00 2001
From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com>
Date: Tue, 24 Nov 2026 02:40:08 +0800
Subject: [PATCH 3/5] fix: harden console self-update for real release packages
- Copy the restart runner with every runtime import (restart-runner.js,
code-swap.js, version.js, update-state.js) and fail the apply when the
runner exits during the startup grace window instead of reporting a task
that never restarted.
- Accept official tar/zip relative symlinks that stay inside the extraction
root while still refusing absolute, drive-qualified, escaping and hard-link
entries.
- Have the restart runner take over the update lock for the same task, keep
live or unreadable locks, and copy EXDEV entries into a temporary name
before renaming so a partial copy cannot replace the previous tree.
- Disable console apply for Windows release packages with
WINDOWS_APPLY_UNVERIFIED while still reporting available versions.
- Clarify in zh/en docs and five-language console copy that SHA256SUMS.txt is
an integrity checksum, not a signature, and that verification targets the
official Linux x64 build-release.yml package.
- Add tests for the failing EXDEV copy, live/unreadable/dead locks, same-task
lock takeover, a real spawned runner compiled from source, and
initialization leaving another live process's task untouched.
---
docs/README.en.md | 2 +-
docs/README.zh-CN.md | 2 +-
src/updater/archive.test.ts | 51 ++++-
src/updater/archive.ts | 113 ++++++++++-
src/updater/code-swap.test.ts | 53 ++++-
src/updater/code-swap.ts | 109 +++++++++-
src/updater/deployment.test.ts | 26 +++
src/updater/deployment.ts | 9 +-
src/updater/restart-runner.ts | 24 ++-
src/updater/update-service.test.ts | 134 +++++++++++++
src/updater/update-service.ts | 74 +++++--
src/updater/update-state.test.ts | 63 +++++-
src/updater/update-state.ts | 201 ++++++++++++++++---
web/src/components/admin/AdminOperations.vue | 2 +
web/src/i18n/admin-organization.ts | 20 +-
15 files changed, 793 insertions(+), 90 deletions(-)
diff --git a/docs/README.en.md b/docs/README.en.md
index b286f21..a45c8cf 100644
--- a/docs/README.en.md
+++ b/docs/README.en.md
@@ -117,7 +117,7 @@ Do not run `docker compose down -v`; it removes the `webspeak-data` volume, incl
Download the matching `windows-x64.zip`, `linux-x64.tar.gz`, or `linux-arm64.tar.gz` from [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest). Extract it and run the included launcher. Packages include the Node.js runtime and production dependencies. Docker images support amd64/arm64.
-A release-package install can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Docker and source deployments cannot apply an update from the console.
+Linux x64 release packages that match the official `build-release.yml` layout can be upgraded from the administration console. It checks the official GitHub Releases, refuses a package without a matching `SHA256SUMS.txt` entry, replaces only application code and restarts the process. `SHA256SUMS.txt` is an integrity checksum only, not a digital signature. `data/`, `config.json`, `certs/`, installed skins and plugins are preserved. Export a backup before starting. Windows release packages can check for versions, but console apply is disabled until it is verified on a real Windows install; download the new package and replace it manually. Linux arm64 shares the same code path as x64 but has not been exercised in this environment. Docker and source deployments cannot apply an update from the console.
Android APKs for `arm64-v8a`, `armeabi-v7a`, and `x86_64` are also attached. They use debug signing for sideload testing; they are not Google Play packages, and real-device voice still needs validation.
diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md
index a1a4a1b..fbcdec6 100644
--- a/docs/README.zh-CN.md
+++ b/docs/README.zh-CN.md
@@ -134,7 +134,7 @@ docker compose up -d
从 [GitHub Releases](https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/latest) 下载与系统和架构匹配的 `windows-x64.zip`、`linux-x64.tar.gz` 或 `linux-arm64.tar.gz`,解压后运行对应启动脚本。发布包自带 Node.js 运行时和生产依赖。Docker 镜像支持 amd64/arm64。
-发布包安装可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Docker 和源码运行不能在控制台应用更新。
+Linux x64 发布包(已按官方 `build-release.yml` 产物形态验证)可以在管理控制台直接升级:控制台只读取官方 GitHub Releases,缺少匹配的 `SHA256SUMS.txt` 条目时拒绝安装,校验通过后仅替换程序代码并重启进程。`SHA256SUMS.txt` 只是 SHA-256 校验和,不是数字签名。`data/`、`config.json`、`certs/`、已安装的皮肤和插件都会保留。开始前建议先导出备份。Windows 发布包可以检查版本,但控制台应用更新尚未经真实 Windows 环境验证,因此已禁用,请下载新包后手动替换。Linux arm64 与 x64 使用同一代码路径,但未在本环境实测。Docker 和源码运行不能在控制台应用更新。
Release 同时提供 Android `arm64-v8a`、`armeabi-v7a` 和 `x86_64` APK。它们使用 debug 签名,可手动侧载测试;不是 Google Play 发布包,Android 真机语音仍需验收。
diff --git a/src/updater/archive.test.ts b/src/updater/archive.test.ts
index fcb270f..0c9d950 100644
--- a/src/updater/archive.test.ts
+++ b/src/updater/archive.test.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { ArchiveError, extractReleaseArchive } from "./archive.js";
@@ -58,13 +58,48 @@ test("zip entries that traverse or use absolute paths are rejected before writin
}
});
-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("official relative .bin symlinks are accepted and resolve inside the package", async t => {
+ const { archive, destination } = fixture(t, "release.tar.gz", createTarGz([
+ { name: "webspeak/", type: "directory" },
+ { name: "webspeak/node_modules/nanoid/bin/nanoid.cjs", data: "#!/usr/bin/env node\nconsole.log('nanoid');\n", mode: 0o755 },
+ { name: "webspeak/node_modules/.bin/nanoid", type: "symlink", linkname: "../nanoid/bin/nanoid.cjs" },
+ ]));
+ await extractReleaseArchive(archive, destination, "release.tar.gz");
+ const link = path.join(destination, "webspeak/node_modules/.bin/nanoid");
+ assert.equal(lstatSync(link).isSymbolicLink(), true);
+ assert.equal(readlinkSync(link), "../nanoid/bin/nanoid.cjs");
+ assert.equal(readFileSync(link, "utf8"), "#!/usr/bin/env node\nconsole.log('nanoid');\n");
+});
+
+test("zip relative symlinks are accepted while absolute targets are refused", async t => {
+ const accepted = fixture(t, "release.zip", createZip([
+ { name: "webspeak/real.txt", data: "payload" },
+ { name: "webspeak/link.txt", data: "real.txt", mode: 0o120777 },
+ ]));
+ await extractReleaseArchive(accepted.archive, accepted.destination, "release.zip");
+ const link = path.join(accepted.destination, "webspeak/link.txt");
+ assert.equal(lstatSync(link).isSymbolicLink(), true);
+ assert.equal(readlinkSync(link), "real.txt");
+ assert.equal(readFileSync(link, "utf8"), "payload");
+
+ const refused = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
+ await assert.rejects(extractReleaseArchive(refused.archive, refused.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
+});
+
+test("absolute, escaping, empty and hard-link entries are refused", async t => {
+ const absoluteTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "/etc/passwd" }]));
+ await assert.rejects(extractReleaseArchive(absoluteTar.archive, absoluteTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
+ const driveTar = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname: "C:\\Windows\\system32" }]));
+ await assert.rejects(extractReleaseArchive(driveTar.archive, driveTar.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
+ const hardlink = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "hardlink", linkname: "target" }]));
+ await assert.rejects(extractReleaseArchive(hardlink.archive, hardlink.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
+ for (const linkname of ["", "..", "../outside", "a/../../../outside", "\\etc\\passwd"]) {
+ const escaping = fixture(t, "release.tar.gz", createTarGz([{ name: "link", type: "symlink", linkname }]));
+ await assert.rejects(extractReleaseArchive(escaping.archive, escaping.destination, "release.tar.gz"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
+ assert.equal(existsSync(path.join(escaping.directory, "outside")), false);
+ }
+ const zipAbsolute = fixture(t, "release.zip", createZip([{ name: "link", data: "/etc/passwd", mode: 0o120777 }]));
+ await assert.rejects(extractReleaseArchive(zipAbsolute.archive, zipAbsolute.destination, "release.zip"), rejectsWith("UPDATE_ARCHIVE_UNSAFE"));
});
test("unsupported archive formats and malformed archives are rejected", async t => {
diff --git a/src/updater/archive.ts b/src/updater/archive.ts
index 57f66b7..497a745 100644
--- a/src/updater/archive.ts
+++ b/src/updater/archive.ts
@@ -1,5 +1,5 @@
import { createReadStream, createWriteStream, type Stats } from "node:fs";
-import { chmod, mkdir, open, stat, writeFile } from "node:fs/promises";
+import { chmod, mkdir, open, stat, symlink, writeFile, type FileHandle } from "node:fs/promises";
import path from "node:path";
import { once } from "node:events";
import { createGunzip, createInflateRaw } from "node:zlib";
@@ -80,6 +80,47 @@ function resolveEntry(destination: string, relative: string): string {
return target;
}
+const SYMLINK_ROOT = "/__webspeak_extract_root__";
+
+/**
+ * Official release packages use relative links inside node_modules/.bin
+ * (for example `nanoid -> ../nanoid/bin/nanoid.cjs`). A link is accepted only
+ * when its target is relative and, after lexical normalization, still points
+ * strictly inside the extraction root. Absolute paths, drive letters, parent
+ * traversal, empty targets and links that resolve to the root itself are
+ * rejected before anything is created.
+ */
+export function safeSymlinkTarget(entryRelative: string, rawTarget: string): string {
+ if (!rawTarget) unsafe("Archive symbolic link has an empty target.");
+ if (rawTarget.includes("\0")) unsafe("Archive symbolic link target is invalid.");
+ const normalized = rawTarget.replaceAll("\\", "/");
+ if (normalized.startsWith("/")) unsafe("Archive symbolic link uses an absolute target.");
+ if (/^[A-Za-z]:/.test(normalized)) unsafe("Archive symbolic link target is drive-qualified.");
+ const entryDirectory = path.posix.dirname(entryRelative);
+ const resolved = path.posix.resolve(SYMLINK_ROOT, entryDirectory === "." ? "" : entryDirectory, normalized);
+ if (!resolved.startsWith(`${SYMLINK_ROOT}/`)) {
+ unsafe("Archive symbolic link escapes the extraction directory.");
+ }
+ return normalized;
+}
+
+async function createSymlink(destination: string, relative: string, linkTarget: string): Promise {
+ const root = path.resolve(destination);
+ const target = resolveEntry(destination, relative);
+ // Second boundary check against the real destination, not only the
+ // archive-relative form. The link is never dereferenced while validating.
+ const lexicallyResolved = path.resolve(destination, path.posix.dirname(relative), linkTarget);
+ if (lexicallyResolved === root || !lexicallyResolved.startsWith(root + path.sep)) {
+ unsafe("Archive symbolic link escapes the extraction directory.");
+ }
+ try {
+ await symlink(linkTarget, target);
+ } catch (error) {
+ if (error instanceof ArchiveError) throw error;
+ throw new ArchiveError("UPDATE_ARCHIVE_INVALID", `Archive symbolic link ${relative} could not be created.`);
+ }
+}
+
function isZeroBlock(buffer: Buffer): boolean {
for (const byte of buffer) if (byte !== 0) return false;
return true;
@@ -205,13 +246,12 @@ async function extractTarGz(file: string, destination: string, limits: ExtractLi
continue;
}
const entryName = pax.path ?? longName ?? name;
+ const linkName = pax.linkpath ?? readCString(header.subarray(157, 257));
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") {
+ if (type === "1") unsafe(`Archive entry ${entryName} is a hard link; hard links are not accepted.`);
+ if (type !== "0" && type !== "2" && type !== "7" && type !== "5") {
throw new ArchiveError("UPDATE_ARCHIVE_UNSUPPORTED", `Archive entry ${entryName} has unsupported type ${type}.`);
}
entries++;
@@ -225,6 +265,14 @@ async function extractTarGz(file: string, destination: string, limits: ExtractLi
await reader.skip(padded);
continue;
}
+ if (type === "2") {
+ if (size !== 0) invalid(`Archive symbolic link ${entryName} has unexpected content.`);
+ const linkTarget = safeSymlinkTarget(relative, linkName);
+ await mkdir(path.dirname(target), { recursive: true });
+ await createSymlink(destination, relative, linkTarget);
+ await reader.skip(padded);
+ continue;
+ }
await mkdir(path.dirname(target), { recursive: true });
const stream = createWriteStream(target, { mode: mode || 0o644, flags: "wx" });
try {
@@ -253,12 +301,47 @@ interface ZipEntry {
localOffset: number;
mode: number;
directory: boolean;
+ symlink: boolean;
}
const EOCD_SIGNATURE = 0x06054b50;
const CENTRAL_SIGNATURE = 0x02014b50;
const LOCAL_SIGNATURE = 0x04034b50;
+async function readZipEntryBuffer(
+ handle: FileHandle,
+ entry: ZipEntry,
+ file: string,
+ archiveSize: number,
+ limit: number,
+): Promise {
+ 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 > archiveSize) invalid(`ZIP entry ${entry.name} is truncated.`);
+ if (entry.compressedSize === 0) return Buffer.alloc(0);
+ const chunks: Buffer[] = [];
+ let total = 0;
+ const collector = new StreamTransform({
+ transform(chunk: Buffer, _encoding, callback) {
+ total += chunk.length;
+ if (total > limit) {
+ callback(new ArchiveError("UPDATE_ARCHIVE_UNSAFE", `ZIP symbolic link ${entry.name} has an oversized target.`));
+ return;
+ }
+ chunks.push(chunk);
+ callback();
+ },
+ });
+ const source = createReadStream(file, { start: dataStart, end: dataStart + entry.compressedSize - 1 });
+ if (entry.method === 8) await pipeline(source, createInflateRaw(), collector);
+ else await pipeline(source, collector);
+ return Buffer.concat(chunks);
+}
+
async function extractZip(file: string, destination: string, limits: ExtractLimits): Promise {
const handle = await open(file, "r");
try {
@@ -313,15 +396,21 @@ async function extractZip(file: string, destination: string, limits: ExtractLimi
}
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) {
+ if (fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000 && fileType !== 0o120000) {
unsafe(`ZIP entry ${name} has an unsupported file type.`);
}
- const directoryEntry = name.endsWith("/") || fileType === 0o040000;
+ const symlinkEntry = fileType === 0o120000;
+ if (symlinkEntry && uncompressedSize > 64 * 1024) {
+ unsafe(`ZIP symbolic link ${name} has an oversized target.`);
+ }
+ const directoryEntry = !symlinkEntry && (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 });
+ entries.push({
+ name, flags, method, compressedSize, uncompressedSize, localOffset,
+ mode: unixMode & 0o777, directory: directoryEntry, symlink: symlinkEntry,
+ });
}
for (const entry of entries) {
const relative = safeArchivePath(entry.name);
@@ -332,6 +421,12 @@ async function extractZip(file: string, destination: string, limits: ExtractLimi
continue;
}
await mkdir(path.dirname(target), { recursive: true });
+ if (entry.symlink) {
+ const rawTarget = (await readZipEntryBuffer(handle, entry, file, info.size, 64 * 1024)).toString("utf8");
+ const linkTarget = safeSymlinkTarget(relative, rawTarget);
+ await createSymlink(destination, relative, linkTarget);
+ continue;
+ }
if (entry.compressedSize === 0) {
await writeFile(target, Buffer.alloc(0), { mode: entry.mode || 0o644, flag: "wx" });
continue;
diff --git a/src/updater/code-swap.test.ts b/src/updater/code-swap.test.ts
index f44224c..a613f5f 100644
--- a/src/updater/code-swap.test.ts
+++ b/src/updater/code-swap.test.ts
@@ -1,10 +1,10 @@
import assert from "node:assert/strict";
import test, { type TestContext } from "node:test";
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import {
- CodeSwapError, locatePackageRoot, restoreCode, swapCode, validateStagedPackage,
+ CodeSwapError, locatePackageRoot, restoreCode, setCodeSwapCopyForTests, swapCode, validateStagedPackage,
} from "./code-swap.js";
import { createPackageFiles } from "./test-support.js";
@@ -114,6 +114,55 @@ test("code swap copies across filesystems when rename reports EXDEV", t => {
assert.equal(existsSync(path.join(staged, "package.json")), false);
});
+test("a cross-device copy that fails halfway leaves the complete previous tree in place", t => {
+ const shared = "/dev/shm";
+ if (!existsSync(shared)) {
+ t.skip("no separate filesystem available for the EXDEV test");
+ return;
+ }
+ const root = path.join(workspace(t), "root"), backup = path.join(workspace(t), "backup");
+ const stagedBase = mkdtempSync(path.join(shared, "webspeak-swap-fail-"));
+ t.after(() => {
+ setCodeSwapCopyForTests(null);
+ rmSync(stagedBase, { recursive: true, force: true });
+ });
+ const staged = path.join(stagedBase, "staged");
+
+ 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" });
+ if (statSync(root).dev === statSync(staged).dev) {
+ t.skip("tmp and /dev/shm share a device on this system");
+ return;
+ }
+
+ let copies = 0;
+ setCodeSwapCopyForTests((_from, to) => {
+ copies += 1;
+ // Simulate the fallback copy dying after it has written part of the
+ // entry, which is exactly the state that must never reach the root.
+ mkdirSync(to, { recursive: true });
+ writeFileSync(path.join(to, "index.js"), "half");
+ throw new Error("simulated copy failure");
+ });
+
+ assert.throws(() => swapCode(root, staged, backup), (error: unknown) =>
+ error instanceof CodeSwapError && error.code === "UPDATE_SWAP_FAILED");
+ assert.equal(copies, 1);
+
+ // The previous tree was restored completely, with no half-copied entry.
+ 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(root, "data", "webspeak.db"), "utf8"), "data-content");
+ assert.deepEqual(readdirSync(root).filter((entry) => entry.includes(".copy-")), []);
+ // The backup was not turned into a half-copied source for a later restore.
+ assert.equal(existsSync(path.join(backup, "dist", "index.js")), false);
+ // A failed copy leaves the staged package untouched for diagnosis/retry.
+ assert.equal(readFileSync(path.join(staged, "dist", "index.js"), "utf8"), "new code");
+});
+
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 });
diff --git a/src/updater/code-swap.ts b/src/updater/code-swap.ts
index c99aa7a..a4870fc 100644
--- a/src/updater/code-swap.ts
+++ b/src/updater/code-swap.ts
@@ -1,4 +1,5 @@
-import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync } from "node:fs";
+import { randomBytes } from "node:crypto";
+import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { parseStableVersion } from "./version.js";
@@ -79,14 +80,38 @@ export function locatePackageRoot(extractedDir: string, version: string, platfor
function moveEntry(from: string, to: string): void {
try {
renameSync(from, to);
+ return;
} catch (error) {
// Staging and backups may live on another filesystem than the install
- // directory. A rename cannot cross devices, so fall back to a copy that
- // only removes the source once the copy has completed.
+ // directory. A rename cannot cross devices, so fall back to a copy.
if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
- cpSync(from, to, { recursive: true, force: false, errorOnExist: true, preserveTimestamps: true });
- rmSync(from, { recursive: true, force: true });
}
+ // Copy into a temporary sibling first: a failure halfway through must
+ // never leave a partial entry at `to`, because rollback would otherwise
+ // mistake it for the complete previous version.
+ const temporary = `${to}.copy-${process.pid}-${randomBytes(6).toString("hex")}`;
+ try {
+ copyEntry(from, temporary);
+ renameSync(temporary, to);
+ } catch (error) {
+ rmSync(temporary, { recursive: true, force: true });
+ throw error;
+ }
+ // The copy is committed at `to`. Removing the source is cleanup only.
+ try { rmSync(from, { recursive: true, force: true }); } catch { /* Source remains for later cleanup. */ }
+}
+
+type CopyEntry = (from: string, to: string) => void;
+
+const defaultCopyEntry: CopyEntry = (from, to) => {
+ cpSync(from, to, { recursive: true, force: false, errorOnExist: true, preserveTimestamps: true });
+};
+
+let copyEntry: CopyEntry = defaultCopyEntry;
+
+/** Test seam for exercising a cross-device copy that fails halfway through. */
+export function setCodeSwapCopyForTests(copy: CopyEntry | null): void {
+ copyEntry = copy ?? defaultCopyEntry;
}
function moveIfPresent(from: string, to: string): void {
@@ -95,18 +120,76 @@ function moveIfPresent(from: string, to: string): void {
moveEntry(from, to);
}
+/**
+ * Backups written by this version contain only atomically moved entries.
+ * The manifest records which entries were moved completely, so a backup that
+ * was partially written by an older implementation (or tampered with) can be
+ * rejected instead of overwriting an intact install tree.
+ */
+const SWAP_MANIFEST = ".webspeak-swap.json";
+
+function writeSwapManifest(backupDir: string, entries: string[]): void {
+ const target = path.join(backupDir, SWAP_MANIFEST);
+ const temporary = `${target}.${process.pid}.tmp`;
+ writeFileSync(temporary, JSON.stringify({ schemaVersion: 1, entries }, null, 2), "utf8");
+ renameSync(temporary, target);
+}
+
+function readSwapManifest(backupDir: string): Set | null {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(path.join(backupDir, SWAP_MANIFEST), "utf8"));
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const record = parsed as Record;
+ if (record.schemaVersion !== 1 || !Array.isArray(record.entries)) return null;
+ return new Set(record.entries.filter((entry): entry is string => typeof entry === "string"));
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Undo only the entries that this swap actually moved. The entry whose move
+ * failed is left untouched: its source is still intact and no partial
+ * destination exists.
+ */
+function restoreMovedEntries(rootDir: string, backupDir: string, movedToBackup: string[], movedToRoot: string[]): void {
+ const rejected = path.join(backupDir, "rejected");
+ for (const entry of [...movedToRoot].reverse()) {
+ moveIfPresent(path.join(rootDir, entry), path.join(rejected, entry));
+ }
+ for (const entry of [...movedToBackup].reverse()) {
+ const saved = path.join(backupDir, entry);
+ if (!existsSync(saved)) continue;
+ const current = path.join(rootDir, entry);
+ if (existsSync(current)) moveIfPresent(current, path.join(rejected, entry));
+ moveIfPresent(saved, current);
+ }
+}
+
/**
* 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 {
+ const movedToBackup: string[] = [];
+ const movedToRoot: string[] = [];
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));
+ writeSwapManifest(backupDir, []);
+ for (const entry of CODE_ENTRIES) {
+ if (!existsSync(path.join(rootDir, entry))) continue;
+ moveIfPresent(path.join(rootDir, entry), path.join(backupDir, entry));
+ movedToBackup.push(entry);
+ writeSwapManifest(backupDir, movedToBackup);
+ }
+ for (const entry of CODE_ENTRIES) {
+ if (!existsSync(path.join(stagedRoot, entry))) continue;
+ moveIfPresent(path.join(stagedRoot, entry), path.join(rootDir, entry));
+ movedToRoot.push(entry);
+ }
} catch (error) {
- try { restoreCode(rootDir, backupDir); }
+ try { restoreMovedEntries(rootDir, backupDir, movedToBackup, movedToRoot); }
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.");
@@ -115,19 +198,25 @@ export function swapCode(rootDir: string, stagedRoot: string, backupDir: string)
/**
* Restore the previous code. New code is moved aside instead of deleted so it
- * remains available for diagnostics.
+ * remains available for diagnostics. When a swap manifest exists, only
+ * entries it proves were moved completely are considered.
*/
export function restoreCode(rootDir: string, backupDir: string): void {
if (!existsSync(backupDir)) throw new CodeSwapError("UPDATE_ROLLBACK_FAILED", "Code backup directory is missing.");
+ const manifest = readSwapManifest(backupDir);
const rejected = path.join(backupDir, "rejected");
try {
for (const entry of CODE_ENTRIES) {
+ if (manifest && !manifest.has(entry)) continue;
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));
+ for (const entry of CODE_ENTRIES) {
+ if (manifest && !manifest.has(entry)) continue;
+ 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.");
}
diff --git a/src/updater/deployment.test.ts b/src/updater/deployment.test.ts
index 4a00841..d5e417c 100644
--- a/src/updater/deployment.test.ts
+++ b/src/updater/deployment.test.ts
@@ -103,6 +103,32 @@ test("asset names and platform support are pinned to official release shapes", (
assert.equal(upgradePathFor("source"), "source");
});
+test("windows release packages are visible but apply stays disabled", t => {
+ const root = releasePackageRoot(t, "win32");
+ const windows = detectDeployment({
+ rootDir: root,
+ env: {},
+ isDocker: false,
+ platform: "win32",
+ architecture: "x64",
+ });
+ assert.equal(windows.mode, "release-package");
+ assert.equal(windows.assetKind, "windows-x64");
+ assert.equal(windows.applyAllowed, false);
+ assert.equal(windows.reasonCode, "WINDOWS_APPLY_UNVERIFIED");
+ assert.equal(windows.upgradePath, "release-package");
+
+ const linux = detectDeployment({
+ rootDir: releasePackageRoot(t),
+ env: {},
+ isDocker: false,
+ platform: "linux",
+ architecture: "x64",
+ });
+ assert.equal(linux.applyAllowed, true);
+ assert.equal(linux.reasonCode, null);
+});
+
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" });
diff --git a/src/updater/deployment.ts b/src/updater/deployment.ts
index 5e982de..4497cc5 100644
--- a/src/updater/deployment.ts
+++ b/src/updater/deployment.ts
@@ -35,15 +35,22 @@ export function detectDeployment(options: DeploymentDetectionOptions): Deploymen
mode = packaged ? "release-package" : "source";
}
const assetKind = mode === "release-package" ? assetKindFor(platform, architecture) : null;
+ let applyAllowed = mode === "release-package" && assetKind !== 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";
+ else if (platform === "win32") {
+ // The copy-node.exe-then-swap approach has not been verified against a
+ // real Windows release package. Report versions, but never fake an apply.
+ applyAllowed = false;
+ reasonCode = "WINDOWS_APPLY_UNVERIFIED";
+ }
return {
mode,
platform,
architecture,
- applyAllowed: mode === "release-package" && assetKind !== null,
+ applyAllowed,
reasonCode,
upgradePath: upgradePathFor(mode),
assetKind,
diff --git a/src/updater/restart-runner.ts b/src/updater/restart-runner.ts
index 068e762..d42e905 100644
--- a/src/updater/restart-runner.ts
+++ b/src/updater/restart-runner.ts
@@ -5,6 +5,7 @@ import https from "node:https";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { CodeSwapError, restoreCode, swapCode } from "./code-swap.js";
+import { takeOverUpdateLock } from "./update-state.js";
import type { PersistedUpdateState } from "./update-state.js";
import type { UpdateTaskView } from "../shared/update.js";
@@ -267,13 +268,6 @@ async function stopApp(child: ChildProcess | undefined): Promise {
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 {
const plan = readPlan(planPath);
const state = new StateWriter(plan);
@@ -281,7 +275,16 @@ export async function runRestartPlan(planPath: string): Promise {
let newApp: ChildProcess | undefined;
state.status("restarting");
state.step("restart", "running");
+ // Take over the update lock before doing anything else. The parent process
+ // is about to exit and its lock would otherwise have a dead pid, letting a
+ // second instance starting in this window roll the healthy code back.
+ let releaseLock: (() => void) | null = null;
try {
+ try {
+ releaseLock = takeOverUpdateLock(plan.lockPath, plan.taskId);
+ } catch (error) {
+ throw new RunnerError("UPDATE_LOCK_FAILED", error instanceof Error ? error.message : "The update lock could not be taken over.");
+ }
await waitForParent(plan.waitForPid, plan.parentTimeoutMs);
state.step("swap", "running");
swapCode(plan.rootDir, plan.stagedRoot, plan.backupDir);
@@ -295,7 +298,8 @@ export async function runRestartPlan(planPath: string): Promise {
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);
+ releaseLock();
+ releaseLock = null;
try { rmSync(plan.stagedRoot, { recursive: true, force: true }); } catch { /* Best effort. */ }
return 0;
} catch (error) {
@@ -316,7 +320,7 @@ export async function runRestartPlan(planPath: string): Promise {
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);
+ releaseLock?.();
return 1;
}
}
@@ -327,7 +331,7 @@ export async function runRestartPlan(planPath: string): Promise {
} else {
state.status("failed", { code, message });
}
- removeLock(plan);
+ releaseLock?.();
return 1;
}
}
diff --git a/src/updater/update-service.test.ts b/src/updater/update-service.test.ts
index 96faf82..6fec5d6 100644
--- a/src/updater/update-service.test.ts
+++ b/src/updater/update-service.test.ts
@@ -1,8 +1,11 @@
import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
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 { fileURLToPath } from "node:url";
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";
@@ -439,3 +442,134 @@ test("initialization keeps a live task but reconciles it once its process is gon
assert.equal(restarted.getStatus().task?.status, "failed");
assert.equal(restarted.getStatus().task?.errorCode, "UPDATE_INTERRUPTED");
});
+
+test("initialization does not roll back a task whose lock belongs to another live process", async t => {
+ const fixture = createService(t, [], new Map());
+ const taskId = "upd_other_process";
+ const statePath = path.join(fixture.dataDir, "updates", "state.json");
+ const lockPath = path.join(fixture.dataDir, "updates", "update.lock");
+ const owner = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
+ t.after(() => { try { owner.kill("SIGKILL"); } catch { /* Already gone. */ } });
+ await once(owner, "spawn");
+ assert.ok(owner.pid);
+
+ writeUpdateState(statePath, {
+ schemaVersion: 1,
+ task: {
+ id: taskId, 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: [],
+ },
+ });
+ writeFileSync(lockPath, JSON.stringify({ pid: owner.pid, taskId, 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:10:00.000Z"),
+ });
+ restarted.initialize();
+
+ const status = restarted.getStatus();
+ assert.equal(status.task?.status, "restarting");
+ assert.equal(status.task?.errorCode, null);
+ assert.equal(status.task?.rolledBack, false);
+ assert.equal(existsSync(lockPath), true);
+});
+
+/** Every module the detached runner imports, compiled side by side. */
+const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"];
+
+async function compileRunnerSources(destination: string): Promise {
+ const { build } = await import("esbuild");
+ const sourceDirectory = path.dirname(fileURLToPath(import.meta.url));
+ await build({
+ entryPoints: RUNNER_RUNTIME_FILES.map((file) => path.join(sourceDirectory, file.replace(/\.js$/, ".ts"))),
+ outdir: destination,
+ bundle: false,
+ format: "esm",
+ platform: "node",
+ target: "node22",
+ logLevel: "silent",
+ });
+}
+
+function processIsAlive(pid: number): boolean {
+ try { process.kill(pid, 0); return true; }
+ catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
+}
+
+async function stopProcess(pid: number): Promise {
+ try { process.kill(pid, "SIGKILL"); } catch { /* Already gone. */ }
+ const deadline = Date.now() + 5_000;
+ while (Date.now() < deadline && processIsAlive(pid)) {
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
+
+test("the real restart runner starts with every runtime module and survives the grace window", async t => {
+ const directory = workspace(t);
+ const compiled = path.join(directory, "compiled");
+ await compileRunnerSources(compiled);
+ const rootDir = path.join(directory, "app");
+ createPackageFiles(rootDir, "0.3.2");
+ const dataDir = path.join(directory, "data");
+ const updatesDir = path.join(dataDir, "updates");
+ mkdirSync(updatesDir, { recursive: true });
+ const taskId = "upd_real_runner";
+ const statePath = path.join(updatesDir, "state.json");
+ writeUpdateState(statePath, {
+ schemaVersion: 1,
+ task: {
+ id: taskId, 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 planPath = path.join(updatesDir, "plan.json");
+ const runnerDirectory = path.join(updatesDir, "runner");
+ const lockPath = path.join(updatesDir, "update.lock");
+ writeFileSync(planPath, JSON.stringify({
+ schemaVersion: 1,
+ taskId,
+ rootDir,
+ statePath,
+ lockPath,
+ stagedRoot: path.join(updatesDir, "staged"),
+ backupDir: path.join(updatesDir, "backups", taskId),
+ fromVersion: "0.3.2",
+ targetVersion: "0.4.0",
+ nodePath: process.execPath,
+ appEntry: path.join(rootDir, "dist", "index.js"),
+ // Deliberately not 3040 so the test cannot collide with a real server.
+ health: { protocol: "http", port: 39999, path: "/api/health" },
+ // The test process stays alive, so the runner waits instead of swapping.
+ waitForPid: process.pid,
+ parentTimeoutMs: 60_000,
+ healthTimeoutMs: 100,
+ pollIntervalMs: 50,
+ appLogPath: path.join(updatesDir, "app.log"),
+ }, null, 2));
+
+ const service = new UpdateService({
+ rootDir, dataDir, currentVersion: "0.3.2", logger,
+ platform: "linux", architecture: "x64", env: {}, isDocker: false,
+ fetch: fakeFetch([], new Map()),
+ runnerSourceDir: compiled,
+ runnerStartupTimeoutMs: 600,
+ });
+ // Call the real launcher: no spawn mock, the compiled runner is executed.
+ const pid = await service.launchRunner(planPath, runnerDirectory);
+ t.after(() => stopProcess(pid));
+
+ assert.ok(Number.isInteger(pid) && pid > 0, "the runner reported a pid");
+ for (const file of RUNNER_RUNTIME_FILES) {
+ assert.equal(existsSync(path.join(runnerDirectory, file)), true, `${file} was copied next to the runner`);
+ }
+ assert.doesNotThrow(() => process.kill(pid, 0), "the runner is still alive after the grace window");
+ const lock = JSON.parse(readFileSync(lockPath, "utf8"));
+ assert.equal(lock.taskId, taskId);
+ assert.equal(lock.pid, pid);
+ const log = readFileSync(path.join(updatesDir, "runner.log"), "utf8");
+ assert.ok(!log.includes("ERR_MODULE_NOT_FOUND"), `runner log has no missing module: ${log}`);
+});
diff --git a/src/updater/update-service.ts b/src/updater/update-service.ts
index a1a90fd..c0548d7 100644
--- a/src/updater/update-service.ts
+++ b/src/updater/update-service.ts
@@ -69,10 +69,12 @@ export interface UpdateServiceOptions {
apiBaseUrl?: string;
repository?: string;
now?: () => Date;
- /** Compiled directory containing restart-runner.js and code-swap.js. */
+ /** Compiled directory containing the restart runner and its runtime imports. */
runnerSourceDir?: string;
/** Test seam replacing the detached runner spawn. */
launchRunner?: (planPath: string, runnerDir: string) => Promise;
+ /** How long a freshly spawned runner must stay alive before apply succeeds. */
+ runnerStartupTimeoutMs?: number;
healthTimeoutMs?: number;
downloadTimeoutMs?: number;
}
@@ -80,6 +82,13 @@ export interface UpdateServiceOptions {
const CHECKSUM_LIMIT = 1024 * 1024;
const DOWNLOAD_LIMIT = 512 * 1024 * 1024;
+/**
+ * Every local module the restart runner imports at runtime. The runner is
+ * copied into an isolated directory under data/updates, so any omission here
+ * makes Node fail with ERR_MODULE_NOT_FOUND before the helper can swap code.
+ */
+const RUNNER_RUNTIME_FILES = ["restart-runner.js", "code-swap.js", "version.js", "update-state.js"] as const;
+
interface DownloadResult {
sha256: string;
bytes: number;
@@ -366,6 +375,9 @@ export class UpdateService {
try { rmSync(taskDirectory, { recursive: true, force: true }); } catch { /* Best effort. */ }
this.releaseLock?.();
this.releaseLock = null;
+ // A runner that died after taking over leaves its own pid in the lock.
+ // Only a provably dead owner is removed; a live lock is left alone.
+ clearStaleUpdateLock(this.lockPath);
throw updateError;
} finally {
this.applying = false;
@@ -465,16 +477,27 @@ export class UpdateService {
return { sha256: hash.digest("hex"), bytes };
}
- private async launchRunner(planPath: string, runnerDirectory: string): Promise {
+ /**
+ * Copy the runner and all of its runtime imports into an isolated directory,
+ * start it detached, and wait briefly to prove it did not die on startup.
+ * A successful spawn alone is not enough: Node resolves the whole ESM module
+ * graph before executing the helper, so a missing file only shows up as an
+ * early exit. Returning here means the helper is actually running.
+ */
+ async launchRunner(planPath: string, runnerDirectory: string): Promise {
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);
+ const missing = RUNNER_RUNTIME_FILES.filter((file) => !existsSync(path.join(sourceDirectory, file)));
+ if (missing.length > 0) {
+ throw new UpdateError(
+ "UPDATE_RUNNER_MISSING",
+ `The compiled restart runner is incomplete (missing ${missing.join(", ")}); 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"));
+ for (const file of RUNNER_RUNTIME_FILES) {
+ copyFileSync(path.join(sourceDirectory, file), path.join(runnerDirectory, file));
+ }
writeFileSync(path.join(runnerDirectory, "package.json"), JSON.stringify({ type: "module" }), "utf8");
let nodePath: string;
if (this.deployment.platform === "win32") {
@@ -484,10 +507,12 @@ export class UpdateService {
nodePath = process.execPath;
}
const log = path.join(path.dirname(planPath), "runner.log");
- await new Promise((resolve, reject) => {
+ const graceMs = this.options.runnerStartupTimeoutMs ?? 750;
+ return new Promise((resolve, reject) => {
let child: ChildProcess;
+ let fd: number | null = null;
try {
- const fd = openSync(log, "a");
+ fd = openSync(log, "a");
child = spawn(nodePath, [path.join(runnerDirectory, "restart-runner.js"), planPath], {
cwd: this.options.rootDir,
env: process.env,
@@ -495,13 +520,36 @@ export class UpdateService {
windowsHide: true,
stdio: ["ignore", fd, fd],
});
- closeSync(fd);
} catch (error) {
reject(error);
return;
+ } finally {
+ if (fd !== null) closeSync(fd);
}
- child.once("error", reject);
- child.once("spawn", () => { child.unref(); resolve(); });
+ let settled = false;
+ let timer: NodeJS.Timeout | undefined;
+ const fail = (message: string) => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ reject(new UpdateError("UPDATE_RUNNER_FAILED", message, 500));
+ };
+ child.once("error", (error) => fail(error.message));
+ child.once("exit", (code, signal) => {
+ fail(`The restart runner exited before taking over (code ${code ?? "none"}, signal ${signal ?? "none"}).`);
+ });
+ child.once("spawn", () => {
+ child.unref();
+ timer = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ if (!child.pid) {
+ reject(new UpdateError("UPDATE_RUNNER_FAILED", "The restart runner did not report a process id.", 500));
+ return;
+ }
+ resolve(child.pid);
+ }, graceMs);
+ });
});
}
}
diff --git a/src/updater/update-state.test.ts b/src/updater/update-state.test.ts
index f2ceef9..a88dac0 100644
--- a/src/updater/update-state.test.ts
+++ b/src/updater/update-state.test.ts
@@ -1,4 +1,6 @@
import assert from "node:assert/strict";
+import { spawn, type ChildProcess } from "node:child_process";
+import { once } from "node:events";
import test, { type TestContext } from "node:test";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -6,7 +8,7 @@ import path from "node:path";
import type { UpdateTaskView } from "../shared/update.js";
import {
acquireUpdateLock, clearStaleUpdateLock, emptyUpdateState, isActiveTaskStatus, readUpdateState,
- reconcileInterruptedState, UpdateLockedError, writeUpdateState,
+ reconcileInterruptedState, takeOverUpdateLock, UpdateLockedError, updateLockIsHeld, writeUpdateState,
} from "./update-state.js";
function workspace(t: TestContext): string {
@@ -32,6 +34,14 @@ function task(overrides: Partial = {}): UpdateTaskView {
};
}
+/** A second process that stays alive while a lock records its pid. */
+async function liveProcess(t: TestContext): Promise {
+ const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { stdio: "ignore" });
+ t.after(() => { try { child.kill("SIGKILL"); } catch { /* Already gone. */ } });
+ await once(child, "spawn");
+ return child;
+}
+
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());
@@ -89,6 +99,57 @@ test("locks left by dead processes are reclaimed while live locks are preserved"
assert.equal(existsSync(lock), false);
});
+test("a live lock and an unreadable lock are never cleared, and count as held", async t => {
+ const directory = workspace(t), lock = path.join(directory, "update.lock");
+ const owner = await liveProcess(t);
+ writeFileSync(lock, JSON.stringify({ pid: owner.pid, taskId: "live-task", createdAt: "2026-01-01T00:00:00.000Z" }));
+ clearStaleUpdateLock(lock);
+ assert.equal(existsSync(lock), true);
+ assert.equal(updateLockIsHeld(lock), true);
+ assert.equal(updateLockIsHeld(lock, "live-task"), true);
+ assert.equal(updateLockIsHeld(lock, "other-task"), false);
+ assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
+
+ // A lock that cannot be parsed may belong to a live owner, so it must not
+ // be deleted and must conservatively block new updates.
+ writeFileSync(lock, "not a lock record");
+ clearStaleUpdateLock(lock);
+ assert.equal(existsSync(lock), true);
+ assert.equal(updateLockIsHeld(lock), true);
+ assert.throws(() => acquireUpdateLock(lock, "new-task"), (error: unknown) => error instanceof UpdateLockedError);
+});
+
+test("a lock left by a dead process is reported free and reclaimed", 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" }));
+ assert.equal(updateLockIsHeld(lock), false);
+ clearStaleUpdateLock(lock);
+ assert.equal(existsSync(lock), false);
+ const release = acquireUpdateLock(lock, "new-task");
+ assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "new-task");
+ release();
+});
+
+test("the restart runner can take over its own task but never another task's lock", async t => {
+ const directory = workspace(t), lock = path.join(directory, "update.lock");
+ const previousOwner = await liveProcess(t);
+ writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-shared", createdAt: "2026-01-01T00:00:00.000Z" }));
+ assert.doesNotThrow(() => process.kill(previousOwner.pid!, 0), "the original owner is still alive");
+
+ const release = takeOverUpdateLock(lock, "task-shared");
+ const record = JSON.parse(readFileSync(lock, "utf8"));
+ assert.equal(record.pid, process.pid);
+ assert.equal(record.taskId, "task-shared");
+ assert.equal(updateLockIsHeld(lock, "task-shared"), true);
+ release();
+ assert.equal(existsSync(lock), false);
+
+ writeFileSync(lock, JSON.stringify({ pid: previousOwner.pid, taskId: "task-other", createdAt: "2026-01-01T00:00:00.000Z" }));
+ assert.throws(() => takeOverUpdateLock(lock, "task-shared"), (error: unknown) => error instanceof UpdateLockedError);
+ assert.equal(JSON.parse(readFileSync(lock, "utf8")).taskId, "task-other");
+ assert.equal(updateLockIsHeld(lock, "task-other"), true);
+});
+
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" }) });
diff --git a/src/updater/update-state.ts b/src/updater/update-state.ts
index 0ec34eb..b2635ee 100644
--- a/src/updater/update-state.ts
+++ b/src/updater/update-state.ts
@@ -1,4 +1,5 @@
-import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
+import { randomBytes } from "node:crypto";
+import { mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import path from "node:path";
import type { UpdateTaskStatus, UpdateTaskView } from "../shared/update.js";
@@ -11,6 +12,8 @@ export interface UpdateLockRecord {
pid: number;
taskId: string;
createdAt: string;
+ /** Opaque process start marker; guards against PID reuse where available. */
+ processStart?: string | null;
}
export class UpdateLockedError extends Error {
@@ -119,50 +122,190 @@ function processIsAlive(pid: number): boolean {
}
}
+/**
+ * Linux exposes the process start time in /proc//stat. It is used only
+ * as an extra guard against PID reuse: when it is unavailable (Windows,
+ * macOS, restricted /proc) liveness falls back to the pid check alone and
+ * never throws.
+ */
+function processStartMarker(pid: number): string | null {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ const close = stat.lastIndexOf(")");
+ if (close < 0) return null;
+ const fields = stat.slice(close + 2).trim().split(/\s+/);
+ // Field 3 is the state; starttime is field 22, i.e. index 19 here.
+ return fields[19] ?? null;
+ } catch {
+ return null;
+ }
+}
+
+function parseLockRecord(raw: string): UpdateLockRecord | null {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
+ const record = parsed as Record;
+ const pid = Number(record.pid);
+ if (!Number.isInteger(pid) || pid < 0 || typeof record.taskId !== "string" || !record.taskId) return null;
+ return {
+ pid,
+ taskId: record.taskId,
+ createdAt: typeof record.createdAt === "string" ? record.createdAt : "",
+ processStart: typeof record.processStart === "string" ? record.processStart : null,
+ };
+ } catch {
+ return null;
+ }
+}
+
+interface LockFile {
+ raw: string;
+ record: UpdateLockRecord | null;
+}
+
+/**
+ * Missing lock => null. A lock that exists but cannot be read or parsed is
+ * reported with `record: null`; callers must treat it as potentially held
+ * rather than deleting a lock another process may still own.
+ */
+function readLockFile(lockPath: string): LockFile | null {
+ try {
+ const raw = readFileSync(lockPath, "utf8");
+ return { raw, record: parseLockRecord(raw) };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ return { raw: "", record: null };
+ }
+}
+
+function lockOwnerIsAlive(record: UpdateLockRecord): boolean {
+ if (!processIsAlive(record.pid)) return false;
+ if (!record.processStart) return true;
+ const current = processStartMarker(record.pid);
+ // If the platform cannot report a start marker, keep the pid-only answer.
+ return current === null || current === record.processStart;
+}
+
+function lockPayload(taskId: string): string {
+ return JSON.stringify({
+ pid: process.pid,
+ taskId,
+ createdAt: new Date().toISOString(),
+ processStart: processStartMarker(process.pid),
+ } satisfies UpdateLockRecord);
+}
+
+function releaseLock(lockPath: string, payload: string, taskId: string): () => void {
+ return () => {
+ const file = readLockFile(lockPath);
+ // Never delete a lock that became unreadable or was replaced by another
+ // process; only remove the exact record this process wrote.
+ if (!file || !file.record || file.raw !== payload) return;
+ if (file.record.taskId !== taskId || file.record.pid !== process.pid) return;
+ try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
+ };
+}
+
+/** Remove a lock only after proving the observed record is dead and unchanged. */
+function reclaimDeadLock(lockPath: string, observed: LockFile): void {
+ const current = readLockFile(lockPath);
+ if (!current || current.raw !== observed.raw) return;
+ try { unlinkSync(lockPath); } catch { /* Another process reclaimed it. */ }
+}
+
/**
* Cross-process mutex. Lock files written by a dead process are reclaimed so
- * a crash cannot permanently block the maintenance page.
+ * a crash cannot permanently block the maintenance page. A lock that cannot
+ * be parsed is treated as held: refusing an update is safer than deleting a
+ * live lock.
*/
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++) {
+ const payload = lockPayload(taskId);
+ for (let attempt = 0; attempt < 4; attempt++) {
try {
writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
- return () => {
- try {
- const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial;
- if (current.taskId === taskId) unlinkSync(lockPath);
- } catch { /* The lock may already have been reclaimed. */ }
- };
+ return releaseLock(lockPath, payload, taskId);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
- let current: Partial = {};
- try { current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial; } 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. */ }
+ const file = readLockFile(lockPath);
+ if (!file) continue;
+ if (!file.record) {
+ throw new UpdateLockedError("An unreadable update lock is present; refusing to start an update.");
+ }
+ if (file.record.pid === process.pid && file.record.taskId === taskId) {
+ return releaseLock(lockPath, file.raw, taskId);
+ }
+ if (lockOwnerIsAlive(file.record)) throw new UpdateLockedError();
+ reclaimDeadLock(lockPath, file);
}
}
throw new UpdateLockedError();
}
-export function clearStaleUpdateLock(lockPath: string): void {
- try {
- const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial;
- if (!processIsAlive(Number(current.pid))) unlinkSync(lockPath);
- } catch {
- try { if (existsSync(lockPath)) unlinkSync(lockPath); } catch { /* Best effort. */ }
+/**
+ * The restart runner inherits an update that its parent process started but
+ * cannot finish. It must own the lock while it swaps and health-checks the
+ * new code, otherwise a second instance starting in that window would see a
+ * dead parent pid and roll the healthy code back.
+ *
+ * Only the same task may be taken over. A live lock for another task is
+ * never stolen, and an unreadable lock is refused.
+ */
+export function takeOverUpdateLock(lockPath: string, taskId: string): () => void {
+ mkdirSync(path.dirname(lockPath), { recursive: true });
+ const payload = lockPayload(taskId);
+ for (let attempt = 0; attempt < 4; attempt++) {
+ const file = readLockFile(lockPath);
+ if (!file) {
+ try {
+ writeFileSync(lockPath, payload, { encoding: "utf8", mode: 0o600, flag: "wx" });
+ return releaseLock(lockPath, payload, taskId);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
+ throw error;
+ }
+ }
+ if (!file.record) {
+ throw new UpdateLockedError("The update lock is unreadable; the restart runner will not take over.");
+ }
+ if (file.record.taskId !== taskId) {
+ throw new UpdateLockedError("A different update task holds the lock; the restart runner will not steal it.");
+ }
+ const temporary = `${lockPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
+ try {
+ writeFileSync(temporary, payload, { encoding: "utf8", mode: 0o600 });
+ renameSync(temporary, lockPath);
+ return releaseLock(lockPath, payload, taskId);
+ } catch (error) {
+ try { rmSync(temporary, { force: true }); } catch { /* Best effort. */ }
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
+ throw error;
+ }
}
+ throw new UpdateLockedError("The update lock could not be taken over.");
}
-/** True when a live process still owns the lock, optionally for a specific task. */
+/**
+ * Remove a lock only when its owner is provably dead. Unreadable locks are
+ * left in place so a live owner is never deleted by mistake.
+ */
+export function clearStaleUpdateLock(lockPath: string): void {
+ const file = readLockFile(lockPath);
+ if (!file || !file.record) return;
+ if (lockOwnerIsAlive(file.record)) return;
+ reclaimDeadLock(lockPath, file);
+}
+
+/**
+ * True when a live process still owns the lock, optionally for a specific
+ * task. An unreadable lock is conservatively reported as held.
+ */
export function updateLockIsHeld(lockPath: string, taskId?: string): boolean {
- try {
- const current = JSON.parse(readFileSync(lockPath, "utf8")) as Partial;
- if (!processIsAlive(Number(current.pid))) return false;
- return taskId === undefined || current.taskId === taskId;
- } catch {
- return false;
- }
+ const file = readLockFile(lockPath);
+ if (!file) return false;
+ if (!file.record) return true;
+ if (!lockOwnerIsAlive(file.record)) return false;
+ return taskId === undefined || file.record.taskId === taskId;
}
diff --git a/web/src/components/admin/AdminOperations.vue b/web/src/components/admin/AdminOperations.vue
index 33f680f..e2af1c2 100644
--- a/web/src/components/admin/AdminOperations.vue
+++ b/web/src/components/admin/AdminOperations.vue
@@ -303,6 +303,7 @@
{{ tr('updateSelectRelease') }}
+
{{ tr('updateChecksumNotice') }}
@@ -349,6 +349,7 @@ function blockedReasonText(code: string | null) {
switch (code) {
case 'DEPLOYMENT_DOCKER': return tr('updateBlockedDocker');
case 'DEPLOYMENT_SOURCE': return tr('updateBlockedSource');
+ case 'DEPLOYMENT_SUPERVISED': return tr('updateBlockedSupervised');
case 'PLATFORM_UNSUPPORTED': return tr('updateBlockedPlatform');
case 'ARCH_UNSUPPORTED': return tr('updateBlockedArch');
case 'WINDOWS_APPLY_UNVERIFIED': return tr('updateBlockedWindows');
diff --git a/web/src/i18n/admin-organization.ts b/web/src/i18n/admin-organization.ts
index 8095ff1..21259a0 100644
--- a/web/src/i18n/admin-organization.ts
+++ b/web/src/i18n/admin-organization.ts
@@ -21,6 +21,7 @@ const zh = {
updateChecksumMissing: "该版本缺少 SHA256SUMS.txt,已拒绝更新。", updateAssetMissing: "该版本没有适用于当前平台和架构的发布包。",
updateBlockedDocker: "容器内不能替换镜像。请保留 webspeak-data volume,在宿主机执行 docker compose pull && docker compose up -d;不要执行 docker compose down -v。",
updateBlockedSource: "源码运行没有捆绑运行时,控制台无法安全切换版本。请拉取源码后自行构建(npm ci && npm run build && npm run web:build),或改用发布包/Docker Compose。",
+ updateBlockedSupervised: "此实例由 systemd、PM2 等进程管理器托管,目前只能检查版本。请停止服务,手动替换发布包中的程序文件后再启动,并保留 data/、config.json 和 certs/。",
updateBlockedPlatform: "当前平台没有官方发布包,只能检查版本。", updateBlockedArch: "当前架构没有官方发布包,只能检查版本。",
updateBlockedWindows: "Windows 发布包的控制台更新尚未在真实 Windows 环境验证,已禁用;请下载新版发布包后手动替换。",
updateBlockedArm64: "Linux arm64 发布包的控制台更新尚未在真实硬件实测,已禁用;请下载新版发布包后手动替换。",
@@ -70,6 +71,7 @@ const en = {
updateChecksumMissing: "This release has no SHA256SUMS.txt; the update is refused.", updateAssetMissing: "This release has no package for the current platform and architecture.",
updateBlockedDocker: "An image cannot be replaced from inside the container. Keep the webspeak-data volume and run docker compose pull && docker compose up -d on the host. Never run docker compose down -v.",
updateBlockedSource: "Source installs have no bundled runtime, so the console cannot switch versions safely. Pull the source and rebuild (npm ci && npm run build && npm run web:build), or use a release package/Docker Compose.",
+ updateBlockedSupervised: "This instance runs under a process manager such as systemd or PM2; only version checks are available. Stop the service, replace the package's application files manually, then start it again. Preserve data/, config.json and certs/.",
updateBlockedPlatform: "No official package exists for this platform; only version checks are available.", updateBlockedArch: "No official package exists for this architecture; only version checks are available.",
updateBlockedWindows: "Console updates for Windows release packages are disabled until they are verified on a real Windows install. Download the new package and replace it manually.",
updateBlockedArm64: "Console updates for Linux arm64 release packages are disabled until they are verified on real hardware. Download the new package and replace it manually.",
@@ -118,6 +120,7 @@ const de = {
updateChecksumMissing: "Diesem Release fehlt SHA256SUMS.txt; das Update wird abgelehnt.", updateAssetMissing: "Dieses Release hat kein Paket für Plattform und Architektur.",
updateBlockedDocker: "Ein Image kann nicht im Container ersetzt werden. Das Volume webspeak-data behalten und auf dem Host docker compose pull && docker compose up -d ausführen. Niemals docker compose down -v verwenden.",
updateBlockedSource: "Quellinstallationen haben keine mitgelieferte Laufzeit; die Konsole kann Versionen nicht sicher wechseln. Quellen aktualisieren und neu bauen (npm ci && npm run build && npm run web:build) oder Release-Paket/Docker Compose verwenden.",
+ updateBlockedSupervised: "Diese Instanz wird etwa von systemd oder PM2 verwaltet; nur Versionsprüfungen sind verfügbar. Dienst stoppen, Programmdateien manuell ersetzen und wieder starten. data/, config.json und certs/ behalten.",
updateBlockedPlatform: "Für diese Plattform gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.", updateBlockedArch: "Für diese Architektur gibt es kein offizielles Paket; nur Versionsprüfungen sind möglich.",
updateBlockedWindows: "Konsolen-Updates für Windows-Release-Pakete sind deaktiviert, bis sie auf einer echten Windows-Installation geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
updateBlockedArm64: "Konsolen-Updates für Linux-arm64-Release-Pakete sind deaktiviert, bis sie auf echter Hardware geprüft wurden. Laden Sie das neue Paket herunter und ersetzen Sie es manuell.",
@@ -166,6 +169,7 @@ const ru = {
updateChecksumMissing: "В релизе нет SHA256SUMS.txt; обновление отклонено.", updateAssetMissing: "В релизе нет пакета для текущей платформы и архитектуры.",
updateBlockedDocker: "Образ нельзя заменить изнутри контейнера. Сохраните том webspeak-data и выполните на хосте docker compose pull && docker compose up -d. Никогда не запускайте docker compose down -v.",
updateBlockedSource: "В установке из исходников нет встроенной среды выполнения, поэтому консоль не может безопасно сменить версию. Обновите исходники и пересоберите (npm ci && npm run build && npm run web:build) или используйте пакет релиза/Docker Compose.",
+ updateBlockedSupervised: "Экземпляр управляется systemd, PM2 или другим менеджером процессов; доступна только проверка версий. Остановите службу, вручную замените файлы программы и запустите её снова. Сохраните data/, config.json и certs/.",
updateBlockedPlatform: "Для этой платформы нет официального пакета; доступна только проверка версий.", updateBlockedArch: "Для этой архитектуры нет официального пакета; доступна только проверка версий.",
updateBlockedWindows: "Обновление из консоли для релизных пакетов Windows отключено до проверки на реальной установке Windows. Скачайте новый пакет и замените его вручную.",
updateBlockedArm64: "Обновление из консоли для релизных пакетов Linux arm64 отключено до проверки на реальном оборудовании. Скачайте новый пакет и замените его вручную.",
@@ -214,6 +218,7 @@ const ja = {
updateChecksumMissing: "このリリースには SHA256SUMS.txt がないため、更新を拒否しました。", updateAssetMissing: "このリリースには現在のプラットフォームとアーキテクチャ向けのパッケージがありません。",
updateBlockedDocker: "コンテナ内からイメージは置き換えられません。webspeak-data ボリュームを保持し、ホストで docker compose pull && docker compose up -d を実行してください。docker compose down -v は実行しないでください。",
updateBlockedSource: "ソース実行には同梱ランタイムがないため、安全にバージョンを切り替えられません。ソースを取得して再ビルドする(npm ci && npm run build && npm run web:build)か、リリースパッケージ/Docker Compose を使用してください。",
+ updateBlockedSupervised: "このインスタンスは systemd や PM2 などで管理されているため、バージョン確認のみ可能です。サービスを停止し、プログラムファイルを手動で置き換えて再起動してください。data/、config.json、certs/ は保持してください。",
updateBlockedPlatform: "このプラットフォーム向けの公式パッケージがないため、バージョン確認のみ可能です。", updateBlockedArch: "このアーキテクチャ向けの公式パッケージがないため、バージョン確認のみ可能です。",
updateBlockedWindows: "Windows リリースパッケージのコンソール更新は、実際の Windows 環境で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
updateBlockedArm64: "Linux arm64 リリースパッケージのコンソール更新は、実機で検証するまで無効です。新しいパッケージをダウンロードして手動で置き換えてください。",
diff --git a/web/test/admin-view.test.mjs b/web/test/admin-view.test.mjs
index b58742c..d6d00ac 100644
--- a/web/test/admin-view.test.mjs
+++ b/web/test/admin-view.test.mjs
@@ -725,6 +725,35 @@ test("settings and operations render explicit localized sections with valid deep
}
});
+test("check-only deployments retain release checks and notes without install controls", async () => {
+ const { createSSRApp } = await import("vue");
+ const { renderToString } = await import("vue/server-renderer");
+ const { default: Operations } = await vite.ssrLoadModule("/src/components/admin/AdminOperations.vue");
+ await mount("/admin/operations?section=maintenance");
+ const model = reactive(state.adminOperations);
+ for (const [mode, reasonCode] of [["source", "DEPLOYMENT_SOURCE"], ["docker", "DEPLOYMENT_DOCKER"],
+ ["release-package", "WINDOWS_APPLY_UNVERIFIED"], ["release-package", "LINUX_ARM64_APPLY_UNVERIFIED"], ["release-package", "DEPLOYMENT_SUPERVISED"]]) {
+ model.operations.update.deployment = { mode, platform: "linux", architecture: "x64", applyAllowed: false, reasonCode, upgradePath: "release-package" };
+ let checked = false;
+ handler = path => {
+ assert.equal(path, "/update/check"); checked = true;
+ return Promise.resolve(json({ currentVersion: "0.3.2", releases: [{ version: "0.4.0", canApply: false, blockedReason: reasonCode,
+ tag: "v0.4.0", assetName: "webspeak-webclient-v0.4.0-linux-x64.tar.gz", assetSize: 100,
+ assetAvailable: true, hasChecksums: true, digest: null,
+ publishedAt: "2026-11-25T00:00:00.000Z", releaseUrl: "https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak/releases/tag/v0.4.0" }] }));
+ };
+ await model.checkForUpdates();
+ assert.equal(checked, true);
+ assert.equal(state.errorMessage, "");
+ const html = await renderToString(createSSRApp(Operations, { model: state.adminOperations, i18n: state.i18n, initialSection: "maintenance" }));
+ assert.ok(html.includes(state.i18n.tr("updateCheckAction")), reasonCode);
+ assert.ok(html.includes("/releases/tag/v0.4.0"), reasonCode);
+ assert.ok(html.includes('data-admin-update="check"'), reasonCode);
+ assert.ok(!html.includes('data-admin-update="apply"'), reasonCode);
+ if (reasonCode === "DEPLOYMENT_SUPERVISED") assert.ok(html.includes(state.i18n.tr("updateBlockedSupervised")));
+ }
+});
+
test("update error codes resolve to their dedicated five-language labels", async () => {
const { adminOrganizationCopy } = await vite.ssrLoadModule("/src/i18n/admin-organization.ts");
await mount("/admin/server");