/** * Two read-only questions apply asks before it touches anything: * * - is the node stopped? The server writes NO pid file or lock (checked in * `server/backend`), so the proof is "no process holds a file of this data * dir open". Never answered by opening the database. * - is the backup real? It exists, is not empty, is readable, and is not * inside the tree the migration is about to rename. */ import { execFile } from 'node:child_process' import { existsSync, readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs' import path from 'node:path' export type HolderProbe = | { readonly status: 'free' } | { readonly status: 'held'; readonly pids: readonly number[] } | { readonly status: 'unknown'; readonly reason: string } /** Injectable so a spec can say "held" without a real process. */ export interface ProcessProbe { holders(root: string, files: readonly string[]): Promise } function underRoot(target: string, root: string): boolean { return target === root || target.startsWith(root.endsWith(path.sep) ? root : root + path.sep) } function procHolders(root: string, files: ReadonlySet): HolderProbe { const pids: number[] = [] let unreadable = 0 for (const entry of readdirSync('/proc')) { if (!/^\d+$/.test(entry)) continue const pid = Number(entry) if (pid === process.pid) continue let fds: string[] try { fds = readdirSync(`/proc/${entry}/fd`) } catch { unreadable += 1 continue } for (const fd of fds) { let target: string try { target = readlinkSync(`/proc/${entry}/fd/${fd}`) } catch { continue } if (files.has(target) || underRoot(target, root)) { pids.push(pid) break } } } if (pids.length > 0) return { status: 'held', pids } if (unreadable > 0 && process.getuid?.() !== 0) { return { status: 'unknown', reason: `${unreadable} processes could not be inspected; run the MCP as root or as the data directory's owner`, } } return { status: 'free' } } function lsof(args: readonly string[]): Promise { return new Promise((resolve) => { execFile('lsof', ['-t', ...args], { timeout: 20_000 }, (error, stdout) => { const pids = stdout .split('\n') .map((line) => Number(line.trim())) .filter((n) => Number.isInteger(n) && n > 0 && n !== process.pid) if (pids.length > 0) return resolve({ status: 'held', pids }) if (error === null) return resolve({ status: 'free' }) // lsof exits 1 with no output when nothing matched; anything else is not an answer. const code: unknown = Reflect.get(error, 'code') if (code === 1) return resolve({ status: 'free' }) return resolve({ status: 'unknown', reason: `lsof is not usable here (${String(code)})` }) }) }) } export const realProcessProbe: ProcessProbe = { async holders(root, files) { if (existsSync('/proc/self/fd')) return procHolders(root, new Set(files)) const existing = files.filter((file) => existsSync(file)) const byFile = existing.length > 0 ? await lsof(['--', ...existing]) : { status: 'free' as const } if (byFile.status !== 'free') return byFile return lsof(['+d', root]) }, } // ── backup ───────────────────────────────────────────────────────────────── export type BackupVerdict = | { readonly ok: true; readonly kind: 'directory' | 'archive'; readonly bytes: number } | { readonly ok: false; readonly reason: string } const MAX_BACKUP_ENTRIES = 50_000 const SETTINGS_DB = /^(?:camstack|dominevo)\.db$/ const MASTER_KEY = 'master.key' interface Walk { readonly files: number readonly bytes: number readonly hasSettingsDb: boolean readonly hasMasterKey: boolean } function walkBackup(dir: string): Walk { let files = 0 let bytes = 0 let hasSettingsDb = false let hasMasterKey = false const stack = [dir] while (stack.length > 0 && files < MAX_BACKUP_ENTRIES) { const current = stack.pop() if (current === undefined) break for (const entry of readdirSync(current, { withFileTypes: true })) { const full = path.join(current, entry.name) if (entry.isDirectory()) stack.push(full) else if (entry.isFile()) { files += 1 bytes += statSync(full).size if (SETTINGS_DB.test(entry.name)) hasSettingsDb = true if (entry.name === MASTER_KEY) hasMasterKey = true } } } return { files, bytes, hasSettingsDb, hasMasterKey } } function tarEntries(file: string): Promise { return new Promise((resolve) => { execFile( 'tar', ['-tf', file], { timeout: 120_000, maxBuffer: 256 * 1024 * 1024 }, (error, out) => { resolve(error === null && out.length > 0 ? out.split('\n').filter((l) => l !== '') : null) }, ) }) } function realOrResolved(p: string): string { try { return realpathSync(p) } catch { return path.resolve(p) } } /** What the backup must carry: each part only when the data dir being migrated has it. */ export interface BackupRequirements { readonly settingsDb: boolean readonly masterKey: boolean } function missingParts(hasDb: boolean, hasKey: boolean, need: BackupRequirements): string | null { const dbMissing = need.settingsDb && !hasDb const keyMissing = need.masterKey && !hasKey if (!dbMissing && !keyMissing) return null const missing = [ dbMissing ? 'the settings database (camstack.db or dominevo.db)' : null, keyMissing ? 'the keychain master.key' : null, ] return `the backup does not contain ${missing.filter((m) => m !== null).join(' and ')}; a copy of the whole data dir is required` } /** Exists, non-empty, outside `root` after symlinks, and holds the settings database and the master key only when the data dir has them (a directory copy, or a tar whose listing has them). */ export async function verifyBackup( backupPath: string, root: string, need: BackupRequirements, ): Promise { const resolved = realOrResolved(backupPath) if (underRoot(resolved, realOrResolved(root))) { return { ok: false, reason: 'the backup is inside the directory being migrated; copy it elsewhere', } } let stat try { stat = statSync(resolved) } catch { return { ok: false, reason: 'the backup path does not exist' } } try { if (stat.isDirectory()) { const walk = walkBackup(resolved) if (walk.files === 0 || walk.bytes === 0) return { ok: false, reason: 'the backup directory is empty' } const missing = missingParts(walk.hasSettingsDb, walk.hasMasterKey, need) if (missing !== null) return { ok: false, reason: missing } return { ok: true, kind: 'directory', bytes: walk.bytes } } if (!stat.isFile() || stat.size === 0) return { ok: false, reason: 'the backup file is empty' } const entries = await tarEntries(resolved) if (entries === null) return { ok: false, reason: 'the backup file is not a readable archive (tar -tf failed); a lone .db is not a backup', } const names = entries.map((e) => path.basename(e.replace(/\/$/, ''))) const missing = missingParts( names.some((n) => SETTINGS_DB.test(n)), names.includes(MASTER_KEY), need, ) if (missing !== null) return { ok: false, reason: missing } return { ok: true, kind: 'archive', bytes: stat.size } } catch (error) { return { ok: false, reason: `the backup could not be read: ${error instanceof Error ? error.message : String(error)}`, } } }