Add Svelte web client and service worker
Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and sync over SSE, all split modes, currencies with ECB rate prefill, photos, comments, history and rewind, stats, recurring expenses, CSV and backup, EN/CS, dark/light theme, Web Push decrypted in the service worker. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
This commit is contained in:
parent
f67add3660
commit
8fbbb4933e
53 changed files with 4558 additions and 37 deletions
296
apps/web/src/lib/session.svelte.ts
Normal file
296
apps/web/src/lib/session.svelte.ts
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
// One open group: its keys, decrypted log, derived state, and sync with the
|
||||
// server. Changes are encrypted, written to the local outbox first, then
|
||||
// uploaded, so the app works offline (SPEC.md §4.1, §10.1).
|
||||
import {
|
||||
balances, dueOccurrences, logOrder, replay, SCHEMA_VERSION,
|
||||
type Activity, type EventBody, type GroupEvent, type GroupState, type EventPlaintext,
|
||||
} from '@oweme/core';
|
||||
import { decryptEvent } from './events.ts';
|
||||
import { api, ApiError, isOffline, listen } from './api.ts';
|
||||
import { decryptBytes, deriveKeys, encryptBytes, encryptJson, randomId, type GroupKeys } from './crypto.ts';
|
||||
import {
|
||||
del, deviceId, get, getAll, groupRange, outboxFor, put, putEvents, updateGroup,
|
||||
type LocalGroup, type OutboxItem, type StoredBlob, type StoredEvent,
|
||||
} from './idb.ts';
|
||||
import { today } from './format.ts';
|
||||
|
||||
export type Status = 'loading' | 'online' | 'offline' | 'gone' | 'error';
|
||||
|
||||
export class GroupSession {
|
||||
readonly id: string;
|
||||
local = $state<LocalGroup>() as LocalGroup;
|
||||
status = $state<Status>('loading');
|
||||
/** seq rollback detected: server is behind what we've seen */
|
||||
rollback = $state(false);
|
||||
synced = $state.raw<GroupEvent[]>([]);
|
||||
pending = $state.raw<GroupEvent[]>([]);
|
||||
state = $state.raw<GroupState>({ group: null, members: [], expenses: {}, comments: {}, recurring: {} });
|
||||
activity = $state.raw<Activity[]>([]);
|
||||
balances = $state.raw<Record<string, number>>({});
|
||||
|
||||
keys!: GroupKeys;
|
||||
private device = '';
|
||||
private abort = new AbortController();
|
||||
private syncing: Promise<void> | null = null;
|
||||
private resync = false;
|
||||
private generatedRecurring = false;
|
||||
private retryTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
constructor(local: LocalGroup) {
|
||||
this.id = local.id;
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
/** Load from IndexedDB, then start syncing in the background. */
|
||||
async open(): Promise<void> {
|
||||
this.keys = await deriveKeys(this.local.secret);
|
||||
this.device = await deviceId();
|
||||
const stored = await getAll<StoredEvent>('events', groupRange(this.id));
|
||||
const out = await outboxFor(this.id);
|
||||
this.synced = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e);
|
||||
this.pending = (await Promise.all(out.map((e) => decryptEvent(this.keys, this.id, { ...e, seq: null })))).filter((e): e is GroupEvent => !!e);
|
||||
this.recompute();
|
||||
if (this.local.gone) {
|
||||
this.status = 'gone';
|
||||
return;
|
||||
}
|
||||
addEventListener('online', this.onOnline);
|
||||
void this.sync();
|
||||
void this.stream();
|
||||
}
|
||||
|
||||
close() {
|
||||
this.abort.abort();
|
||||
clearTimeout(this.retryTimer);
|
||||
removeEventListener('online', this.onOnline);
|
||||
}
|
||||
|
||||
private onOnline = () => void this.sync();
|
||||
|
||||
get me(): string | null {
|
||||
const me = this.local.me;
|
||||
return me && this.state.members.some((m) => m.id === me) ? me : null;
|
||||
}
|
||||
|
||||
get base(): string {
|
||||
return this.state.group?.baseCurrency ?? this.local.baseCurrency;
|
||||
}
|
||||
|
||||
memberName(id: string | null | undefined): string {
|
||||
return this.state.members.find((m) => m.id === id)?.name ?? '?';
|
||||
}
|
||||
|
||||
private recompute() {
|
||||
const r = replay(logOrder(this.synced, this.pending));
|
||||
this.state = r.state;
|
||||
this.activity = r.activity;
|
||||
this.balances = balances(r.state);
|
||||
const g = r.state.group;
|
||||
if (g) {
|
||||
const myBalance = this.local.me ? (this.balances[this.local.me] ?? null) : null;
|
||||
const patch = { name: g.name, icon: g.icon, baseCurrency: g.baseCurrency, myBalance };
|
||||
if (Object.entries(patch).some(([k, v]) => this.local[k as keyof LocalGroup] !== v)) {
|
||||
this.local = { ...this.local, ...patch };
|
||||
void updateGroup(this.id, patch);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async setMe(memberId: string | null) {
|
||||
this.local = { ...this.local, me: memberId };
|
||||
await updateGroup(this.id, { me: memberId });
|
||||
this.recompute();
|
||||
}
|
||||
|
||||
/** Record a change: encrypt → outbox → apply locally → upload. */
|
||||
async emit(...bodies: EventBody[]): Promise<void> {
|
||||
const items: OutboxItem[] = [];
|
||||
const evs: GroupEvent[] = [];
|
||||
for (const body of bodies) {
|
||||
const id = randomId(16);
|
||||
const plain = { ...body, v: SCHEMA_VERSION, actor: this.me, at: new Date().toISOString() } as EventPlaintext;
|
||||
const { iv, ct } = await encryptJson(this.keys.encKey, plain, `${this.id}|${id}`);
|
||||
items.push({ g: this.id, id, deviceId: this.device, iv, ct });
|
||||
evs.push({ ...plain, id, seq: null, deviceId: this.device } as GroupEvent);
|
||||
}
|
||||
for (const it of items) await put('outbox', it);
|
||||
this.pending = [...this.pending, ...evs];
|
||||
this.recompute();
|
||||
void this.sync();
|
||||
}
|
||||
|
||||
/** Encrypt a photo blob and queue it for upload. Returns its id. */
|
||||
async addBlob(data: ArrayBuffer): Promise<string> {
|
||||
const id = randomId(18);
|
||||
const enc = await encryptBytes(this.keys.encKey, data, `${this.id}|${id}`);
|
||||
await put('blobs', { g: this.id, id, data: enc, uploaded: false } satisfies StoredBlob);
|
||||
return id;
|
||||
}
|
||||
|
||||
private blobUrls = new Map<string, Promise<string>>();
|
||||
|
||||
/** Object URL for a photo blob (from the local cache or the server). */
|
||||
blobUrl(blobId: string, type = 'image/webp'): Promise<string> {
|
||||
let p = this.blobUrls.get(blobId);
|
||||
if (!p) {
|
||||
p = (async () => {
|
||||
let rec = await get<StoredBlob>('blobs', [this.id, blobId]);
|
||||
if (!rec) {
|
||||
const data = await api.getBlob(this.id, this.keys.authToken, blobId);
|
||||
rec = { g: this.id, id: blobId, data, uploaded: true };
|
||||
await put('blobs', rec);
|
||||
}
|
||||
const plain = await decryptBytes(this.keys.encKey, rec.data, `${this.id}|${blobId}`);
|
||||
return URL.createObjectURL(new Blob([plain], { type }));
|
||||
})();
|
||||
p.catch(() => this.blobUrls.delete(blobId));
|
||||
this.blobUrls.set(blobId, p);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/** Upload outbox, then pull new events. Coalesces concurrent calls. */
|
||||
sync(): Promise<void> {
|
||||
if (this.syncing) {
|
||||
this.resync = true;
|
||||
return this.syncing;
|
||||
}
|
||||
this.syncing = (async () => {
|
||||
try {
|
||||
do {
|
||||
this.resync = false;
|
||||
await this.flush();
|
||||
await this.pull();
|
||||
} while (this.resync);
|
||||
this.status = 'online';
|
||||
await this.generateRecurring();
|
||||
} catch (e) {
|
||||
this.handleError(e);
|
||||
} finally {
|
||||
this.syncing = null;
|
||||
}
|
||||
})();
|
||||
return this.syncing;
|
||||
}
|
||||
|
||||
private handleError(e: unknown) {
|
||||
if (e instanceof ApiError && e.status === 404) {
|
||||
this.status = 'gone';
|
||||
void updateGroup(this.id, { gone: true });
|
||||
this.close();
|
||||
return;
|
||||
}
|
||||
if (this.abort.signal.aborted) return;
|
||||
this.status = isOffline(e) ? 'offline' : 'error';
|
||||
if (!(e instanceof ApiError)) console.warn('sync failed', e);
|
||||
clearTimeout(this.retryTimer);
|
||||
this.retryTimer = setTimeout(() => void this.sync(), 15_000);
|
||||
}
|
||||
|
||||
private async flush() {
|
||||
// Photos first, so no event ever references a blob the server lacks.
|
||||
const blobs = (await getAll<StoredBlob>('blobs')).filter((b) => b.g === this.id && !b.uploaded);
|
||||
for (const b of blobs) {
|
||||
await api.putBlob(this.id, this.keys.authToken, b.id, b.data);
|
||||
await put('blobs', { ...b, uploaded: true });
|
||||
}
|
||||
const out = await outboxFor(this.id);
|
||||
for (let i = 0; i < out.length; i += 100) {
|
||||
const chunk = out.slice(i, i + 100);
|
||||
await api.append(this.id, this.keys.authToken, chunk.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct })));
|
||||
// The pull that follows stores them with their seqs.
|
||||
for (const it of chunk) await del('outbox', it.n!);
|
||||
}
|
||||
}
|
||||
|
||||
private async pull() {
|
||||
for (;;) {
|
||||
const { events, latest } = await api.events(this.id, this.keys.authToken, this.local.lastSeq);
|
||||
if (latest < this.local.lastSeq) this.rollback = true;
|
||||
if (events.length === 0) break;
|
||||
const stored = events.map((e) => ({ ...e, g: this.id }));
|
||||
await putEvents(stored);
|
||||
const dec = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e);
|
||||
const lastSeq = stored[stored.length - 1].seq;
|
||||
this.local = { ...this.local, lastSeq };
|
||||
await updateGroup(this.id, { lastSeq });
|
||||
const ids = new Set(dec.map((e) => e.id));
|
||||
this.synced = [...this.synced, ...dec];
|
||||
this.pending = this.pending.filter((e) => !ids.has(e.id));
|
||||
this.recompute();
|
||||
if (lastSeq >= latest) break;
|
||||
}
|
||||
}
|
||||
|
||||
/** Create due recurring occurrences, once per open, after a full sync. */
|
||||
private async generateRecurring() {
|
||||
if (this.generatedRecurring) return;
|
||||
this.generatedRecurring = true;
|
||||
await this.createDueOccurrences();
|
||||
}
|
||||
|
||||
/** Emit any recurring occurrences that are due but missing. */
|
||||
async createDueOccurrences() {
|
||||
const due = dueOccurrences(this.state, today());
|
||||
if (due.length) await this.emit(...due.map((e) => ({ type: 'expense.created' as const, data: e })));
|
||||
}
|
||||
|
||||
/** Keep an SSE stream open; reconnect with backoff. */
|
||||
private async stream() {
|
||||
let delay = 1000;
|
||||
while (!this.abort.signal.aborted) {
|
||||
try {
|
||||
await listen(this.id, this.keys.authToken, this.abort.signal, (seq) => {
|
||||
delay = 1000;
|
||||
if (seq !== this.local.lastSeq) void this.sync();
|
||||
});
|
||||
} catch (e) {
|
||||
if (this.abort.signal.aborted) return;
|
||||
if (e instanceof ApiError && e.status === 404) return this.handleError(e);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
delay = Math.min(delay * 2, 60_000);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every event in log order, as stored (for backups). */
|
||||
async rawEvents(): Promise<StoredEvent[]> {
|
||||
return (await getAll<StoredEvent>('events', groupRange(this.id))).sort((a, b) => a.seq - b.seq);
|
||||
}
|
||||
}
|
||||
|
||||
let current: GroupSession | null = null;
|
||||
|
||||
/** The session for a group id, opening it (and closing any other). */
|
||||
export async function openSession(id: string): Promise<GroupSession | null> {
|
||||
if (current?.id === id) return current;
|
||||
current?.close();
|
||||
current = null;
|
||||
const local = await get<LocalGroup>('groups', id);
|
||||
if (!local) return null;
|
||||
await updateGroup(id, { lastOpened: Date.now() });
|
||||
const s = new GroupSession(local);
|
||||
current = s;
|
||||
await s.open();
|
||||
return s;
|
||||
}
|
||||
|
||||
export function closeSession(id: string) {
|
||||
if (current?.id === id) {
|
||||
current.close();
|
||||
current = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Save a group (from a link) on this device. */
|
||||
export async function addGroup(id: string, secret: string, extra: Partial<LocalGroup> = {}): Promise<void> {
|
||||
const existing = await get<LocalGroup>('groups', id);
|
||||
if (existing) {
|
||||
if (existing.secret !== secret) await updateGroup(id, { secret, gone: false });
|
||||
return;
|
||||
}
|
||||
await put('groups', {
|
||||
id, secret, name: '', icon: '', baseCurrency: 'EUR', me: null, myBalance: null,
|
||||
lastSeq: 0, lastOpened: Date.now(), push: false, notifiedSeq: 0, ...extra,
|
||||
} satisfies LocalGroup);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue