feat(webui): config backup/restore core (Wave A2)

Pure, tested backup module: buildBackup (allowlist → JSON bundle, credential
files gated), validateBackup (version/app/known-filename/no-traversal/entry
shape — rejects wholesale), applyBackup (snapshot-then-write, skips
credentials unless opted in). Credentials = webui.json + key.pem; cert.pem is
public and always travels. fs glue lands next in server.ts.
This commit is contained in:
DrSmoothl
2026-06-18 14:56:12 +08:00
parent a38b33c8aa
commit b71aedaa60
2 changed files with 223 additions and 0 deletions
+105
View File
@@ -0,0 +1,105 @@
// 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.
// 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.
export const BACKUP_VERSION = 1;
export const BACKUP_APP = 'snowluma';
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. */
credential: boolean;
}
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: 'webui.json', binary: false, credential: true },
{ name: 'key.pem', binary: false, credential: true },
{ name: 'ui-assets/background', binary: true, credential: false },
];
const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f]));
export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string }
export interface Backup {
version: number;
app: string;
createdAt?: string;
files: Record<string, BackupEntry>;
}
/** Assemble a bundle from the allowlist. `readFile` returns null for missing. */
export function buildBackup(
readFile: (name: string) => Buffer | null,
opts: { includeCredentials: boolean },
createdAt: string,
): Backup {
const files: Record<string, BackupEntry> = {};
for (const spec of BACKUP_FILES) {
if (spec.credential && !opts.includeCredentials) continue;
const buf = readFile(spec.name);
if (!buf) continue;
files[spec.name] = spec.binary
? { encoding: 'base64', data: buf.toString('base64') }
: { encoding: 'utf8', data: buf.toString('utf8') };
}
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 } {
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
return { ok: false, error: 'backup must be an object' };
}
const b = parsed as Record<string, unknown>;
if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' };
if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` };
if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) {
return { ok: false, error: 'backup.files must be an object' };
}
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 (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}` };
if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` };
}
return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record<string, BackupEntry> } };
}
/**
* Apply a (already-validated) bundle. For each file: snapshot the current one
* (so a bad restore is recoverable) then write the decoded bytes. Credential
* files are skipped unless `restoreCredentials`.
*/
export function applyBackup(
backup: Backup,
io: { snapshot: (name: string) => void; write: (name: string, data: Buffer) => void },
opts: { restoreCredentials: boolean },
): { restored: string[]; skipped: string[] } {
const restored: string[] = [];
const skipped: string[] = [];
for (const [name, entry] of Object.entries(backup.files)) {
const spec = SPEC_BY_NAME.get(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);
}
return { restored, skipped };
}
+118
View File
@@ -0,0 +1,118 @@
import { describe, it, expect } from 'vitest';
import { BACKUP_FILES, buildBackup, validateBackup, applyBackup } from '../src/webui/backup';
const TS = '2026-06-18T00:00:00.000Z';
function reader(map: Record<string, Buffer>) {
return (name: string): Buffer | null => map[name] ?? null;
}
describe('buildBackup', () => {
it('includes present non-credential files and skips missing ones', () => {
const b = buildBackup(reader({
'runtime.json': Buffer.from('{"webuiPort":5099}'),
'ui.json': Buffer.from('{}'),
}), { includeCredentials: false }, TS);
expect(b.version).toBe(1);
expect(b.app).toBe('snowluma');
expect(b.createdAt).toBe(TS);
expect(Object.keys(b.files).sort()).toEqual(['runtime.json', 'ui.json']);
expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' });
});
it('excludes credential files (webui.json, key.pem) unless includeCredentials', () => {
const map = {
'runtime.json': Buffer.from('{}'),
'webui.json': Buffer.from('{"hash":"x"}'),
'key.pem': Buffer.from('KEY'),
'cert.pem': Buffer.from('CERT'),
};
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']);
});
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);
expect(b.files['ui-assets/background']).toEqual({ encoding: 'base64', data: png.toString('base64') });
});
});
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('rejects a non-object / wrong app / wrong version', () => {
expect(validateBackup(null).ok).toBe(false);
expect(validateBackup({ ...good, app: 'other' }).ok).toBe(false);
expect(validateBackup({ ...good, version: 999 }).ok).toBe(false);
});
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);
});
it('rejects a malformed entry', () => {
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'rot13', data: 'x' } } }).ok).toBe(false);
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'utf8' } } }).ok).toBe(false);
});
});
describe('applyBackup', () => {
function makeIo() {
const snapshots: string[] = [];
const writes: Record<string, string> = {};
return {
snapshots, writes,
io: {
snapshot: (name: string) => { snapshots.push(name); },
write: (name: string, data: Buffer) => { writes[name] = data.toString(); },
},
};
}
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']);
});
it('skips credential files unless restoreCredentials', () => {
const { io, writes } = makeIo();
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' },
},
};
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');
});
});
it('BACKUP_FILES marks webui.json and key.pem as credentials', () => {
const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort();
expect(creds).toEqual(['key.pem', 'webui.json']);
});