diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 8e326eb6..2feb1c4b 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -101,11 +101,6 @@ export function buildBackup( return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files }; } -/** Validate a parsed bundle wholesale — any defect rejects the whole import. */ -export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | { ok: false; error: string } { - return validateBackupEntries(parsed, () => false); -} - function validateBackupEntries( parsed: unknown, skipEntryValidation: (spec: BackupFileSpec) => boolean, @@ -132,25 +127,6 @@ function validateBackupEntries( return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record } }; } -/** - * Decode a validated bundle for the legacy HTTP restore path. The production - * route switches to restoreBackup once the transaction module is introduced. - */ -export function planRestore( - backup: Backup, - opts: { restoreCredentials: boolean }, -): { restore: Array<{ name: string; data: Buffer }>; skipped: string[] } { - const restore: Array<{ name: string; data: Buffer }> = []; - const skipped: string[] = []; - for (const [name, entry] of Object.entries(backup.files)) { - const spec = specFor(name); - if (!spec) { skipped.push(name); continue; } - if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; } - restore.push({ name, data: Buffer.from(entry.data, entry.encoding) }); - } - return { restore, skipped }; -} - export interface PreparedRestoreFile { name: string; data: Buffer; diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 2162de2c..45ad1ee8 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -13,7 +13,7 @@ import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/one import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { execSync } from 'child_process'; import { randomBytes } from 'crypto'; -import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'; +import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs'; import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; @@ -31,7 +31,8 @@ import { } from './consent'; import { resolveTlsContext, validateTlsPair } from './tls'; import { coerceSettingsPatch } from './system-settings'; -import { buildBackup, planRestore, validateBackup } from './backup'; +import { buildBackup } from './backup'; +import { restoreBackup, RestoreTransactionError, type RestorePhase } from './restore'; import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs'; import { createFramePusher } from './debug-stream'; import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools'; @@ -72,6 +73,82 @@ const TOKEN_TTL_MS = 24 * 60 * 60 * 1000; const AVATAR_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const AVATAR_BROWSER_CACHE_SECONDS = 30 * 24 * 60 * 60; +export interface RestoreFailureBody { + success: false; + message: string; + transactionId: string; + phase: RestorePhase; + committed: boolean; + rollbackSucceeded?: boolean; + snapshotDir?: string; + failedFiles: string[]; +} + +/** Translate transaction facts into an operator-facing HTTP failure. */ +export function describeRestoreFailure(error: RestoreTransactionError): { + status: 400 | 500; + body: RestoreFailureBody; +} { + const detail = error.cause instanceof Error ? error.cause.message : error.message; + let message: string; + + if (error.phase === 'preflight') { + message = `备份校验失败:${detail}`; + } else if (error.rollbackSucceeded === false) { + const recovery = error.snapshotDir ? `,恢复资料保留在 ${error.snapshotDir}` : ''; + message = `恢复失败,且自动回滚不完整。请勿重启或继续修改配置;事务 ID:${error.transactionId}${recovery}。请检查服务器日志。`; + } else if (error.committed) { + const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; + message = `配置已恢复,但临时事务目录清理失败;重启后配置仍会生效。事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; + } else if (error.phase === 'cleanup') { + const configState = error.rollbackSucceeded === true ? '当前配置已自动回滚' : '当前配置未改动'; + const retained = error.snapshotDir ? `,临时事务资料保留在 ${error.snapshotDir}` : ''; + message = `恢复失败,${configState},但临时事务目录清理失败;事务 ID:${error.transactionId}${retained}。请检查服务器日志。`; + } else if (error.rollbackSucceeded === true) { + message = `恢复失败,当前配置已自动回滚。事务 ID:${error.transactionId}。请检查服务器日志。`; + } else { + message = `恢复失败,当前配置未改动。事务 ID:${error.transactionId}。请检查服务器日志。`; + } + + return { + status: error.phase === 'preflight' ? 400 : 500, + body: { + success: false, + message, + transactionId: error.transactionId, + phase: error.phase, + committed: error.committed, + ...(error.rollbackSucceeded === undefined ? {} : { rollbackSucceeded: error.rollbackSucceeded }), + ...(error.snapshotDir === undefined ? {} : { snapshotDir: error.snapshotDir }), + failedFiles: error.failedFiles, + }, + }; +} + +function isMissingPath(error: unknown): boolean { + return error instanceof Error && 'code' in error && error.code === 'ENOENT'; +} + +/** Read one allowlisted config file; I/O failures other than absence are fatal. */ +export function readBackupConfigFile(configDir: string, name: string): Buffer | null { + try { + return readFileSync(path.join(configDir, name)); + } catch (error) { + if (isMissingPath(error)) return null; + throw error; + } +} + +/** List per-account OneBot config candidates; an unreadable directory is fatal. */ +export function listPerUinOneBotConfigFiles(configDir: string): string[] { + try { + return readdirSync(configDir).filter((name) => /^onebot_\d+\.json$/.test(name)); + } catch (error) { + if (isMissingPath(error)) return []; + throw error; + } +} + // Endpoints that an auth-required-but-must-change-password session can still hit. const MUST_CHANGE_ALLOWLIST = new Set([ '/api/status', @@ -855,27 +932,25 @@ export async function initWebUI( }); // ── Config backup / restore (Wave A2) ── - const cfgPath = (name: string) => path.join('config', name); - const readCfg = (name: string): Buffer | null => { - const p = cfgPath(name); - return existsSync(p) ? readFileSync(p) : null; - }; - - const listPerUinOnebot = (): string[] => { - try { - return existsSync('config') ? readdirSync('config').filter((n) => /^onebot_\d+\.json$/.test(n)) : []; - } catch { return []; } - }; - app.get('/api/system/backup/export', (c) => { - const includeCredentials = c.req.query('credentials') === '1'; - const ts = new Date().toISOString(); - const bundle = buildBackup(readCfg, listPerUinOnebot(), { includeCredentials }, ts); - c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`); - // Bundle may carry the TLS private key / password hash — never cache it. - c.header('Cache-Control', 'no-store, max-age=0'); - c.header('Pragma', 'no-cache'); - return c.json(bundle); + try { + const includeCredentials = c.req.query('credentials') === '1'; + const ts = new Date().toISOString(); + const bundle = buildBackup( + (name) => readBackupConfigFile('config', name), + listPerUinOneBotConfigFiles('config'), + { includeCredentials }, + ts, + ); + c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`); + // Bundle may carry the TLS private key / password hash — never cache it. + c.header('Cache-Control', 'no-store, max-age=0'); + c.header('Pragma', 'no-cache'); + return c.json(bundle); + } catch (error) { + log.error('backup export failed: %s', error instanceof Error ? error.stack ?? error.message : String(error)); + return c.json({ success: false, message: '导出失败,请检查服务器日志' }, 500); + } }); app.post('/api/system/backup/import', async (c) => { @@ -893,50 +968,19 @@ export async function initWebUI( return c.json({ success: false, message: '请求格式错误' }, 400); } const { backup, restoreCredentials } = body as { backup?: unknown; restoreCredentials?: unknown }; - const v = validateBackup(backup); - if (!v.ok) return c.json({ success: false, message: v.error }, 400); - - const plan = planRestore(v.backup, { restoreCredentials: restoreCredentials === true }); - // Snapshot the current (about-to-be-overwritten) config so a restore is - // recoverable; one timestamped dir per import. - const snapDir = path.join('config', `.restore-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`); - // Two-phase write for near-atomicity: stage every file as a .tmp first, then - // rename them all. A failure during staging touches no live file; rename - // almost never fails, shrinking the half-applied window to near zero. - const staged: Array<{ tmp: string; dest: string; name: string }> = []; try { - for (const { name } of plan.restore) { - const src = cfgPath(name); - if (!existsSync(src)) continue; - const snap = path.join(snapDir, name); - mkdirSync(path.dirname(snap), { recursive: true }); - copyFileSync(src, snap); - } - for (const { name, data } of plan.restore) { - const dest = cfgPath(name); - mkdirSync(path.dirname(dest), { recursive: true }); - const tmp = dest + '.restore.tmp'; - writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined); - staged.push({ tmp, dest, name }); - } - for (const { tmp, dest, name } of staged) { - renameSync(tmp, dest); - if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } } - } - return c.json({ - success: true, - restored: plan.restore.map((r) => r.name), - skipped: plan.skipped, - snapshotDir: snapDir, - restartRequiredToApply: true, + const result = restoreBackup(backup, { + configDir: 'config', + restoreCredentials: restoreCredentials === true, }); + return c.json({ success: true, ...result }); } catch (err) { - // Clean up any staged .tmp not yet renamed (staging-phase failure leaves - // the live config untouched; a rare rename-phase failure may be partial, - // recoverable from the snapshot dir). - for (const { tmp } of staged) { try { if (existsSync(tmp)) rmSync(tmp, { force: true }); } catch { /* ignore */ } } - log.warn('backup import failed: %s', err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500); + if (err instanceof RestoreTransactionError) { + const failure = describeRestoreFailure(err); + return c.json(failure.body, failure.status); + } + log.error('backup import failed unexpectedly: %s', err instanceof Error ? err.stack ?? err.message : String(err)); + return c.json({ success: false, message: '恢复遇到未预期错误,请检查服务器日志' }, 500); } }); diff --git a/packages/core/tests/webui-backup-http.test.ts b/packages/core/tests/webui-backup-http.test.ts new file mode 100644 index 00000000..b3016c9c --- /dev/null +++ b/packages/core/tests/webui-backup-http.test.ts @@ -0,0 +1,35 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { + listPerUinOneBotConfigFiles, + readBackupConfigFile, +} from '../src/webui/server'; + +describe('backup filesystem adapter', () => { + let root: string; + + beforeEach(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-backup-http-')); + }); + + afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); + }); + + it('treats only a missing file as absent', () => { + expect(readBackupConfigFile(root, 'missing.json')).toBeNull(); + + fs.mkdirSync(path.join(root, 'runtime.json')); + expect(() => readBackupConfigFile(root, 'runtime.json')).toThrow(); + }); + + it('treats only a missing config directory as an empty OneBot list', () => { + expect(listPerUinOneBotConfigFiles(path.join(root, 'missing'))).toEqual([]); + + const notDirectory = path.join(root, 'not-a-directory'); + fs.writeFileSync(notDirectory, 'x'); + expect(() => listPerUinOneBotConfigFiles(notDirectory)).toThrow(); + }); +}); diff --git a/packages/core/tests/webui-restore-http.test.ts b/packages/core/tests/webui-restore-http.test.ts new file mode 100644 index 00000000..16097822 --- /dev/null +++ b/packages/core/tests/webui-restore-http.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, it } from 'vitest'; +import { RestorePreflightError } from '../src/webui/backup'; +import { describeRestoreFailure } from '../src/webui/server'; +import { RestoreTransactionError } from '../src/webui/restore'; + +function failure( + phase: RestoreTransactionError['phase'], + options: Partial<{ + cause: unknown; + rollbackSucceeded: boolean; + snapshotDir: string; + committed: boolean; + failedFiles: string[]; + }> = {}, +): RestoreTransactionError { + return new RestoreTransactionError({ + phase, + transactionId: `tx-${phase}`, + message: `restore ${phase} failed`, + cause: options.cause ?? new Error(`${phase} root cause`), + rollbackSucceeded: options.rollbackSucceeded, + snapshotDir: options.snapshotDir, + committed: options.committed, + failedFiles: options.failedFiles, + }); +} + +describe('describeRestoreFailure', () => { + it('returns a client error with the semantic preflight detail', () => { + const error = failure('preflight', { + cause: new RestorePreflightError('runtime.json', '$.webuiPort must be 1-65535'), + failedFiles: ['runtime.json'], + }); + + expect(describeRestoreFailure(error)).toEqual({ + status: 400, + body: { + success: false, + message: '备份校验失败:runtime.json: $.webuiPort must be 1-65535', + transactionId: 'tx-preflight', + phase: 'preflight', + committed: false, + failedFiles: ['runtime.json'], + }, + }); + }); + + it('says the live config was rolled back after a commit failure', () => { + const error = failure('commit', { + rollbackSucceeded: true, + failedFiles: ['notifications.json'], + }); + + expect(describeRestoreFailure(error)).toEqual({ + status: 500, + body: { + success: false, + message: '恢复失败,当前配置已自动回滚。事务 ID:tx-commit。请检查服务器日志。', + transactionId: 'tx-commit', + phase: 'commit', + committed: false, + rollbackSucceeded: true, + failedFiles: ['notifications.json'], + }, + }); + }); + + it('keeps recovery coordinates visible when rollback is incomplete', () => { + const error = failure('rollback', { + rollbackSucceeded: false, + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-rollback', + failedFiles: ['runtime.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.status).toBe(500); + expect(response.body).toEqual(expect.objectContaining({ + success: false, + transactionId: 'tx-rollback', + phase: 'rollback', + committed: true, + rollbackSucceeded: false, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-rollback', + failedFiles: ['runtime.json'], + })); + expect(response.body.message).toContain('自动回滚不完整'); + expect(response.body.message).toContain('请勿重启或继续修改配置'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-rollback'); + }); + + it('distinguishes a committed restore from a failed restore when only cleanup fails', () => { + const error = failure('cleanup', { + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + }); + + const response = describeRestoreFailure(error); + expect(response.status).toBe(500); + expect(response.body).toEqual(expect.objectContaining({ + success: false, + transactionId: 'tx-cleanup', + phase: 'cleanup', + committed: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + })); + expect(response.body.message).toContain('配置已恢复'); + expect(response.body.message).toContain('重启后配置仍会生效'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); + + it('surfaces retained transaction files when pre-commit cleanup fails', () => { + const error = failure('cleanup', { + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + failedFiles: ['notifications.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.body.message).toContain('当前配置未改动'); + expect(response.body.message).toContain('临时事务目录清理失败'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); + + it('surfaces retained transaction files after rollback cleanup fails', () => { + const error = failure('cleanup', { + rollbackSucceeded: true, + snapshotDir: '/srv/snowluma/config/.restore-transaction-tx-cleanup', + failedFiles: ['notifications.json'], + }); + + const response = describeRestoreFailure(error); + expect(response.body.message).toContain('当前配置已自动回滚'); + expect(response.body.message).toContain('临时事务目录清理失败'); + expect(response.body.message).toContain('/srv/snowluma/config/.restore-transaction-tx-cleanup'); + }); +}); diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx index 87366ea3..2c226796 100644 --- a/packages/webui/src/components/settings/system-panel.tsx +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -43,7 +43,7 @@ export function SystemPanel() { const [restoreCreds, setRestoreCreds] = useState(false); const fileRef = useRef(null); - const load = async () => { + const load = async (): Promise => { try { const res = await api.systemSettings.get(); setData(res); @@ -51,8 +51,10 @@ export function SystemPanel() { setHost(res.settings.webuiHost); setTrustProxy(res.settings.trustProxy); setTlsEnabled(res.settings.tlsEnabled); + return true; } catch { setMsg({ kind: 'err', text: '加载系统设置失败' }); + return false; } finally { setLoading(false); } @@ -136,11 +138,19 @@ export function SystemPanel() { let parsed: Record; try { parsed = JSON.parse(text); } catch { flash('err', '文件不是有效的 JSON'); return; } const res = await api.systemSettings.importBackup(parsed, restoreCreds); - const parts = [`已恢复 ${res.restored.length} 项`]; - if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(凭据未恢复)`); - flash('ok', `${parts.join(',')},重启后生效`); + const parts = res.restored.length ? [`已恢复 ${res.restored.length} 项`] : ['没有可恢复的配置']; + if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(敏感配置,含 OneBot 配置)`); + if (res.migrated.length) parts.push(`兼容转换 ${res.migrated.length} 项`); + const summary = `${parts.join(',')}${res.restartRequiredToApply ? ',重启后生效' : ''}`; + const refreshed = await load(); + flash( + refreshed ? 'ok' : 'err', + refreshed ? summary : `${summary};但界面状态刷新失败,请手动刷新页面`, + ); } catch (e) { - flash('err', e instanceof Error ? e.message : '恢复失败'); + const message = e instanceof Error ? e.message : '恢复失败'; + const refreshed = await load(); + flash('err', refreshed ? message : `${message};界面状态刷新失败,请手动刷新页面`); } finally { setSaving(false); if (fileRef.current) fileRef.current.value = ''; @@ -263,16 +273,16 @@ export function SystemPanel() { 配置备份 / 恢复 - 导出/导入全部配置(OneBot、外观、通知、系统设置、证书)。不含消息数据库。 + 备份外观、通知、系统设置和证书等配置;敏感开关还会包含 OneBot 配置。不含消息数据库。
- - + +
{exportCreds && ( -

⚠ 备份文件将包含登录口令哈希与 TLS 私钥,请妥善保管。

+

⚠ 将额外包含 WebUI 登录状态、TLS 私钥,以及带访问令牌的 OneBot 配置,请妥善保管。

)}
-

恢复前会自动把当前配置快照到 config/.restore-backup-*;恢复后需重启生效。

+

恢复前会校验本次要恢复的配置;写入过程中出错会自动回滚,成功后临时快照会删除。恢复后需重启生效。

diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 666a47b4..0bff6327 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -164,7 +164,7 @@ export interface ApiClient { deleteCert(): Promise; /** Download the config backup bundle (credentials gated). */ exportBackup(includeCredentials: boolean): Promise; - /** Validate + restore a bundle (snapshots current config first). */ + /** Validate + restore a bundle as one process-level transaction. */ importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise; }; diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 83bbb0a3..abf27b58 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -253,9 +253,11 @@ export type DebugStreamMessage = // server validates; the client never inspects its internals. export type BackupBundle = Record; export interface BackupImportResult { + success: true; + transactionId: string; restored: string[]; skipped: string[]; - snapshotDir: string; + migrated: Array<{ name: string; fields: string[] }>; restartRequiredToApply: boolean; }