diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 132cf4e9..32a645ae 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -1,12 +1,16 @@ // WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle // { version, app, createdAt, files: { "": { encoding, data } } } // over an explicit allowlist (never a whole-dir sweep) so a stray/unknown file -// can't leak and an import can't path-traverse. Credentials (webui.json password -// hash + key.pem private key) are gated by a toggle on both export and import. +// can't leak and an import can't path-traverse. +// +// Credentials are gated by a toggle on both export and import. The credential +// set is: webui.json (password hash), key.pem (TLS private key), AND every +// OneBot config (onebot.json + per-account onebot_.json) — those carry the +// OneBot access token, so a no-credentials backup must NOT include them. // cert.pem is public so it always travels. // -// Pure functions here (read/write/snapshot injected) — the fs glue lives in -// server.ts. Restore is restart-to-apply, like the rest of A1. +// Pure functions here (read/list/decode); the fs glue (atomic two-phase write, +// snapshot) lives in server.ts. Restore is restart-to-apply, like A1. export const BACKUP_VERSION = 1; export const BACKUP_APP = 'snowluma'; @@ -15,22 +19,33 @@ export interface BackupFileSpec { /** Path relative to the config dir; also the bundle key. */ name: string; binary: boolean; - /** Sensitive (private key / password hash) — gated by the credentials toggle. */ + /** Sensitive (private key / password hash / access token) — credential-gated. */ credential: boolean; } +/** Static allowlist. Per-account `onebot_.json` are matched by pattern. */ export const BACKUP_FILES: readonly BackupFileSpec[] = [ { name: 'runtime.json', binary: false, credential: false }, { name: 'ui.json', binary: false, credential: false }, - { name: 'onebot.json', binary: false, credential: false }, { name: 'notifications.json', binary: false, credential: false }, { name: 'cert.pem', binary: false, credential: false }, + { name: 'ui-assets/background', binary: true, credential: false }, { name: 'webui.json', binary: false, credential: true }, { name: 'key.pem', binary: false, credential: true }, - { name: 'ui-assets/background', binary: true, credential: false }, + // OneBot config carries the access token → credential. + { name: 'onebot.json', binary: false, credential: true }, ]; const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f])); +const PER_UIN_ONEBOT = /^onebot_\d+\.json$/; + +/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */ +export function specFor(name: string): BackupFileSpec | null { + const s = SPEC_BY_NAME.get(name); + if (s) return s; + if (PER_UIN_ONEBOT.test(name)) return { name, binary: false, credential: true }; + return null; +} export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string } export interface Backup { @@ -40,14 +55,22 @@ export interface Backup { files: Record; } -/** Assemble a bundle from the allowlist. `readFile` returns null for missing. */ +/** + * Assemble a bundle from the allowlist plus any per-account onebot files. + * `readFile` returns null for missing. + */ export function buildBackup( readFile: (name: string) => Buffer | null, + perUinOnebotNames: readonly string[], opts: { includeCredentials: boolean }, createdAt: string, ): Backup { const files: Record = {}; - for (const spec of BACKUP_FILES) { + const all: BackupFileSpec[] = [ + ...BACKUP_FILES, + ...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })), + ]; + for (const spec of all) { if (spec.credential && !opts.includeCredentials) continue; const buf = readFile(spec.name); if (!buf) continue; @@ -71,7 +94,7 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | } const files = b.files as Record; for (const [name, entry] of Object.entries(files)) { - if (!SPEC_BY_NAME.has(name)) return { ok: false, error: `unknown file in backup: ${name}` }; + if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` }; if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` }; const e = entry as Record; if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` }; @@ -81,25 +104,22 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | } /** - * Apply a (already-validated) bundle. For each file: snapshot the current one - * (so a bad restore is recoverable) then write the decoded bytes. Credential + * Decide what a (validated) bundle would restore: decode each non-skipped file + * to bytes. Pure — the caller (server.ts) does the atomic two-phase fs write so + * a mid-restore failure can't leave a half-applied live config. Credential * files are skipped unless `restoreCredentials`. */ -export function applyBackup( +export function planRestore( backup: Backup, - io: { snapshot: (name: string) => void; write: (name: string, data: Buffer) => void }, opts: { restoreCredentials: boolean }, -): { restored: string[]; skipped: string[] } { - const restored: string[] = []; +): { 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 = SPEC_BY_NAME.get(name); + const spec = specFor(name); if (!spec) { skipped.push(name); continue; } // validated, but be defensive if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; } - const data = Buffer.from(entry.data, entry.encoding); - io.snapshot(name); - io.write(name, data); - restored.push(name); + restore.push({ name, data: Buffer.from(entry.data, entry.encoding) }); } - return { restored, skipped }; + return { restore, skipped }; } diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index aa0c91e6..845de415 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -7,7 +7,7 @@ import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig } from '@snowluma/onebot/types'; import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime'; import { randomBytes } from 'crypto'; -import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'; +import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs'; import { createServer as createHttpsServer } from 'https'; import { Hono, type Context } from 'hono'; import os from 'os'; @@ -16,7 +16,7 @@ import { fileURLToPath } from 'url'; import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth'; import { resolveTlsContext, validateTlsPair } from './tls'; import { coerceSettingsPatch } from './system-settings'; -import { applyBackup, buildBackup, validateBackup } from './backup'; +import { buildBackup, planRestore, validateBackup } from './backup'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { findAvailablePort } from './port'; import { @@ -505,11 +505,20 @@ export async function initWebUI( 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, { includeCredentials }, ts); + 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); }); @@ -531,37 +540,47 @@ export async function initWebUI( const v = validateBackup(backup); if (!v.ok) return c.json({ success: false, message: v.error }, 400); - // Snapshot the current config before overwriting so a bad restore is + 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 { - const res = applyBackup(v.backup, { - snapshot: (name) => { - const src = cfgPath(name); - if (!existsSync(src)) return; - const dest = path.join(snapDir, name); - mkdirSync(path.dirname(dest), { recursive: true }); - copyFileSync(src, dest); - }, - write: (name, data) => { - const dest = cfgPath(name); - mkdirSync(path.dirname(dest), { recursive: true }); - const tmp = dest + '.tmp'; - writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined); - renameSync(tmp, dest); - if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } } - }, - }, { restoreCredentials: restoreCredentials === true }); + 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: res.restored, - skipped: res.skipped, + restored: plan.restore.map((r) => r.name), + skipped: plan.skipped, snapshotDir: snapDir, restartRequiredToApply: true, }); } 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: '恢复失败,请检查服务器日志(原配置已快照备份)' }, 500); + return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500); } }); diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts index 3d2fbfba..e907ec13 100644 --- a/packages/core/tests/webui-backup.test.ts +++ b/packages/core/tests/webui-backup.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { BACKUP_FILES, buildBackup, validateBackup, applyBackup } from '../src/webui/backup'; +import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup'; const TS = '2026-06-18T00:00:00.000Z'; @@ -12,7 +12,7 @@ describe('buildBackup', () => { const b = buildBackup(reader({ 'runtime.json': Buffer.from('{"webuiPort":5099}'), 'ui.json': Buffer.from('{}'), - }), { includeCredentials: false }, TS); + }), [], { includeCredentials: false }, TS); expect(b.version).toBe(1); expect(b.app).toBe('snowluma'); expect(b.createdAt).toBe(TS); @@ -20,32 +20,49 @@ describe('buildBackup', () => { expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' }); }); - it('excludes credential files (webui.json, key.pem) unless includeCredentials', () => { + it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => { const map = { 'runtime.json': Buffer.from('{}'), 'webui.json': Buffer.from('{"hash":"x"}'), 'key.pem': Buffer.from('KEY'), 'cert.pem': Buffer.from('CERT'), + 'onebot.json': Buffer.from('{"accessToken":"t"}'), + 'onebot_12345.json': Buffer.from('{"accessToken":"t2"}'), }; - const without = buildBackup(reader(map), { includeCredentials: false }, TS); - expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']); // cert is public - const withCreds = buildBackup(reader(map), { includeCredentials: true }, TS); - expect(Object.keys(withCreds.files).sort()).toEqual(['cert.pem', 'key.pem', 'runtime.json', 'webui.json']); + const perUin = ['onebot_12345.json']; + const without = buildBackup(reader(map), perUin, { includeCredentials: false }, TS); + // only public files survive a no-credentials export + expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']); + const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS); + expect(Object.keys(withCreds.files).sort()).toEqual( + ['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'], + ); }); it('base64-encodes binary files (background image)', () => { const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]); - const b = buildBackup(reader({ 'ui-assets/background': png }), { includeCredentials: false }, TS); + const b = buildBackup(reader({ 'ui-assets/background': png }), [], { includeCredentials: false }, TS); expect(b.files['ui-assets/background']).toEqual({ encoding: 'base64', data: png.toString('base64') }); }); }); +describe('specFor', () => { + it('resolves static names and per-uin onebot pattern; rejects others', () => { + expect(specFor('runtime.json')?.credential).toBe(false); + expect(specFor('onebot.json')?.credential).toBe(true); + expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true }); + expect(specFor('onebot_.json')).toBeNull(); + expect(specFor('../evil')).toBeNull(); + expect(specFor('onebot_12.json.bak')).toBeNull(); + }); +}); + describe('validateBackup', () => { const good = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8', data: '{}' } } }; - it('accepts a well-formed bundle', () => { - const r = validateBackup(good); - expect(r.ok).toBe(true); + it('accepts a well-formed bundle (incl. per-uin onebot)', () => { + expect(validateBackup(good).ok).toBe(true); + expect(validateBackup({ ...good, files: { 'onebot_42.json': { encoding: 'utf8', data: '{}' } } }).ok).toBe(true); }); it('rejects a non-object / wrong app / wrong version', () => { @@ -57,6 +74,7 @@ describe('validateBackup', () => { it('rejects an unknown / path-traversal filename', () => { expect(validateBackup({ ...good, files: { '../evil': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); expect(validateBackup({ ...good, files: { 'unknown.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); + expect(validateBackup({ ...good, files: { 'onebot_../x.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false); }); it('rejects a malformed entry', () => { @@ -65,54 +83,46 @@ describe('validateBackup', () => { }); }); -describe('applyBackup', () => { - function makeIo() { - const snapshots: string[] = []; - const writes: Record = {}; - return { - snapshots, writes, - io: { - snapshot: (name: string) => { snapshots.push(name); }, - write: (name: string, data: Buffer) => { writes[name] = data.toString(); }, +describe('planRestore', () => { + it('decodes restored files to bytes (utf8 + base64)', () => { + const png = Buffer.from([1, 2, 3, 4]); + const backup = { + version: 1, app: 'snowluma', + files: { + 'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' }, + 'ui-assets/background': { encoding: 'base64' as const, data: png.toString('base64') }, }, }; - } - - it('snapshots then writes each restored file', () => { - const { io, snapshots, writes } = makeIo(); - const backup = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' } } }; - const res = applyBackup(backup, io, { restoreCredentials: false }); - expect(snapshots).toContain('runtime.json'); - expect(writes['runtime.json']).toBe('{"a":1}'); - expect(res.restored).toEqual(['runtime.json']); + const { restore, skipped } = planRestore(backup, { restoreCredentials: false }); + expect(skipped).toEqual([]); + const byName = Object.fromEntries(restore.map((r) => [r.name, r.data])); + expect(byName['runtime.json'].toString()).toBe('{"a":1}'); + expect(byName['ui-assets/background'].equals(png)).toBe(true); }); - it('skips credential files unless restoreCredentials', () => { - const { io, writes } = makeIo(); + it('skips all credential files unless restoreCredentials', () => { const backup = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8' as const, data: '{}' }, 'webui.json': { encoding: 'utf8' as const, data: '{"hash":"x"}' }, 'key.pem': { encoding: 'utf8' as const, data: 'KEY' }, + 'onebot.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, + 'onebot_7.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' }, }, }; - const res = applyBackup(backup, io, { restoreCredentials: false }); - expect(writes['webui.json']).toBeUndefined(); - expect(writes['key.pem']).toBeUndefined(); - expect(res.skipped.sort()).toEqual(['key.pem', 'webui.json']); - expect(res.restored).toEqual(['runtime.json']); - }); - - it('restores credentials when opted in', () => { - const { io, writes } = makeIo(); - const backup = { version: 1, app: 'snowluma', files: { 'webui.json': { encoding: 'utf8' as const, data: 'H' } } }; - applyBackup(backup, io, { restoreCredentials: true }); - expect(writes['webui.json']).toBe('H'); + const skip = planRestore(backup, { restoreCredentials: false }); + expect(skip.restore.map((r) => r.name)).toEqual(['runtime.json']); + expect(skip.skipped.sort()).toEqual(['key.pem', 'onebot.json', 'onebot_7.json', 'webui.json']); + const keep = planRestore(backup, { restoreCredentials: true }); + expect(keep.restore.map((r) => r.name).sort()).toEqual( + ['key.pem', 'onebot.json', 'onebot_7.json', 'runtime.json', 'webui.json'], + ); }); }); -it('BACKUP_FILES marks webui.json and key.pem as credentials', () => { +it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => { const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort(); - expect(creds).toEqual(['key.pem', 'webui.json']); + expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']); + expect(specFor('cert.pem')?.credential).toBe(false); });