From 2b5cd719c104b47475788db76437b526f0d8ac5e Mon Sep 17 00:00:00 2001 From: mnovak Date: Mon, 2 Nov 2026 00:20:58 +0100 Subject: [PATCH] [storage] CareLog: Append-only care events and the kept identity, checked against the contract --- packages/storage/package.json | 2 + packages/storage/src/index.ts | 104 +++++++++++++++++++++-- packages/storage/test/care.test.ts | 114 ++++++++++++++++++++++++++ packages/storage/test/profile.test.ts | 10 +-- 4 files changed, 217 insertions(+), 13 deletions(-) create mode 100644 packages/storage/test/care.test.ts diff --git a/packages/storage/package.json b/packages/storage/package.json index 099dcc9..32f6c2e 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -16,6 +16,8 @@ }, "dependencies": { "@rosea/engine": "workspace:*", + "@rosea/identity": "workspace:*", + "@rosea/schema": "workspace:*", "dexie": "4.4.6" }, "devDependencies": { diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 2760d02..3cc722e 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -1,15 +1,20 @@ /** * 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`, written by the sunset-place question - * (.agents/features/sunset-place.md). + * 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 type { NamedPlace } from '@rosea/engine'; +import { isIdentity, type Identity } from '@rosea/identity'; +import { DATABASE_NAME, type CareEvent } from '@rosea/schema'; -export const DATABASE_NAME = 'rosea'; +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' }; @@ -18,18 +23,39 @@ 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'; -export interface Profile { +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; 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 { @@ -43,12 +69,45 @@ export function asSunsetPlace(value: unknown): SunsetPlace | 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; +} + 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' }); } } @@ -56,8 +115,12 @@ class RoseaDatabase extends Dexie { * Opens the player's database. `options` lets a test pass fake-indexeddb; the app * passes nothing and gets the browser's IndexedDB. */ -export function openProfile(options?: DexieOptions): Profile { +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; + }; return { async loadSunsetPlace() { const row = await db.profile.get(SUNSET_PLACE); @@ -68,13 +131,38 @@ export function openProfile(options?: DexieOptions): Profile { return place; }, async saveSunsetPlace(place) { - // Write a fresh plain copy, never the caller's object: a Svelte 5 state Proxy - // cannot be structured-cloned, and IndexedDB refuses it (DataCloneError). The - // same shape check as on reading, so nothing malformed is ever written. 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)); + }, close() { db.close(); } diff --git a/packages/storage/test/care.test.ts b/packages/storage/test/care.test.ts new file mode 100644 index 0000000..6b9f217 --- /dev/null +++ b/packages/storage/test/care.test.ts @@ -0,0 +1,114 @@ +import { createIdentity } from '@rosea/identity'; +import type { CareEvent } from '@rosea/schema'; +import { validateCareEvent } from '@rosea/schema/validate'; +import Dexie from 'dexie'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { asCareEvent, openStorage, type Storage } from '../src/index.js'; + +const KEY = 'K'.repeat(87); +const water: CareEvent = { + kind: 'care', ts: 1774944000000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'water', + trace: 'petal:pale-pink', messageId: null, clientVersion: '0.1.0', amount: 0.5 +}; +const weed: CareEvent = { kind: 'care', ts: 1774944060000, localDay: '2026-03-31', from: KEY, to: KEY, act: 'weed', trace: 'petal:pale-pink', messageId: null, clientVersion: '0.1.0' }; + +const opened: Storage[] = []; +const open = (indexedDB: IDBFactory = new IDBFactory()): Storage => { + const s = openStorage({ indexedDB, IDBKeyRange }); + opened.push(s); + return s; +}; +afterEach(() => { + for (const s of opened.splice(0)) s.close(); + vi.restoreAllMocks(); +}); + +describe('the care log', () => { + it('appends and comes back in the order written, across a reopen', async () => { + const factory = new IDBFactory(); + const s = open(factory); + await s.appendCare(water); + await s.appendCare(new Proxy(weed, {})); // as Svelte 5 state would hand it over + s.close(); + expect(await open(factory).loadCare()).toEqual([water, weed]); + }); + + it('refuses to append anything the contract refuses', async () => { + const s = open(); + for (const bad of [ + { ...water, note: 'hello' }, + { ...weed, amount: 0.5 }, + { ...water, amount: 2 }, + { ...weed, messageId: 'meet me at the station' } + ]) { + await expect(s.appendCare(bad as CareEvent)).rejects.toThrow(/unknown shape/); + } + expect(await s.loadCare()).toEqual([]); + }); + + it('a broken entry already in the log is skipped and said, never removed', async () => { + const factory = new IDBFactory(); + const s = open(factory); + await s.appendCare(water); + s.close(); + const raw = new Dexie('rosea', { indexedDB: factory, IDBKeyRange }); + raw.version(2).stores({ profile: 'key', events: '++id', keys: 'id' }); + await raw.table('events').add({ event: { kind: 'care', act: 'dance' } }); + raw.close(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); + expect(await open(factory).loadCare()).toEqual([water]); + expect(warn).toHaveBeenCalledWith(expect.stringMatching(/skipped, not removed/), expect.anything()); + }); +}); + +describe('asCareEvent agrees with the schema\'s own validator', () => { + const variants: Record[] = [ + water, weed, + { ...water, amount: 0 }, { ...water, amount: 1 }, { ...water, amount: 1.5 }, { ...water, amount: -1 }, + { ...water, amount: undefined }, { ...weed, amount: 0.2 }, { ...weed, act: 'water' }, + { ...weed, act: 'wind' }, { ...weed, ts: -1 }, { ...weed, ts: 1.5 }, { ...weed, localDay: '2026-3-31' }, + { ...weed, from: 'short' }, { ...weed, trace: 'petal:Pink' }, { ...weed, messageId: 'ps-23-4' }, + { ...weed, messageId: 'x'.repeat(65) }, { ...weed, clientVersion: '1.0' }, { ...weed, kind: 'sunset' }, + { ...weed, extra: true } + ].map((v) => Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined))); + + it.each(variants.map((v, i) => [i, v] as const))('variant %i', (_i, v) => { + expect(asCareEvent(v) !== null).toBe(validateCareEvent(v).ok); + }); +}); + +describe('the identity', () => { + it('is kept once; a second, racing one is dropped and the first returned', async () => { + const factory = new IDBFactory(); + const s = open(factory); + const [first, second] = [await createIdentity(), await createIdentity()]; + const [a, b] = await Promise.all([s.keepIdentity(first), open(factory).keepIdentity(second)]); + expect(a.publicKey).toBe(b.publicKey); + expect((await open(factory).loadIdentity())?.publicKey).toBe(a.publicKey); + }); + + it('the private key comes back still unexportable', async () => { + const factory = new IDBFactory(); + await open(factory).keepIdentity(await createIdentity()); + const back = await open(factory).loadIdentity(); + expect(back?.privateKey.extractable).toBe(false); + }); + + it('nothing kept reads null', async () => { + expect(await open().loadIdentity()).toBeNull(); + }); +}); + +describe('the database version', () => { + it('upgrading from version 1 keeps the sunset place', async () => { + const factory = new IDBFactory(); + const v1 = new Dexie('rosea', { indexedDB: factory, IDBKeyRange }); + v1.version(1).stores({ profile: 'key' }); + await v1.table('profile').put({ key: 'sunsetPlace', value: { kind: 'device-zone' } }); + v1.close(); + const s = open(factory); + expect(await s.loadSunsetPlace()).toEqual({ kind: 'device-zone' }); + expect(await s.loadCare()).toEqual([]); + }); +}); diff --git a/packages/storage/test/profile.test.ts b/packages/storage/test/profile.test.ts index 06e3a81..19af9a9 100644 --- a/packages/storage/test/profile.test.ts +++ b/packages/storage/test/profile.test.ts @@ -1,16 +1,16 @@ import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { asSunsetPlace, openProfile, type Profile, type SunsetPlace } from '../src/index.js'; +import { asSunsetPlace, openStorage, type Storage, type SunsetPlace } from '../src/index.js'; const brno: SunsetPlace = { kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } }; -const opened: Profile[] = []; +const opened: Storage[] = []; /** A fresh, empty fake database per call unless one is passed: tests never share state. */ -function open(indexedDB: IDBFactory = new IDBFactory()): Profile { - const p = openProfile({ indexedDB, IDBKeyRange }); +function open(indexedDB: IDBFactory = new IDBFactory()): Storage { + const p = openStorage({ indexedDB, IDBKeyRange }); opened.push(p); return p; } @@ -83,7 +83,7 @@ describe('the profile store — the sunset place', () => { it('a database that cannot open rejects, so the app can fall back to the session', async () => { const broken = new IDBFactory(); broken.open = () => { throw new DOMException('blocked by the browser', 'SecurityError'); }; - await expect(openProfile({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow(); + await expect(openStorage({ indexedDB: broken, IDBKeyRange }).loadSunsetPlace()).rejects.toThrow(); }); });