diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 93e5fae0..3dcd2bba 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -64,16 +64,52 @@ function ensureConfigDir(): void { fs.mkdirSync(CONFIG_DIR, { recursive: true }); } -function isValidState(value: unknown): value is WebuiAuthState { - if (!value || typeof value !== 'object') return false; +/** + * Validate credential state before it crosses a persistence boundary. + * + * The hash/salt lengths are part of the on-disk contract: accepting any hex + * string here only postpones failure until password verification, where the + * operator would be locked out after a restore. + */ +export function prepareWebuiAuthStateForRestore(value: unknown): WebuiAuthState { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('credential state must be an object'); + } const v = value as Record; - return ( - typeof v.passwordHash === 'string' && - typeof v.passwordSalt === 'string' && - typeof v.mustChangePassword === 'boolean' && - /^[0-9a-f]+$/i.test(v.passwordHash) && - /^[0-9a-f]+$/i.test(v.passwordSalt) - ); + if (typeof v.passwordHash !== 'string' || !/^[0-9a-f]{128}$/i.test(v.passwordHash)) { + throw new Error('passwordHash must be exactly 128 hexadecimal characters'); + } + if (typeof v.passwordSalt !== 'string' || !/^[0-9a-f]{32}$/i.test(v.passwordSalt)) { + throw new Error('passwordSalt must be exactly 32 hexadecimal characters'); + } + if (typeof v.mustChangePassword !== 'boolean') { + throw new Error('mustChangePassword must be a boolean'); + } + if (typeof v.generatedAt !== 'string' || !Number.isFinite(Date.parse(v.generatedAt))) { + throw new Error('generatedAt must be a valid timestamp'); + } + if (typeof v.updatedAt !== 'string' || !Number.isFinite(Date.parse(v.updatedAt))) { + throw new Error('updatedAt must be a valid timestamp'); + } + const allowed = new Set(['passwordHash', 'passwordSalt', 'mustChangePassword', 'generatedAt', 'updatedAt']); + const unknown = Object.keys(v).find((key) => !allowed.has(key)); + if (unknown) throw new Error(`unknown field $.${unknown}`); + return { + passwordHash: v.passwordHash, + passwordSalt: v.passwordSalt, + mustChangePassword: v.mustChangePassword, + generatedAt: v.generatedAt, + updatedAt: v.updatedAt, + }; +} + +function isValidState(value: unknown): value is WebuiAuthState { + try { + prepareWebuiAuthStateForRestore(value); + return true; + } catch { + return false; + } } function generateInitialState(initialPassword: string): WebuiAuthState { diff --git a/packages/core/src/webui/backup.ts b/packages/core/src/webui/backup.ts index 7a97a913..8e326eb6 100644 --- a/packages/core/src/webui/backup.ts +++ b/packages/core/src/webui/backup.ts @@ -9,11 +9,23 @@ // OneBot access token, so a no-credentials backup must NOT include them. // cert.pem is public so it always travels. // -// 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. +// Pure functions here own bundle validation and semantic preflight. Filesystem +// transaction choreography lives in restore.ts. A non-empty restore remains +// restart-to-apply, like A1. + +import { normalizeRuntimeConfig } from '@snowluma/common/runtime'; +import { isRealUin } from '@snowluma/common/uin'; +import { normalizeGlobalSettings } from '@snowluma/onebot/global-config'; +import { prepareOneBotConfigForRestore } from '@snowluma/onebot/config'; +import { isIP } from 'node:net'; +import { normalizeNotificationsConfig } from '../notifications/config'; +import { prepareWebuiAuthStateForRestore } from './auth'; +import { MAX_BACKGROUND_BYTES, normalizeStoredUiConfig, sniffImageMime } from './ui-config'; +import { validateTlsPair } from './tls'; export const BACKUP_VERSION = 1; export const BACKUP_APP = 'snowluma'; +export const MAX_BACKUP_DECODED_BYTES = 32 * 1024 * 1024; export interface BackupFileSpec { /** Path relative to the config dir; also the bundle key. */ @@ -40,13 +52,18 @@ export const BACKUP_FILES: readonly BackupFileSpec[] = [ ]; const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f])); -const PER_UIN_ONEBOT = /^onebot_\d+\.json$/; +const PER_UIN_ONEBOT = /^onebot_(\d+)\.json$/; + +function isPerUinOneBotName(name: string): boolean { + const match = PER_UIN_ONEBOT.exec(name); + return match !== null && isRealUin(match[1]); +} /** 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 }; + if (isPerUinOneBotName(name)) return { name, binary: false, credential: true }; return null; } @@ -71,7 +88,7 @@ export function buildBackup( const files: Record = {}; const all: BackupFileSpec[] = [ ...BACKUP_FILES, - ...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })), + ...perUinOnebotNames.filter(isPerUinOneBotName).map((n) => ({ name: n, binary: false, credential: true })), ]; for (const spec of all) { if (spec.credential && !opts.includeCredentials) continue; @@ -86,6 +103,13 @@ export function buildBackup( /** 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, +): { 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' }; } @@ -97,7 +121,9 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | } const files = b.files as Record; for (const [name, entry] of Object.entries(files)) { - if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` }; + const spec = specFor(name); + if (!spec) return { ok: false, error: `unknown file in backup: ${name}` }; + if (skipEntryValidation(spec)) continue; 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}` }; @@ -107,10 +133,8 @@ export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | } /** - * 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`. + * 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, @@ -120,9 +144,426 @@ export function planRestore( const skipped: string[] = []; for (const [name, entry] of Object.entries(backup.files)) { const spec = specFor(name); - if (!spec) { skipped.push(name); continue; } // validated, but be defensive + 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; + mode: 0o600 | 0o644; +} + +export interface RestoreMigration { + name: string; + fields: string[]; +} + +export interface PreparedRestorePlan { + restore: PreparedRestoreFile[]; + skipped: string[]; + migrated: RestoreMigration[]; +} + +export interface PrepareRestoreOptions { + restoreCredentials: boolean; + /** Read an existing live file for overlay-wide validation (TLS/UI). */ + readCurrent: (name: string) => Buffer | null; + /** Current per-account configs affected when onebot.json is replaced. */ + listCurrentOneBotNames?: () => string[]; +} + +export class RestorePreflightError extends Error { + readonly file: string; + + constructor(file: string, message: string, options?: { cause?: unknown }) { + super(`${file}: ${message}`, options); + this.name = 'RestorePreflightError'; + this.file = file; + } +} + +/** + * Validate every selected file semantically and materialize canonical bytes + * before the transaction is allowed to touch live configuration. + */ +export function prepareRestorePlan(parsed: unknown, opts: PrepareRestoreOptions): PreparedRestorePlan { + const checked = validateBackupEntries(parsed, (spec) => spec.credential && !opts.restoreCredentials); + if (!checked.ok) throw new RestorePreflightError('', checked.error); + + const restore: PreparedRestoreFile[] = []; + const skipped: string[] = []; + const migrated: RestoreMigration[] = []; + const selected: Array<{ name: string; data: Buffer; spec: BackupFileSpec }> = []; + let decodedBytes = 0; + + for (const [name, entry] of Object.entries(checked.backup.files)) { + const spec = specFor(name); + if (!spec) throw new RestorePreflightError(name, 'file is not in the restore allowlist'); + if (spec.credential && !opts.restoreCredentials) { + skipped.push(name); + continue; + } + if (entry.encoding !== (spec.binary ? 'base64' : 'utf8')) { + throw new RestorePreflightError(name, `encoding must be ${spec.binary ? 'base64' : 'utf8'}`); + } + + const decoded = decodeEntryStrict(name, entry); + decodedBytes += decoded.length; + if (decodedBytes > MAX_BACKUP_DECODED_BYTES) { + throw new RestorePreflightError(name, `selected files exceed ${String(MAX_BACKUP_DECODED_BYTES)} decoded bytes`); + } + + selected.push({ name, data: decoded, spec }); + } + + const selectedGlobal = selected.find((file) => file.name === 'onebot.json'); + const selectedPerUin = selected.filter((file) => isPerUinOneBotName(file.name)); + const selectedPerUinRaw = new Map(selectedPerUin.map((file) => [file.name, parseJson(file.name, file.data)])); + const perUinNeedsGlobal = [...selectedPerUinRaw.values()].some((raw) => !isPlainObject(raw) || raw.mode !== 'snapshot'); + let effectiveGlobalOneBot: unknown; + let preparedGlobalOneBot: ReturnType | null = null; + if (selectedGlobal) { + if (!opts.listCurrentOneBotNames) { + throw new RestorePreflightError('onebot.json', 'current per-account config listing is required to validate the effective overlay'); + } + const raw = parseJson(selectedGlobal.name, selectedGlobal.data); + preparedGlobalOneBot = prepareOneBotOrThrow(selectedGlobal.name, raw, 'global'); + effectiveGlobalOneBot = preparedGlobalOneBot.value; + } else if (perUinNeedsGlobal) { + const current = readCurrentForPreflight(opts, 'onebot.json'); + if (current) { + const raw = parseJson('onebot.json', current); + effectiveGlobalOneBot = prepareOneBotOrThrow('onebot.json', raw, 'global').value; + } + } + + for (const { name, data, spec } of selected) { + let prepared: { data: Buffer; migratedFields: string[] }; + if (name === 'onebot.json') { + const global = preparedGlobalOneBot!; + prepared = { data: serializeJson(global.value), migratedFields: global.migratedFields }; + } else if (isPerUinOneBotName(name)) { + const raw = selectedPerUinRaw.get(name); + const onebot = prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); + prepared = { data: serializeJson(onebot.value), migratedFields: onebot.migratedFields }; + } else { + prepared = prepareFile(name, data); + } + restore.push({ name, data: prepared.data, mode: spec.credential ? 0o600 : 0o644 }); + if (prepared.migratedFields.length > 0) { + migrated.push({ name, fields: [...prepared.migratedFields].sort() }); + } + } + + if (selectedGlobal) { + const selectedNames = new Set(selected.map((file) => file.name)); + let currentNames: string[]; + try { + currentNames = opts.listCurrentOneBotNames!(); + } catch (error) { + throw new RestorePreflightError('onebot.json', `failed to list current per-account configs: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } + for (const name of currentNames) { + if (!isPerUinOneBotName(name) || selectedNames.has(name)) continue; + const current = readCurrentForPreflight(opts, name); + if (!current) continue; + const raw = parseJson(name, current); + prepareOneBotOrThrow(name, raw, 'per-uin', effectiveGlobalOneBot); + } + } + + validateEffectiveTls(restore, opts); + validateEffectiveUi(restore, opts); + return { restore, skipped, migrated }; +} + +function decodeEntryStrict(name: string, entry: BackupEntry): Buffer { + if (entry.encoding === 'utf8') return Buffer.from(entry.data, 'utf8'); + if (!isCanonicalBase64(entry.data)) { + throw new RestorePreflightError(name, 'data is not canonical base64'); + } + return Buffer.from(entry.data, 'base64'); +} + +function isCanonicalBase64(value: string): boolean { + if (value.length === 0) return true; + if (value.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) { + return false; + } + return Buffer.from(value, 'base64').toString('base64') === value; +} + +function prepareFile(name: string, data: Buffer): { data: Buffer; migratedFields: string[] } { + try { + switch (name) { + case 'runtime.json': + return prepareRuntimeJson(name, data); + case 'ui.json': + return prepareNormalizedJson(name, data, normalizeStoredUiConfig); + case 'notifications.json': + return prepareNormalizedJson(name, data, normalizeNotificationsConfig); + case 'snowluma.json': + return prepareGlobalSettingsJson(name, data); + case 'webui.json': { + const value = parseJson(name, data); + const canonical = prepareWebuiAuthStateForRestore(value); + return { data: serializeJson(canonical), migratedFields: [] }; + } + case 'ui-assets/background': + if (data.length > MAX_BACKGROUND_BYTES) { + throw new Error(`image exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`); + } + if (!sniffImageMime(data)) throw new Error('image must be PNG, JPEG, or WebP'); + return { data, migratedFields: [] }; + case 'cert.pem': + case 'key.pem': + if (!data.toString('utf8').trim()) throw new Error('PEM file must not be empty'); + return { data, migratedFields: [] }; + default: + throw new Error('file is not in the restore allowlist'); + } + } catch (error) { + if (error instanceof RestorePreflightError) throw error; + throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error }); + } +} + +function prepareOneBotOrThrow( + name: string, + value: unknown, + scope: 'global' | 'per-uin', + inheritedGlobal?: unknown, +): ReturnType { + try { + return prepareOneBotConfigForRestore(value, scope, inheritedGlobal); + } catch (error) { + throw new RestorePreflightError(name, error instanceof Error ? error.message : String(error), { cause: error }); + } +} + +function readCurrentForPreflight(opts: PrepareRestoreOptions, name: string): Buffer | null { + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } +} + +function parseJson(name: string, data: Buffer): unknown { + try { + return JSON.parse(data.toString('utf8')) as unknown; + } catch (error) { + // V8 may quote the offending input in SyntaxError.message. Some restored + // JSON files contain credentials, so expose only a fixed diagnostic while + // retaining the original exception as the in-process cause. + throw new RestorePreflightError(name, 'invalid JSON', { cause: error }); + } +} + +function prepareNormalizedJson(name: string, data: Buffer, normalize: (value: unknown) => T): { + data: Buffer; + migratedFields: string[]; +} { + const raw = parseJson(name, data); + const canonical = normalize(raw); + const migratedFields: string[] = []; + assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); + return { data: serializeJson(canonical), migratedFields }; +} + +function prepareRuntimeJson(name: string, data: Buffer): { + data: Buffer; + migratedFields: string[]; +} { + const prepared = prepareNormalizedJson(name, data, normalizeRuntimeConfig); + const runtime = JSON.parse(prepared.data.toString('utf8')) as ReturnType; + if (!runtime.webuiHost || !isValidBindHost(runtime.webuiHost)) { + throw new RestorePreflightError(name, '$.webuiHost is not a valid TCP bind host'); + } + return prepared; +} + +function prepareGlobalSettingsJson(name: string, data: Buffer): { + data: Buffer; + migratedFields: string[]; +} { + const raw = parseJson(name, data); + const normalized = normalizeGlobalSettings(raw); + const canonical: Record = { rkey: normalized.rkey }; + // Missing is the existing one-shot migration sentinel: startup scans legacy + // onebot*.json only until snowluma.json first carries this key. + if (isPlainObject(raw) && Object.prototype.hasOwnProperty.call(raw, 'musicSignUrl')) { + canonical.musicSignUrl = normalized.musicSignUrl; + } + const migratedFields: string[] = []; + assertNoLossyNormalization(name, raw, canonical, '$', migratedFields); + return { data: serializeJson(canonical), migratedFields }; +} + +function assertNoLossyNormalization( + name: string, + raw: unknown, + canonical: unknown, + at: string, + additions: string[], +): void { + if (isPlainObject(raw)) { + if (!isPlainObject(canonical)) throw new RestorePreflightError(name, `${at} has an invalid type`); + for (const [key, rawValue] of Object.entries(raw)) { + const child = `${at}.${key}`; + if (!Object.prototype.hasOwnProperty.call(canonical, key)) { + throw new RestorePreflightError(name, `${child} is unsupported or would be discarded`); + } + assertNoLossyNormalization(name, rawValue, canonical[key], child, additions); + } + for (const key of Object.keys(canonical)) { + if (!Object.prototype.hasOwnProperty.call(raw, key)) additions.push(`${at}.${key}`); + } + return; + } + if (Array.isArray(raw)) { + if (!Array.isArray(canonical) || raw.length !== canonical.length) { + throw new RestorePreflightError(name, `${at} contains an invalid, duplicate, or discarded item`); + } + raw.forEach((value, index) => { + assertNoLossyNormalization(name, value, canonical[index], `${at}[${String(index)}]`, additions); + }); + return; + } + if (!Object.is(raw, canonical)) { + if (isKnownLosslessScalarCoercion(name, at, raw, canonical)) { + additions.push(at); + return; + } + throw new RestorePreflightError(name, `${at} is invalid or would be changed`); + } +} + +function isKnownLosslessScalarCoercion(name: string, at: string, raw: unknown, canonical: unknown): boolean { + if (typeof raw === 'string' && typeof canonical === 'string' && raw.trim() === canonical) { + return true; + } + if (typeof raw === 'string' && typeof canonical === 'number') { + const parsed = Number(raw.trim()); + return raw.trim().length > 0 && Number.isFinite(parsed) && Object.is(parsed, canonical); + } + if ( + name === 'runtime.json' && + (at === '$.hookAutoLoad' || at === '$.webuiTls.enabled') && + typeof canonical === 'boolean' + ) { + if (raw === 1 || raw === 0) return canonical === (raw === 1); + if (typeof raw !== 'string') return false; + const token = raw.trim().toLowerCase(); + const truthy = new Set(['true', '1', 'yes', 'on']); + const falsy = new Set(['false', '0', 'no', 'off', '']); + return (canonical && truthy.has(token)) || (!canonical && falsy.has(token)); + } + return false; +} + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function serializeJson(value: unknown): Buffer { + return Buffer.from(JSON.stringify(value, null, 2), 'utf8'); +} + +function isValidBindHost(value: string): boolean { + const host = value.trim(); + if (!host || host !== value || host.length > 253 || /[\s/?#@]/u.test(host)) return false; + if (host.includes(':')) return isIP(host) === 6; + if (/^[\d.]+$/.test(host)) { + return isIP(host) === 4; + } + const normalized = host.endsWith('.') ? host.slice(0, -1) : host; + return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(? [file.name, file.data])); + const pairTouched = byName.has('cert.pem') || byName.has('key.pem'); + const tlsRelated = pairTouched || byName.has('runtime.json'); + if (!tlsRelated) return; + + const readEffective = (name: string): Buffer | null => { + const prepared = byName.get(name); + if (prepared) return prepared; + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } + }; + const runtime = readEffective('runtime.json'); + let tlsEnabled = false; + if (runtime) { + try { + tlsEnabled = normalizeRuntimeConfig(JSON.parse(runtime.toString('utf8')) as unknown).webuiTls?.enabled === true; + } catch (error) { + throw new RestorePreflightError('runtime.json', 'effective runtime config is invalid JSON', { cause: error }); + } + } + + if (!tlsEnabled && !pairTouched) return; + const cert = readEffective('cert.pem'); + const key = readEffective('key.pem'); + + if (cert && key) { + const valid = validateTlsPair(cert, key); + if (!valid.ok) throw new RestorePreflightError('cert.pem + key.pem', valid.reason ?? 'TLS pair is invalid'); + return; + } + if (tlsEnabled) { + throw new RestorePreflightError('cert.pem + key.pem', 'TLS is enabled but the effective certificate/private-key pair is incomplete'); + } +} + +function validateEffectiveUi(restore: PreparedRestoreFile[], opts: PrepareRestoreOptions): void { + const byName = new Map(restore.map((file) => [file.name, file.data])); + if (!byName.has('ui.json') && !byName.has('ui-assets/background')) return; + + const readEffective = (name: string): Buffer | null => { + const prepared = byName.get(name); + if (prepared) return prepared; + try { + return opts.readCurrent(name); + } catch (error) { + throw new RestorePreflightError(name, `failed to read current file: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); + } + }; + const uiBytes = readEffective('ui.json'); + if (!uiBytes) return; + + let ui; + try { + ui = normalizeStoredUiConfig(JSON.parse(uiBytes.toString('utf8')) as unknown); + } catch (error) { + throw new RestorePreflightError('ui.json', 'effective UI config is invalid JSON', { cause: error }); + } + const background = ui.appearance.background; + if (!background.hasImage) return; + + const image = readEffective('ui-assets/background'); + if (!image) { + throw new RestorePreflightError('ui.json + ui-assets/background', 'background metadata says an image exists, but the effective image is missing'); + } + if (image.length > MAX_BACKGROUND_BYTES) { + throw new RestorePreflightError('ui.json + ui-assets/background', `effective background exceeds ${String(MAX_BACKGROUND_BYTES)} bytes`); + } + const mime = sniffImageMime(image); + if (!mime) { + throw new RestorePreflightError('ui.json + ui-assets/background', 'effective background is not PNG, JPEG, or WebP'); + } + if (mime !== background.imageMime) { + throw new RestorePreflightError( + 'ui.json + ui-assets/background', + `background metadata MIME ${background.imageMime} does not match image bytes ${mime}`, + ); + } +} diff --git a/packages/core/src/webui/ui-config.ts b/packages/core/src/webui/ui-config.ts index 240d2970..b8830ac2 100644 --- a/packages/core/src/webui/ui-config.ts +++ b/packages/core/src/webui/ui-config.ts @@ -474,6 +474,11 @@ function imageStateFromParsed(parsed: unknown): ServerImageState { return sanitizeImageState(parsed.appearance.background); } +/** Normalize a complete ui.json read from disk or a backup bundle. */ +export function normalizeStoredUiConfig(value: unknown): UiConfig { + return normalizeUiConfig(value, imageStateFromParsed(value)); +} + function normalizeBackground(value: unknown, imageState: ServerImageState): UiBackground { const v = isObject(value) ? value : {}; let type = oneOf(v.type, ['none', 'solid', 'gradient', 'image'], DEFAULT_BACKGROUND.type); @@ -615,7 +620,7 @@ export function loadUiConfig(): UiConfig { const parsed = JSON.parse(raw) as unknown; // On load, the file itself is the source of truth for the server-managed // image fields — so they survive restarts (don't reset to defaults). - const normalized = normalizeUiConfig(parsed, imageStateFromParsed(parsed)); + const normalized = normalizeStoredUiConfig(parsed); // Re-persist only if normalization changed something (corrupt/old file), // so we self-heal on disk without rewriting on every boot. if (JSON.stringify(parsed) !== JSON.stringify(normalized)) { diff --git a/packages/core/tests/webui-backup.test.ts b/packages/core/tests/webui-backup.test.ts index e907ec13..446475b9 100644 --- a/packages/core/tests/webui-backup.test.ts +++ b/packages/core/tests/webui-backup.test.ts @@ -1,5 +1,12 @@ import { describe, it, expect } from 'vitest'; -import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup'; +import { + BACKUP_FILES, + MAX_BACKUP_DECODED_BYTES, + RestorePreflightError, + specFor, + buildBackup, + prepareRestorePlan, +} from '../src/webui/backup'; const TS = '2026-06-18T00:00:00.000Z'; @@ -39,6 +46,11 @@ describe('buildBackup', () => { ); }); + it('does not export a per-UIN file that the import allowlist must reject', () => { + const b = buildBackup(reader({ 'onebot_1.json': Buffer.from('{}') }), ['onebot_1.json'], { includeCredentials: true }, TS); + expect(b.files).toEqual({}); + }); + 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); @@ -54,70 +66,8 @@ describe('specFor', () => { 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 (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', () => { - 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); - expect(validateBackup({ ...good, files: { 'onebot_../x.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('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') }, - }, - }; - 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 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 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'], - ); + expect(specFor('onebot_1.json')).toBeNull(); + expect(specFor('onebot_12345678901.json')).toBeNull(); }); }); @@ -126,3 +76,684 @@ it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.p expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']); expect(specFor('cert.pem')?.credential).toBe(false); }); + +describe('prepareRestorePlan — strict semantic preflight', () => { + const backupWith = (files: Record) => ({ + version: 1, + app: 'snowluma', + files, + }); + + it.each([ + ['non-object bundle', null, /backup must be an object/i], + ['wrong app', { version: 1, app: 'other', files: {} }, /not a SnowLuma backup/i], + ['wrong version', { version: 999, app: 'snowluma', files: {} }, /unsupported backup version/i], + [ + 'malformed entry', + { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8' } } }, + /bad data for runtime\.json/i, + ], + ])('rejects %s through the production preflight entrypoint', (_label, input, expected) => { + expect(() => prepareRestorePlan(input, { + restoreCredentials: false, + readCurrent: () => null, + })).toThrow(expected); + }); + + it('canonicalizes a recognized older runtime config and reports added fields', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{"webuiPort":5099}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({ + webuiPort: 5099, + hookAutoLoad: false, + webuiHost: '0.0.0.0', + webuiTls: { enabled: false }, + trustProxy: '', + }); + expect(prepared.migrated).toEqual([{ + name: 'runtime.json', + fields: ['$.hookAutoLoad', '$.trustProxy', '$.webuiHost', '$.webuiTls'], + }]); + }); + + it('rejects a present runtime value that normalization would silently replace', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{"webuiPort":70000}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrowError(expect.objectContaining>({ + name: 'RestorePreflightError', + file: 'runtime.json', + })); + }); + + it('rejects a notification channel that total normalization would silently drop', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'notifications.json': { + encoding: 'utf8', + data: JSON.stringify({ + version: 1, + debounceSeconds: 30, + channels: [{ id: 'ops', name: 'Ops', url: 'file:///tmp/leak', bodyTemplate: '{}', enabled: true }], + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/notifications\.json.*channels/i); + }); + + it('does not validate credential files that the operator chose to skip', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'webui.json': { encoding: 'utf8', data: '{definitely broken' }, + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(prepared.skipped).toEqual(['webui.json']); + expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']); + }); + + it('does not require even a well-formed entry envelope for a skipped credential', () => { + const prepared = prepareRestorePlan({ + version: 1, + app: 'snowluma', + files: { + 'webui.json': { encoding: 'rot13' }, + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }, + }, { restoreCredentials: false, readCurrent: () => null }); + + expect(prepared.skipped).toEqual(['webui.json']); + expect(prepared.restore.map((entry) => entry.name)).toEqual(['runtime.json']); + }); + + it('rejects malformed WebUI credential state when credential restore is enabled', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'webui.json': { + encoding: 'utf8', + data: JSON.stringify({ passwordHash: 'zz', passwordSalt: '00', mustChangePassword: false }), + }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + )).toThrow(/webui\.json.*passwordHash/i); + }); + + it('does not copy malformed sensitive JSON contents into the reported error', () => { + const secret = 'super-secret-token'; + let thrown: unknown; + try { + prepareRestorePlan( + backupWith({ + 'onebot.json': { encoding: 'utf8', data: secret }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'onebot.json: invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('rejects a background blob whose bytes are not a supported image', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui-assets/background': { + encoding: 'base64', + data: Buffer.from('not an image').toString('base64'), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui-assets\/background.*PNG.*JPEG.*WebP/i); + }); + + it('rejects an invalid effective TLS pair', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'not a certificate' }, + 'key.pem': { encoding: 'utf8', data: 'not a private key' }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/cert\.pem.*key\.pem/i); + }); + + it('fails fast when TLS validation needs a malformed current runtime config', () => { + const secret = 'runtime-secret-fragment'; + let thrown: unknown; + + try { + prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'not a certificate' }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'runtime.json' ? Buffer.from(secret) : null, + }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'runtime.json: effective runtime config is invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('assigns restrictive modes to every credential file', () => { + const validAuth = { + passwordHash: 'ab'.repeat(64), + passwordSalt: 'cd'.repeat(16), + mustChangePassword: false, + generatedAt: TS, + updatedAt: TS, + }; + const prepared = prepareRestorePlan( + backupWith({ + 'webui.json': { encoding: 'utf8', data: JSON.stringify(validAuth) }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + ); + + expect(prepared.restore).toEqual([ + expect.objectContaining({ name: 'webui.json', mode: 0o600 }), + ]); + }); + + it('rejects an encoding that does not match the allowlisted file kind', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'base64', data: Buffer.from('{}').toString('base64') }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*encoding must be utf8/i); + }); + + it('rejects non-canonical base64 instead of accepting Node partial decoding', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui-assets/background': { encoding: 'base64', data: '%%%%' }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/background.*canonical base64/i); + }); + + it('enforces the decoded-byte cap independently of request Content-Length', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'cert.pem': { encoding: 'utf8', data: 'x'.repeat(MAX_BACKUP_DECODED_BYTES + 1) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/decoded bytes/i); + }); + + it('rejects lossy normalization in global SnowLuma settings', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ rkey: { fallbackServers: ['file:///tmp/not-http'] }, musicSignUrl: '' }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/snowluma\.json.*fallbackServers/i); + }); + + it('rejects a present invalid UI value instead of silently defaulting it', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui.json': { + encoding: 'utf8', + data: JSON.stringify({ appearance: { mode: 'ultraviolet' } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui\.json.*mode/i); + }); + + it('migrates a known legacy per-account OneBot layout to a canonical overlay', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + httpServers: [{ name: 'legacy-http', port: '3100' }], + messageFormat: 'string', + reportSelfMessage: true, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.mode).toBe('overlay'); + expect(canonical.networks.httpServers).toEqual([expect.objectContaining({ + name: 'legacy-http', + port: 3100, + messageFormat: 'string', + reportSelfMessage: true, + })]); + expect(prepared.migrated).toEqual([{ name: 'onebot_12345.json', fields: ['$'] }]); + }); + + it('rejects a OneBot adapter that compatibility parsing would discard', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ networks: { httpServers: [{ name: 'broken', port: 0 }] } }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/onebot_12345\.json.*port/i); + }); + + it('rejects enabling TLS when the effective pair is incomplete', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { + encoding: 'utf8', + data: JSON.stringify({ webuiTls: { enabled: true } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/cert\.pem.*key\.pem.*incomplete/i); + }); + + it('rejects a UI config that claims a background image which is absent from the effective overlay', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'ui.json': { + encoding: 'utf8', + data: JSON.stringify({ + appearance: { + background: { + type: 'image', + hasImage: true, + imageMime: 'image/png', + imageVersion: 1, + }, + }, + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/ui\.json.*background.*missing/i); + }); + + it('does not expose malformed current UI contents while validating a restored background', () => { + const secret = 'ui-secret-fragment'; + let thrown: unknown; + + try { + prepareRestorePlan( + backupWith({ + 'ui-assets/background': { + encoding: 'base64', + data: Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).toString('base64'), + }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'ui.json' ? Buffer.from(secret) : null, + }, + ); + } catch (error) { + thrown = error; + } + + expect(thrown).toEqual(expect.objectContaining({ + name: 'RestorePreflightError', + message: 'ui.json: effective UI config is invalid JSON', + })); + expect((thrown as Error).message).not.toContain(secret); + }); + + it('rejects a OneBot global/per-account overlay that is invalid only after merge', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ + httpServers: [{ name: 'dup', port: 3100 }], + }), + }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'overlay', + wsClients: [{ name: 'dup', url: 'ws://127.0.0.1:9000' }], + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null, listCurrentOneBotNames: () => [] }, + )).toThrow(/onebot_12345\.json.*duplicated/i); + }); + + it('validates current per-account overlays affected by a restored global OneBot config', () => { + const currentPerUin = Buffer.from(JSON.stringify({ + mode: 'overlay', + wsClients: [{ name: 'dup', url: 'ws://127.0.0.1:9000' }], + })); + expect(() => prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ httpServers: [{ name: 'dup', port: 3100 }] }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot_54321.json' ? currentPerUin : null, + listCurrentOneBotNames: () => ['onebot_54321.json'], + }, + )).toThrow(/onebot_54321\.json.*duplicated/i); + }); + + it('canonicalizes a per-account overlay against the effective global OneBot config', () => { + const currentGlobal = Buffer.from(JSON.stringify({ + messageFormat: 'string', + reportSelfMessage: true, + statusCommand: { trigger: '#global' }, + notifications: { channelIds: ['ops'] }, + })); + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'overlay', + httpClients: [{ name: 'remote', url: 'https://example.test/onebot' }], + }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot.json' ? currentGlobal : null, + }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.mode).toBe('overlay'); + expect(canonical.networks.httpClients[0]).toEqual(expect.objectContaining({ + messageFormat: 'string', + reportSelfMessage: true, + })); + expect(canonical.statusCommand.trigger).toBe('#global'); + expect(canonical.notifications.channelIds).toEqual(['ops']); + }); + + it('accepts lossless scalar spellings already supported by the runtime owner', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { + encoding: 'utf8', + data: JSON.stringify({ webuiPort: '5099', hookAutoLoad: 1, webuiTls: { enabled: 0 } }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.webuiPort).toBe(5099); + expect(canonical.hookAutoLoad).toBe(true); + expect(canonical.webuiTls.enabled).toBe(false); + }); + + it('accepts owner-supported whitespace trimming without accepting changed values', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ + rkey: { fallbackServers: [' https://a.example/r '] }, + musicSignUrl: ' https://sign.example/card ', + }), + }, + }), + { restoreCredentials: false, readCurrent: () => null }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8'))).toEqual({ + rkey: { fallbackServers: ['https://a.example/r'] }, + musicSignUrl: 'https://sign.example/card', + }); + }); + + it('does not read an unrelated current global OneBot file for a snapshot restore', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ mode: 'snapshot' }), + }, + }), + { + restoreCredentials: true, + readCurrent: (name) => name === 'onebot.json' ? Buffer.from('{broken') : null, + }, + ); + + expect(JSON.parse(prepared.restore[0].data.toString('utf8')).mode).toBe('snapshot'); + }); + + it('canonicalizes owner-supported OneBot notification id trimming and deduplication', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + notifications: { channelIds: [' ops ', 'ops'] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.notifications.channelIds).toEqual(['ops']); + }); + + it('accepts disabled OneBot clients whose legacy config omitted the unused URL', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { + httpClients: [{ name: 'http-off', enabled: false }], + wsClients: [{ name: 'ws-off', enabled: false }], + }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.networks.httpClients[0].url).toBe(''); + expect(canonical.networks.wsClients[0].url).toBe(''); + }); + + it('measures a OneBot status trigger after owner-supported whitespace trimming', () => { + const trigger = 'a'.repeat(32); + const prepared = prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + statusCommand: { trigger: ` ${trigger} ` }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + const canonical = JSON.parse(prepared.restore[0].data.toString('utf8')); + expect(canonical.statusCommand.trigger).toBe(trigger); + }); + + it('preserves the missing musicSignUrl migration sentinel in an older global config', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'snowluma.json': { + encoding: 'utf8', + data: JSON.stringify({ rkey: { fallbackServers: [] } }), + }, + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ musicSignUrl: 'https://legacy.example/sign' }), + }, + }), + { + restoreCredentials: true, + readCurrent: () => null, + listCurrentOneBotNames: () => [], + }, + ); + + const byName = Object.fromEntries(prepared.restore.map((file) => [ + file.name, + JSON.parse(file.data.toString('utf8')), + ])); + expect(byName['snowluma.json']).not.toHaveProperty('musicSignUrl'); + expect(byName['onebot.json'].musicSignUrl).toBe('https://legacy.example/sign'); + }); + + it('preserves legacy per-account defaults that apply to inherited global adapters', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot.json': { + encoding: 'utf8', + data: JSON.stringify({ httpServers: [{ name: 'global-http', port: 3100 }] }), + }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ messageFormat: 'string', reportSelfMessage: true }), + }, + }), + { + restoreCredentials: true, + readCurrent: () => null, + listCurrentOneBotNames: () => [], + }, + ); + + const perUin = prepared.restore.find((file) => file.name === 'onebot_12345.json')!; + expect(JSON.parse(perUin.data.toString('utf8')).networks.httpServers[0]).toEqual(expect.objectContaining({ + name: 'global-http', + messageFormat: 'string', + reportSelfMessage: true, + })); + }); + + it('rejects per-account filenames that startup would immediately delete', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_1.json': { encoding: 'utf8', data: JSON.stringify({ mode: 'snapshot' }) }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/unknown file/i); + }); + + it('rejects syntactically invalid WebUI and OneBot bind hosts', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: 'bad host' }) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*webuiHost/i); + + expect(() => prepareRestorePlan( + backupWith({ + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { httpServers: [{ name: 'bad', host: 'bad host', port: 3100 }] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + )).toThrow(/onebot_12345\.json.*host/i); + }); + + it('keeps valid IPv6 bind hosts while applying syntax checks', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: '::' }) }, + 'onebot_12345.json': { + encoding: 'utf8', + data: JSON.stringify({ + mode: 'snapshot', + networks: { httpServers: [{ name: 'v6', host: '::1', port: 3100 }] }, + }), + }, + }), + { restoreCredentials: true, readCurrent: () => null }, + ); + + expect(prepared.restore.map((file) => file.name).sort()).toEqual(['onebot_12345.json', 'runtime.json']); + }); + + it('rejects malformed IPv6 zone syntax that Node cannot bind', () => { + expect(() => prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: JSON.stringify({ webuiHost: '::1%bad%extra' }) }, + }), + { restoreCredentials: false, readCurrent: () => null }, + )).toThrow(/runtime\.json.*webuiHost/i); + }); + + it('ignores untouched invalid PEM files while effective TLS is disabled', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'runtime.json': { encoding: 'utf8', data: '{}' }, + }), + { + restoreCredentials: false, + readCurrent: (name) => name === 'cert.pem' || name === 'key.pem' ? Buffer.from('invalid PEM') : null, + }, + ); + + expect(prepared.restore.map((file) => file.name)).toEqual(['runtime.json']); + }); + + it('does not inspect invalid per-UIN files that startup cleanup owns', () => { + const prepared = prepareRestorePlan( + backupWith({ + 'onebot.json': { encoding: 'utf8', data: '{}' }, + }), + { + restoreCredentials: true, + readCurrent: (name) => { + if (name === 'onebot_1.json') throw new Error('invalid UIN file should not be read'); + return null; + }, + listCurrentOneBotNames: () => ['onebot_1.json'], + }, + ); + + expect(prepared.restore.map((file) => file.name)).toEqual(['onebot.json']); + }); +}); diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 45acb727..7375e1e9 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -2,6 +2,7 @@ import { createLogger } from '@snowluma/common/logger'; import { isRealUin } from '@snowluma/common/uin'; import { randomBytes } from 'crypto'; import fs from 'fs'; +import { isIP } from 'node:net'; import path from 'path'; import type { HttpClientNetwork, @@ -127,6 +128,237 @@ export function saveOneBotConfig( saveJson(perUinPath, toJsonObject(config, options.mode ?? 'snapshot')); } +export interface PreparedOneBotConfigRestore { + value: JsonObject; + migratedFields: string[]; +} + +/** + * Parse and canonicalize an on-disk OneBot config without touching the + * filesystem. Restore uses this owner-provided seam so legacy layouts are + * migrated deliberately while malformed values cannot disappear through the + * normal load path's permissive compatibility parser. + */ +export function prepareOneBotConfigForRestore( + value: unknown, + scope: 'global' | 'per-uin', + inheritedGlobal?: unknown, +): PreparedOneBotConfigRestore { + if (!isObject(value)) invalid('restore source must be an object'); + validateOneBotRestoreSource(value); + + let global: JsonObject | null = null; + if (inheritedGlobal !== undefined && inheritedGlobal !== null) { + if (!isObject(inheritedGlobal)) invalid('inherited global restore source must be an object'); + validateOneBotRestoreSource(inheritedGlobal); + global = inheritedGlobal; + } + + // onebot.json is an inheritance source. Materializing its adapter defaults + // in isolation changes how existing per-UIN legacy overlays are interpreted. + // Strictly validate it, but preserve its source structure. + if (scope === 'global') { + return { value, migratedFields: [] }; + } + + const sources = value.mode !== PER_UIN_SNAPSHOT_MARKER && global + ? [global, value] + : [value]; + const config = fromJson(sources, false); + const mode = scope === 'per-uin' && value.mode === PER_UIN_SNAPSHOT_MARKER + ? 'snapshot' + : 'overlay'; + const canonical = toJsonObject(config, mode); + + // These legacy global defaults also apply to adapters declared by a + // per-account overlay. Keep them until every overlay has naturally been + // materialized, otherwise canonicalizing onebot.json changes inheritance. + // Keep the one known cross-file legacy field until startup's existing + // migrateGlobalSettings copy-up moves it into snowluma.json. + if (Object.prototype.hasOwnProperty.call(value, 'musicSignUrl')) { + canonical.musicSignUrl = value.musicSignUrl; + } + + return { + value: canonical, + migratedFields: JSON.stringify(value) === JSON.stringify(canonical) ? [] : ['$'], + }; +} + +const RESTORE_TOP_LEVEL_KEYS = new Set([ + 'mode', 'networks', 'statusCommand', 'notifications', 'musicSignUrl', + 'httpServers', 'httpClients', 'httpPostEndpoints', 'wsServers', 'wsClients', + 'messageFormat', 'reportSelfMessage', +]); + +const RESTORE_NETWORK_KEYS = new Set(['httpServers', 'httpClients', 'wsServers', 'wsClients']); +const RESTORE_BASE_ADAPTER_KEYS = ['name', 'enabled', 'accessToken', 'messageFormat', 'reportSelfMessage'] as const; + +function validateOneBotRestoreSource(value: JsonObject): void { + rejectUnknownKeys(value, RESTORE_TOP_LEVEL_KEYS, '$'); + if (value.mode !== undefined && value.mode !== 'snapshot' && value.mode !== 'overlay') { + invalid('$.mode must be snapshot or overlay'); + } + if (value.messageFormat !== undefined && parseMessageFormat(value.messageFormat) === undefined) { + invalid('$.messageFormat must be array or string'); + } + if (value.reportSelfMessage !== undefined && typeof value.reportSelfMessage !== 'boolean') { + invalid('$.reportSelfMessage must be a boolean'); + } + if (value.musicSignUrl !== undefined) { + if (typeof value.musicSignUrl !== 'string') invalid('$.musicSignUrl must be a string'); + const url = value.musicSignUrl.trim(); + if (url && !isHttpUrlForRestore(url)) invalid('$.musicSignUrl must be empty or an http(s) URL'); + } + + const networks = value.networks; + if (networks !== undefined) { + if (!isObject(networks)) invalid('$.networks must be an object'); + rejectUnknownKeys(networks, RESTORE_NETWORK_KEYS, '$.networks'); + } + + const counts: Record = { + httpServers: 0, + httpClients: 0, + wsServers: 0, + wsClients: 0, + }; + const visit = (owner: JsonObject, key: keyof OneBotNetworks, pathPrefix: string): void => { + if (owner[key] === undefined) return; + counts[key] += validateRestoreAdapterArray(owner[key], key, `${pathPrefix}.${key}`); + }; + if (isObject(networks)) { + for (const key of RESTORE_NETWORK_KEYS) visit(networks, key as keyof OneBotNetworks, '$.networks'); + } + for (const key of RESTORE_NETWORK_KEYS) visit(value, key as keyof OneBotNetworks, '$'); + if (value.httpPostEndpoints !== undefined) { + counts.httpClients += validateRestoreAdapterArray(value.httpPostEndpoints, 'httpClients', '$.httpPostEndpoints'); + } + + validateRestoreStatusCommand(value.statusCommand); + validateRestoreNotifications(value.notifications); + + const parsed = fromJson([value], false); + for (const key of RESTORE_NETWORK_KEYS) { + const kind = key as keyof OneBotNetworks; + if (parsed.networks[kind].length !== counts[kind]) { + invalid(`$.${kind} contains a duplicate or unusable adapter`); + } + } +} + +function validateRestoreAdapterArray(value: unknown, kind: keyof OneBotNetworks, at: string): number { + if (!Array.isArray(value)) invalid(`${at} must be an array`); + const specific = kind === 'httpServers' || kind === 'wsServers' + ? ['host', 'port', 'path'] + : kind === 'httpClients' + ? ['url', 'timeoutMs'] + : ['url', 'role', 'reconnectIntervalMs']; + if (kind === 'wsServers') specific.push('role'); + const allowed = new Set([...RESTORE_BASE_ADAPTER_KEYS, ...specific]); + + value.forEach((raw, index) => { + const pathAt = `${at}[${String(index)}]`; + if (!isObject(raw)) invalid(`${pathAt} must be an object`); + rejectUnknownKeys(raw, allowed, pathAt); + if (raw.name !== undefined && typeof raw.name !== 'string') invalid(`${pathAt}.name must be a string`); + if (raw.enabled !== undefined && typeof raw.enabled !== 'boolean') invalid(`${pathAt}.enabled must be a boolean`); + if (raw.accessToken !== undefined && typeof raw.accessToken !== 'string') invalid(`${pathAt}.accessToken must be a string`); + if (raw.messageFormat !== undefined && parseMessageFormat(raw.messageFormat) === undefined) { + invalid(`${pathAt}.messageFormat must be array or string`); + } + if (raw.reportSelfMessage !== undefined && typeof raw.reportSelfMessage !== 'boolean') { + invalid(`${pathAt}.reportSelfMessage must be a boolean`); + } + + if (kind === 'httpServers' || kind === 'wsServers') { + const port = parseRestoreInteger(raw.port); + if (port === null || port <= 0 || port > 65535) invalid(`${pathAt}.port must be an integer between 1 and 65535`); + if (raw.host !== undefined && typeof raw.host !== 'string') invalid(`${pathAt}.host must be a string`); + if (raw.path !== undefined && typeof raw.path !== 'string') invalid(`${pathAt}.path must be a string`); + } else { + if (raw.url !== undefined && typeof raw.url !== 'string') invalid(`${pathAt}.url must be a string`); + if (raw.url === undefined && raw.enabled !== false) invalid(`${pathAt}.url is required while the adapter is enabled`); + } + if (kind === 'httpClients' && raw.timeoutMs !== undefined) { + const timeout = parseRestoreInteger(raw.timeoutMs); + if (timeout === null || timeout <= 0 || timeout > NODE_TIMER_MAX_MS) { + invalid(`${pathAt}.timeoutMs must be an integer between 1 and ${NODE_TIMER_MAX_MS}`); + } + } + if (kind === 'wsServers' || kind === 'wsClients') { + const role = raw.role; + if (role !== undefined && !['api', 'event', 'universal'].includes(String(role).toLowerCase())) { + invalid(`${pathAt}.role must be Api, Event, or Universal`); + } + } + if (kind === 'wsClients' && raw.reconnectIntervalMs !== undefined) { + const interval = parseRestoreInteger(raw.reconnectIntervalMs); + if (interval === null || interval < 1000 || interval > NODE_TIMER_MAX_MS) { + invalid(`${pathAt}.reconnectIntervalMs must be an integer between 1000 and ${NODE_TIMER_MAX_MS}`); + } + } + }); + return value.length; +} + +function validateRestoreStatusCommand(value: unknown): void { + if (value === undefined) return; + if (!isObject(value)) invalid('$.statusCommand must be an object'); + rejectUnknownKeys(value, new Set(['enabled', 'swallow', 'cooldownSeconds', 'trigger']), '$.statusCommand'); + if (value.enabled !== undefined && typeof value.enabled !== 'boolean') invalid('$.statusCommand.enabled must be a boolean'); + if (value.swallow !== undefined && typeof value.swallow !== 'boolean') invalid('$.statusCommand.swallow must be a boolean'); + if (value.cooldownSeconds !== undefined) { + const cooldown = parseRestoreInteger(value.cooldownSeconds); + if (cooldown === null || cooldown < 0 || cooldown > STATUS_COMMAND_COOLDOWN_MAX) { + invalid(`$.statusCommand.cooldownSeconds must be an integer between 0 and ${STATUS_COMMAND_COOLDOWN_MAX}`); + } + } + if (value.trigger !== undefined) { + const trigger = typeof value.trigger === 'string' ? value.trigger.trim() : ''; + if ( + typeof value.trigger !== 'string' || !trigger || /[\r\n]/.test(value.trigger) || + trigger.length > STATUS_COMMAND_TRIGGER_MAX_LENGTH + ) { + invalid(`$.statusCommand.trigger must be non-empty, single-line, and <= ${STATUS_COMMAND_TRIGGER_MAX_LENGTH} characters`); + } + } +} + +function validateRestoreNotifications(value: unknown): void { + if (value === undefined) return; + if (!isObject(value)) invalid('$.notifications must be an object'); + rejectUnknownKeys(value, new Set(['channelIds']), '$.notifications'); + if (value.channelIds === undefined) return; + if (!Array.isArray(value.channelIds)) invalid('$.notifications.channelIds must be an array'); + value.channelIds.forEach((id, index) => { + if (typeof id !== 'string') invalid(`$.notifications.channelIds[${String(index)}] must be a string`); + const normalized = id.trim(); + if (!normalized || normalized.length > 64 || !/^[\w.-]+$/.test(normalized)) { + invalid(`$.notifications.channelIds[${String(index)}] is invalid`); + } + }); +} + +function rejectUnknownKeys(value: JsonObject, allowed: ReadonlySet, at: string): void { + const unknown = Object.keys(value).find((key) => !allowed.has(key)); + if (unknown) invalid(`${at}.${unknown} is not supported`); +} + +function parseRestoreInteger(value: unknown): number | null { + const number = typeof value === 'string' && value.trim() ? Number(value) : value; + return typeof number === 'number' && Number.isSafeInteger(number) ? number : null; +} + +function isHttpUrlForRestore(value: string): boolean { + try { + const parsed = new URL(value); + return (parsed.protocol === 'http:' || parsed.protocol === 'https:') && parsed.host.length > 0; + } catch { + return false; + } +} + /** Validate the normalized, public OneBot configuration shape before it is * persisted or compiled into a live network plan. Adapter names form one * process-wide namespace per account, not four independent namespaces. */ @@ -251,6 +483,7 @@ function validateServer(item: JsonObject, at: string): void { if (typeof item.host !== 'string') invalid(`${at}.host must be a string`); if (!item.host.trim()) invalid(`${at}.host must be a non-empty string when provided`); if (item.host !== item.host.trim()) invalid(`${at}.host must not have surrounding whitespace`); + if (!isValidBindHost(item.host)) invalid(`${at}.host must be a valid TCP bind host`); } if (item.path !== undefined) { if (typeof item.path !== 'string') invalid(`${at}.path must be a string`); @@ -714,3 +947,13 @@ function saveJson(filePath: string, json: JsonObject): void { function isObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } + +function isValidBindHost(value: string): boolean { + if (!value || value.length > 253 || /[\s/?#@]/u.test(value)) return false; + if (value.includes(':')) return isIP(value) === 6; + if (/^[\d.]+$/.test(value)) { + return isIP(value) === 4; + } + const normalized = value.endsWith('.') ? value.slice(0, -1) : value; + return normalized.split('.').every((label) => /^(?!-)[A-Za-z0-9-]{1,63}(?