diff --git a/packages/storage/src/index.ts b/packages/storage/src/index.ts index 3cc722e..e0c368f 100644 --- a/packages/storage/src/index.ts +++ b/packages/storage/src/index.ts @@ -10,7 +10,7 @@ * may enter a log that is never edited. */ import Dexie, { type DexieOptions, type Table } from 'dexie'; -import type { NamedPlace } from '@rosea/engine'; +import { newCare, type NamedPlace } from '@rosea/engine'; import { isIdentity, type Identity } from '@rosea/identity'; import { DATABASE_NAME, type CareEvent } from '@rosea/schema'; @@ -35,6 +35,17 @@ interface KeyRow { 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. */ @@ -50,6 +61,15 @@ export interface Storage { */ 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; } @@ -98,6 +118,23 @@ export function asCareEvent(value: unknown): CareEvent | null { 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; @@ -121,7 +158,7 @@ export function openStorage(options?: DexieOptions): Storage { const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null; return id && isIdentity(id) ? id : null; }; - return { + const api: Storage = { async loadSunsetPlace() { const row = await db.profile.get(SUNSET_PLACE); if (row === undefined) return null; @@ -163,8 +200,36 @@ export function openStorage(options?: DexieOptions): Storage { 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; } diff --git a/packages/storage/test/rose-file.test.ts b/packages/storage/test/rose-file.test.ts new file mode 100644 index 0000000..e362664 --- /dev/null +++ b/packages/storage/test/rose-file.test.ts @@ -0,0 +1,91 @@ +import { createIdentity } from '@rosea/identity'; +import type { CareEvent } from '@rosea/schema'; +import { IDBFactory, IDBKeyRange } from 'fake-indexeddb'; +import { afterEach, describe, expect, it } from 'vitest'; +import { asRoseFile, openStorage, ROSE_FILE_FORMAT, type Storage } from '../src/index.js'; + +const OLD = 'O'.repeat(87); +const NEW = 'N'.repeat(87); +const act = (to: string, ts: number): CareEvent => ({ + kind: 'care', ts, localDay: '2026-03-01', from: to, to, act: 'water', + trace: 'petal:rose', messageId: null, clientVersion: '0.1.0', amount: 0.5 +}); + +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(); +}); + +describe('saving the rose to a file', () => { + it('holds her keys and her care, and nothing else: no private key, no town', async () => { + const s = open(); + // A real identity is kept, so a leak of anything from it would have something to leak. + await s.keepIdentity(await createIdentity()); + await s.saveSunsetPlace({ kind: 'town', town: { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' } }); + await s.appendCare(act(OLD, 1)); + const file = await s.exportRose(OLD); + expect(file).toStrictEqual({ format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [act(OLD, 1)] }); + expect(JSON.stringify(file)).not.toMatch(/Brno|privateKey|CryptoKey/); + }); + + it('survives a trip through JSON text unchanged', async () => { + const s = open(); + await s.appendCare(act(OLD, 1)); + const file = await s.exportRose(OLD); + expect(asRoseFile(JSON.parse(JSON.stringify(file)))).toEqual(file); + }); +}); + +describe('bringing her back', () => { + it('on a new device: her old key joins the past keys and all her care comes back', async () => { + const old = open(); + await old.appendCare(act(OLD, 1)); + await old.appendCare(act(OLD, 2)); + const file = JSON.parse(JSON.stringify(await old.exportRose(OLD))); + + const fresh = open(); + expect(await fresh.importRose(file, NEW)).toEqual({ added: 2 }); + expect(await fresh.loadPastKeys()).toEqual([OLD]); + expect(await fresh.loadCare()).toEqual([act(OLD, 1), act(OLD, 2)]); + }); + + it('twice is the same as once, and the care given here meanwhile stays', async () => { + const old = open(); + await old.appendCare(act(OLD, 1)); + const file = await old.exportRose(OLD); + const here = open(); + await here.appendCare(act(NEW, 5)); + await here.importRose(file, NEW); + expect(await here.importRose(file, NEW)).toEqual({ added: 0 }); + expect(await here.loadCare()).toEqual([act(NEW, 5), act(OLD, 1)]); + expect(await here.loadPastKeys()).toEqual([OLD]); + }); + + it('a file saved on this very device adds nothing and does not list its own key as past', async () => { + const s = open(); + await s.appendCare(act(NEW, 1)); + expect(await s.importRose(await s.exportRose(NEW), NEW)).toEqual({ added: 0 }); + expect(await s.loadPastKeys()).toEqual([]); + }); + + it('refuses anything that is not a rose, and changes nothing', async () => { + const s = open(); + await s.appendCare(act(NEW, 1)); + for (const bad of [ + null, 'rose', { format: 'other', version: 1, keys: [OLD], events: [] }, + { format: ROSE_FILE_FORMAT, version: 2, keys: [OLD], events: [] }, + { format: ROSE_FILE_FORMAT, version: 1, keys: [], events: [] }, + { format: ROSE_FILE_FORMAT, version: 1, keys: ['short'], events: [] }, + { format: ROSE_FILE_FORMAT, version: 1, keys: [OLD], events: [{ ...act(OLD, 1), note: 'hello' }] } + ]) { + await expect(s.importRose(bad, NEW)).rejects.toThrow(/does not hold a rose/); + } + expect(await s.loadCare()).toEqual([act(NEW, 1)]); + expect(await s.loadPastKeys()).toEqual([]); + }); +});