fix(webui): A2 backup — per-uin onebot config, no-store, atomic restore
Adversarial Wave A2 pass, 3 MAJORs: - #3/#3b: the allowlist missed per-account config/onebot_<uin>.json (the file that actually carries each account's network config + OneBot access token). Add it via an /^onebot_\d+\.json$/ pattern; classify ALL onebot config (global + per-uin) as credential since it holds the access token — a no-credentials backup no longer leaks tokens. Export scans config/ for them. - #6: GET export could carry the private key/hash; add Cache-Control: no-store + Pragma so the response is never cached. - #4: refactor applyBackup → pure planRestore + a two-phase atomic restore in server.ts (snapshot → stage all .tmp → rename all), so a staging failure leaves the live config untouched; clean up stray tmp on failure.
This commit is contained in:
3 files changed
+140
-91
No files matched your search
@@ -1,12 +1,16 @@
|
||||
// WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle
|
||||
// { version, app, createdAt, files: { "<name>": { 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_<uin>.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_<uin>.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<string, BackupEntry>;
|
||||
}
|
||||
|
||||
/** 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<string, BackupEntry> = {};
|
||||
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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
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 };
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user