/** * The settings database, on a STOPPED node only. `planDb` opens it read-only * and counts; `applyDb` does everything in one transaction and rolls back on * any error. The keychain rows are re-encrypted here (they are bound to their * names), so a node that is migrated by file renames alone could not read a * single secret afterwards. * * Nothing in this file prints, returns or logs a plaintext: counts, table and * column names, refs (which name an owner and a field, never a value). */ import { DatabaseSync, type SQLInputValue, type SQLOutputValue } from 'node:sqlite' import { decryptValue, encryptValue, envelopeKeyId, fingerprint, MQTT_CIPHERTEXT, reencryptMqtt, unwrapDek, wrapDek, type MqttKeys, } from './crypto.js' import { planCoreBlocks, rewriteCoreBlocks, type CoreBlockPlan, type UnreadableBlock, } from './core-blocks.js' import { storageRootsIn } from './markers.js' import { hasOldName, NEW_REF_TOKEN, NEW_SCOPE_PREFIX, OLD_REF_TOKEN, OLD_SCOPE_PREFIX, renamedName, REPORT_ONLY_TOKENS, TOKEN_REWRITES, } from './names.js' type Row = Record const SECRETS_TABLE = 'keychain:secrets' const KEYS_TABLE = 'keychain:keys' const CREDENTIALS_TABLE = 'device_credentials' /** Their cells carry ciphertext bound to the name; the explicit keychain step owns them. */ const KEYCHAIN_OWNED: ReadonlySet = new Set([SECRETS_TABLE, KEYS_TABLE]) export interface TableRename { readonly from: string readonly to: string /** `none`: free. `empty-target`: the new name holds an empty table the new build created; it is dropped first. `blocked`: both hold rows. */ readonly target: 'none' | 'empty-target' | 'blocked' } export interface CellCount { readonly table: string readonly column: string readonly token: string readonly rows: number } export interface KeychainCounts { readonly wrapsToMigrate: number readonly wrapsAlreadyMigrated: number readonly secretsToReencrypt: number } export interface DeviceCredentialNotice { readonly id: string readonly userId: string readonly deviceName: string readonly platform: string readonly enrolledVia: string readonly lastUsedAt: number | null } export interface MqttCounts { readonly keyFile: 'absent' | 'raw-key' | 'passphrase' readonly toReencrypt: number readonly alreadyNew: number /** Cannot be opened with either key: left untouched, named so the operator re-enters the password. */ readonly unreadable: number } export interface DbPlan { readonly file: string readonly tableRenames: readonly TableRename[] readonly indexRenames: readonly { readonly from: string; readonly to: string }[] readonly cells: readonly CellCount[] readonly placeCells: readonly CellCount[] /** Core blocks whose stored source imports the old scope; apply rewrites the specifiers. */ readonly coreBlocks: readonly CoreBlockPlan[] /** `blocks` rows that could not be read (left untouched). */ readonly coreBlocksUnreadable: readonly UnreadableBlock[] /** Every `blocks` row id. */ readonly coreBlockIds: readonly string[] /** Absolute `basePath` of every storage location in the database. */ readonly storageRoots: readonly string[] readonly keychain: KeychainCounts readonly mqtt: MqttCounts readonly reenroll: readonly DeviceCredentialNotice[] /** Reasons apply must refuse; the tool surfaces them verbatim. */ readonly blockers: readonly string[] /** True when apply has any work in this file. */ readonly hasWork: boolean } export interface KeyInputs { /** Master keys (KEK) the operator supplied or the data dir holds. */ readonly keks: readonly Buffer[] readonly mqtt: MqttKeys | null } // ── helpers ──────────────────────────────────────────────────────────────── function str(v: SQLOutputValue | undefined): string | null { return typeof v === 'string' ? v : null } function num(v: SQLOutputValue | undefined): number | null { if (typeof v === 'number') return v if (typeof v === 'bigint') return Number(v) return null } function q(identifier: string): string { return `"${identifier.replaceAll('"', '""')}"` } function all(db: DatabaseSync, sql: string, ...params: SQLInputValue[]): Row[] { return db.prepare(sql).all(...params) } function count(db: DatabaseSync, sql: string, ...params: SQLInputValue[]): number { return num(db.prepare(sql).get(...params)?.['n']) ?? 0 } function tableNames(db: DatabaseSync): string[] { return all(db, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'") .map((r) => str(r['name'])) .filter((n): n is string => n !== null) } /** Ordinary tables: no virtual table and none of its shadow tables. */ function ordinaryTables(db: DatabaseSync): string[] { const rows = all( db, "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'", ) const virtual = rows .filter((r) => (str(r['sql']) ?? '').toUpperCase().startsWith('CREATE VIRTUAL')) .map((r) => str(r['name'])) .filter((n): n is string => n !== null) return rows .map((r) => str(r['name'])) .filter((n): n is string => n !== null) .filter((n) => !virtual.some((v) => n === v || n.startsWith(`${v}_`))) } function textColumns(db: DatabaseSync, table: string): string[] { return all(db, `PRAGMA table_xinfo(${q(table)})`) .filter((c) => num(c['hidden']) === 0 && /CHAR|CLOB|TEXT|JSON|^$/i.test(str(c['type']) ?? '')) .map((c) => str(c['name'])) .filter((n): n is string => n !== null) } function hasTable(db: DatabaseSync, name: string): boolean { return tableNames(db).includes(name) } // ── keychain ─────────────────────────────────────────────────────────────── interface WrapUpdate { readonly wrapId: string readonly wrappedDek: string readonly kekFingerprint: string } interface SecretUpdate { readonly oldRef: string readonly newRef: string readonly owner: string readonly ciphertext: string } interface KeychainActions { readonly wrapUpdates: readonly WrapUpdate[] readonly secretUpdates: readonly SecretUpdate[] readonly alreadyMigrated: number readonly blockers: readonly string[] } function keychainActions(db: DatabaseSync, keks: readonly Buffer[]): KeychainActions { const blockers: string[] = [] const wrapUpdates: WrapUpdate[] = [] const deks = new Map() let alreadyMigrated = 0 if (hasTable(db, KEYS_TABLE)) { for (const row of all( db, `SELECT wrapId, keyId, wrappedDek, kekFingerprint FROM ${q(KEYS_TABLE)}`, )) { const wrapId = str(row['wrapId']) const keyId = str(row['keyId']) const wrapped = str(row['wrappedDek']) const fp = str(row['kekFingerprint']) if (wrapId === null || keyId === null || wrapped === null || fp === null) continue const migrated = keks.find((k) => fingerprint(k, 'new') === fp) if (migrated !== undefined) { const dek = unwrapDek(migrated, wrapped, keyId, 'new') if (dek === null) blockers.push(`wrap ${wrapId}: already on the new fingerprint but does not unwrap`) else if (!deks.has(keyId)) deks.set(keyId, dek) alreadyMigrated += 1 continue } const kek = keks.find((k) => fingerprint(k, 'old') === fp) if (kek === undefined) { blockers.push( `wrap ${wrapId}: its master key (fingerprint ${fp.slice(0, 16)}) was not supplied; pass the file in masterKeyFiles`, ) continue } const dek = unwrapDek(kek, wrapped, keyId, 'old') if (dek === null) { blockers.push(`wrap ${wrapId}: does not unwrap with the supplied master key`) continue } if (!deks.has(keyId)) deks.set(keyId, dek) wrapUpdates.push({ wrapId, wrappedDek: wrapDek(kek, dek, keyId, 'new'), kekFingerprint: fingerprint(kek, 'new'), }) } } const secretUpdates: SecretUpdate[] = [] if (hasTable(db, SECRETS_TABLE)) { const rows = all( db, `SELECT ref, owner, ciphertext FROM ${q(SECRETS_TABLE)} WHERE instr(ref, ?) > 0`, OLD_REF_TOKEN, ) for (const row of rows) { const ref = str(row['ref']) const owner = str(row['owner']) const ciphertext = str(row['ciphertext']) if (ref === null || owner === null || ciphertext === null) continue const dek = deks.get(envelopeKeyId(ciphertext) ?? '') const plain = dek === undefined ? null : decryptValue(dek, ref, ciphertext) if (dek === undefined || plain === null) { blockers.push(`secret ${ref}: cannot be decrypted with the data key; nothing was changed`) continue } const newRef = ref.replaceAll(OLD_REF_TOKEN, NEW_REF_TOKEN) const keyId = envelopeKeyId(ciphertext) ?? '' const next = encryptValue(dek, keyId, newRef, plain) plain.fill(0) secretUpdates.push({ oldRef: ref, newRef, owner: owner.startsWith(OLD_SCOPE_PREFIX) ? NEW_SCOPE_PREFIX + owner.slice(OLD_SCOPE_PREFIX.length) : owner, ciphertext: next, }) } } return { wrapUpdates, secretUpdates, alreadyMigrated, blockers } } // ── mqtt ─────────────────────────────────────────────────────────────────── interface MqttCell { readonly table: string readonly column: string readonly value: string } function mqttCells(db: DatabaseSync, tables: readonly string[]): MqttCell[] { const out: MqttCell[] = [] for (const table of tables) { if (KEYCHAIN_OWNED.has(table)) continue for (const column of textColumns(db, table)) { const rows = all( db, `SELECT DISTINCT ${q(column)} AS v FROM ${q(table)} WHERE typeof(${q(column)}) = 'text' AND instr(${q(column)}, 'enc:v1:') > 0`, ) for (const row of rows) { const value = str(row['v']) if (value !== null) out.push({ table, column, value }) } } } return out } function classifyMqtt(cells: readonly MqttCell[], keys: MqttKeys | null): MqttCounts { const keyFile = keys === null ? 'absent' : keys.saltDerived ? 'passphrase' : 'raw-key' let toReencrypt = 0 let alreadyNew = 0 let unreadable = 0 for (const cell of cells) { for (const match of cell.value.match(MQTT_CIPHERTEXT) ?? []) { if (keys === null) unreadable += 1 else if (!keys.saltDerived) alreadyNew += 1 else if (reencryptMqtt(match, keys) !== null) toReencrypt += 1 else if (reencryptMqtt(match, { ...keys, oldKey: keys.newKey }) !== null) alreadyNew += 1 else unreadable += 1 } } return { keyFile, toReencrypt, alreadyNew, unreadable } } // ── plan ─────────────────────────────────────────────────────────────────── /** Virtual tables and their shadow tables that carry the old scope: they cannot be renamed by `ALTER TABLE`, so apply refuses. */ function virtualOldNamed(db: DatabaseSync): string[] { const ordinary = new Set(ordinaryTables(db)) return tableNames(db).filter((n) => !ordinary.has(n) && n.includes(OLD_SCOPE_PREFIX)) } function virtualBlockers(db: DatabaseSync): string[] { return virtualOldNamed(db).map( (n) => `table ${n}: a virtual or shadow table with the old name cannot be renamed here; drop or rebuild it by hand`, ) } function planTableRenames(db: DatabaseSync): TableRename[] { const names = ordinaryTables(db) return names .filter((n) => n.includes(OLD_SCOPE_PREFIX)) .map((from) => { const to = from.split(OLD_SCOPE_PREFIX).join(NEW_SCOPE_PREFIX) if (!names.includes(to)) return { from, to, target: 'none' as const } const empty = count(db, `SELECT count(*) AS n FROM ${q(to)}`) === 0 return { from, to, target: empty ? ('empty-target' as const) : ('blocked' as const) } }) } function planIndexRenames(db: DatabaseSync): { from: string; to: string }[] { return all(db, "SELECT name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL") .map((r) => str(r['name'])) .filter((n): n is string => n !== null && hasOldName(n)) .map((from) => ({ from, to: renamedName(from) })) } function countCells( db: DatabaseSync, tables: readonly string[], tokens: readonly string[], ): CellCount[] { const out: CellCount[] = [] for (const table of tables) { for (const column of textColumns(db, table)) { for (const token of tokens) { const rows = count( db, `SELECT count(*) AS n FROM ${q(table)} WHERE typeof(${q(column)}) = 'text' AND instr(${q(column)}, ?) > 0`, token, ) if (rows > 0) out.push({ table, column, token, rows }) } } } return out } function readReenroll(db: DatabaseSync): DeviceCredentialNotice[] { if (!hasTable(db, CREDENTIALS_TABLE)) return [] const now = Date.now() return all( db, `SELECT id, userId, deviceName, platform, enrolledVia, lastUsedAt, expiresAt FROM ${q(CREDENTIALS_TABLE)} WHERE revokedAt IS NULL`, ) .filter((r) => { const expires = num(r['expiresAt']) ?? 0 return (expires < 1e11 ? expires * 1000 : expires) > now }) .map((r) => ({ id: str(r['id']) ?? '', userId: str(r['userId']) ?? '', deviceName: str(r['deviceName']) ?? '', platform: str(r['platform']) ?? '', enrolledVia: str(r['enrolledVia']) ?? '', lastUsedAt: num(r['lastUsedAt']), })) } /** Read-only: what apply would do to this file. */ export function planDb(file: string, keys: KeyInputs, dataRoot: string): DbPlan { const db = new DatabaseSync(file, { readOnly: true }) try { const tables = ordinaryTables(db) const generic = tables.filter((t) => !KEYCHAIN_OWNED.has(t)) const cells = countCells( db, generic, TOKEN_REWRITES.map((t) => t.from), ) const placeCells = countCells(db, tables, [...REPORT_ONLY_TOKENS]) const found = planCoreBlocks(db) const coreBlocks = found.toRewrite const storageRoots = storageRootsIn(db, dataRoot) const tableRenames = planTableRenames(db) const indexRenames = planIndexRenames(db) const actions = keychainActions(db, keys.keks) const mqtt = classifyMqtt(mqttCells(db, tables), keys.mqtt) const blockers = [ ...actions.blockers, ...virtualBlockers(db), ...tableRenames .filter((t) => t.target === 'blocked') .map((t) => `table ${t.from}: ${t.to} already holds rows; resolve by hand`), ] const keychain: KeychainCounts = { wrapsToMigrate: actions.wrapUpdates.length, wrapsAlreadyMigrated: actions.alreadyMigrated, secretsToReencrypt: actions.secretUpdates.length, } const hasWork = cells.length > 0 || coreBlocks.length > 0 || tableRenames.length > 0 || indexRenames.length > 0 || keychain.wrapsToMigrate > 0 || keychain.secretsToReencrypt > 0 || mqtt.toReencrypt > 0 return { file, tableRenames, indexRenames, cells, placeCells, coreBlocks, coreBlocksUnreadable: found.unreadable, coreBlockIds: found.ids, storageRoots, keychain, mqtt, reenroll: readReenroll(db), blockers, hasWork, } } finally { db.close() } } // ── apply ────────────────────────────────────────────────────────────────── export interface DbApplyResult { readonly tablesRenamed: number readonly indexesRenamed: number readonly cellsRewritten: number /** Stored core-block sources whose module specifiers moved to the new scope. */ readonly coreBlockSourcesRewritten: number readonly wrapsRewrapped: number readonly secretsReencrypted: number readonly mqttReencrypted: number readonly integrity: string } function rewriteCells(db: DatabaseSync, tables: readonly string[]): number { let changed = 0 for (const table of tables) { for (const column of textColumns(db, table)) { for (const { from, to } of TOKEN_REWRITES) { const r = db .prepare( `UPDATE ${q(table)} SET ${q(column)} = replace(${q(column)}, ?, ?) WHERE typeof(${q(column)}) = 'text' AND instr(${q(column)}, ?) > 0`, ) .run(from, to, from) changed += Number(r.changes) } } } return changed } function reencryptMqttCells(db: DatabaseSync, tables: readonly string[], keys: MqttKeys): number { if (!keys.saltDerived) return 0 let done = 0 for (const cell of mqttCells(db, tables)) { let next = cell.value for (const match of cell.value.match(MQTT_CIPHERTEXT) ?? []) { const moved = reencryptMqtt(match, keys) if (moved === null) continue next = next.split(match).join(moved) done += 1 } if (next === cell.value) continue db.prepare(`UPDATE ${q(cell.table)} SET ${q(cell.column)} = ? WHERE ${q(cell.column)} = ?`).run( next, cell.value, ) } return done } function renameIndexes(db: DatabaseSync): number { let moved = 0 for (const { from, to } of planIndexRenames(db)) { const sql = str( db.prepare('SELECT sql FROM sqlite_master WHERE type = ? AND name = ?').get('index', from)?.[ 'sql' ], ) if (sql === null) continue db.exec(`DROP INDEX ${q(from)}`) // The stored statement spells the name bare, quoted with " or in brackets; only the first mention is the index name. const named = sql.replace( /^(\s*CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?)(?:"([^"]+)"|\[([^\]]+)\]|`([^`]+)`|(\S+))/i, (_m, head: string) => `${head}${q(to)}`, ) if (named === sql) throw new Error(`index ${from}: could not find its name in the stored statement`) db.exec(named) moved += 1 } return moved } /** One transaction. Throws (after the rollback) with a message that carries no cell value. */ export function applyDb(file: string, keys: KeyInputs): DbApplyResult { const db = new DatabaseSync(file) try { db.exec('BEGIN IMMEDIATE') try { const actions = keychainActions(db, keys.keks) const blockers = [...actions.blockers, ...virtualBlockers(db)] if (blockers.length > 0) throw new Error(blockers.join('; ')) const tables = ordinaryTables(db) for (const w of actions.wrapUpdates) { db.prepare( `UPDATE ${q(KEYS_TABLE)} SET wrappedDek = ?, kekFingerprint = ? WHERE wrapId = ?`, ).run(w.wrappedDek, w.kekFingerprint, w.wrapId) } for (const s of actions.secretUpdates) { db.prepare( `UPDATE ${q(SECRETS_TABLE)} SET ref = ?, owner = ?, ciphertext = ? WHERE ref = ?`, ).run(s.newRef, s.owner, s.ciphertext, s.oldRef) } const mqttReencrypted = keys.mqtt === null ? 0 : reencryptMqttCells(db, tables, keys.mqtt) const cellsRewritten = rewriteCells( db, tables.filter((t) => !KEYCHAIN_OWNED.has(t)), ) const coreBlockSourcesRewritten = rewriteCoreBlocks(db) let tablesRenamed = 0 for (const t of planTableRenames(db)) { if (t.target === 'blocked') throw new Error(`table ${t.from}: ${t.to} already holds rows`) if (t.target === 'empty-target') db.exec(`DROP TABLE ${q(t.to)}`) db.exec(`ALTER TABLE ${q(t.from)} RENAME TO ${q(t.to)}`) tablesRenamed += 1 } const indexesRenamed = renameIndexes(db) const check = all(db, 'PRAGMA quick_check').map((r) => str(r['quick_check']) ?? '') const integrity = check.join(',') if (integrity !== 'ok') throw new Error(`quick_check failed: ${integrity.slice(0, 200)}`) db.exec('COMMIT') db.exec('PRAGMA wal_checkpoint(TRUNCATE)') return { tablesRenamed, indexesRenamed, cellsRewritten, coreBlockSourcesRewritten, wrapsRewrapped: actions.wrapUpdates.length, secretsReencrypted: actions.secretUpdates.length, mqttReencrypted, integrity, } } catch (error) { try { db.exec('ROLLBACK') } catch { // no transaction left to roll back } throw error } } finally { db.close() } }