import Database from 'better-sqlite3'; import fs from 'node:fs'; import path from 'node:path'; import { config } from './config.js'; fs.mkdirSync(config.dataDir, { recursive: true }); export const db = new Database(path.join(config.dataDir, 'keep.db')); db.pragma('journal_mode = WAL'); db.exec(` CREATE TABLE IF NOT EXISTS vaults ( vault_key TEXT PRIMARY KEY, ciphertext BLOB NOT NULL, nonce BLOB NOT NULL, -- Exactly one previous version, retained as a rollback safety net for -- an accidental bad push — not a full history. NULL if there is no -- previous version, or if the last push explicitly purged it. prev_ciphertext BLOB, prev_nonce BLOB, updated_at INTEGER NOT NULL, updated_by TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS recipients ( recipient_id TEXT PRIMARY KEY, label TEXT NOT NULL, public_key TEXT NOT NULL, created_at INTEGER NOT NULL ); -- Deleting a row IS the revocation for that (vault, recipient) pair. CREATE TABLE IF NOT EXISTS vault_grants ( vault_key TEXT NOT NULL, recipient_id TEXT NOT NULL, wrapped_key TEXT NOT NULL, -- base64 crypto_box_seal(vault_symmetric_key, recipient_pubkey) -- Read implied write in the original design; resolved to a real -- capability distinction — a recipient that only needs to pull a -- vault (e.g. an automated deploy identity) shouldn't also be able -- to overwrite it. Defaults to 1 so nothing existing changes. can_write INTEGER NOT NULL DEFAULT 1, granted_at INTEGER NOT NULL, PRIMARY KEY (vault_key, recipient_id) ); -- Mirrors vault_grants, but for the one retained previous version — -- wrapped keys as they were at push time, so a recipient who had -- access to the previous version can still unwrap it via --previous -- even if their current grant has since changed. CREATE TABLE IF NOT EXISTS vault_grants_previous ( vault_key TEXT NOT NULL, recipient_id TEXT NOT NULL, wrapped_key TEXT NOT NULL, PRIMARY KEY (vault_key, recipient_id) ); CREATE TABLE IF NOT EXISTS access_log ( id INTEGER PRIMARY KEY AUTOINCREMENT, vault_key TEXT NOT NULL, recipient_id TEXT NOT NULL, action TEXT NOT NULL, accessed_at INTEGER NOT NULL ); `); export interface VaultRow { vault_key: string; ciphertext: Buffer; nonce: Buffer; prev_ciphertext: Buffer | null; prev_nonce: Buffer | null; updated_at: number; updated_by: string; } export interface RecipientRow { recipient_id: string; label: string; public_key: string; created_at: number; } export interface GrantRow { vault_key: string; recipient_id: string; wrapped_key: string; can_write: number; granted_at: number; } export function getVault(vaultKey: string): VaultRow | undefined { return db.prepare(`SELECT * FROM vaults WHERE vault_key = ?`).get(vaultKey) as VaultRow | undefined; } // `purge`: skip retaining the outgoing version as "previous" — used for // compromise-driven rotations, where the whole point is that the old // value stops being retrievable by anyone. A purge also clears out // whatever previous version already existed, since it would defeat the // purpose to still leave the version-before-that recoverable. export function pushVault( vaultKey: string, ciphertext: Buffer, nonce: Buffer, updatedBy: string, wrappedByRecipientId: Map, purge: boolean, ): void { const tx = db.transaction(() => { const existing = getVault(vaultKey); const now = Math.floor(Date.now() / 1000); if (purge) { db.prepare( `INSERT INTO vaults (vault_key, ciphertext, nonce, prev_ciphertext, prev_nonce, updated_at, updated_by) VALUES (?, ?, ?, NULL, NULL, ?, ?) ON CONFLICT(vault_key) DO UPDATE SET ciphertext = excluded.ciphertext, nonce = excluded.nonce, prev_ciphertext = NULL, prev_nonce = NULL, updated_at = excluded.updated_at, updated_by = excluded.updated_by`, ).run(vaultKey, ciphertext, nonce, now, updatedBy); db.prepare(`DELETE FROM vault_grants_previous WHERE vault_key = ?`).run(vaultKey); } else { db.prepare( `INSERT INTO vaults (vault_key, ciphertext, nonce, prev_ciphertext, prev_nonce, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(vault_key) DO UPDATE SET ciphertext = excluded.ciphertext, nonce = excluded.nonce, prev_ciphertext = excluded.prev_ciphertext, prev_nonce = excluded.prev_nonce, updated_at = excluded.updated_at, updated_by = excluded.updated_by`, ).run(vaultKey, ciphertext, nonce, existing?.ciphertext ?? null, existing?.nonce ?? null, now, updatedBy); // Move the current grants (as they stood before this push) into // vault_grants_previous, so someone who had access to the // outgoing version can still pull it via --previous. db.prepare(`DELETE FROM vault_grants_previous WHERE vault_key = ?`).run(vaultKey); if (existing) { db.prepare( `INSERT INTO vault_grants_previous (vault_key, recipient_id, wrapped_key) SELECT vault_key, recipient_id, wrapped_key FROM vault_grants WHERE vault_key = ?`, ).run(vaultKey); } } db.prepare(`DELETE FROM vault_grants WHERE vault_key = ?`).run(vaultKey); const insert = db.prepare( `INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, can_write, granted_at) VALUES (?, ?, ?, ?, ?)`, ); for (const [recipientId, { wrappedKey, canWrite }] of wrappedByRecipientId) { insert.run(vaultKey, recipientId, wrappedKey, canWrite ? 1 : 0, now); } }); tx(); } export function getVaultGrantsPrevious(vaultKey: string, recipientId: string): string | undefined { const row = db.prepare( `SELECT wrapped_key FROM vault_grants_previous WHERE vault_key = ? AND recipient_id = ?`, ).get(vaultKey, recipientId) as { wrapped_key: string } | undefined; return row?.wrapped_key; } export function getRecipient(recipientId: string): RecipientRow | undefined { return db.prepare(`SELECT * FROM recipients WHERE recipient_id = ?`).get(recipientId) as RecipientRow | undefined; } export function listRecipients(): RecipientRow[] { return db.prepare(`SELECT * FROM recipients ORDER BY created_at ASC`).all() as RecipientRow[]; } export function createRecipient(recipientId: string, label: string, publicKey: string): void { db.prepare( `INSERT INTO recipients (recipient_id, label, public_key, created_at) VALUES (?, ?, ?, ?)`, ).run(recipientId, label, publicKey, Math.floor(Date.now() / 1000)); } export function deleteRecipient(recipientId: string): void { const tx = db.transaction(() => { db.prepare(`DELETE FROM recipients WHERE recipient_id = ?`).run(recipientId); db.prepare(`DELETE FROM vault_grants WHERE recipient_id = ?`).run(recipientId); db.prepare(`DELETE FROM vault_grants_previous WHERE recipient_id = ?`).run(recipientId); }); tx(); } export function hasGrant(vaultKey: string, recipientId: string): boolean { const row = db.prepare( `SELECT 1 FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`, ).get(vaultKey, recipientId); return row != null; } export function hasWriteGrant(vaultKey: string, recipientId: string): boolean { const row = db.prepare( `SELECT can_write FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`, ).get(vaultKey, recipientId) as { can_write: number } | undefined; return row != null && row.can_write === 1; } export function getGrant(vaultKey: string, recipientId: string): GrantRow | undefined { return db.prepare( `SELECT * FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`, ).get(vaultKey, recipientId) as GrantRow | undefined; } export function listGrantsForVault(vaultKey: string): GrantRow[] { return db.prepare(`SELECT * FROM vault_grants WHERE vault_key = ?`).all(vaultKey) as GrantRow[]; } export function setGrant(vaultKey: string, recipientId: string, wrappedKeyB64: string, canWrite: boolean): void { db.prepare( `INSERT INTO vault_grants (vault_key, recipient_id, wrapped_key, can_write, granted_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(vault_key, recipient_id) DO UPDATE SET wrapped_key = excluded.wrapped_key, can_write = excluded.can_write, granted_at = excluded.granted_at`, ).run(vaultKey, recipientId, wrappedKeyB64, canWrite ? 1 : 0, Math.floor(Date.now() / 1000)); } export function deleteGrant(vaultKey: string, recipientId: string): void { db.prepare(`DELETE FROM vault_grants WHERE vault_key = ? AND recipient_id = ?`).run(vaultKey, recipientId); } export function logAccess(vaultKey: string, recipientId: string, action: 'pull' | 'push' | 'grant' | 'revoke'): void { db.prepare( `INSERT INTO access_log (vault_key, recipient_id, action, accessed_at) VALUES (?, ?, ?, ?)`, ).run(vaultKey, recipientId, action, Math.floor(Date.now() / 1000)); } export function getAccessLog(vaultKey: string, limit = 50): { recipient_id: string; action: string; accessed_at: number }[] { return db.prepare( `SELECT recipient_id, action, accessed_at FROM access_log WHERE vault_key = ? ORDER BY accessed_at DESC LIMIT ?`, ).all(vaultKey, limit) as { recipient_id: string; action: string; accessed_at: number }[]; }