// Backup file (SPEC.md ยง7.6): the encrypted event log and photos plus the // group secret, so the group can be restored even if every link is lost. // Events and photos stay encrypted inside; the secret makes the file as // sensitive as the link. import type { GroupEvent } from '@oweme/core'; import { api, ApiError } from './api.ts'; import { b64uDecode, b64uEncode, deriveKeys, isGroupId, isGroupSecret, sha256hex } from './crypto.ts'; import { get, put, type StoredBlob } from './idb.ts'; import { decryptEvent } from './events.ts'; import { addGroup, type GroupSession } from './session.svelte.ts'; interface BackupFile { format: 'oweme-backup'; v: 1; groupId: string; secret: string; createdAt: string; events: { id: string; deviceId: string; iv: string; ct: string }[]; blobs: { id: string; data: string }[]; } function photoIds(events: GroupEvent[]): string[] { const ids = new Set(); for (const e of events) { if ((e.type === 'expense.created' || e.type === 'expense.updated') && e.data?.photo) { ids.add(e.data.photo.blobId); ids.add(e.data.photo.thumbBlobId); } } return [...ids]; } export async function makeBackup(s: GroupSession): Promise { await s.sync(); const raw = await s.rawEvents(); const blobs: BackupFile['blobs'] = []; for (const id of photoIds(s.synced)) { let rec = await get('blobs', [s.id, id]); if (!rec) { try { rec = { g: s.id, id, data: await api.getBlob(s.id, s.keys.authToken, id), uploaded: true }; await put('blobs', rec); } catch { continue; // missing photo shouldn't block the rest of the backup } } blobs.push({ id, data: b64uEncode(new Uint8Array(rec.data)) }); } const file: BackupFile = { format: 'oweme-backup', v: 1, groupId: s.id, secret: s.local.secret, createdAt: new Date().toISOString(), events: raw.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct })), blobs, }; return JSON.stringify(file); } /** Restore a backup to this server. Returns the group id and whether it already existed. */ export async function restoreBackup(text: string): Promise<{ id: string; existed: boolean }> { let f: BackupFile; try { f = JSON.parse(text); } catch { throw new Error('bad file'); } if (f?.format !== 'oweme-backup' || !isGroupId(f.groupId) || !isGroupSecret(f.secret) || !Array.isArray(f.events) || !f.events.length) throw new Error('bad file'); const keys = await deriveKeys(f.secret); // Make sure the key really opens this data before uploading anything. if (!(await decryptEvent(keys, f.groupId, { ...f.events[0], seq: 0 }))) throw new Error('bad file'); let existed = false; try { await api.createGroup(f.groupId, await sha256hex(keys.authToken)); } catch (e) { if (e instanceof ApiError && e.status === 409) existed = true; else throw e; } // Uploads are idempotent (by event and blob id), so this also completes // an interrupted restore, and is harmless for a group that already exists. for (const b of f.blobs ?? []) await api.putBlob(f.groupId, keys.authToken, b.id, b64uDecode(b.data).buffer); for (let i = 0; i < f.events.length; i += 200) await api.append(f.groupId, keys.authToken, f.events.slice(i, i + 200)); await addGroup(f.groupId, f.secret); return { id: f.groupId, existed }; }