// SQLite storage. Everything group-related is ciphertext the server cannot // read; the only plaintext is ids, sizes, timestamps and push endpoints. import { DatabaseSync } from 'node:sqlite'; import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; export interface StoredEvent { seq: number; id: string; deviceId: string; iv: string; ct: string; } export interface PushSub { endpoint: string; p256dh: string; auth: string; deviceId: string; } export interface RatesDay { date: string; rates: Record; sources: Record; } export class Store { readonly db: DatabaseSync; constructor(dataDir: string) { mkdirSync(dataDir, { recursive: true }); this.db = new DatabaseSync(join(dataDir, 'oweme.sqlite')); this.db.exec(` PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON; CREATE TABLE IF NOT EXISTS groups ( id TEXT PRIMARY KEY, auth_hash TEXT NOT NULL, bytes INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL ); CREATE TABLE IF NOT EXISTS events ( group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, seq INTEGER NOT NULL, id TEXT NOT NULL, device_id TEXT NOT NULL, iv TEXT NOT NULL, ct TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (group_id, seq), UNIQUE (group_id, id) ); CREATE TABLE IF NOT EXISTS blobs ( group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, id TEXT NOT NULL, size INTEGER NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (group_id, id) ); CREATE TABLE IF NOT EXISTS push_subs ( group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, endpoint TEXT NOT NULL, p256dh TEXT NOT NULL, auth TEXT NOT NULL, device_id TEXT NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (group_id, endpoint) ); CREATE TABLE IF NOT EXISTS rates ( date TEXT PRIMARY KEY, json TEXT NOT NULL ); -- Supplementary rates (see rates.ts), kept apart so ECB refreshes never -- overwrite them and ECB always wins for currencies both publish. CREATE TABLE IF NOT EXISTS rates_extra ( date TEXT PRIMARY KEY, source TEXT NOT NULL, json TEXT NOT NULL ); `); } tx(fn: () => T): T { this.db.exec('BEGIN IMMEDIATE'); try { const r = fn(); this.db.exec('COMMIT'); return r; } catch (e) { this.db.exec('ROLLBACK'); throw e; } } createGroup(id: string, authHash: string): boolean { const r = this.db .prepare('INSERT OR IGNORE INTO groups (id, auth_hash, created_at) VALUES (?, ?, ?)') .run(id, authHash, Date.now()); return r.changes === 1; } getGroup(id: string): { authHash: string; bytes: number } | undefined { const r = this.db.prepare('SELECT auth_hash, bytes FROM groups WHERE id = ?').get(id) as | { auth_hash: string; bytes: number } | undefined; return r && { authHash: r.auth_hash, bytes: r.bytes }; } deleteGroup(id: string): void { this.db.prepare('DELETE FROM groups WHERE id = ?').run(id); } addBytes(id: string, n: number): void { this.db.prepare('UPDATE groups SET bytes = bytes + ? WHERE id = ?').run(n, id); } latestSeq(groupId: string): number { const r = this.db.prepare('SELECT MAX(seq) AS s FROM events WHERE group_id = ?').get(groupId) as { s: number | null }; return r.s ?? 0; } eventsAfter(groupId: string, after: number, limit: number): StoredEvent[] { return this.db .prepare('SELECT seq, id, device_id AS deviceId, iv, ct FROM events WHERE group_id = ? AND seq > ? ORDER BY seq LIMIT ?') .all(groupId, after, limit) as unknown as StoredEvent[]; } /** Existing seq for an event id (idempotent retries), if any. */ seqOf(groupId: string, id: string): number | undefined { const r = this.db.prepare('SELECT seq FROM events WHERE group_id = ? AND id = ?').get(groupId, id) as { seq: number } | undefined; return r?.seq; } insertEvent(groupId: string, seq: number, e: Omit): void { this.db .prepare('INSERT INTO events (group_id, seq, id, device_id, iv, ct, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)') .run(groupId, seq, e.id, e.deviceId, e.iv, e.ct, Date.now()); } hasBlob(groupId: string, id: string): boolean { return !!this.db.prepare('SELECT 1 FROM blobs WHERE group_id = ? AND id = ?').get(groupId, id); } insertBlob(groupId: string, id: string, size: number): void { this.db.prepare('INSERT INTO blobs (group_id, id, size, created_at) VALUES (?, ?, ?, ?)').run(groupId, id, size, Date.now()); } upsertPush(groupId: string, s: PushSub): void { this.db .prepare( `INSERT INTO push_subs (group_id, endpoint, p256dh, auth, device_id, created_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT (group_id, endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, device_id = excluded.device_id`, ) .run(groupId, s.endpoint, s.p256dh, s.auth, s.deviceId, Date.now()); } deletePush(groupId: string, endpoint: string): void { this.db.prepare('DELETE FROM push_subs WHERE group_id = ? AND endpoint = ?').run(groupId, endpoint); } deletePushEverywhere(endpoint: string): void { this.db.prepare('DELETE FROM push_subs WHERE endpoint = ?').run(endpoint); } pushSubs(groupId: string): PushSub[] { return this.db .prepare('SELECT endpoint, p256dh, auth, device_id AS deviceId FROM push_subs WHERE group_id = ?') .all(groupId) as unknown as PushSub[]; } saveRates(date: string, rates: Record): void { this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates)); } saveExtraRates(date: string, source: string, rates: Record): void { this.db .prepare('INSERT OR REPLACE INTO rates_extra (date, source, json) VALUES (?, ?, ?)') .run(date, source, JSON.stringify(rates)); } /** * ECB rates for the latest published date on or before `date`, plus * supplementary rates for currencies the ECB doesn't publish. `sources` * names the origin of each supplementary rate (":"). * Supplementary rates older than a week before `date` are not used. */ ratesOn(date: string): RatesDay | undefined { const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as | { date: string; json: string } | undefined; if (!r) return undefined; const rates: Record = JSON.parse(r.json); const sources: Record = {}; const weekBefore = new Date(Date.parse(date) - 7 * 86400_000).toISOString().slice(0, 10); const x = this.db .prepare('SELECT date, source, json FROM rates_extra WHERE date <= ? AND date >= ? ORDER BY date DESC LIMIT 1') .get(date, weekBefore) as { date: string; source: string; json: string } | undefined; if (x) { for (const [code, rate] of Object.entries(JSON.parse(x.json) as Record)) { if (code in rates) continue; rates[code] = rate; sources[code] = `${x.source}:${x.date}`; } } return { date: r.date, rates, sources }; } latestRatesDate(): string | undefined { const r = this.db.prepare('SELECT MAX(date) AS d FROM rates').get() as { d: string | null }; return r.d ?? undefined; } }