[storage] RoseFile: Save the rose's keys and care to a file and bring them back additively; never the town or the private key

This commit is contained in:
2026-11-02 00:44:18 +01:00
parent cc9cc11b0b
commit a63232e8d7
2 changed files with 158 additions and 2 deletions
+67 -2
View File
@@ -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<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 }>;
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<string, unknown>;
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<ProfileRow, string>;
events!: Table<EventRow, number>;
@@ -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;
}