/** * The `inventory` and `apply` stages. Both gather the same facts and share one * list of refusals, so an inventory already tells an assistant what apply would * say no to with the same arguments. */ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync, } from 'node:fs' import path from 'node:path' import { z } from 'zod' import { decodeKeyMaterial, mqttKeysFor, type MqttKeys } from './crypto.js' import { applyMaterialised, planMaterialised, type MaterialisedPlan } from './core-blocks.js' import { applyDb, planDb, type DbApplyResult, type DbPlan, type KeyInputs } from './db.js' import { applyFiles, planFiles, type FileApplyResult, type FilePlan, type RenameEntry, } from './files.js' import { applyMarkers, planMarkers, type MarkerApplyResult, type MarkerPlan } from './markers.js' import { verifyBackup, type BackupVerdict, type ProcessProbe } from './probe.js' export const MigrateArgsShape = { stage: z.enum(['inventory', 'apply', 'checklist']), path: z .string() .min(1) .optional() .describe( 'inventory / apply: a hub data dir, an agent dir, ~/.camstack, or a desktop userData dir', ), nodeStopped: z .boolean() .optional() .describe( 'You attest the node (container, service, app) is stopped. Required by apply; lets inventory preview the database.', ), backupPath: z .string() .min(1) .optional() .describe('apply: a backup of the data dir (directory copy or archive), outside it'), confirm: z.boolean().optional().describe('apply: must be true'), masterKeyFiles: z .array(z.string().min(1)) .optional() .describe( 'The keychain master key file(s), e.g. the mounted secret. /.keychain/master.key is tried by default. Their contents are never returned.', ), extraRoots: z .array(z.string().min(1)) .optional() .describe('Storage roots outside the data dir that carry a location marker'), reportPath: z .string() .min(1) .optional() .describe('apply: where the JSON report goes (default: next to the backup)'), } export const MigrateArgsSchema = z.object(MigrateArgsShape) export type MigrateArgs = z.infer export type RefusalCode = | 'path-required' | 'path-missing' | 'confirm-required' | 'node-not-attested' | 'node-running' | 'liveness-unknown' | 'backup-required' | 'backup-invalid' | 'key-unreadable' | 'database-conflict' | 'rename-conflict' | 'keychain-blocked' | 'database-unreadable' export interface Refusal { readonly code: RefusalCode readonly message: string } export interface MigrateDeps { readonly probe: ProcessProbe readonly now: () => Date /** Only a spec sets this: the function that renames one entry (default `fs.renameSync`). */ readonly renameEntry?: RenameEntry } export interface DatabaseEntry { readonly path: string readonly bytes: number readonly role: 'settings' | 'other' readonly opened: boolean readonly note: string readonly plan?: DbPlan } interface Facts { readonly root: string readonly files: FilePlan readonly settingsDb: string | null readonly dbEntries: readonly DatabaseEntry[] readonly dbPlan: DbPlan | null readonly refusals: readonly Refusal[] readonly backup: BackupVerdict | null readonly keySource: KeySource /** Storage roots outside the data dir whose old marker apply copies; null until the database was read. */ readonly markers: MarkerPlan | null readonly materialised: MaterialisedPlan } const SETTINGS_DB_NAMES: readonly string[] = ['camstack.db', 'dominevo.db'] function sizeOf(file: string): number { try { return statSync(file).size } catch { return 0 } } function readKey(file: string): Buffer | null { try { return decodeKeyMaterial(readFileSync(file, 'utf8')) } catch { return null } } function loadKeys(root: string, args: MigrateArgs, refusals: Refusal[]): KeyInputs { const wanted = [...(args.masterKeyFiles ?? [])] const fallback = path.join(root, '.keychain', 'master.key') if (existsSync(fallback) && !wanted.includes(fallback)) wanted.push(fallback) const keks: Buffer[] = [] for (const file of wanted) { const key = readKey(file) if (key === null) { refusals.push({ code: 'key-unreadable', message: `${file}: not a readable 32-byte key file (base64 or hex)`, }) continue } keks.push(key) } return { keks, mqtt: mqttKeysIn(root) } } export type KeySource = 'data-dir' | 'external' | 'none' /** Where the master key comes from, by path only: a key file outside the data dir survives the migration on its own. */ function keySourceOf(root: string, args: MigrateArgs): KeySource { const real = (p: string): string => { try { return realpathSync(p) } catch { return path.resolve(p) } } const realRoot = real(root) const supplied = (args.masterKeyFiles ?? []).filter((f) => existsSync(f)) const inside = (f: string): boolean => `${real(f)}${path.sep}`.startsWith(`${realRoot}${path.sep}`) // Any key in use inside the data dir (the default file counts) means the backup must carry it. if (supplied.some(inside) || existsSync(path.join(root, '.keychain', 'master.key'))) return 'data-dir' return supplied.length > 0 ? 'external' : 'none' } function mqttKeysIn(root: string): MqttKeys | null { const dataDir = path.join(root, 'addons-data') try { // Directories are listed lazily by name; only an mqtt addon's data dir can hold the retired key. for (const name of readdirNames(dataDir)) { if (!/mqtt/i.test(name)) continue const file = path.join(dataDir, name, '.secret-key') if (existsSync(file)) return mqttKeysFor(readFileSync(file)) } } catch { return null } return null } function readdirNames(dir: string): string[] { try { return readdirSync(dir) } catch { return [] } } function dbFiles(files: FilePlan): { settings: string | null; others: string[]; both: boolean } { const settings = files.databases.filter((f) => SETTINGS_DB_NAMES.includes(path.basename(f))) const others = files.databases.filter((f) => !SETTINGS_DB_NAMES.includes(path.basename(f))) return { settings: settings.find((f) => f.endsWith('camstack.db')) ?? settings[0] ?? null, others, both: settings.length > 1, } } function holderFiles(root: string, files: FilePlan): string[] { return files.databases .flatMap((f) => [f, `${f}-wal`, `${f}-shm`]) .concat(path.join(root, '.keychain', 'master.key')) } async function gather( args: MigrateArgs, deps: MigrateDeps, wantApply: boolean, ): Promise { if (args.path === undefined) return { code: 'path-required', message: 'pass the data directory as `path`' } const root = path.resolve(args.path) if (!existsSync(root) || !statSync(root).isDirectory()) { return { code: 'path-missing', message: `${root} is not a directory` } } const refusals: Refusal[] = [] const files = planFiles( root, (args.extraRoots ?? []).map((p) => path.resolve(p)), ) for (const c of files.changes) { if (c.kind === 'rename' && c.conflict) { refusals.push({ code: 'rename-conflict', message: `${c.from}: ${c.to} already exists` }) } } const { settings, others, both } = dbFiles(files) if (both) { refusals.push({ code: 'database-conflict', message: 'both camstack.db and dominevo.db exist; a node already booted on the new build. Keep the one with data and move the other aside by hand', }) } if (wantApply && args.confirm !== true) { refusals.push({ code: 'confirm-required', message: 'set confirm: true' }) } if (args.nodeStopped !== true) { refusals.push({ code: 'node-not-attested', message: 'set nodeStopped: true once the node is stopped (container, service or app)', }) } let stopped = false const probe = await deps.probe.holders(root, holderFiles(root, files)) if (probe.status === 'held') { refusals.push({ code: 'node-running', message: `process(es) ${probe.pids.join(', ')} hold files of this data dir open; stop the node`, }) } else if (probe.status === 'unknown') { refusals.push({ code: 'liveness-unknown', message: probe.reason }) } else { stopped = args.nodeStopped === true } const keySource = keySourceOf(root, args) let backup: BackupVerdict | null = null if (wantApply) { if (args.backupPath === undefined) { refusals.push({ code: 'backup-required', message: 'pass backupPath: a copy or archive of the data dir, outside it', }) } else { backup = await verifyBackup(args.backupPath, root, { settingsDb: settings !== null, masterKey: keySource === 'data-dir', }) if (!backup.ok) refusals.push({ code: 'backup-invalid', message: backup.reason }) } } const keys = loadKeys(root, args, refusals) let dbPlan: DbPlan | null = null let markers: MarkerPlan | null = null const entries: DatabaseEntry[] = [] for (const file of [...(settings === null ? [] : [settings]), ...others]) { const role = file === settings ? 'settings' : 'other' const base: Omit = { path: file, bytes: sizeOf(file), role } if (role !== 'settings') { entries.push({ ...base, opened: false, note: "reported only: not rewritten (it holds telemetry or an addon's own data)", }) continue } if (!stopped) { entries.push({ ...base, opened: false, note: 'not opened: the node is not confirmed stopped', }) continue } try { dbPlan = planDb(file, keys, root) entries.push({ ...base, opened: true, note: 'planned read-only', plan: dbPlan }) markers = planMarkers(dbPlan.storageRoots, [ root, ...(args.extraRoots ?? []).map((p) => path.resolve(p)), ]) for (const message of dbPlan.blockers) refusals.push({ code: 'keychain-blocked', message }) } catch (error) { refusals.push({ code: 'database-unreadable', message: `${file}: ${error instanceof Error ? error.message : String(error)}`, }) entries.push({ ...base, opened: false, note: 'could not be opened read-only' }) } } return { root, files, settingsDb: settings, dbEntries: entries, dbPlan, refusals, backup, keySource, markers, materialised: planMaterialised(root, dbPlan === null ? null : dbPlan.coreBlockIds), } } function isFacts(value: Facts | Refusal): value is Facts { return 'root' in value } export interface InventoryResult { readonly status: 'ok' | 'refused' readonly stage: 'inventory' readonly root?: string readonly changes?: FilePlan['changes'] readonly reportOnly?: FilePlan['reportOnly'] readonly databases?: readonly DatabaseEntry[] readonly reenroll?: DbPlan['reenroll'] readonly nodeStoppedConfirmed?: boolean /** Where the master key comes from (never its bytes). */ readonly keySource?: KeySource /** Storage roots on other mounts: which get the new marker, which are unreachable. */ readonly storageRoots?: MarkerPlan /** Materialised core-block packages apply deletes (the node rebuilds them from the rewritten rows). */ readonly staleCoreBlockPackages?: readonly string[] /** Core-block packages with an old import but no row: left alone. */ readonly coreBlockPackagesWithoutRow?: readonly string[] /** What apply would refuse on with these same arguments (it also wants backupPath and confirm). */ readonly applyWouldRefuse?: readonly Refusal[] readonly error?: Refusal } export async function inventory(args: MigrateArgs, deps: MigrateDeps): Promise { const facts = await gather(args, deps, false) if (!isFacts(facts)) return { status: 'refused', stage: 'inventory', error: facts } return { status: 'ok', stage: 'inventory', root: facts.root, changes: facts.files.changes, reportOnly: facts.files.reportOnly, databases: facts.dbEntries, ...(facts.dbPlan === null ? {} : { reenroll: facts.dbPlan.reenroll }), nodeStoppedConfirmed: facts.dbPlan !== null, keySource: facts.keySource, ...(facts.markers === null ? {} : { storageRoots: facts.markers }), staleCoreBlockPackages: facts.materialised.stale, coreBlockPackagesWithoutRow: facts.materialised.noRow, applyWouldRefuse: facts.refusals, } } export interface ApplyReport { readonly tool: 'migrate_from_camstack' readonly stage: 'apply' readonly startedAt: string readonly finishedAt: string readonly root: string readonly backup: BackupVerdict readonly keySource: KeySource readonly database: DbApplyResult | null readonly files: FileApplyResult readonly storageRoots: MarkerApplyResult | null readonly coreBlockPackagesRemoved: readonly string[] readonly notices: { readonly mustReenroll: DbPlan['reenroll'] readonly databasesNotRewritten: readonly string[] readonly archivesNotRewritten: readonly string[] readonly oldNamedLeftAsIs: readonly string[] readonly placesNamedInTheDatabase: DbPlan['placeCells'] readonly mqtt: DbPlan['mqtt'] | null /** Roots to fix by hand: mount them, then copy .camstack-location to .dominevo-location. */ readonly storageRoots: { readonly unreachable: MarkerPlan['unreachable'] } /** Block rows that could not be read, and packages with no row: left as they are. */ readonly coreBlocks: { readonly unreadable: DbPlan['coreBlocksUnreadable'] readonly packagesWithoutRow: readonly string[] } } } export interface ApplyResult { readonly status: 'applied' | 'nothing-to-do' | 'refused' | 'failed' readonly stage: 'apply' readonly refusals?: readonly Refusal[] readonly error?: string readonly reportPath?: string readonly report?: ApplyReport /** On a failed file step or report write: what was done and what remains, inline. */ readonly files?: FileApplyResult } function reportTarget(args: MigrateArgs, now: Date): string { if (args.reportPath !== undefined) return path.resolve(args.reportPath) const stamp = now.toISOString().replace(/[:.]/g, '-') const beside = args.backupPath === undefined ? process.cwd() : path.dirname(path.resolve(args.backupPath)) return path.join(beside, `migrate-from-camstack-report-${stamp}.json`) } export async function apply(args: MigrateArgs, deps: MigrateDeps): Promise { const startedAt = deps.now() const facts = await gather(args, deps, true) if (!isFacts(facts)) return { status: 'refused', stage: 'apply', refusals: [facts] } if (facts.refusals.length > 0) return { status: 'refused', stage: 'apply', refusals: facts.refusals } const backup = facts.backup if (backup === null || !backup.ok) return { status: 'refused', stage: 'apply', refusals: [{ code: 'backup-required', message: 'no verified backup' }], } const hasWork = facts.files.changes.length > 0 || (facts.dbPlan?.hasWork ?? false) || (facts.markers?.toCopy.length ?? 0) > 0 || facts.materialised.stale.length > 0 if (!hasWork) return { status: 'nothing-to-do', stage: 'apply' } const keys = loadKeys(facts.root, args, []) let database: DbApplyResult | null = null try { if (facts.settingsDb !== null && facts.dbPlan?.hasWork === true) database = applyDb(facts.settingsDb, keys) } catch (error) { return { status: 'failed', stage: 'apply', error: `database step rolled back, nothing was renamed: ${error instanceof Error ? error.message : String(error)}`, } } const files = applyFiles(facts.files, deps.renameEntry) const coreBlockPackagesRemoved = applyMaterialised(facts.materialised) const storageRoots = facts.markers === null || files.failed !== undefined ? null : applyMarkers(facts.markers) const report: ApplyReport = { tool: 'migrate_from_camstack', stage: 'apply', startedAt: startedAt.toISOString(), finishedAt: deps.now().toISOString(), root: facts.root, backup, keySource: facts.keySource, database, files, storageRoots, coreBlockPackagesRemoved, notices: { mustReenroll: facts.dbPlan?.reenroll ?? [], databasesNotRewritten: facts.dbEntries.filter((d) => d.role === 'other').map((d) => d.path), archivesNotRewritten: facts.files.reportOnly .filter((r) => r.category === 'archive') .map((r) => r.path), oldNamedLeftAsIs: facts.files.reportOnly .filter((r) => r.category === 'old-named') .map((r) => r.path), placesNamedInTheDatabase: facts.dbPlan?.placeCells ?? [], mqtt: facts.dbPlan?.mqtt ?? null, coreBlocks: { unreadable: facts.dbPlan?.coreBlocksUnreadable ?? [], packagesWithoutRow: facts.materialised.noRow, }, storageRoots: { unreachable: storageRoots?.unreachable ?? facts.markers?.unreachable ?? [] }, }, } const reportPath = reportTarget(args, deps.now()) try { writeFileSync(reportPath, `${JSON.stringify(report, null, 2)}\n`, { mode: 0o600 }) } catch (error) { return { status: 'failed', stage: 'apply', error: `the database and file steps ran (done: ${files.done.length}, remaining: ${files.remaining.length}) but the report could not be written to ${reportPath}: ${error instanceof Error ? error.message : String(error)}. The lists are in this result; do not lose them`, report, files, } } if (files.failed !== undefined) { return { status: 'failed', stage: 'apply', error: `the database step is committed; the file step stopped at "${files.failed.entry}": ${files.failed.error}. Done: ${files.done.length} entries. Remaining: ${files.remaining.length} entries (listed in the report). Fix the cause and run apply again: it continues`, reportPath, report, files, } } return { status: 'applied', stage: 'apply', reportPath, report } }