diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index 88e7fc3c..c6b48829 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -136,13 +136,6 @@ jobs: SNOWLUMA_TARGET: ${{ matrix.target }} run: pnpm run build:all - # Bundle production node_modules into dist/ before packaging — mirrors - # release.yml. Without this the `-lite` tarball has no runtime deps and the - # Docker image (which bakes the lite tarball) can't start. - - name: Bundle runtime dependencies - working-directory: dist - run: npm install --omit=dev - - name: Verify release layout run: pnpm check:release-layout diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5ddd8ea2..d4120689 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -85,10 +85,6 @@ jobs: SNOWLUMA_TARGET: ${{ matrix.target }} run: pnpm run build:all - - name: Bundle runtime dependencies - working-directory: dist - run: npm install --omit=dev - - name: Verify release layout run: pnpm check:release-layout diff --git a/AGENTS.md b/AGENTS.md index f8ccc63b..5df5519c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,6 +33,10 @@ This is a pnpm workspace. Package ownership matters more than directory names: `packages/bridge` owns process connectivity; the account-level Bridge lives in `packages/core/src/bridge`. Start at [the application entry](packages/core/src/index.ts) to follow their composition. +[The entry point](packages/core/src/index.ts) applies pending updates before starting runtime services. [The updater](packages/core/src/update) owns staging and replacement; [Core's build configuration](packages/core/vite.config.ts) emits the release manifest from its build outputs and runtime assets. Keep Core in one bundle and native libraries lazy-loaded so startup can recover an interrupted update before opening native files. + +Application versions come from the root `package.json` through `@snowluma/common/version`. Use `pnpm bump ` to update workspace manifests, or `pnpm bump` to sync them after editing the root version. + Read the relevant owner before changing a path: | Change | Start here | diff --git a/README.md b/README.md index 7632816f..fe5c7d9d 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生 ## 快速开始 -1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 22.13+(23 系需 23.4+)。 +1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载对应平台的完整发行包并解压。Lite 版需 Node.js 24+。 2. Windows 运行 `launcher.bat`;Linux 执行: ```bash @@ -53,6 +53,8 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生 3. 打开 [`http://localhost:5099`](http://localhost:5099),使用启动日志中的初始密码登录 WebUI,按引导接入 QQ 进程并配置 OneBot 连接。 +在「设置 → 关于 → 软件更新」下载新版本,再点「重启更新」。文件优先暂存于系统临时目录,不可用时使用安装目录的 `tmp/update`,下次启动时替换并清理,配置、日志与消息数据保留。更新沿用当前 Node.js;容器部署请更新镜像。 + ## 接入与文档 | 入口 | 文档 | @@ -65,7 +67,7 @@ JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非 ## 开发 -需要 Node.js 22.13+(23 系需 23.4+)与 pnpm 10.28.0,日常开发基于 `dev` 分支: +需要 Node.js 24+ 与 pnpm 11.25.0,日常开发基于 `dev` 分支: ```bash git clone https://github.com/SnowLuma/SnowLuma.git diff --git a/packages/common/package.json b/packages/common/package.json index 4d0243dd..10841f8d 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -8,6 +8,10 @@ "main": "./src/index.ts", "types": "./src/index.ts", "exports": { + "./version": { + "types": "./src/version.ts", + "default": "./src/version.ts" + }, ".": { "types": "./src/index.ts", "default": "./src/index.ts" diff --git a/packages/common/src/version.ts b/packages/common/src/version.ts new file mode 100644 index 00000000..4a8f75e1 --- /dev/null +++ b/packages/common/src/version.ts @@ -0,0 +1,3 @@ +import manifest from '../../../package.json' with { type: 'json' }; + +export const APP_VERSION = manifest.version; diff --git a/packages/core/package.json b/packages/core/package.json index 76c7e631..5208aeda 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -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", diff --git a/packages/core/src/env.d.ts b/packages/core/src/env.d.ts index 32800b0b..2889cd7c 100644 --- a/packages/core/src/env.d.ts +++ b/packages/core/src/env.d.ts @@ -1,2 +1,2 @@ declare const __BUILD_WEBUI__: boolean; -declare const __APP_VERSION__: string; +declare const __PACKAGED__: boolean; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b4c5a6af..d37fc34e 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -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) => { diff --git a/packages/core/src/native-stage-sync.ts b/packages/core/src/native-stage-sync.ts index 6cc46eee..9c2a45e9 100644 --- a/packages/core/src/native-stage-sync.ts +++ b/packages/core/src/native-stage-sync.ts @@ -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; diff --git a/packages/core/src/webui/update-check.ts b/packages/core/src/update/check.ts similarity index 87% rename from packages/core/src/webui/update-check.ts rename to packages/core/src/update/check.ts index 0749d5ee..5396ee01 100644 --- a/packages/core/src/webui/update-check.ts +++ b/packages/core/src/update/check.ts @@ -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 { * are not cached so the next check retries. */ export async function getUpdateInfo(force = false): Promise { - const current = currentVersion(); + const current = APP_VERSION; if (!isEnabled()) { return { ...emptyResult(current), error: 'disabled' }; diff --git a/packages/core/src/update/download.ts b/packages/core/src/update/download.ts new file mode 100644 index 00000000..97b19c92 --- /dev/null +++ b/packages/core/src/update/download.ts @@ -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 { + 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 { + 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('更新包版本或平台不匹配'); + } +} diff --git a/packages/core/src/update/files.ts b/packages/core/src/update/files.ts new file mode 100644 index 00000000..e9a2938e --- /dev/null +++ b/packages/core/src/update/files.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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; +} diff --git a/packages/core/src/update/service.ts b/packages/core/src/update/service.ts new file mode 100644 index 00000000..1e854993 --- /dev/null +++ b/packages/core/src/update/service.ts @@ -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 => { + 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>; diff --git a/packages/core/src/update/startup.ts b/packages/core/src/update/startup.ts new file mode 100644 index 00000000..11a3f8b8 --- /dev/null +++ b/packages/core/src/update/startup.ts @@ -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 { + let stopping = false; + let child: ReturnType | 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((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; + } +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index e6447c55..99c68f08 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -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 }> { 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) => + 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((resolve, reject) => { listeningServer.close((err) => (err ? reject(err) : resolve())); }); diff --git a/packages/core/src/webui/sse-response.ts b/packages/core/src/webui/sse-response.ts index 94e3448c..d4a0c5e6 100644 --- a/packages/core/src/webui/sse-response.ts +++ b/packages/core/src/webui/sse-response.ts @@ -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({ 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, { diff --git a/packages/core/src/webui/update-routes.ts b/packages/core/src/webui/update-routes.ts new file mode 100644 index 00000000..984bb8cf --- /dev/null +++ b/packages/core/src/webui/update-routes.ts @@ -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; +} diff --git a/packages/core/tests/helpers/update-fixture.ts b/packages/core/tests/helpers/update-fixture.ts new file mode 100644 index 00000000..4a2cae56 --- /dev/null +++ b/packages/core/tests/helpers/update-fixture.ts @@ -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 { + 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; +} diff --git a/packages/core/tests/sse-response.test.ts b/packages/core/tests/sse-response.test.ts index b6ed29b2..c6e97074 100644 --- a/packages/core/tests/sse-response.test.ts +++ b/packages/core/tests/sse-response.test.ts @@ -7,6 +7,25 @@ function fakeCtx(signal: AbortSignal): Parameters[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), () => { diff --git a/packages/core/tests/update-directory.test.ts b/packages/core/tests/update-directory.test.ts new file mode 100644 index 00000000..3250258a --- /dev/null +++ b/packages/core/tests/update-directory.test.ts @@ -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(); + 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('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'); + }); +}); diff --git a/packages/core/tests/update-download.test.ts b/packages/core/tests/update-download.test.ts new file mode 100644 index 00000000..7243abbb --- /dev/null +++ b/packages/core/tests/update-download.test.ts @@ -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 = {}; + + 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( + '版本或平台不匹配', + ); + }); +}); diff --git a/packages/core/tests/update-entry.test.ts b/packages/core/tests/update-entry.test.ts new file mode 100644 index 00000000..f14135c7 --- /dev/null +++ b/packages/core/tests/update-entry.test.ts @@ -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' }); + }); +}); diff --git a/packages/core/tests/update-files.test.ts b/packages/core/tests/update-files.test.ts new file mode 100644 index 00000000..c4092161 --- /dev/null +++ b/packages/core/tests/update-files.test.ts @@ -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(); + 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('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('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('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'); + }); +}); diff --git a/packages/core/tests/update-service.test.ts b/packages/core/tests/update-service.test.ts new file mode 100644 index 00000000..93a0f3ca --- /dev/null +++ b/packages/core/tests/update-service.test.ts @@ -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((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'); + }); +}); diff --git a/packages/core/tests/webui-update-check.test.ts b/packages/core/tests/webui-update-check.test.ts index b4609d6f..4b7f8535 100644 --- a/packages/core/tests/webui-update-check.test.ts +++ b/packages/core/tests/webui-update-check.test.ts @@ -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([ diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index ad3086a3..2a399dc0 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -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` / `protobuf_decode` // 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, }, }); diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index 2ff49f23..9eadeea3 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -1,9 +1,7 @@ +import { APP_VERSION } from '@snowluma/common/version'; import { defineAction } from '../action-kit'; import { okResponse } from '../types'; -// 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。 -const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev'; - export const actions = [ defineAction({ name: 'get_login_info', @@ -72,7 +70,7 @@ export const actions = [ run: () => { return okResponse({ app_name: 'SnowLuma', - app_version: `${appVersion}-node`, + app_version: `${APP_VERSION}-node`, protocol_version: 'v11', }); }, diff --git a/packages/onebot/src/env.d.ts b/packages/onebot/src/env.d.ts index 32800b0b..53e7e23f 100644 --- a/packages/onebot/src/env.d.ts +++ b/packages/onebot/src/env.d.ts @@ -1,2 +1 @@ declare const __BUILD_WEBUI__: boolean; -declare const __APP_VERSION__: string; diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 289aafd7..e1ab8f04 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -1,3 +1,4 @@ +import { APP_VERSION } from '@snowluma/common/version'; import { createLogger, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import { @@ -621,7 +622,7 @@ export class OneBotInstance { private async replyStatus(isGroup: boolean, sessionId: number): Promise { const text = buildStatusText({ - version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev', + version: APP_VERSION, platform: process.platform, arch: process.arch, uptimeMs: this.ctx.getUptimeMs(), diff --git a/packages/websocket/src/native.ts b/packages/websocket/src/native.ts index 7beada79..71a4d563 100644 --- a/packages/websocket/src/native.ts +++ b/packages/websocket/src/native.ts @@ -132,5 +132,22 @@ function tryLoad(): NativeAddon { } } -const addon: NativeAddon = tryLoad(); -export default addon; +let addon: NativeAddon | undefined; + +function getAddon(): NativeAddon { + return (addon ??= tryLoad()); +} + +const native: NativeAddon = { + get Parser() { + return getAddon().Parser; + }, + buildFrame(...args) { + return getAddon().buildFrame(...args); + }, + computeAcceptKey(key) { + return getAddon().computeAcceptKey(key); + }, +}; + +export default native; diff --git a/packages/websocket/tests/native.test.ts b/packages/websocket/tests/native.test.ts index f437fd9b..d47c0208 100644 --- a/packages/websocket/tests/native.test.ts +++ b/packages/websocket/tests/native.test.ts @@ -92,7 +92,9 @@ function restoreDevNoNative(): void { } async function loadNative(): Promise { - return (await import('../src/native')).default; + const addon = (await import('../src/native')).default; + void addon.Parser; + return addon; } function installFakeAddon(exports: NativeAddon): string[] { @@ -403,6 +405,17 @@ describe('addon path resolution', () => { afterEach(cleanupLoaderTest); + it('does not load a native library until first use, then caches it', async () => { + const opened = installFakeAddon(fakeAddon('lazy')); + existsSyncMock.mockReturnValue(true); + const addon = (await import('../src/native')).default; + expect(opened).toEqual([]); + expect(existsSyncMock).not.toHaveBeenCalled(); + expect(addon.computeAcceptKey(RFC_KEY)).toBe('lazy'); + expect(addon.computeAcceptKey(RFC_KEY)).toBe('lazy'); + expect(opened).toHaveLength(1); + }); + it('dlopens the first existing websocket--.node candidate', async () => { const opened = installFakeAddon(fakeAddon('from-first-hit')); const winner = candidatePaths()[2]!; diff --git a/packages/webui/README.md b/packages/webui/README.md index 586c1efb..af6baf26 100644 --- a/packages/webui/README.md +++ b/packages/webui/README.md @@ -68,6 +68,10 @@ account does not delay other accounts. ## Local development +Packaged installations offer download and restart controls in Settings → About. +Downloads are verified and staged; files are applied before the application starts. +Restart confirmation uses the shared modal, and download results use action feedback. + On Windows, the native API logs the process token and EXE integrity label once at startup. A Low (or lower) token triggers a WebUI warning; file labels and query failures alone do not. “临时关闭” lasts for the tab session, including diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index 54435a5c..a6728559 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -1,3 +1,4 @@ +import { APP_VERSION } from '@/types'; import { createContext, useContext, @@ -93,6 +94,7 @@ import { settingsRoute, type SettingsTab } from '@/router'; import { NotificationsPanel } from '@/components/settings/notifications-panel'; import { GlobalConfigPanel } from '@/components/settings/global-config-panel'; import { SystemPanel } from '@/components/settings/system-panel'; +import { UpdateInstaller } from '@/components/settings/update-installer'; import { StoragePanel } from '@/components/settings/storage-panel'; import { DeveloperCrashProbe, developerCrashReducer } from '@/components/settings/developer-tools'; @@ -1864,31 +1866,8 @@ function DeveloperPanel() { const REPO_URL = 'https://github.com/SnowLuma/SnowLuma'; -// Best-effort guess of the release asset matching the running platform, so -// the user knows which file to grab on the GitHub release page. Returns null -// for platforms with no official asset (e.g. macOS). -function assetHint(latest: string, platform?: string, arch?: string): string | null { - if (!platform) { - return null; - } - - const tag = `v${latest}`; - - if (platform === 'win32') { - return `SnowLuma-${tag}-win-x64.zip`; - } - - if (platform === 'linux') { - return `SnowLuma-${tag}-linux-${arch === 'arm64' ? 'arm64' : 'x64'}.tar.gz`; - } - - return null; -} - -// Advisory software update, shown as a grouped list. Read-only: links to the -// GitHub release; SnowLuma never downloads or applies anything itself. function UpdateGroup() { - const { updateInfo, refreshUpdate, systemInfo, resources } = useAppState(); + const { updateInfo, refreshUpdate, resources } = useAppState(); const { runAction } = useActionFeedback(); const [checking, setChecking] = useState(false); @@ -1899,7 +1878,7 @@ function UpdateGroup() { await runAction( { title: '正在检查更新', - detail: `当前版本 v${__APP_VERSION__}`, + detail: `当前版本 v${APP_VERSION}`, successTitle: '更新检查完成', successDetail: (result) => result?.hasUpdate && result.latest @@ -1954,7 +1933,6 @@ function UpdateGroup() { if (updateInfo?.hasUpdate && updateInfo.latest) { const latest = updateInfo.latest; - const hint = assetHint(latest, systemInfo?.platform, systemInfo?.arch); detail = (
@@ -1974,17 +1952,10 @@ function UpdateGroup() { {updateInfo.notes} )} - {hint && ( -

- 适合你的平台: - {hint} - (在下载页选择) -

- )} {updateInfo.htmlUrl && ( )} @@ -1993,10 +1964,10 @@ function UpdateGroup() { } return ( - + - v{__APP_VERSION__} + v{APP_VERSION} @@ -2029,6 +2000,7 @@ function UpdateGroup() {
{detail} + ); } @@ -2059,7 +2031,7 @@ function AboutPanel() {
SnowLuma - v{__APP_VERSION__} + v{APP_VERSION}

diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx index b063a634..c7ac67d3 100644 --- a/packages/webui/src/components/settings/system-panel.tsx +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -1,9 +1,4 @@ -// Settings → 服务 tab (Wave A1). Edits the WebUI listener's own config -// (port / bind host / trust-proxy / HTTPS). Listener-level changes are -// persisted but apply only after a restart — there is no supervisor to -// self-restart, so we never offer a "restart now" button, only a banner. -// Fields currently pinned by SNOWLUMA_* env vars are flagged (edits to them -// won't take effect until the env var is removed). +// Listener changes apply after restart; environment overrides remain authoritative. import { useEffect, useRef, useState } from 'react'; import { motion } from 'motion/react'; import { diff --git a/packages/webui/src/components/settings/update-installer.tsx b/packages/webui/src/components/settings/update-installer.tsx new file mode 100644 index 00000000..3bba660f --- /dev/null +++ b/packages/webui/src/components/settings/update-installer.tsx @@ -0,0 +1,165 @@ +import { useEffect, useState } from 'react'; +import { Download, Loader2, RefreshCw } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { ConfirmDialog } from '@/components/confirm-dialog'; +import { useActionFeedback } from '@/contexts/ActionFeedbackContext'; +import { useApi } from '@/lib/api'; +import type { UpdateStatus } from '@/types'; + +export function UpdateInstaller({ version }: { version: string | null }) { + const api = useApi(); + const { startAction, runAction } = useActionFeedback(); + const [status, setStatus] = useState(null); + const [error, setError] = useState(null); + const [confirmRestart, setConfirmRestart] = useState(false); + const [submitting, setSubmitting] = useState(false); + const phase = status?.phase; + + useEffect(() => { + if (phase !== undefined && phase !== 'downloading') { + return; + } + + let disposed = false; + let timer: ReturnType; + const activity = phase === 'downloading' ? startAction({ title: '正在下载更新' }) : null; + + const poll = async () => { + try { + const next = await api.update.status(); + + if (disposed && !activity) { + return; + } + + if (!disposed) { + setStatus(next); + setError(null); + } + + if (next.phase === 'ready') { + activity?.succeed({ title: '更新已就绪', detail: '重启后生效' }); + } else if (next.phase === 'error') { + activity?.fail(next.message, { title: '更新失败' }); + } else if (next.phase === 'downloading') { + timer = setTimeout(() => { + void poll(); + }, 1000); + } + } catch (caught) { + const message = caught instanceof Error ? caught.message : String(caught); + activity?.fail(message, { title: '读取更新状态失败' }); + + if (!disposed) { + setError(message); + timer = setTimeout(() => { + void poll(); + }, 5000); + } + } + }; + + void poll(); + + return () => { + disposed = true; + + if (!activity) { + clearTimeout(timer); + } + }; + }, [api, phase, startAction]); + + const download = async () => { + if (!version) { + return; + } + + setSubmitting(true); + setError(null); + + try { + setStatus(await api.update.download(version)); + } catch (caught) { + const message = caught instanceof Error ? caught.message : String(caught); + setError(message); + setStatus(null); + startAction({ title: '下载更新' }).fail(message, { title: '下载失败' }); + } finally { + setSubmitting(false); + } + }; + + const restart = async () => { + await runAction( + { + title: '正在重启', + successTitle: '已请求重启', + successDetail: '稍后刷新页面', + errorTitle: '重启失败', + }, + async () => { + setStatus(await api.update.restart()); + }, + ); + }; + + if (status?.phase === 'idle' && !version && !error) { + return null; + } + + return ( +

+ {error && ( +

+ {error} +

+ )} + {status?.phase === 'error' && ( +

+ {status.message} +

+ )} + {status?.phase === 'unavailable' && ( +

{status.message}

+ )} + {status?.phase === 'downloading' && ( +

+ + 正在下载 v{status.version} +

+ )} + {status?.phase === 'restarting' &&

正在重启,稍后刷新页面。

} + {status?.phase === 'ready' && ( +
+ v{status.version} 已就绪 + +
+ )} + {version && (phase === 'idle' || phase === 'error') && ( + + )} + +
+ ); +} diff --git a/packages/webui/src/env.d.ts b/packages/webui/src/env.d.ts deleted file mode 100644 index 41fad5b5..00000000 --- a/packages/webui/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -declare const __APP_VERSION__: string; diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 5c6a86ea..da1910a1 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -23,6 +23,7 @@ import type { UiAppearance, UiConfig, UpdateInfo, + UpdateStatus, } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-form'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; @@ -219,6 +220,9 @@ class HttpApiClient implements ApiClient { this.update = { check: (force) => this.getJson(`/api/update/check${force ? '?force=true' : ''}`), + status: () => this.getJson('/api/update/status'), + download: (version) => this.postJson('/api/update/download', { version }), + restart: () => this.postJson('/api/update/restart'), }; this.systemSettings = { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index dd8c5aae..27f18611 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -27,6 +27,7 @@ import type { UiAppearance, UiConfig, UpdateInfo, + UpdateStatus, } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-form'; @@ -275,6 +276,9 @@ export interface ApiClient { update: { /** Advisory check for a newer stable release. Read-only — never downloads. */ check(force?: boolean): Promise; + status(): Promise; + download(version: string): Promise; + restart(): Promise; }; // ---- WebUI customization (config/ui.json) ---- diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 9b807a85..187810b5 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -1,8 +1,14 @@ export const APP_NAME = 'SnowLuma'; // Injected at build time by Vite from the monorepo root package.json. -export const APP_VERSION = __APP_VERSION__; +export { APP_VERSION } from '@snowluma/common/version'; -/** Advisory update-availability info from `GET /api/update/check`. */ +export type UpdateStatus = { current: string } & ( + | { phase: 'unavailable' | 'error'; message: string } + | { phase: 'idle' } + | { phase: 'downloading' | 'ready' | 'restarting'; version: string } +); + +/** Update-availability info from `GET /api/update/check`. */ export interface UpdateInfo { /** The running build's version (no `v` prefix). */ current: string; diff --git a/packages/webui/tests/update-api.test.ts b/packages/webui/tests/update-api.test.ts new file mode 100644 index 00000000..7a370a94 --- /dev/null +++ b/packages/webui/tests/update-api.test.ts @@ -0,0 +1,43 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createApiClient } from '../src/lib/api/client'; + +afterEach(() => vi.unstubAllGlobals()); + +describe('update API', () => { + it('sends authenticated download and restart requests', async () => { + const fetchMock = vi.fn(async () => + Response.json({ current: '1.0.0', phase: 'ready', version: '2.0.0' }), + ); + vi.stubGlobal('fetch', fetchMock); + const api = createApiClient({ tokenStore: { load: () => 'token', save: () => undefined } }); + await api.update.download('2.0.0'); + await api.update.restart(); + await api.update.status(); + expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ + '/api/update/download', + '/api/update/restart', + '/api/update/status', + ]); + expect(fetchMock).toHaveBeenNthCalledWith( + 1, + '/api/update/download', + expect.objectContaining({ + method: 'POST', + body: JSON.stringify({ version: '2.0.0' }), + headers: new Headers({ + 'Content-Type': 'application/json', + 'X-SnowLuma-Token': 'token', + }), + }), + ); + }); + + it('surfaces a rejected restart instead of treating it as complete', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => Response.json({ message: '更新包尚未就绪' }, { status: 409 })), + ); + const api = createApiClient({ tokenStore: { load: () => 'token', save: () => undefined } }); + await expect(api.update.restart()).rejects.toThrow('更新包尚未就绪'); + }); +}); diff --git a/packages/webui/vite.config.ts b/packages/webui/vite.config.ts index 410656fa..7900db03 100644 --- a/packages/webui/vite.config.ts +++ b/packages/webui/vite.config.ts @@ -1,4 +1,3 @@ -import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { defineConfig } from 'vite'; @@ -7,11 +6,6 @@ import tailwindcss from '@tailwindcss/vite'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); -// Single source of truth for the user-facing app version: monorepo root package.json. -const rootPkg = JSON.parse( - fs.readFileSync(path.resolve(__dirname, '../../package.json'), 'utf-8'), -) as { version: string }; - export default defineConfig({ plugins: [tailwindcss(), react()], resolve: { @@ -19,9 +13,6 @@ export default defineConfig({ '@': path.resolve(__dirname, 'src'), }, }, - define: { - __APP_VERSION__: JSON.stringify(rootPkg.version), - }, server: { port: 5178, strictPort: false, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 47c53dc6..191e955a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -143,9 +143,15 @@ importers: '@snowluma/websocket': specifier: workspace:* version: link:../websocket + fflate: + specifier: ^0.8.3 + version: 0.8.3 otpauth: specifier: ^9.5.1 version: 9.5.1 + tar: + specifier: ^7.5.13 + version: 7.5.22 devDependencies: '@hono/node-server': specifier: ^1.19.15 @@ -2509,6 +2515,9 @@ packages: picomatch: optional: true + fflate@0.8.3: + resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==} + figlet@1.11.0: resolution: {integrity: sha512-EEx3OS/l2bFqcUNN2NM9FPJp8vAMrgbCxsbl2hbcJNNxOEwVe3mEzrhan7TbJQViZa8mMqhihlbCaqD+LyYKTQ==} engines: {node: '>= 17.0.0'} @@ -3848,7 +3857,6 @@ snapshots: '@isaacs/fs-minipass@4.0.1': dependencies: minipass: 7.1.3 - optional: true '@istanbuljs/schema@0.1.6': {} @@ -5102,8 +5110,7 @@ snapshots: dependencies: readdirp: 4.1.2 - chownr@3.0.0: - optional: true + chownr@3.0.0: {} class-variance-authority@0.7.1: dependencies: @@ -5398,6 +5405,8 @@ snapshots: optionalDependencies: picomatch: 4.0.4 + fflate@0.8.3: {} + figlet@1.11.0: dependencies: commander: 14.0.3 @@ -5714,13 +5723,11 @@ snapshots: dependencies: brace-expansion: 5.0.9 - minipass@7.1.3: - optional: true + minipass@7.1.3: {} minizlib@3.1.0: dependencies: minipass: 7.1.3 - optional: true mlly@1.8.2: dependencies: @@ -6129,7 +6136,6 @@ snapshots: minipass: 7.1.3 minizlib: 3.1.0 yallist: 5.0.0 - optional: true thenify-all@1.6.0: dependencies: @@ -6357,8 +6363,7 @@ snapshots: yallist@3.1.1: {} - yallist@5.0.0: - optional: true + yallist@5.0.0: {} yocto-queue@0.1.0: {} diff --git a/tools/bump-version.mjs b/tools/bump-version.mjs index 506a3f64..f12bfcf9 100644 --- a/tools/bump-version.mjs +++ b/tools/bump-version.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // Sync the `version` field across the monorepo root and every workspace package. -// Usage: pnpm bump (e.g. pnpm bump 0.2.0) +// Usage: pnpm bump [version]; without an argument, sync the root version. import { readFile, writeFile, readdir } from 'node:fs/promises'; import { existsSync } from 'node:fs'; import path from 'node:path'; @@ -9,11 +9,7 @@ import { fileURLToPath } from 'node:url'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(__dirname, '..'); -const nextVersion = process.argv[2]; -if (!nextVersion) { - console.error('Usage: pnpm bump (e.g. pnpm bump 0.2.0)'); - process.exit(1); -} +const nextVersion = process.argv[2] ?? JSON.parse(await readFile(path.join(repoRoot, 'package.json'), 'utf8')).version; if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(nextVersion)) { console.error(`Invalid semver: "${nextVersion}"`); process.exit(1); diff --git a/tools/check-release-layout.mjs b/tools/check-release-layout.mjs index a0789e4f..08631bc1 100644 --- a/tools/check-release-layout.mjs +++ b/tools/check-release-layout.mjs @@ -11,8 +11,21 @@ if (!fs.statSync(entryPoint, { throwIfNoEntry: false })?.isFile()) { throw new Error(`release entry point must be at the archive root: ${entryPoint}`); } +const release = JSON.parse(fs.readFileSync(path.join(root, 'release.json'), 'utf8')); +const runtimePackage = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); +if (release.version !== runtimePackage.version) { + throw new Error('release version does not match its runtime package'); +} +const actualEntries = fs.readdirSync(root).filter(name => !['node', 'node.exe'].includes(name)); +if (JSON.stringify([...release.entries].sort()) !== JSON.stringify(actualEntries.sort())) { + throw new Error('release file manifest does not match the packaged files'); +} + const sqliteRoot = path.join(root, 'native', 'sqlite'); const sqlite = JSON.parse(fs.readFileSync(path.join(sqliteRoot, 'manifest.json'), 'utf8')); +if (release.target !== sqlite.target) { + throw new Error('release target does not match its native artifacts'); +} if (sqlite.package !== '@appthreat/sqlite3' || sqlite.version !== '9.1.0' || sqlite.nativeInterface !== 1 || !/^(win32|linux|darwin)-(x64|arm64)$/.test(sqlite.target)) { throw new Error('release has an invalid SQLite native manifest');