[storage] CareLog: Append-only care events and the kept identity, checked against the contract

This commit is contained in:
2026-11-02 00:20:58 +01:00
parent d091c31b49
commit 2b5cd719c1
4 changed files with 217 additions and 13 deletions
+2
View File
@@ -16,6 +16,8 @@
},
"dependencies": {
"@rosea/engine": "workspace:*",
"@rosea/identity": "workspace:*",
"@rosea/schema": "workspace:*",
"dexie": "4.4.6"
},
"devDependencies": {
+96 -8
View File
@@ -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<SunsetPlace | null>;
saveSunsetPlace(place: SunsetPlace): Promise<void>;
/** Appends one act of care. The log is never edited or shortened. */
appendCare(event: CareEvent): Promise<void>;
/** The whole care log, in the order it was written. */
loadCare(): Promise<CareEvent[]>;
/**
* 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<Identity>;
loadIdentity(): Promise<Identity | null>;
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<string, unknown>;
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<ProfileRow, string>;
events!: Table<EventRow, number>;
keys!: Table<KeyRow, string>;
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();
}
+114
View File
@@ -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<string, unknown>[] = [
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([]);
});
});
+5 -5
View File
@@ -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();
});
});