348 lines
16 KiB
TypeScript
348 lines
16 KiB
TypeScript
/**
|
|
* 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 her opened petals, day-sentence.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, newOpened, type NamedPlace } from '@rosea/engine';
|
|
import { isIdentity, type Identity } from '@rosea/identity';
|
|
import { DATABASE_NAME, type CareEvent, type SentenceOpened } 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. Version 2 adds her opened petals (day-sentence.md P7);
|
|
* a version 1 file is still read, as one with none.
|
|
*/
|
|
export const ROSE_FILE_FORMAT = 'rosea-rose';
|
|
export interface RoseFile {
|
|
readonly format: typeof ROSE_FILE_FORMAT;
|
|
readonly version: 2;
|
|
/** The keys that have named her, the one she had when saved first. Public keys only. */
|
|
readonly keys: readonly string[];
|
|
readonly events: readonly CareEvent[];
|
|
readonly opened: readonly SentenceOpened[];
|
|
}
|
|
|
|
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[]>;
|
|
/** Appends one opened petal (day-sentence.md P6). Never edited. */
|
|
appendOpened(event: SentenceOpened): Promise<void>;
|
|
/** Every opened petal, in the order written. */
|
|
loadOpened(): Promise<SentenceOpened[]>;
|
|
/**
|
|
* 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>;
|
|
/** Keys the rose was named by before, on another device; the current one is not among them. */
|
|
loadPastKeys(): Promise<string[]>;
|
|
/** The rose, as a file the player keeps (keep-her-safe.md). */
|
|
exportRose(currentKey: string): Promise<RoseFile>;
|
|
/**
|
|
* 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; readonly petals: number }>;
|
|
/**
|
|
* Hears what another tab of the garden wrote (two-tabs.md): `'log'` or `'place'`,
|
|
* after it committed. Read storage again on it. Returns the way to stop hearing.
|
|
*/
|
|
onChange(listener: (what: Change) => void): () => void;
|
|
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<string, unknown>;
|
|
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<string, unknown>;
|
|
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<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;
|
|
}
|
|
|
|
const OPENED_KEYS = new Set(['kind', 'ts', 'localDay', 'from', 'messageId', 'clientVersion']);
|
|
|
|
/** The sentence-opened contract (sentence-opened.schema.json), checked by hand for the same reason as care. */
|
|
export function asSentenceOpened(value: unknown): SentenceOpened | null {
|
|
if (typeof value !== 'object' || value === null) return null;
|
|
const v = value as Record<string, unknown>;
|
|
if (Object.keys(v).some((k) => !OPENED_KEYS.has(k))) return null;
|
|
if (v['kind'] !== 'sentence-opened' || !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)) return null;
|
|
const messageId = v['messageId'];
|
|
if (!(matches(messageId, /^[a-z0-9]+(-[a-z0-9]+)*$/) && messageId.length <= 64)) return null;
|
|
if (!matches(v['clientVersion'], /^\d+\.\d+\.\d+$/)) return null;
|
|
return { kind: 'sentence-opened', ts: v['ts'] as number, localDay: v['localDay'], from: v['from'], messageId, clientVersion: v['clientVersion'] };
|
|
}
|
|
|
|
/** Kinds the log holds besides care, each read by its own loader: not broken entries. */
|
|
const OTHER_KINDS: ReadonlySet<unknown> = new Set(['sentence-opened']);
|
|
const kindOf = (event: unknown): unknown => (typeof event === 'object' && event !== null ? (event as { kind?: unknown }).kind : undefined);
|
|
|
|
const isKeyList = (x: unknown): x is string[] => Array.isArray(x) && x.every((k) => matches(k, KEY));
|
|
|
|
/** Every item through `check`, or null if any one fails it. */
|
|
function every<T>(items: unknown, check: (x: unknown) => T | null): T[] | null {
|
|
if (!Array.isArray(items)) return null;
|
|
const out: T[] = [];
|
|
for (const item of items as unknown[]) {
|
|
const plain = check(item);
|
|
if (plain === null) return null;
|
|
out.push(plain);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* The shape check for a saved rose, version 1 or 2. Every act must pass the care
|
|
* event contract and every petal the sentence-opened one. It answers as version 2.
|
|
*/
|
|
export function asRoseFile(value: unknown): RoseFile | null {
|
|
if (typeof value !== 'object' || value === null) return null;
|
|
const v = value as Record<string, unknown>;
|
|
if (v['format'] !== ROSE_FILE_FORMAT || (v['version'] !== 1 && v['version'] !== 2)) return null;
|
|
if (!isKeyList(v['keys']) || v['keys'].length === 0) return null;
|
|
const events = every(v['events'], asCareEvent);
|
|
const opened = v['version'] === 1 ? ('opened' in v ? null : []) : every(v['opened'], asSentenceOpened);
|
|
if (events === null || opened === null) return null;
|
|
return { format: ROSE_FILE_FORMAT, version: 2, keys: [...new Set(v['keys'])], events, opened };
|
|
}
|
|
|
|
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' });
|
|
}
|
|
}
|
|
|
|
/** What another tab changed (two-tabs.md W2): only which part, never the data. */
|
|
export type Change = 'log' | 'place';
|
|
|
|
/** The channel every tab of the garden announces its writes on (two-tabs.md W1). */
|
|
export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`;
|
|
|
|
/**
|
|
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
|
|
* passes nothing and gets the browser's IndexedDB. `settings.channel` names the
|
|
* channel writes are announced on (null: none), so tests can keep theirs apart.
|
|
*/
|
|
export function openStorage(options?: DexieOptions, settings: { readonly channel?: string | null } = {}): Storage {
|
|
const db = new RoseaDatabase(options);
|
|
const channelName = settings.channel === undefined ? CHANGES_CHANNEL : settings.channel;
|
|
// Where BroadcastChannel does not exist, each tab simply keeps its own view (W5).
|
|
const channel = channelName !== null && typeof BroadcastChannel === 'function' ? new BroadcastChannel(channelName) : null;
|
|
const listeners = new Set<(what: Change) => void>();
|
|
if (channel) {
|
|
channel.onmessage = (message: MessageEvent<unknown>) => {
|
|
const what = message.data;
|
|
if (what !== 'log' && what !== 'place') return;
|
|
for (const listener of listeners) {
|
|
try {
|
|
listener(what);
|
|
} catch (error) {
|
|
console.error('storage: a listener for changes in another tab failed', error);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
/** Called only after a write committed, so the other tab reads what was written. A tab never hears itself (W3). */
|
|
const announce = (what: Change): void => {
|
|
try {
|
|
channel?.postMessage(what);
|
|
} catch (error) {
|
|
console.warn('storage: could not tell the other tabs about a change; they will see it on their next load', error);
|
|
}
|
|
};
|
|
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 });
|
|
announce('place');
|
|
},
|
|
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 });
|
|
announce('log');
|
|
},
|
|
async loadCare() {
|
|
const rows = await db.events.orderBy('id').toArray();
|
|
const events: CareEvent[] = [];
|
|
for (const row of rows) {
|
|
if (OTHER_KINDS.has(kindOf(row.event))) continue;
|
|
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 appendOpened(event) {
|
|
const plain = asSentenceOpened(event);
|
|
if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape');
|
|
await db.events.add({ event: plain });
|
|
announce('log');
|
|
},
|
|
async loadOpened() {
|
|
const rows = await db.events.orderBy('id').toArray();
|
|
const opened: SentenceOpened[] = [];
|
|
for (const row of rows) {
|
|
if (kindOf(row.event) !== 'sentence-opened') continue;
|
|
const e = asSentenceOpened(row.event);
|
|
if (e === null) console.warn('storage: an opened petal has an unknown shape; it is skipped, not removed', row);
|
|
else opened.push(e);
|
|
}
|
|
return opened;
|
|
},
|
|
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: 2, keys: [...new Set([currentKey, ...past])],
|
|
events: await api.loadCare(), opened: await api.loadOpened()
|
|
};
|
|
},
|
|
async importRose(file, currentKey) {
|
|
const rose = asRoseFile(file);
|
|
if (rose === null) throw new TypeError('storage: this file does not hold a rose');
|
|
const result = await 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 rows = (await db.events.orderBy('id').toArray()).map((r) => r.event);
|
|
const existing = rows.map(asCareEvent).filter((e): e is CareEvent => e !== null);
|
|
const existingOpened = rows.map(asSentenceOpened).filter((e): e is SentenceOpened => e !== null);
|
|
const added = newCare(existing, rose.events);
|
|
const petals = newOpened(existingOpened, rose.opened);
|
|
await db.events.bulkAdd([...added, ...petals].map((event) => ({ event })));
|
|
return { added: added.length, petals: petals.length };
|
|
});
|
|
// After the commit: her keys and her log both changed for the other tabs.
|
|
announce('log');
|
|
return result;
|
|
},
|
|
onChange(listener) {
|
|
listeners.add(listener);
|
|
return () => listeners.delete(listener);
|
|
},
|
|
close() {
|
|
listeners.clear();
|
|
channel?.close();
|
|
db.close();
|
|
}
|
|
};
|
|
return api;
|
|
}
|