[storage] CareLog: Append-only care events and the kept identity, checked against the contract
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user