import { Database } from 'bun:sqlite'; import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault'; /** * SQLite-backed VaultStore for the V4.13 encrypted file store. * * Three tables, mirroring the model: an owner key per vault, the * content-addressed objects, and the append-only manifest log. The relay * never decrypts anything — it enforces auth, verifies that an object's bytes * hash to its name, and refuses a commit whose objects are not all present. * * A fourth table, `shade_vault_refs`, records which objects each version * references (the commit's signed hashes plus its manifest). The relay cannot * read manifests, so this is what prune computes garbage from. Versions from * before it existed have `refs_known = 0`, and every object that was in the * database when the columns were added is `pinned` — see `VaultPrunePlan` for * why that is the safe reading and how the pins are eventually released. * * Objects are stored as BLOBs rather than base64 text. A workspace backup is * a few hundred files where the blob primitive holds one small profile, so the * 33% base64 overhead stops being a rounding error. * * Docker usage: set `SHADE_VAULT_DB_PATH` (falls back to `/data/shade-vault.db`). * **Set it.** The blob store's equivalent was missing from `docker-compose.yml` * for months and nobody noticed, because the in-memory fallback works * perfectly until the container is recreated — at which point everything is * gone, with no error anywhere. That happened on 2026-08-12. */ export class SqliteVaultStore implements VaultStore { private db: Database; private stmts!: { getOwner: ReturnType; setOwner: ReturnType; hasObject: ReturnType; putObject: ReturnType; getObject: ReturnType; head: ReturnType; log: ReturnType; logLimit: ReturnType; appendLog: ReturnType; appendRef: ReturnType; pinAll: ReturnType; usage: ReturnType; }; constructor(dbPath?: string) { const path = dbPath ?? process.env.SHADE_VAULT_DB_PATH ?? '/data/shade-vault.db'; this.db = new Database(path, { create: true }); this.db.exec('PRAGMA journal_mode=WAL'); this.ensureTables(); this.prepareStatements(); } private ensureTables() { this.db.exec(` CREATE TABLE IF NOT EXISTS shade_vault_owners ( vault_id TEXT PRIMARY KEY, owner_pubkey BLOB NOT NULL, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS shade_vault_objects ( vault_id TEXT NOT NULL, hash TEXT NOT NULL, bytes BLOB NOT NULL, size INTEGER NOT NULL, created_at INTEGER NOT NULL, pinned INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (vault_id, hash) ); CREATE TABLE IF NOT EXISTS shade_vault_log ( vault_id TEXT NOT NULL, seq INTEGER NOT NULL, manifest TEXT NOT NULL, at INTEGER NOT NULL, bytes INTEGER NOT NULL, refs_known INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (vault_id, seq) ); CREATE TABLE IF NOT EXISTS shade_vault_refs ( vault_id TEXT NOT NULL, seq INTEGER NOT NULL, hash TEXT NOT NULL, PRIMARY KEY (vault_id, seq, hash) ); CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash); `); // Databases from before ref tracking. The defaults here are the whole // migration: every existing log row becomes untracked (refs_known = 0), // and every existing object pinned (pinned = 1), because any of them may // be referenced by one of those rows. New rows always set both columns // explicitly, so these defaults only ever apply to the old ones. const has = (table: string, column: string): boolean => (this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some( (c) => c.name === column, ); this.db.transaction(() => { if (!has('shade_vault_log', 'refs_known')) { this.db.exec( 'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0', ); } if (!has('shade_vault_objects', 'pinned')) { this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1'); } })(); } private prepareStatements() { this.stmts = { getOwner: this.db.prepare('SELECT owner_pubkey FROM shade_vault_owners WHERE vault_id = ?'), setOwner: this.db.prepare( 'INSERT OR REPLACE INTO shade_vault_owners (vault_id, owner_pubkey, created_at) VALUES (?, ?, ?)', ), hasObject: this.db.prepare( 'SELECT 1 FROM shade_vault_objects WHERE vault_id = ? AND hash = ? LIMIT 1', ), // An object's name IS its content hash, so a repeat upload is the same // bytes by definition — ignoring it is correct, not lossy. putObject: this.db.prepare( 'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)', ), getObject: this.db.prepare( 'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?', ), head: this.db.prepare('SELECT MAX(seq) AS head FROM shade_vault_log WHERE vault_id = ?'), log: this.db.prepare( 'SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq ASC', ), logLimit: this.db.prepare( 'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC', ), appendLog: this.db.prepare( 'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)', ), appendRef: this.db.prepare( 'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)', ), pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'), usage: this.db.prepare( 'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?', ), }; } async getOwner(vaultId: string): Promise { const row = this.stmts.getOwner.get(vaultId) as { owner_pubkey: Uint8Array } | null; return row ? new Uint8Array(row.owner_pubkey) : null; } async setOwner(vaultId: string, publicKey: Uint8Array): Promise { this.stmts.setOwner.run(vaultId, publicKey, Date.now()); } async hasObject(vaultId: string, hash: string): Promise { return this.stmts.hasObject.get(vaultId, hash) !== null; } async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise { this.stmts.putObject.run(vaultId, hash, bytes, bytes.length, Date.now()); } async getObject(vaultId: string, hash: string): Promise { const row = this.stmts.getObject.get(vaultId, hash) as { bytes: Uint8Array } | null; return row ? new Uint8Array(row.bytes) : null; } async head(vaultId: string): Promise { const row = this.stmts.head.get(vaultId) as { head: number | null } | null; return row?.head ?? 0; } async log(vaultId: string, limit?: number): Promise { const rows = ( limit === undefined ? this.stmts.log.all(vaultId) : this.stmts.logLimit.all(vaultId, limit) ) as VaultLogEntry[]; return rows; } async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise { this.db.transaction(() => { this.stmts.appendLog.run( vaultId, entry.seq, entry.manifest, entry.at, entry.bytes, refs ? 1 : 0, ); if (refs) { for (const h of refs) this.stmts.appendRef.run(vaultId, entry.seq, h); } else { // Untracked: it can reference anything stored so far, so pin all of it. this.stmts.pinAll.run(vaultId); } })(); } /** * One transaction, so a commit cannot interleave between deciding what is * garbage and deleting it. bun:sqlite is synchronous, and a write * transaction holds the database lock for its whole duration. */ async prune(vaultId: string, plan: VaultPrunePlan): Promise { return this.db.transaction((): VaultPruneResult => { const keep = new Set(plan.keep); const rows = this.db .prepare('SELECT seq, refs_known FROM shade_vault_log WHERE vault_id = ?') .all(vaultId) as Array<{ seq: number; refs_known: number }>; const removed = rows.filter((r) => r.seq <= plan.upTo && !keep.has(r.seq)).map((r) => r.seq); const untrackedRemains = rows.some( (r) => r.refs_known === 0 && !(r.seq <= plan.upTo && !keep.has(r.seq)), ); // The removed seqs go into a temp table so every query below can say // "the log as it will be" without string-building an IN list. this.db.exec( 'CREATE TEMP TABLE IF NOT EXISTS shade_vault_prune_removed (seq INTEGER PRIMARY KEY)', ); this.db.exec('DELETE FROM shade_vault_prune_removed'); const addRemoved = this.db.prepare('INSERT INTO shade_vault_prune_removed (seq) VALUES (?)'); for (const seq of removed) addRemoved.run(seq); if (!untrackedRemains) { // No version with an unknown reference set is left, so nothing can // depend on a pin any more. this.db.prepare('UPDATE shade_vault_objects SET pinned = 0 WHERE vault_id = ?').run(vaultId); } // Garbage: not pinned, not used by a remaining version, and — if no // version ever used it — older than the grace for in-flight uploads. const garbage = this.db .prepare( `SELECT o.hash AS hash, o.size AS size FROM shade_vault_objects o WHERE o.vault_id = ?1 AND o.pinned = 0 AND NOT EXISTS ( SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash AND r.seq NOT IN (SELECT seq FROM shade_vault_prune_removed)) AND NOT EXISTS ( SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash AND l.seq NOT IN (SELECT seq FROM shade_vault_prune_removed)) AND ( o.created_at <= ?2 OR EXISTS (SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash) OR EXISTS (SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash))`, ) .all(vaultId, plan.protectSince) as Array<{ hash: string; size: number }>; const delObject = this.db.prepare( 'DELETE FROM shade_vault_objects WHERE vault_id = ? AND hash = ?', ); let freedBytes = 0; for (const g of garbage) { delObject.run(vaultId, g.hash); freedBytes += g.size; } this.db .prepare( 'DELETE FROM shade_vault_refs WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)', ) .run(vaultId); this.db .prepare( 'DELETE FROM shade_vault_log WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)', ) .run(vaultId); this.db.exec('DELETE FROM shade_vault_prune_removed'); return { removedVersions: removed.length, removedObjects: garbage.length, freedBytes }; })(); } async usage(vaultId: string): Promise { const row = this.stmts.usage.get(vaultId) as { total: number } | null; return row?.total ?? 0; } close(): void { this.db.close(); } }