feat(core): add staged self-updates and unify application version

This commit is contained in:
手瓜一十雪 committed 2026-10-18 12:50:11 +08:00
1 parent c54aeffc77
commit 5032cbb8c0
45 files changed
+1860 -165

No files matched your search

+4 -2
View File
@@ -34,7 +34,7 @@
},
"scripts": {
"build": "vite build",
"build:all": "cross-env BUILD_WEBUI=true vite build",
"build:all": "cross-env BUILD_WEBUI=true pnpm build",
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
@@ -48,7 +48,9 @@
"@snowluma/protocol": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*",
"otpauth": "^9.5.1"
"fflate": "^0.8.3",
"otpauth": "^9.5.1",
"tar": "^7.5.22"
},
"devDependencies": {
"@hono/node-server": "^1.19.15",
+1 -1
View File
@@ -1,2 +1,2 @@
declare const __BUILD_WEBUI__: boolean;
declare const __APP_VERSION__: string;
declare const __PACKAGED__: boolean;
+35 -7
View File
@@ -1,4 +1,5 @@
import { getRuntimeIntegrity, HookManager } from '@snowluma/bridge';
import { APP_VERSION } from '@snowluma/common/version';
import { configureFileTransport } from '@snowluma/common/log-file-transport';
import { closeLogger, createLogger } from '@snowluma/common/logger';
import {
@@ -15,14 +16,20 @@ import {
runMessageStoreMigrationWorker,
} from '@snowluma/onebot/message-store-migration-worker';
import { workerData } from 'node:worker_threads';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { BridgeManager } from './bridge/manager';
import { createNotificationManager } from './notifications/manager';
import { createStateWiring } from './webui/state-wiring';
import { initWebUI } from './webui/server';
import { bindSystemFaceCatalog } from './sys-face-catalog';
import { readAppVersion, startNativeStageSync, tempStagePath } from './native-stage-sync';
import { startNativeStageSync, tempStagePath } from './native-stage-sync';
import { logRuntimeIntegrity } from './runtime-integrity-log';
import { RESTART_EXIT_CODE, runApplication } from './update/startup';
const log = createLogger('App');
const updateRoot =
typeof __PACKAGED__ === 'undefined' ? undefined : path.dirname(fileURLToPath(import.meta.url));
function installProcessGuards(): void {
// Last-resort process guards. This is a long-running daemon: a hooked QQ pipe
@@ -54,7 +61,7 @@ async function main() {
log.info('SnowLuma starting');
logRuntimeIntegrity(getRuntimeIntegrity());
const stopNativeStageSync = startNativeStageSync({
version: readAppVersion(import.meta.url),
version: APP_VERSION,
dataDir: 'data',
tempPath: tempStagePath(),
});
@@ -108,7 +115,6 @@ async function main() {
process.env.SNOWLUMA_DEV_WEBUI === '1'
) {
try {
const { initWebUI } = await import('./webui/server');
const started = await initWebUI(
runtimeConfig.webuiPort || 5099,
oneBotManager,
@@ -119,6 +125,10 @@ async function main() {
tlsEnabled: runtimeConfig.webuiTls?.enabled,
trustProxy: runtimeConfig.trustProxy,
stateBus: stateWiring.bus,
updateRoot,
restart: () => {
void shutdown('update', RESTART_EXIT_CODE);
},
},
);
stopWebUI = started.stop;
@@ -131,14 +141,14 @@ async function main() {
// SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path.
let shutdownStarted = false;
const shutdown = (signal: string) => async () => {
const shutdown = async (signal: string, requestedExitCode = 0) => {
if (shutdownStarted) {
return;
}
shutdownStarted = true;
log.warn(`Shutting down (${signal})...`);
let exitCode = 0;
let exitCode = requestedExitCode;
try {
await oneBotManager.dispose();
@@ -219,8 +229,24 @@ async function main() {
process.exit(exitCode);
};
process.on('SIGINT', shutdown('SIGINT'));
process.on('SIGTERM', shutdown('SIGTERM'));
process.on('SIGINT', () => {
void shutdown('SIGINT');
});
process.on('SIGTERM', () => {
void shutdown('SIGTERM');
});
if (process.send) {
process.on('message', (message) => {
if (message === 'shutdown') {
void shutdown('launcher');
}
});
process.on('disconnect', () => {
void shutdown('launcher disconnected');
});
process.send('ready');
}
}
function resolveAutoLoad(fromConfig: boolean | undefined): boolean {
@@ -245,6 +271,8 @@ if (isMessageStoreMigrationWorkerData(workerData)) {
runMessageStoreMigrationWorker(workerData).catch(() => {
process.exitCode = 1;
});
} else if (updateRoot && !process.env.SNOWLUMA_UPDATE_ROOT) {
void runApplication(updateRoot);
} else {
installProcessGuards();
main().catch(async (error) => {
-19
View File
@@ -109,25 +109,6 @@ export function tempStagePath(
return `/tmp/sl-${uid}/${STAGE_FILE_NAME}`;
}
export function readAppVersion(moduleUrl: string | URL = import.meta.url): string {
if (typeof __APP_VERSION__ === 'string' && __APP_VERSION__) {
return __APP_VERSION__;
}
try {
const raw = readFileSync(new URL('../package.json', moduleUrl), 'utf8');
const version = JSON.parse(raw).version;
if (typeof version === 'string' && version.trim()) {
return version.trim();
}
} catch {
// Built layouts that do not sit next to a package manifest keep the fallback.
}
return '0.0.0';
}
export function errorCode(error: unknown): string {
if (error && typeof error === 'object' && 'code' in error) {
const code = (error as { code?: unknown }).code;
@@ -1,15 +1,4 @@
// Advisory update check against the public GitHub Releases API.
//
// Strictly read-only (T0): SnowLuma never downloads or applies anything
// itself — cross-platform self-update is a minefield (Windows locks loaded
// .node/.dll/node.exe, Docker bakes the app into image layers, bare installs
// have no supervisor). We only tell the WebUI that a newer *stable* release
// exists and link the user to it; they download and apply manually.
//
// The result is cached to stay well under GitHub's 60 req/hr unauthenticated
// rate limit, and every failure degrades silently (the UI just shows
// "无法检查更新" rather than nagging).
import { APP_VERSION } from '@snowluma/common/version';
import { createLogger } from '@snowluma/common/logger';
import { createSingleFlightCache } from '@snowluma/common/single-flight-cache';
@@ -46,10 +35,6 @@ interface GithubRelease {
published_at?: string;
}
export function currentVersion(): string {
return typeof __APP_VERSION__ === 'string' && __APP_VERSION__ ? __APP_VERSION__ : '0.0.0';
}
function isEnabled(): boolean {
const v = (process.env.SNOWLUMA_UPDATE_CHECK ?? '').trim().toLowerCase();
return v !== '0' && v !== 'false' && v !== 'off' && v !== 'no';
@@ -173,7 +158,7 @@ async function fetchLatest(current: string): Promise<UpdateCheckResult> {
* are not cached so the next check retries.
*/
export async function getUpdateInfo(force = false): Promise<UpdateCheckResult> {
const current = currentVersion();
const current = APP_VERSION;
if (!isEnabled()) {
return { ...emptyResult(current), error: 'disabled' };
+187
View File
@@ -0,0 +1,187 @@
import { createHash } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { unzipSync } from 'fflate';
import { x as extractTar } from 'tar';
import { isRuntimeEntry, readManifest } from './files';
interface ReleaseAsset {
url: string;
size: number;
digest: string;
}
export function assetName(version: string, target: string): string {
const platform = target.replace('win32', 'win');
return `SnowLuma-v${version}-${platform}-lite.${target.startsWith('win32') ? 'zip' : 'tar.gz'}`;
}
async function releaseAsset(version: string, target: string): Promise<ReleaseAsset> {
const name = assetName(version, target);
const response = await fetch(
`https://api.github.com/repos/SnowLuma/SnowLuma/releases/tags/v${version}`,
{
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'SnowLuma',
'X-GitHub-Api-Version': '2022-11-28',
},
signal: AbortSignal.timeout(15_000),
},
);
if (!response.ok) {
throw new Error(`获取更新失败: GitHub ${response.status}`);
}
const release: unknown = await response.json();
if (
!release ||
typeof release !== 'object' ||
!('assets' in release) ||
!Array.isArray(release.assets)
) {
throw new Error('发布信息无效');
}
const asset: unknown = release.assets.find(
(item: unknown) =>
item !== null && typeof item === 'object' && 'name' in item && item.name === name,
);
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v${version}/${name}`;
if (
!asset ||
typeof asset !== 'object' ||
!('size' in asset) ||
typeof asset.size !== 'number' ||
!Number.isSafeInteger(asset.size) ||
asset.size <= 0 ||
!('digest' in asset) ||
typeof asset.digest !== 'string' ||
!/^sha256:[a-f0-9]{64}$/.test(asset.digest)
) {
throw new Error('更新包不存在或缺少校验信息');
}
return { url, size: asset.size, digest: asset.digest };
}
export function archivePath(name: string): string {
const normalized = name.replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/$/, '');
if (normalized === '.' || normalized === '') {
return '';
}
const parts = normalized.split('/');
if (
!isRuntimeEntry(parts[0]) ||
parts.some((part) => !part || part === '.' || part === '..' || /[:\0]/.test(part))
) {
throw new Error(`更新包路径无效: ${name}`);
}
return normalized;
}
export async function downloadUpdate(
directory: string,
version: string,
target: string,
): Promise<void> {
const asset = await releaseAsset(version, target);
const response = await fetch(asset.url, { signal: AbortSignal.timeout(10 * 60_000) });
if (!response.ok || !response.body) {
throw new Error(`下载更新失败: HTTP ${response.status}`);
}
const archive = path.join(directory, 'archive');
const hash = createHash('sha256');
let received = 0;
await pipeline(
Readable.fromWeb(response.body),
new Transform({
transform(chunk: Buffer, _encoding, callback) {
received += chunk.length;
if (received > asset.size) {
callback(new Error('更新包大小不匹配'));
return;
}
hash.update(chunk);
callback(null, chunk);
},
}),
createWriteStream(archive, { flags: 'wx' }),
);
if (received !== asset.size || `sha256:${hash.digest('hex')}` !== asset.digest) {
throw new Error('更新包校验失败');
}
const payload = path.join(directory, 'payload');
await mkdir(payload);
if (target.startsWith('win32')) {
const files = unzipSync(await readFile(archive), {
filter: (entry) => {
archivePath(entry.name);
return true;
},
});
for (const [name, bytes] of Object.entries(files)) {
const relative = archivePath(name);
if (!relative || name.endsWith('/')) {
continue;
}
const destination = path.join(payload, relative);
await mkdir(path.dirname(destination), { recursive: true });
await writeFile(destination, bytes, { flag: 'wx' });
}
} else {
let invalidEntry: Error | undefined;
await extractTar({
file: archive,
cwd: payload,
strict: true,
filter: (name, entry) => {
try {
archivePath(name);
if (
!('type' in entry) ||
(entry.type !== 'File' && entry.type !== 'Directory')
) {
throw new Error('更新包包含链接或特殊文件');
}
return true;
} catch (error) {
invalidEntry = error instanceof Error ? error : new Error(String(error));
return false;
}
},
});
if (invalidEntry) {
throw invalidEntry;
}
}
const manifest = await readManifest(payload);
if (manifest.version !== version || manifest.target !== target) {
throw new Error('更新包版本或平台不匹配');
}
}
+272
View File
@@ -0,0 +1,272 @@
import { access, cp, lstat, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { createHash } from 'node:crypto';
import { constants, existsSync } from 'node:fs';
import os from 'node:os';
export const MANIFEST_FILE = 'release.json';
export async function updateDirectory(root: string, temporaryRoot = os.tmpdir()): Promise<string> {
const local = path.join(root, 'tmp', 'update');
// A locally staged update must remain discoverable if system tmp becomes available again.
if (existsSync(local)) {
return local;
}
const identity = createHash('sha256').update(path.resolve(root)).digest('hex').slice(0, 16);
const directory = path.join(temporaryRoot, `snowluma-update-${identity}`);
try {
await mkdir(directory, { recursive: true });
await access(directory, constants.W_OK);
return directory;
} catch (error) {
if (
!(error instanceof Error) ||
!('code' in error) ||
!['EACCES', 'EPERM', 'EROFS'].includes(String(error.code))
) {
throw error;
}
await mkdir(local, { recursive: true });
return local;
}
}
export interface ReleaseManifest {
version: string;
target: string;
entries: string[];
}
const runtimeEntries = new Set([
'native',
'client',
'package.json',
MANIFEST_FILE,
'launcher.bat',
'launcher.sh',
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
]);
export function isRuntimeEntry(name: string): boolean {
return runtimeEntries.has(name) || /^[\w-]+\.mjs(?:\.map)?$/.test(name);
}
function entryList(value: unknown): value is string[] {
return (
Array.isArray(value) &&
value.every((entry) => typeof entry === 'string' && isRuntimeEntry(entry)) &&
new Set(value).size === value.length
);
}
export async function exists(file: string): Promise<boolean> {
try {
await lstat(file);
return true;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
return false;
}
throw error;
}
}
export async function readManifest(root: string): Promise<ReleaseManifest> {
const value: unknown = JSON.parse(await readFile(path.join(root, MANIFEST_FILE), 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('version' in value) ||
typeof value.version !== 'string' ||
!/^\d+\.\d+\.\d+(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.version) ||
!('target' in value) ||
typeof value.target !== 'string' ||
!/^(win32-x64|linux-(x64|arm64))$/.test(value.target) ||
!('entries' in value) ||
!entryList(value.entries)
) {
throw new Error('更新包清单无效');
}
const entries = value.entries;
if (
![
'index.mjs',
'native',
'client',
'package.json',
MANIFEST_FILE,
'check-node-version.cjs',
'EULA.md',
'PRIVACY.md',
value.target.startsWith('win32') ? 'launcher.bat' : 'launcher.sh',
].every((entry) => entries.includes(entry))
) {
throw new Error('更新包清单无效');
}
return { version: value.version, target: value.target, entries: value.entries };
}
async function checkEntryTypes(root: string, entries: string[]): Promise<void> {
for (const entry of entries) {
const stat = await lstat(path.join(root, entry));
const directory = entry === 'native' || entry === 'client';
if (directory ? !stat.isDirectory() : !stat.isFile()) {
throw new Error(`更新包文件类型无效: ${entry}`);
}
}
}
interface Transaction {
entries: string[];
original: string[];
}
async function readTransaction(file: string): Promise<Transaction> {
const value: unknown = JSON.parse(await readFile(file, 'utf8'));
if (
!value ||
typeof value !== 'object' ||
!('entries' in value) ||
!entryList(value.entries) ||
!('original' in value) ||
!entryList(value.original)
) {
throw new Error('更新恢复记录无效');
}
const entries = value.entries;
if (value.original.some((entry) => !entries.includes(entry))) {
throw new Error('更新恢复记录无效');
}
return { entries: value.entries, original: value.original };
}
async function restore(root: string, pending: string, transaction: Transaction): Promise<void> {
for (const entry of transaction.entries) {
const backup = path.join(pending, 'backup', entry);
const destination = path.join(root, entry);
if (transaction.original.includes(entry)) {
await replaceEntry(backup, destination, path.join(root, '.update-install'));
} else {
await rm(destination, { recursive: true, force: true });
}
}
await rm(path.join(pending, 'transaction.json'));
}
async function replaceEntry(source: string, destination: string, temporary: string): Promise<void> {
await rm(temporary, { recursive: true, force: true });
await cp(source, temporary, { recursive: true });
// Files stay present until their replacement is ready, including the entry point.
if ((await lstat(source)).isDirectory()) {
await rm(destination, { recursive: true, force: true });
}
await rename(temporary, destination);
}
// Called before loading native libraries, after the previous process has exited.
export async function applyPendingUpdate(root: string): Promise<string | null> {
const directory = await updateDirectory(root);
const pending = path.join(directory, 'pending');
const completed = path.join(directory, 'completed');
await rm(completed, { recursive: true, force: true });
await rm(path.join(directory, 'downloading'), { recursive: true, force: true });
await rm(path.join(root, '.update-install'), { recursive: true, force: true });
if (!(await exists(pending))) {
await rm(directory, { recursive: true });
return null;
}
const journal = path.join(pending, 'transaction.json');
if (await exists(journal)) {
await restore(root, pending, await readTransaction(journal));
}
const payload = path.join(pending, 'payload');
const next = await readManifest(payload);
const current = await readManifest(root);
if (next.target !== current.target) {
throw new Error('更新包平台不匹配');
}
await checkEntryTypes(payload, next.entries);
const entries = [...new Set([...current.entries, ...next.entries])];
const original: string[] = [];
for (const entry of entries) {
if (await exists(path.join(root, entry))) {
if ((await lstat(path.join(root, entry))).isSymbolicLink()) {
throw new Error(`更新目标不能是符号链接: ${entry}`);
}
original.push(entry);
}
}
const transaction = { entries, original };
const backup = path.join(pending, 'backup');
await rm(backup, { recursive: true, force: true });
await mkdir(backup);
for (const entry of original) {
await cp(path.join(root, entry), path.join(backup, entry), { recursive: true });
}
await writeFile(`${journal}.tmp`, JSON.stringify(transaction));
await rename(`${journal}.tmp`, journal);
try {
for (const entry of next.entries) {
await replaceEntry(
path.join(payload, entry),
path.join(root, entry),
path.join(root, '.update-install'),
);
}
for (const entry of current.entries) {
if (!next.entries.includes(entry)) {
await rm(path.join(root, entry), { recursive: true, force: true });
}
}
// Renaming commits the transaction before cleanup, including across a crash.
await rename(pending, completed);
} catch (error) {
try {
await restore(root, pending, transaction);
} catch (restoreError) {
throw new AggregateError(
[error, restoreError],
'更新失败,恢复未完成;下次启动将继续恢复',
);
}
throw error;
}
await rm(directory, { recursive: true });
return next.version;
}
+101
View File
@@ -0,0 +1,101 @@
import { existsSync } from 'node:fs';
import { mkdir, rename, rm } from 'node:fs/promises';
import path from 'node:path';
import { createLogger } from '@snowluma/common/logger';
import { compareVersions } from './check';
import { downloadUpdate } from './download';
import { exists, MANIFEST_FILE, readManifest, updateDirectory } from './files';
const log = createLogger('Update');
export type UpdateState =
| { phase: 'unavailable'; message: string }
| { phase: 'idle' }
| { phase: 'downloading' | 'ready' | 'restarting'; version: string }
| { phase: 'error'; message: string };
export async function createUpdateService(
root: string | undefined,
current: string,
options: { download?: typeof downloadUpdate; isContainer?: boolean } = {},
) {
const download = options.download ?? downloadUpdate;
let state: UpdateState;
let target = '';
let staging = '';
if (!root || !existsSync(path.join(root, MANIFEST_FILE))) {
state = { phase: 'unavailable', message: '在线更新仅支持发行包' };
} else if (
options.isContainer ??
(existsSync('/.dockerenv') || Boolean(process.env.container))
) {
state = { phase: 'unavailable', message: '请更新容器镜像' };
} else {
const manifest = await readManifest(root);
target = manifest.target;
staging = await updateDirectory(root);
const pending = path.join(staging, 'pending', 'payload');
state = (await exists(pending))
? { phase: 'ready', version: (await readManifest(pending)).version }
: { phase: 'idle' };
}
const prepare = async (version: string): Promise<void> => {
const directory = path.join(staging, 'downloading');
try {
await rm(directory, { recursive: true, force: true });
await mkdir(directory, { recursive: true });
await download(directory, version, target);
await rm(path.join(directory, 'archive'));
await rename(directory, path.join(staging, 'pending'));
state = { phase: 'ready', version };
log.info('v%s 已下载,重启后应用', version);
} catch (error) {
log.error('下载更新失败: %s', error);
let message = error instanceof Error ? error.message : String(error);
try {
await rm(directory, { recursive: true, force: true });
} catch (cleanupError) {
message += `;清理更新文件失败: ${String(cleanupError)}`;
log.error('清理更新文件失败: %s', cleanupError);
}
state = { phase: 'error', message };
}
};
return {
status: () => ({ current, ...state }),
start(version: unknown) {
if (state.phase !== 'idle' && state.phase !== 'error') {
throw new Error(
state.phase === 'unavailable' ? state.message : '更新正在进行或等待重启',
);
}
if (
typeof version !== 'string' ||
!/^\d+\.\d+\.\d+$/.test(version) ||
compareVersions(version, current) <= 0
) {
throw new Error('请选择更新的正式版本');
}
state = { phase: 'downloading', version };
log.info('下载 v%s', version);
void prepare(version);
},
restart() {
if (state.phase !== 'ready') {
throw new Error('更新包尚未就绪');
}
state = { phase: 'restarting', version: state.version };
},
};
}
export type UpdateService = Awaited<ReturnType<typeof createUpdateService>>;
+75
View File
@@ -0,0 +1,75 @@
import { spawn } from 'node:child_process';
import path from 'node:path';
import { applyPendingUpdate } from './files';
export const RESTART_EXIT_CODE = 75;
export async function runApplication(root: string): Promise<void> {
let stopping = false;
let child: ReturnType<typeof spawn> | undefined;
const requestShutdown = () => {
if (child?.connected) {
child.send('shutdown', (error) => {
if (error) {
console.error('[App] 发送退出请求失败:', error);
}
});
}
};
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.on(signal, () => {
stopping = true;
if (process.platform === 'win32') {
requestShutdown();
} else {
child?.kill(signal);
}
});
}
try {
do {
const version = await applyPendingUpdate(root);
if (version) {
console.info(`[Update] 已更新至 v${version}`);
}
if (stopping) {
break;
}
const code = await new Promise<number>((resolve, reject) => {
child = spawn(
process.execPath,
[...process.execArgv, path.join(root, 'index.mjs'), ...process.argv.slice(2)],
{
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
env: { ...process.env, SNOWLUMA_UPDATE_ROOT: root },
},
);
child.once('error', reject);
child.on('message', (message) => {
if (message === 'ready' && stopping) {
requestShutdown();
}
});
child.once('exit', (exitCode, signal) =>
resolve(exitCode ?? (signal === 'SIGINT' ? 130 : 143)),
);
});
child = undefined;
if (code !== RESTART_EXIT_CODE || stopping) {
process.exitCode = code === RESTART_EXIT_CODE ? 0 : code;
break;
}
} while (!stopping);
} catch (error) {
console.error('[Update] 启动失败:', error);
process.exitCode = 1;
}
}
+22 -9
View File
@@ -1,3 +1,4 @@
import { APP_VERSION } from '@snowluma/common/version';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
@@ -77,7 +78,7 @@ import { restoreBackup, RestoreTransactionError, type RestorePhase } from './res
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
import { createFramePusher } from './debug-stream';
import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools';
import { sseResponse } from './sse-response';
import { sseResponse as createSseResponse } from './sse-response';
import { bindStateStream } from './state-stream';
import type { StateBus, StateResource } from './state-bus';
import { startConnectionDiffLoop } from './connection-diff-loop';
@@ -99,7 +100,9 @@ import {
sniffImageMime,
writeBackgroundImage,
} from './ui-config';
import { currentVersion, getUpdateInfo } from './update-check';
import { getUpdateInfo } from '../update/check';
import { createUpdateService } from '../update/service';
import { updateRoutes } from './update-routes';
import { buildFullTraceDownload } from './log-export';
import { loadNotificationsConfig, saveNotificationsConfig } from '../notifications/config';
import type { NotificationManager } from '../notifications/manager';
@@ -629,6 +632,8 @@ export async function initWebUI(
tlsEnabled?: boolean;
trustProxy?: string;
stateBus?: StateBus;
restart?: () => void;
updateRoot?: string;
} = {},
): Promise<{ port: number; stop: () => Promise<void> }> {
const host = listener.host || '127.0.0.1';
@@ -747,6 +752,9 @@ export async function initWebUI(
}
const app = new Hono();
const shutdownStreams = new AbortController();
const sseResponse = (...args: Parameters<typeof createSseResponse>) =>
createSseResponse(args[0], args[1], shutdownStreams.signal);
app.use('*', webuiSecurityHeaders);
registerLoginRequestSecurity(app);
const storageManagement = new StorageManagementService({
@@ -1312,11 +1320,15 @@ export async function initWebUI(
return c.json({ status: 'running' });
});
// Advisory update check — compares the running build against the latest
// GitHub stable release and links the user to it. Read-only: SnowLuma
// never downloads or applies the update itself. `?force=1` bypasses the
// server-side cache (the "立即检查" button). Never errors out — a failed
// check returns `{ hasUpdate: false, error }` and the UI degrades quietly.
const updater = await createUpdateService(
listener.restart ? listener.updateRoot : undefined,
APP_VERSION,
);
app.route(
'/api/update',
updateRoutes(updater, () => listener.restart?.()),
);
app.get('/api/update/check', async (c) => {
const force = c.req.query('force') === 'true' || c.req.query('force') === '1';
return c.json(await getUpdateInfo(force));
@@ -1397,7 +1409,7 @@ export async function initWebUI(
// ── System settings (WebUI listener) — Wave A1 ──
// Listener-level changes (port/host/TLS) are persisted but apply only on the
// next restart (no supervisor → no self-restart). The panel surfaces which
// next restart. The panel surfaces which
// fields are currently overridden by env so edits that won't take effect are
// visible.
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
@@ -1850,7 +1862,7 @@ export async function initWebUI(
app.get('/api/logs/export/trace', (c) => {
const exportedAt = new Date().toISOString();
const download = buildFullTraceDownload(getLogSnapshot(), {
version: currentVersion(),
version: APP_VERSION,
operatingSystem: os.platform(),
architecture: os.arch(),
nodeVersion: process.version,
@@ -2344,6 +2356,7 @@ export async function initWebUI(
port: finalPort,
async stop() {
connectionDiffLoop?.dispose();
shutdownStreams.abort();
await new Promise<void>((resolve, reject) => {
listeningServer.close((err) => (err ? reject(err) : resolve()));
});
+14 -1
View File
@@ -32,7 +32,11 @@ export interface SseChannel {
* previously hand-copied this ~40-line skeleton; a heartbeat-interval /
* teardown-order / header change had to be kept in sync across all three.
*/
export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response {
export function sseResponse(
c: Context,
start: (ch: SseChannel) => void,
shutdown?: AbortSignal,
): Response {
const stream = new ReadableStream<Uint8Array>({
start(controller) {
const encoder = new TextEncoder();
@@ -91,6 +95,15 @@ export function sseResponse(c: Context, start: (ch: SseChannel) => void): Respon
start(ch);
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
c.req.raw.signal.addEventListener('abort', teardown);
shutdown?.addEventListener('abort', teardown, { once: true });
cleanups.push(() => {
c.req.raw.signal.removeEventListener('abort', teardown);
shutdown?.removeEventListener('abort', teardown);
});
if (shutdown?.aborted) {
teardown();
}
},
});
return new Response(stream, {
+38
View File
@@ -0,0 +1,38 @@
import { Hono } from 'hono';
import type { HttpBindings } from '@hono/node-server';
import type { UpdateService } from '../update/service';
export function updateRoutes(service: UpdateService, restart: () => void) {
const app = new Hono<{ Bindings: HttpBindings }>();
app.get('/status', (c) => c.json(service.status()));
app.post('/download', async (c) => {
let body: unknown;
try {
body = await c.req.json();
} catch {
return c.json({ message: '请求必须是 JSON 对象' }, 400);
}
if (!body || typeof body !== 'object' || !('version' in body)) {
return c.json({ message: '缺少更新版本' }, 400);
}
try {
service.start(body.version);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
app.post('/restart', (c) => {
try {
service.restart();
c.env.outgoing.once('finish', restart);
return c.json(service.status(), 202);
} catch (error) {
return c.json({ message: error instanceof Error ? error.message : String(error) }, 409);
}
});
return app;
}
@@ -0,0 +1,37 @@
import { mkdir, writeFile } from 'node:fs/promises';
import path from 'node:path';
import type { ReleaseManifest } from '../../src/update/files';
export async function releaseFixture(
root: string,
version: string,
target = 'win32-x64',
chunk = 'chunk.mjs',
): Promise<ReleaseManifest> {
const entries = [
'index.mjs',
'app.mjs',
chunk,
'native',
'client',
'package.json',
'release.json',
'EULA.md',
'PRIVACY.md',
'check-node-version.cjs',
target.startsWith('win32') ? 'launcher.bat' : 'launcher.sh',
];
const manifest = { version, target, entries };
await mkdir(path.join(root, 'native'), { recursive: true });
await mkdir(path.join(root, 'client'), { recursive: true });
for (const file of entries.filter((entry) => !['native', 'client'].includes(entry))) {
await writeFile(path.join(root, file), version);
}
await writeFile(path.join(root, 'native', 'binding.node'), version);
await writeFile(path.join(root, 'client', 'index.html'), version);
await writeFile(path.join(root, 'package.json'), JSON.stringify({ version }));
await writeFile(path.join(root, 'release.json'), JSON.stringify(manifest));
return manifest;
}
+19
View File
@@ -7,6 +7,25 @@ function fakeCtx(signal: AbortSignal): Parameters<typeof sseResponse>[0] {
}
describe('sseResponse', () => {
it('finishes active streams and releases subscriptions during server shutdown', async () => {
const request = new AbortController();
const shutdown = new AbortController();
let cleanups = 0;
const response = sseResponse(
fakeCtx(request.signal),
(channel) => {
channel.onClose(() => {
cleanups++;
});
},
shutdown.signal,
);
const reader = response.body!.getReader();
shutdown.abort();
expect(await reader.read()).toEqual({ done: true, value: undefined });
request.abort();
expect(cleanups).toBe(1);
});
it('returns an event-stream Response with the SSE headers', () => {
const ac = new AbortController();
const res = sseResponse(fakeCtx(ac.signal), () => {
@@ -0,0 +1,46 @@
import { access, mkdtemp, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { updateDirectory } from '../src/update/files';
vi.mock('node:fs/promises', async (original) => {
const actual = await original<typeof import('node:fs/promises')>();
return { ...actual, access: vi.fn(actual.access) };
});
let root: string;
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-directory-test-'));
});
afterEach(async () => {
vi.mocked(access).mockReset();
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
vi.mocked(access).mockImplementation(actual.access);
await rm(root, { recursive: true, force: true });
});
describe('update staging directory', () => {
it('isolates installations and reuses their staging directory', async () => {
const directory = await updateDirectory(path.join(root, 'app'), root);
expect(path.dirname(directory)).toBe(root);
expect(await updateDirectory(path.join(root, 'app'), root)).toBe(directory);
expect(await updateDirectory(path.join(root, 'other'), root)).not.toBe(directory);
});
it('uses local tmp when system tmp is not writable and keeps it discoverable', async () => {
vi.mocked(access).mockRejectedValueOnce(
Object.assign(new Error('denied'), { code: 'EACCES' }),
);
const directory = await updateDirectory(root, root);
expect(directory).toBe(path.join(root, 'tmp', 'update'));
expect(await updateDirectory(root, root)).toBe(directory);
});
it('surfaces unexpected filesystem failures', async () => {
vi.mocked(access).mockRejectedValueOnce(
Object.assign(new Error('I/O failure'), { code: 'EIO' }),
);
await expect(updateDirectory(root, root)).rejects.toThrow('I/O failure');
});
});
+140
View File
@@ -0,0 +1,140 @@
import { createHash } from 'node:crypto';
import { mkdtemp, readFile, readdir, rm } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { zipSync } from 'fflate';
import { c as createTar } from 'tar';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { archivePath, assetName, downloadUpdate } from '../src/update/download';
import { readManifest } from '../src/update/files';
import { releaseFixture } from './helpers/update-fixture';
let root: string;
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-download-test-'));
});
afterEach(async () => {
vi.unstubAllGlobals();
await rm(root, { recursive: true, force: true });
});
function mockRelease(bytes: Uint8Array, target: string, digest?: string) {
const name = assetName('2.0.0', target);
const url = `https://github.com/SnowLuma/SnowLuma/releases/download/v2.0.0/${name}`;
const fetchMock = vi.fn(async (input: string | URL | Request) => {
if (String(input).startsWith('https://api.github.com/')) {
return Response.json({
assets: [
{
name,
size: bytes.length,
digest:
digest ?? `sha256:${createHash('sha256').update(bytes).digest('hex')}`,
},
],
});
}
expect(input).toBe(url);
return new Response(new Uint8Array(bytes));
});
vi.stubGlobal('fetch', fetchMock);
return fetchMock;
}
describe('release downloads', () => {
it.each(['win32-x64', 'linux-x64', 'linux-arm64'])(
'downloads and validates the %s lite package',
async (target) => {
const source = path.join(root, 'source');
await releaseFixture(source, '2.0.0', target);
let bytes: Uint8Array;
if (target === 'win32-x64') {
const files: Record<string, Uint8Array> = {};
const scan = async (directory: string) => {
for (const entry of await readdir(directory, { withFileTypes: true })) {
const file = path.join(directory, entry.name);
if (entry.isDirectory()) {
await scan(file);
} else {
files[path.relative(source, file).replaceAll('\\', '/')] =
await readFile(file);
}
}
};
await scan(source);
bytes = zipSync(files);
} else {
const archive = path.join(root, 'fixture.tar.gz');
await createTar({ file: archive, cwd: source, gzip: true }, ['.']);
bytes = await readFile(archive);
}
mockRelease(bytes, target);
await downloadUpdate(root, '2.0.0', target);
expect((await readManifest(path.join(root, 'payload'))).target).toBe(target);
expect(await readFile(path.join(root, 'payload/client/index.html'), 'utf8')).toBe(
'2.0.0',
);
},
);
it('rejects a digest mismatch before extracting', async () => {
mockRelease(
new TextEncoder().encode('bad archive'),
'win32-x64',
`sha256:${'0'.repeat(64)}`,
);
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('校验失败');
expect(await readdir(root)).toEqual(['archive']);
});
it('rejects path traversal in a zip before writing payload files', async () => {
mockRelease(zipSync({ '../outside': new Uint8Array([1]) }), 'win32-x64');
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('路径无效');
expect(await readdir(path.join(root, 'payload'))).toEqual([]);
});
it('reports HTTP failures', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => new Response('rate limited', { status: 403 })),
);
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow('GitHub 403');
});
it.each([
'../data',
'/app.mjs',
'native/../../data',
'native/../data',
'native/C:evil',
'native\\..\\data',
'config/runtime.json',
])('rejects unsafe archive path %s', (name) => {
expect(() => archivePath(name)).toThrow('路径无效');
});
it('accepts the root-relative layout used by Linux release archives', () => {
expect(archivePath('./')).toBe('');
expect(archivePath('./native/binding.node')).toBe('native/binding.node');
});
it.each([
['1.0.0', 'win32-x64'],
['2.0.0', 'linux-x64'],
])('rejects a package for version %s and target %s', async (version, target) => {
const manifest = await releaseFixture(path.join(root, 'source'), version, target);
const bytes = zipSync({
'release.json': new TextEncoder().encode(JSON.stringify(manifest)),
});
mockRelease(bytes, 'win32-x64');
await expect(downloadUpdate(root, '2.0.0', 'win32-x64')).rejects.toThrow(
'版本或平台不匹配',
);
});
});
+194
View File
@@ -0,0 +1,194 @@
import { spawn } from 'node:child_process';
import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { builtinModules } from 'node:module';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { build, loadConfigFromFile } from 'vite';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { exists, updateDirectory } from '../src/update/files';
import { releaseFixture } from './helpers/update-fixture';
let compiled: string;
let root: string;
let staging: string;
beforeAll(async () => {
compiled = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-build-'));
const loaded = await loadConfigFromFile(
{ command: 'build', mode: 'production' },
fileURLToPath(new URL('../vite.config.ts', import.meta.url)),
);
if (!loaded) {
throw new Error('missing core build config');
}
const config = loaded.config;
const startup = fileURLToPath(new URL('../src/update/startup.ts', import.meta.url)).replaceAll(
'\\',
'/',
);
const files = fileURLToPath(new URL('../src/update/files.ts', import.meta.url)).replaceAll(
'\\',
'/',
);
const fixture = path.join(compiled, 'fixture.ts').replaceAll('\\', '/');
await writeFile(fixture, '');
for (const version of ['1.0.0', '2.0.0']) {
let loadedFixture = false;
await build({
...config,
configFile: false,
logLevel: 'silent',
plugins: [
{
name: 'fixture-application',
enforce: 'pre',
load(id) {
if (id.replaceAll('\\', '/') !== fixture) {
return null;
}
loadedFixture = true;
return `
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { RESTART_EXIT_CODE, runApplication } from '${startup}';
import { updateDirectory } from '${files}';
const root = path.dirname(fileURLToPath(import.meta.url));
if (!process.env.SNOWLUMA_UPDATE_ROOT) {
await runApplication(root);
} else {
const version = '${version}';
if (process.env.UPDATE_TEST_MODE === 'restart' && version === '1.0.0') {
const staging = await updateDirectory(root);
fs.cpSync(path.join(root, 'candidate'), path.join(staging, 'pending'), {recursive:true});
fs.writeFileSync(path.join(root, 'old-pid'), String(process.pid));
process.exit(RESTART_EXIT_CODE);
}
if (process.env.UPDATE_TEST_MODE === 'fail') {
console.error('startup failed');
process.exit(1);
}
let oldAlive = false;
if (process.platform === 'win32' && fs.existsSync(path.join(root, 'old-pid'))) {
try { process.kill(Number(fs.readFileSync(path.join(root, 'old-pid'), 'utf8')), 0); oldAlive = true; }
catch (error) { if (error.code !== 'ESRCH') throw error; }
}
console.log(JSON.stringify({version, node:process.execPath, cwd:process.cwd(), args:process.argv.slice(2), oldAlive}));
process.exit(0);
}
`;
},
generateBundle(_options, bundle) {
expect(loadedFixture).toBe(true);
const entry = bundle['index.mjs'];
expect(entry.type).toBe('chunk');
if (entry.type !== 'chunk') {
throw new Error('missing entry');
}
expect(
entry.imports.filter(
(id) => !builtinModules.includes(id) && !id.startsWith('node:'),
),
).toEqual([]);
expect(entry.dynamicImports).toEqual([]);
},
},
],
build: {
...config.build,
outDir: path.join(compiled, version),
lib: { entry: { index: fixture }, formats: ['es'], fileName: () => 'index.mjs' },
},
});
}
});
afterAll(async () => {
await rm(compiled, { recursive: true, force: true });
});
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-entry-test-'));
staging = await updateDirectory(root);
await releaseFixture(root, '1.0.0');
await cp(path.join(compiled, '1.0.0/index.mjs'), path.join(root, 'index.mjs'));
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
await rm(staging, { recursive: true, force: true });
});
function run(mode = '', args: string[] = []) {
return new Promise<{ code: number | null; output: string }>((resolve, reject) => {
const child = spawn(process.execPath, [path.join(root, 'index.mjs'), ...args], {
cwd: os.tmpdir(),
stdio: 'pipe',
windowsHide: true,
env: { ...process.env, UPDATE_TEST_MODE: mode },
});
let output = '';
child.stdout.on('data', (data: Buffer) => {
output += data.toString();
});
child.stderr.on('data', (data: Buffer) => {
output += data.toString();
});
child.once('error', reject);
child.once('close', (code) => {
resolve({ code, output });
});
});
}
async function candidate(directory: string) {
await releaseFixture(path.join(directory, 'payload'), '2.0.0');
await cp(path.join(compiled, '2.0.0/index.mjs'), path.join(directory, 'payload/index.mjs'));
}
describe('packaged startup', () => {
it('preserves the exact Node executable, arguments and working directory', async () => {
const result = await run('', ['value with spaces']);
expect(result.code, result.output).toBe(0);
expect(JSON.parse(result.output)).toEqual({
version: '1.0.0',
node: process.execPath,
cwd: os.tmpdir(),
args: ['value with spaces'],
oldAlive: false,
});
});
it('waits for the old process to exit, applies the release, then executes the new code', async () => {
await candidate(path.join(root, 'candidate'));
const result = await run('restart', ['kept']);
expect(result.code, result.output).toBe(0);
expect(result.output).toContain('已更新至 v2.0.0');
expect(JSON.parse(result.output.trim().split('\n').at(-1)!)).toMatchObject({
version: '2.0.0',
args: ['kept'],
oldAlive: false,
});
expect(JSON.parse(await readFile(path.join(root, 'release.json'), 'utf8')).version).toBe(
'2.0.0',
);
expect(await exists(staging)).toBe(false);
});
it('applies an already staged update on ordinary startup', async () => {
await candidate(path.join(staging, 'pending'));
const result = await run();
expect(result.code, result.output).toBe(0);
expect(result.output).toContain('"version":"2.0.0"');
expect(result.output).not.toContain('"version":"1.0.0"');
});
it('propagates an application failure without restarting it', async () => {
expect(await run('fail')).toEqual({ code: 1, output: 'startup failed\n' });
});
});
+184
View File
@@ -0,0 +1,184 @@
import * as fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { applyPendingUpdate, exists, readManifest, updateDirectory } from '../src/update/files';
import { releaseFixture } from './helpers/update-fixture';
vi.mock('node:fs/promises', async (original) => {
const actual = await original<typeof import('node:fs/promises')>();
return { ...actual, rename: vi.fn(actual.rename) };
});
let root: string;
let staging: string;
beforeEach(async () => {
root = await fs.mkdtemp(path.join(os.tmpdir(), 'snowluma-update-test-'));
await releaseFixture(root, '1.0.0', 'win32-x64', 'old.mjs');
staging = await updateDirectory(root);
await releaseFixture(path.join(staging, 'pending/payload'), '2.0.0', 'win32-x64', 'new.mjs');
});
afterEach(async () => {
vi.mocked(fs.rename).mockReset();
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
vi.mocked(fs.rename).mockImplementation(actual.rename);
await fs.rm(root, { recursive: true, force: true });
await fs.rm(staging, { recursive: true, force: true });
});
describe('staged updates', () => {
it('stages outside the installation and only renames replacements on the destination filesystem', async () => {
expect(path.dirname(staging)).toBe(os.tmpdir());
expect(staging.startsWith(root + path.sep)).toBe(false);
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
vi.mocked(fs.rename).mockImplementation(async (source, destination) => {
if (
path.dirname(String(destination)) === root &&
path.dirname(String(source)) !== root
) {
throw Object.assign(new Error('cross-device rename'), { code: 'EXDEV' });
}
return actual.rename(source, destination);
});
expect(await applyPendingUpdate(root)).toBe('2.0.0');
expect(await exists(path.join(root, '.update-install'))).toBe(false);
expect(await exists(staging)).toBe(false);
});
it('rejects an entry point replaced by a directory before touching the installed entry point', async () => {
const entry = path.join(staging, 'pending/payload/index.mjs');
await fs.rm(entry);
await fs.mkdir(entry);
await expect(applyPendingUpdate(root)).rejects.toThrow('文件类型无效');
expect(await fs.readFile(path.join(root, 'index.mjs'), 'utf8')).toBe('1.0.0');
});
it('cleans a download interrupted before staging', async () => {
await fs.mkdir(path.join(staging, 'downloading'));
await fs.writeFile(path.join(staging, 'downloading/archive'), 'partial');
await fs.rm(path.join(staging, 'pending'), { recursive: true });
expect(await applyPendingUpdate(root)).toBeNull();
expect(await exists(staging)).toBe(false);
});
it('replaces program files, removes obsolete chunks and preserves user data and Node', async () => {
for (const file of [
'config/runtime.json',
'data/messages.db',
'logs/current.log',
'tmp/unrelated',
'node.exe',
'custom.mjs',
]) {
await fs.mkdir(path.dirname(path.join(root, file)), { recursive: true });
await fs.writeFile(path.join(root, file), 'keep');
}
expect(await applyPendingUpdate(root)).toBe('2.0.0');
expect((await readManifest(root)).version).toBe('2.0.0');
expect(await fs.readFile(path.join(root, 'native/binding.node'), 'utf8')).toBe('2.0.0');
expect(await exists(path.join(root, 'old.mjs'))).toBe(false);
expect(await exists(path.join(root, 'new.mjs'))).toBe(true);
for (const file of [
'config/runtime.json',
'data/messages.db',
'logs/current.log',
'tmp/unrelated',
'node.exe',
'custom.mjs',
]) {
expect(await fs.readFile(path.join(root, file), 'utf8')).toBe('keep');
}
expect(await fs.readdir(path.join(root, 'tmp'))).toEqual(['unrelated']);
expect(await applyPendingUpdate(root)).toBeNull();
});
it('only installs files declared by the release manifest', async () => {
await fs.writeFile(path.join(staging, 'pending/payload/unlisted.mjs'), 'ignored');
expect(await applyPendingUpdate(root)).toBe('2.0.0');
expect(await exists(path.join(root, 'unlisted.mjs'))).toBe(false);
});
it('restores the entire old release after a replacement fails, then retries on next startup', async () => {
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises');
let failed = false;
vi.mocked(fs.rename).mockImplementation(async (source, destination) => {
if (!failed && destination === path.join(root, 'client')) {
failed = true;
throw new Error('file locked');
}
return actual.rename(source, destination);
});
await expect(applyPendingUpdate(root)).rejects.toThrow('file locked');
expect((await readManifest(root)).version).toBe('1.0.0');
expect(await fs.readFile(path.join(root, 'app.mjs'), 'utf8')).toBe('1.0.0');
expect(await fs.readFile(path.join(root, 'client/index.html'), 'utf8')).toBe('1.0.0');
expect(await exists(path.join(root, 'new.mjs'))).toBe(false);
expect(await exists(path.join(staging, 'pending/payload'))).toBe(true);
await expect(applyPendingUpdate(root)).resolves.toBe('2.0.0');
});
it('recovers an interrupted transaction before retrying', async () => {
const current = await readManifest(root);
const next = await readManifest(path.join(staging, 'pending/payload'));
const backup = path.join(staging, 'pending/backup');
await fs.mkdir(backup);
for (const entry of current.entries) {
await fs.cp(path.join(root, entry), path.join(backup, entry), { recursive: true });
}
await fs.writeFile(
path.join(staging, 'pending/transaction.json'),
JSON.stringify({
entries: [...new Set([...current.entries, ...next.entries])],
original: current.entries,
}),
);
await fs.writeFile(path.join(root, 'app.mjs'), 'interrupted');
await fs.rm(path.join(root, 'native'), { recursive: true });
await fs.writeFile(path.join(root, 'new.mjs'), 'partial');
// Fail before installation so we can inspect the recovered release.
const entry = path.join(staging, 'pending/payload/index.mjs');
await fs.rm(entry);
await fs.mkdir(entry);
await expect(applyPendingUpdate(root)).rejects.toThrow('文件类型无效');
expect(await fs.readFile(path.join(root, 'index.mjs'), 'utf8')).toBe('1.0.0');
expect(await fs.readFile(path.join(root, 'app.mjs'), 'utf8')).toBe('1.0.0');
expect(await fs.readFile(path.join(root, 'native/binding.node'), 'utf8')).toBe('1.0.0');
expect(await exists(path.join(root, 'new.mjs'))).toBe(false);
await fs.rm(entry, { recursive: true });
await fs.writeFile(entry, '2.0.0');
expect(await applyPendingUpdate(root)).toBe('2.0.0');
});
it('cleans an already committed transaction without restoring its backup', async () => {
await fs.rename(path.join(staging, 'pending'), path.join(staging, 'completed'));
expect(await applyPendingUpdate(root)).toBeNull();
expect(await exists(staging)).toBe(false);
});
it.each(['config', '../outside', 'node.exe', 'data', 'C:/outside'])(
'rejects a manifest owning %s',
async (entry) => {
const payload = path.join(staging, 'pending/payload');
const manifest = await readManifest(payload);
manifest.entries.push(entry);
await fs.writeFile(path.join(payload, 'release.json'), JSON.stringify(manifest));
await expect(applyPendingUpdate(root)).rejects.toThrow('清单无效');
expect((await readManifest(root)).version).toBe('1.0.0');
},
);
it('rejects a release for a different platform before replacing anything', async () => {
const payload = path.join(staging, 'pending/payload');
await fs.rm(payload, { recursive: true });
await releaseFixture(payload, '2.0.0', 'linux-x64');
await expect(applyPendingUpdate(root)).rejects.toThrow('平台不匹配');
expect((await readManifest(root)).version).toBe('1.0.0');
});
});
+120
View File
@@ -0,0 +1,120 @@
import { updateDirectory } from '../src/update/files';
import { EventEmitter } from 'node:events';
import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createUpdateService } from '../src/update/service';
import { updateRoutes } from '../src/webui/update-routes';
import { releaseFixture } from './helpers/update-fixture';
let root: string;
let staging: string;
beforeEach(async () => {
root = await mkdtemp(path.join(os.tmpdir(), 'snowluma-update-service-'));
await releaseFixture(root, '1.0.0');
staging = await updateDirectory(root);
});
afterEach(async () => {
vi.unstubAllEnvs();
await rm(root, { recursive: true, force: true });
await rm(staging, { recursive: true, force: true });
});
describe('update service', () => {
it('stages a single download, survives a service reload and leaves running files alone', async () => {
let finish!: () => void;
const wait = new Promise<void>((resolve) => {
finish = resolve;
});
const download = vi.fn(async (directory: string, version: string, target: string) => {
await wait;
await releaseFixture(path.join(directory, 'payload'), version, target);
await writeFile(path.join(directory, 'archive'), 'archive');
});
const service = await createUpdateService(root, '1.0.0', { download, isContainer: false });
service.start('2.0.0');
expect(service.status()).toEqual({
current: '1.0.0',
phase: 'downloading',
version: '2.0.0',
});
expect(() => service.start('2.0.0')).toThrow('正在进行');
finish();
await vi.waitFor(() => expect(service.status().phase).toBe('ready'));
expect(download).toHaveBeenCalledOnce();
expect(await readdir(path.join(staging, 'pending'))).toEqual(['payload']);
const reloaded = await createUpdateService(root, '1.0.0', { download, isContainer: false });
expect(reloaded.status()).toEqual({ current: '1.0.0', phase: 'ready', version: '2.0.0' });
reloaded.restart();
expect(reloaded.status().phase).toBe('restarting');
expect(() => reloaded.restart()).toThrow('尚未就绪');
});
it('cleans a failed download and allows retry', async () => {
const download = vi.fn(async (directory: string) => {
await writeFile(path.join(directory, 'archive'), 'partial');
throw new Error('connection reset');
});
const service = await createUpdateService(root, '1.0.0', { download, isContainer: false });
service.start('2.0.0');
await vi.waitFor(() =>
expect(service.status()).toEqual({
current: '1.0.0',
phase: 'error',
message: 'connection reset',
}),
);
expect(await readdir(staging)).toEqual([]);
expect(() => service.start('2.0.0')).not.toThrow();
await vi.waitFor(() => expect(download).toHaveBeenCalledTimes(2));
await vi.waitFor(() => expect(service.status().phase).toBe('error'));
});
it.each(['1.0.0', '0.9.0', '2.0.0-rc.1', '../../outside', null])(
'rejects invalid or older version %s',
async (version) => {
const download = vi.fn();
const service = await createUpdateService(root, '1.0.0', {
download,
isContainer: false,
});
expect(() => service.start(version)).toThrow('正式版本');
expect(download).not.toHaveBeenCalled();
},
);
it('does not enable updates for a source checkout', async () => {
const service = await createUpdateService(undefined, '1.0.0');
expect(service.status().phase).toBe('unavailable');
expect(() => service.start('2.0.0')).toThrow('发行包');
expect(() => service.restart()).toThrow('尚未就绪');
});
it('does not update container image layers', async () => {
const service = await createUpdateService(root, '1.0.0', { isContainer: true });
expect(service.status()).toMatchObject({ phase: 'unavailable', message: '请更新容器镜像' });
});
it('restarts only after the HTTP response has finished', async () => {
await releaseFixture(path.join(staging, 'pending/payload'), '2.0.0');
const service = await createUpdateService(root, '1.0.0', { isContainer: false });
const restart = vi.fn();
const outgoing = new EventEmitter();
const app = updateRoutes(service, restart);
const response = await app.request('/restart', { method: 'POST' }, { outgoing });
expect(response.status).toBe(202);
expect(await response.json()).toMatchObject({ phase: 'restarting' });
expect(restart).not.toHaveBeenCalled();
outgoing.emit('finish');
expect(restart).toHaveBeenCalledOnce();
});
it.each(['{}', 'not json'])('rejects an invalid download request: %s', async (body) => {
const service = await createUpdateService(root, '1.0.0', { isContainer: false });
const app = updateRoutes(service, vi.fn());
const response = await app.request('/download', { method: 'POST', body });
expect(response.status).toBe(400);
expect(service.status().phase).toBe('idle');
});
});
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { compareVersions, currentVersion, getUpdateInfo } from '../src/webui/update-check';
import { compareVersions, getUpdateInfo } from '../src/update/check';
const LATEST_RELEASE_URL = 'https://api.github.com/repos/SnowLuma/SnowLuma/releases/latest';
const NOTES_MAX = 4_000;
@@ -44,11 +44,7 @@ afterEach(() => {
}
});
describe('currentVersion', () => {
it('falls back to 0.0.0 when the build-time version is unset', () => {
expect(currentVersion()).toBe('0.0.0');
});
});
vi.mock('@snowluma/common/version', () => ({ APP_VERSION: '0.0.0' }));
describe('compareVersions', () => {
it.each([
+48 -11
View File
@@ -6,6 +6,8 @@ import { fileURLToPath } from 'url';
import { defineConfig, PluginOption, UserConfig } from 'vite';
import cp from 'vite-plugin-cp';
import { sqliteBuildPlugin } from '@snowluma/sqlite/vite';
import { APP_VERSION } from '@snowluma/common/version';
import runtimePackage from '../runtime/package.json' with { type: 'json' };
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
@@ -13,11 +15,6 @@ const distDir = path.resolve(repoRoot, 'dist');
const runtimeDir = path.resolve(repoRoot, 'packages', 'runtime');
const nativeDir = path.resolve(runtimeDir, 'native');
// Single source of truth for the user-facing app version: monorepo root package.json.
const rootPkg = JSON.parse(fs.readFileSync(path.resolve(repoRoot, 'package.json'), 'utf-8')) as {
version: string;
};
// vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators.
const toPosix = (p: string) => p.replace(/\\/g, '/');
@@ -38,10 +35,10 @@ const [targetPlatform, targetArch] = targetTriple.split('-');
// Runtime scaffolding files copied into dist/. Windows and Linux use different
// launchers, while both targets ship their matching QQ integration binaries.
const runtimeDistFiles = [
'package.json',
'check-node-version.cjs',
targetPlatform === 'win32' ? 'launcher.bat' : 'launcher.sh',
];
const agreementFiles = ['EULA.md', 'PRIVACY.md'];
// Native binaries shipped for the selected target:
// * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux).
@@ -82,9 +79,7 @@ if (missingNatives.length > 0) {
// Legal docs are served by the WebUI consent gate; a missing one would silently
// disable consent in the shipped build, so fail the build instead (mirrors the
// native-binary guard above).
const missingAgreements = ['EULA.md', 'PRIVACY.md'].filter(
(f) => !fs.existsSync(path.resolve(repoRoot, f)),
);
const missingAgreements = agreementFiles.filter((f) => !fs.existsSync(path.resolve(repoRoot, f)));
if (missingAgreements.length > 0) {
throw new Error(
@@ -94,6 +89,46 @@ if (missingAgreements.length > 0) {
}
const BaseConfigPlugin: PluginOption[] = [
{
name: 'release-metadata',
generateBundle(_options, bundle) {
const entry = bundle['index.mjs'];
if (entry?.type !== 'chunk' || entry.imports.some((id) => !nodeModules.includes(id))) {
this.error('The update entry must only import Node builtins.');
}
this.emitFile({
type: 'asset',
fileName: 'package.json',
source: JSON.stringify({ ...runtimePackage, version: APP_VERSION }, null, 2) + '\n',
});
if (process.env.BUILD_WEBUI === 'true') {
const entries = [
...new Set([
...Object.keys(bundle).map((file) => file.split('/')[0]),
...runtimeDistFiles,
...agreementFiles,
'native',
'client',
'package.json',
'release.json',
]),
].sort();
this.emitFile({
type: 'asset',
fileName: 'release.json',
source:
JSON.stringify(
{ version: APP_VERSION, target: targetTriple, entries },
null,
2,
) + '\n',
});
}
},
},
// Proton substitutes every `protobuf_encode<T>` / `protobuf_decode<T>`
// call site with a monomorphized codec at build time. WITHOUT this
// plugin in the plugins array the runtime fallback in
@@ -122,7 +157,7 @@ const BaseConfigPlugin: PluginOption[] = [
},
// Legal docs served verbatim by the WebUI consent gate. Copied next to
// the bundle so consent.ts's path probe finds them in a packaged deploy.
...['EULA.md', 'PRIVACY.md'].map((file) => ({
...agreementFiles.map((file) => ({
src: toPosix(path.resolve(repoRoot, file)),
dest: distDir,
flatten: true,
@@ -153,6 +188,8 @@ const BaseConfig = (source_map: boolean = false) =>
rollupOptions: {
external: nodeModules,
output: {
// Keep recovery runnable while an interrupted update is being restored.
codeSplitting: false,
// Bundled CommonJS dependencies still need Node's native require.
banner: [
"import { createRequire as __snowlumaCreateRequire } from 'node:module';",
@@ -167,7 +204,7 @@ const BaseConfig = (source_map: boolean = false) =>
},
define: {
__BUILD_WEBUI__: process.env.BUILD_WEBUI === 'true',
__APP_VERSION__: JSON.stringify(rootPkg.version),
__PACKAGED__: true,
},
});