/** * The ONLY module that touches IndexedDB (CLAUDE.md §2). The database `rosea` and its * stores are listed in CLAUDE.md §4; each store arrives with the feature that writes * it. So far: `profile` (the sunset place, sunset-place.md), `events` (the rose's care * log, rose.md) and `keys` (the identity, rose.md). * * The database name changes together with the product name (CLAUDE.md preamble). * Everything written is a fresh plain copy that passed a shape check: a Svelte 5 * state Proxy cannot be structured-cloned (lessons/code.md), and nothing malformed * may enter a log that is never edited. */ import Dexie, { type DexieOptions, type Table } from 'dexie'; import { newCare, type NamedPlace } from '@rosea/engine'; import { isIdentity, type Identity } from '@rosea/identity'; import { DATABASE_NAME, type CareEvent } from '@rosea/schema'; export { DATABASE_NAME }; /** Where the player wants their sunset: a town they chose, or the guess from the device's zone. */ export type SunsetPlace = { readonly kind: 'town'; readonly town: NamedPlace } | { readonly kind: 'device-zone' }; interface ProfileRow { readonly key: string; readonly value: unknown; } interface EventRow { readonly id?: number; readonly event: unknown; } interface KeyRow { readonly id: string; readonly publicKey: string; readonly privateKey: CryptoKey; } const SUNSET_PLACE = 'sunsetPlace'; const SELF = 'self'; const PAST_KEYS = 'pastKeys'; /** The file a rose is saved to and brought back from (keep-her-safe.md K4). Never the private key, never the town. */ export const ROSE_FILE_FORMAT = 'rosea-rose'; export interface RoseFile { readonly format: typeof ROSE_FILE_FORMAT; readonly version: 1; /** The keys that have named her, the one she had when saved first. Public keys only. */ readonly keys: readonly string[]; readonly events: readonly CareEvent[]; } export interface Storage { /** The saved sunset place, or null if the player has not answered yet. */ loadSunsetPlace(): Promise; saveSunsetPlace(place: SunsetPlace): Promise; /** Appends one act of care. The log is never edited or shortened. */ appendCare(event: CareEvent): Promise; /** The whole care log, in the order it was written. */ loadCare(): Promise; /** * The player's identity: the one already kept, or `fresh` kept now. With two tabs * racing, both get the same one: the first write wins and the other is dropped. */ keepIdentity(fresh: Identity): Promise; loadIdentity(): Promise; /** Keys the rose was named by before, on another device; the current one is not among them. */ loadPastKeys(): Promise; /** The rose, as a file the player keeps (keep-her-safe.md). */ exportRose(currentKey: string): Promise; /** * Brings a saved rose back: her keys join the past keys and every act not already * here is appended. Nothing is edited or removed. Rejects a file that is not a rose. */ importRose(file: unknown, currentKey: string): Promise<{ readonly added: number }>; close(): void; } const isNumberIn = (x: unknown, limit: number): x is number => typeof x === 'number' && Number.isFinite(x) && Math.abs(x) <= limit; const isString = (x: unknown): x is string => typeof x === 'string'; const matches = (x: unknown, re: RegExp): x is string => typeof x === 'string' && re.test(x); /** The shape check a stored value must pass. A value from an older version or a broken write fails it. */ export function asSunsetPlace(value: unknown): SunsetPlace | null { if (typeof value !== 'object' || value === null) return null; const v = value as Record; if (v['kind'] === 'device-zone') return { kind: 'device-zone' }; if (v['kind'] !== 'town' || typeof v['town'] !== 'object' || v['town'] === null) return null; const t = v['town'] as Record; if (!isString(t['name']) || t['name'] === '' || !isString(t['region']) || !isString(t['country']) || !isString(t['timeZone'])) return null; if (!isNumberIn(t['lat'], 90) || !isNumberIn(t['lon'], 180)) return null; return { kind: 'town', town: { name: t['name'], region: t['region'], country: t['country'], lat: t['lat'], lon: t['lon'], timeZone: t['timeZone'] } }; } const CARE_KEYS = new Set(['kind', 'ts', 'localDay', 'from', 'to', 'act', 'trace', 'messageId', 'clientVersion', 'amount']); const ACTS = new Set(['water', 'shade', 'weed', 'petals']); const KEY = /^[A-Za-z0-9_-]{32,128}$/; /** * The care event contract (packages/schema care-event.schema.json), checked by hand: * Ajv compiles with `new Function`, which the app's CSP forbids (GAP_ANALYSIS G0.12). * `storage/test` checks this agrees with the schema's own validator. */ export function asCareEvent(value: unknown): CareEvent | null { if (typeof value !== 'object' || value === null) return null; const v = value as Record; if (Object.keys(v).some((k) => !CARE_KEYS.has(k))) return null; if (v['kind'] !== 'care' || !Number.isSafeInteger(v['ts']) || (v['ts'] as number) < 0) return null; if (!matches(v['localDay'], /^\d{4}-\d{2}-\d{2}$/) || !matches(v['from'], KEY) || !matches(v['to'], KEY)) return null; if (!isString(v['act']) || !ACTS.has(v['act']) || !matches(v['trace'], /^petal:[a-z]+(-[a-z]+)*$/)) return null; const messageId = v['messageId']; if (messageId !== null && !(matches(messageId, /^[a-z0-9]+(-[a-z0-9]+)*$/) && messageId.length <= 64)) return null; if (!matches(v['clientVersion'], /^\d+\.\d+\.\d+$/)) return null; const isWater = v['act'] === 'water'; if (isWater !== ('amount' in v)) return null; if (isWater && !(typeof v['amount'] === 'number' && v['amount'] >= 0 && v['amount'] <= 1)) return null; const base = { kind: 'care' as const, ts: v['ts'] as number, localDay: v['localDay'], from: v['from'], to: v['to'], act: v['act'] as CareEvent['act'], trace: v['trace'], messageId, clientVersion: v['clientVersion'] }; return isWater ? { ...base, amount: v['amount'] as number } : base; } const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY)); /** The shape check for a saved rose. Every act must pass the care event contract. */ export function asRoseFile(value: unknown): RoseFile | null { if (typeof value !== 'object' || value === null) return null; const v = value as Record; if (v['format'] !== ROSE_FILE_FORMAT || v['version'] !== 1) return null; if (!isKeyList(v['keys']) || v['keys'].length === 0 || !Array.isArray(v['events'])) return null; const events: CareEvent[] = []; for (const e of v['events'] as unknown[]) { const plain = asCareEvent(e); if (plain === null) return null; events.push(plain); } return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set(v['keys'])], events }; } class RoseaDatabase extends Dexie { profile!: Table; events!: Table; keys!: Table; constructor(options?: DexieOptions) { super(DATABASE_NAME, options); this.version(1).stores({ profile: 'key' }); // Version 2 adds the care log and the identity; version 1 data is kept as it is. this.version(2).stores({ profile: 'key', events: '++id', keys: 'id' }); } } /** * Opens the player's database. `options` lets a test pass fake-indexeddb; the app * passes nothing and gets the browser's IndexedDB. */ export function openStorage(options?: DexieOptions): Storage { const db = new RoseaDatabase(options); const asIdentity = (row: KeyRow | undefined): Identity | null => { const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null; return id && isIdentity(id) ? id : null; }; const api: Storage = { async loadSunsetPlace() { const row = await db.profile.get(SUNSET_PLACE); if (row === undefined) return null; const place = asSunsetPlace(row.value); // Never swallowed: a broken record is said out loud, then the question is asked again. if (place === null) console.warn('storage: the saved sunset place has an unknown shape; asking again', row.value); return place; }, async saveSunsetPlace(place) { const plain = asSunsetPlace(place); if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape'); await db.profile.put({ key: SUNSET_PLACE, value: plain }); }, async appendCare(event) { const plain = asCareEvent(event); if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape'); await db.events.add({ event: plain }); }, async loadCare() { const rows = await db.events.orderBy('id').toArray(); const events: CareEvent[] = []; for (const row of rows) { const e = asCareEvent(row.event); // A broken entry is said out loud and left in place: the log is never edited. if (e === null) console.warn('storage: a care event has an unknown shape; it is skipped, not removed', row); else events.push(e); } return events; }, async keepIdentity(fresh) { if (!isIdentity(fresh)) throw new TypeError('storage: refusing to keep an identity of an unknown shape'); return db.transaction('rw', db.keys, async () => { const kept = asIdentity(await db.keys.get(SELF)); if (kept) return kept; await db.keys.add({ id: SELF, publicKey: fresh.publicKey, privateKey: fresh.privateKey }); return { publicKey: fresh.publicKey, privateKey: fresh.privateKey }; }); }, async loadIdentity() { return asIdentity(await db.keys.get(SELF)); }, async loadPastKeys() { const row = await db.profile.get(PAST_KEYS); if (row === undefined) return []; if (!isKeyList(row.value)) { console.warn('storage: the past keys have an unknown shape; ignoring them', row.value); return []; } return row.value; }, async exportRose(currentKey) { const past = await api.loadPastKeys(); return { format: ROSE_FILE_FORMAT, version: 1, keys: [...new Set([currentKey, ...past])], events: await api.loadCare() }; }, async importRose(file, currentKey) { const rose = asRoseFile(file); if (rose === null) throw new TypeError('storage: this file does not hold a rose'); return db.transaction('rw', db.events, db.profile, async () => { const row = await db.profile.get(PAST_KEYS); const past = isKeyList(row?.value) ? row.value : []; const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey); await db.profile.put({ key: PAST_KEYS, value: keys }); const existing = (await db.events.orderBy('id').toArray()).map((r) => asCareEvent(r.event)).filter((e): e is CareEvent => e !== null); const added = newCare(existing, rose.events); await db.events.bulkAdd(added.map((event) => ({ event }))); return { added: added.length }; }); }, close() { db.close(); } }; return api; }