diff --git a/SPEC.md b/SPEC.md new file mode 100644 index 0000000..a331aad --- /dev/null +++ b/SPEC.md @@ -0,0 +1,531 @@ +# OweMe — Specification + +A mobile-first, end-to-end encrypted group expense splitter (a Settle Up +clone) that runs in any browser, on phones and desktops alike. + +Status: **draft v1** · Last updated: 2026-10-09 + +--- + +## 1. Goals and non-goals + +### Goals + +- Track shared expenses in groups and show **who should pay whom**. +- **End-to-end encrypted**: the server stores only ciphertext and never sees + group names, members, amounts, notes or photos. +- **All calculations happen client-side** (splits, conversions, balances, + settle-up, statistics). +- Works great on a phone, equally well on desktop, installable as a **PWA**, + usable **offline**. +- **Multiple currencies** with exchange rates prefilled from daily reference + rates. +- Czech and English UI; dark and light "money green" theme. +- Trivial self-hosting on a VPS via **podman compose**. + +### Non-goals (v1) + +- User accounts, email, passwords, or recovery of lost group links. +- Per-member permissions (everyone in a group can edit everything; the event + log makes every change reversible). +- Native mobile apps. +- Real payments / bank integration. + +--- + +## 2. Core concepts + +| Term | Meaning | +|---|---| +| **Group** | A shared ledger. Identified by a random ID; unlocked by a secret key carried in the link. | +| **Member** | A named person in a group. Not an account — just a name (plus optional colour/emoji). | +| **Expense** | Someone paid an amount; it is split between some members. | +| **Transfer** | A member paid another member directly (settling a debt). Same model as an expense with exactly one beneficiary. | +| **Event** | One immutable, encrypted change to a group (e.g. "expense created"). The group's state is the replay of its events. | +| **Base currency** | The group's currency for balances and settle-up. | + +--- + +## 3. Access model + +### 3.1 Group links + +``` +https:///g/# +``` + +- `groupId`: 128-bit random, base64url. Visible to the server. +- `groupSecret`: 256-bit random, base64url, in the **URL fragment**. Browsers + never send the fragment to the server (and it is not included in `Referer`). +- From `groupSecret` the client derives, via HKDF-SHA-256: + - `encKey` (info `"oweme/enc/v1"`): AES-256-GCM key for events and blobs. + - `authToken` (info `"oweme/auth/v1"`): bearer token sent to the server. + The server stores only `SHA-256(authToken)` and requires the token for + every read/write of that group. Knowing the `groupId` alone gives nothing. +- Sharing = sending the link (chat, QR code shown in the app). +- **Losing every copy of the link means the group is unrecoverable.** The UI + says so on creation and offers "copy link", "show QR" and "export backup". + +### 3.2 Groups remembered on the device + +- Every group opened on a device is saved locally (IndexedDB): `groupId`, + `groupSecret`, cached name, chosen identity, cached events, last synced + sequence number. +- The home screen lists these groups (name, my balance, last activity) so the + user can browse them without the link. +- "Remove from this device" deletes the local copy only; the group lives on. +- Note: keys are stored unencrypted in the browser's storage. Anyone with + access to the unlocked device/browser profile can open the groups. (A + device-level PIN lock is a possible later addition.) + +### 3.3 Identity ("who are you?") + +- On first opening a group on a device, the user picks themselves from the + member list (or adds themselves as a new member). +- The choice is **remembered per group per device**, and can be changed in + group settings ("I'm not Anna"). +- The identity is used for: "you owe / you are owed" wording, defaulting the + payer on new expenses, attributing events in the history ("Anna edited…"), + and push notification filtering. +- Identity is **not authentication** — anyone with the link can pick any name. + This is an accepted trade-off of the no-accounts model. + +--- + +## 4. Data model + +All amounts are **integers in minor units** of their currency (ISO 4217 +exponent: CZK/EUR/USD = 2, JPY = 0, …). Never floats. + +### 4.1 Event envelope + +Stored by the server: + +```jsonc +{ + "seq": 1042, // assigned by server, strictly increasing per group + "id": "uuid-v7", // assigned by client (idempotent retries) + "deviceId": "random", // so a device can skip notifying itself + "iv": "base64url", // 96-bit, random per event + "ct": "base64url", // AES-GCM(encKey, plaintext, aad = groupId|id) + "createdAt": "server timestamp" +} +``` + +Decrypted plaintext: + +```jsonc +{ + "v": 1, // schema version + "type": "expense.created", + "actor": "memberId|null", + "at": "2026-10-09T12:00:00Z", // client clock + "data": { ... } +} +``` + +### 4.2 Event types + +| Type | Data | +|---|---| +| `group.created` | name, baseCurrency, icon | +| `group.updated` | name / baseCurrency / icon / defaultCategory | +| `member.added` | memberId, name, colour | +| `member.updated` | memberId, name / colour | +| `member.archived` / `member.restored` | memberId (only allowed with zero balance; history kept) | +| `expense.created` / `expense.updated` | full expense object (see 4.3) | +| `expense.deleted` / `expense.restored` | expenseId | +| `comment.added` / `comment.deleted` | commentId, expenseId, text | +| `recurring.created` / `recurring.updated` / `recurring.deleted` | template (see 7.4) | +| `revert` | targetSeq — see 6.2 | + +Updates carry the full new object (not a diff), so the latest event per +entity fully defines it. Conflicts resolve **last-writer-wins by server +`seq`**. + +### 4.3 Expense object + +```jsonc +{ + "id": "uuid", + "kind": "expense", // or "transfer" + "title": "Dinner", + "category": "food", + "date": "2026-10-08", // when it happened (user-editable) + "currency": "EUR", + "amount": 12050, // 120.50 EUR + "rate": "25.214", // decimal string: 1 EUR = 25.214 base; "1" if same currency + "rateSource": "ecb:2026-10-08", // or "manual" + "payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount + "split": { + "mode": "equal", // equal | shares | exact | percent + "entries": [ + { "member": "m1", "value": 1 }, // equal: 1 = included + { "member": "m2", "value": 1 }, + { "member": "m3", "value": 0 } // excluded + ] + }, + "note": "optional text", + "photo": { "blobId": "…", "thumbBlobId": "…", "w": 1600, "h": 1200 } // or null +} +``` + +Split `value` meaning per mode: + +| Mode | value | Validation | +|---|---|---| +| `equal` | 1 included / 0 excluded | ≥ 1 included | +| `shares` | integer weight ≥ 0 (e.g. 2 = double share) | sum > 0 | +| `exact` | amount in minor units | sum == amount | +| `percent` | basis points (100 % = 10000) | sum == 10000 | + +Multiple payers are supported (`payers` list); the default UI shows a single +payer with an "add payer" option. + +--- + +## 5. Calculations (client-side, deterministic) + +All clients must compute **identical** results from the same events, so every +rounding rule is fixed and specified here, and covered by unit tests. + +### 5.1 Splitting with rounding + +1. Compute each member's exact (rational) share of `amount` from the split + weights. +2. Floor each share to a whole minor unit. +3. Distribute the leftover units one by one by **largest remainder**; ties + broken by member order in the group (order of `member.added`). + +Example: 100.00 CZK equally among 3 → 33.34 / 33.33 / 33.33. + +### 5.2 Currency conversion + +- Each expense stores the rate it was entered with. **Balances never change + retroactively** when market rates move. +- Conversion to base: `baseTotal = round_half_even(amount × rate)` adjusted + for the two currencies' exponents. Rates are parsed as exact decimals (no + binary floats; use bigint arithmetic). +- Per-member shares in base currency: split the already-rounded *original* + share vector, then convert it to base using the same largest-remainder + method so that the converted shares sum exactly to `baseTotal`. Payers are + converted the same way. + +### 5.3 Balances + +For each member: `balance = Σ paid (base) − Σ owed (base)` over all non-deleted +expenses and transfers. The sum of all balances is always exactly 0 +(asserted in tests). + +### 5.4 Settle-up suggestions + +Greedy: repeatedly match the largest debtor with the largest creditor and +transfer `min(|debt|, credit)`. Produces at most `n − 1` transfers, usually +the minimum in practice, and is easy to reason about. + +- Shown as "**Petr → Anna: 450 Kč**" cards. +- "Mark as paid" opens a prefilled transfer the user can adjust (partial + payments allowed) and confirm. +- Optional display of balances/suggestions in another currency using the + current rate (display only, clearly labelled). + +--- + +## 6. History and rewind + +### 6.1 History view + +- Group-wide activity feed from the event log: "Anna added *Dinner* · 120.50 + EUR", "Petr changed amount 450 → 540 Kč", "Jana deleted *Taxi*". +- Per-expense history: every version, with a diff of changed fields. + +### 6.2 Rewind + +- **Restore an expense**: undelete, or roll it back to a chosen earlier + version (emits `expense.updated` / `expense.restored` with the old content). +- **Rewind the whole group to a point in time**: emits a `revert { targetSeq }` + event. Replay treats the state as the state at `targetSeq`, and then applies + later events normally. Nothing is ever erased, so a rewind can itself be + undone (revert to the seq just before the revert). +- The log is append-only on the server; there is no destructive delete API + for events (only deleting the entire group, see 8.3). + +--- + +## 7. Features + +### 7.1 Groups + +- Create group: name, base currency (default by locale: CZK for Czech, EUR + otherwise), icon/emoji, initial members. +- Share: copy link, native share sheet, QR code. +- Settings: rename, base currency (change converts nothing retroactively — + existing expenses keep their rates; balances are re-expressed via a stored + rate for the switch, shown to the user before confirming), members, "who am + I", remove from device, export, delete group (see 8.3). + +### 7.2 Expenses + +- Fast add flow optimised for one hand: amount first (numeric keypad), then + title, payer (defaults to me), split (defaults to everyone equally). +- Currency picker with recent currencies first; the rate is prefilled from + the daily rate for the expense date and is editable. +- Split editor: equal / shares / exact / percent tabs; tap to exclude people; + live "remaining to assign" indicator for exact and percent modes. +- **One photo per expense** (receipt), see 9. +- Category, date, note. +- Comments thread on each expense. + +### 7.3 Categories + +Fixed v1 set with icons: food & drink, groceries, transport, accommodation, +entertainment, shopping, utilities, rent, travel, gifts, health, other. +Transfers have their own implicit category. + +### 7.4 Recurring expenses + +- A template (expense object + rule: weekly / monthly / yearly, interval, + start, optional end). +- There is no server-side worker (the server cannot read templates). When any + member's client opens the group and a due occurrence is missing, it creates + it. The occurrence's expense ID is derived deterministically + (`UUIDv5(templateId + occurrenceDate)`), so two clients doing it at once + produce the same ID and replay deduplicates it. +- Occurrences are normal expenses (editable/deletable individually). + +### 7.5 Statistics + +Client-side charts per group, filterable by date range: + +- Spending by category (bar chart). +- Spending per month (bar chart). +- Per member: paid vs. consumed. +- "My spending" view. + +### 7.6 Export / backup / import + +- **CSV export** of expenses (one row per expense, columns per member share) + and of current balances. +- **Encrypted backup**: full event log + photos as one file, encrypted with + the group key. Import restores to the same or a new server. +- **Import from Settle Up**, and from Splitwise as a bonus, from their CSV/Excel + exports. *Needs a sample export file to pin down the format.* + +### 7.7 Push notifications + +- Opt-in per group per device (Web Push, VAPID). +- Because the server cannot read events, the push it sends **contains no + content**, just `{ groupId }`. The service worker wakes, fetches new events, + decrypts them locally and shows "Anna added Dinner · 120.50 EUR". +- The server skips the device that created the event (`deviceId`). +- Notification options: all activity / only expenses involving me. +- iOS: works only when the app is installed to the home screen (iOS 16.4+); + the UI explains this. + +--- + +## 8. Server + +The server is deliberately simple: storage, sync, rates, push. + +### 8.1 API + +All group endpoints require `Authorization: Bearer `. + +| Method & path | Purpose | +|---|---| +| `POST /api/groups` | Create: `{ groupId, authTokenHash }`. Rate-limited per IP. | +| `GET /api/groups/:id/events?after=` | Fetch events after seq (paginated). | +| `POST /api/groups/:id/events` | Append a batch; idempotent by event `id`; returns assigned seqs. | +| `GET /api/groups/:id/stream` | Server-Sent Events: "new seq available" pings for live sync. | +| `PUT /api/groups/:id/blobs/:blobId` | Upload encrypted photo (size-capped). | +| `GET /api/groups/:id/blobs/:blobId` | Download encrypted photo. | +| `POST/DELETE /api/groups/:id/push` | Register/unregister a Web Push subscription. | +| `DELETE /api/groups/:id` | Delete group, events and blobs (requires typing the group name client-side as confirmation). | +| `GET /api/rates?date=YYYY-MM-DD` | Daily reference rates (no auth). | +| `GET /api/health` | Health check. | + +### 8.2 Exchange rates + +- The server fetches **ECB daily reference rates** (~30 currencies, via + Frankfurter or ECB XML directly) once a day and caches them in SQLite, + including history for back-dated expenses. +- Clients fetch from our server only, so third parties don't learn users' IPs + or currency usage. Clients cache rates offline. +- Currencies outside the ECB set can be used with a manually entered rate. +- Behind an interface so a paid intraday provider can be swapped in later. + +### 8.3 Storage and limits + +- SQLite (WAL) for groups, events, push subscriptions, rates. +- Blobs on disk: `data/blobs//`. +- Limits (configurable via env): photo blob ≤ 2 MB, event ≤ 64 KB, + per-group storage ≤ 200 MB, group creation rate limit. +- Inactive-group retention: none by default (configurable). + +--- + +## 9. Photos + +1. User picks/takes a photo (``). +2. Client decodes it, scales it to max 1600 px long edge, plus a 320 px + thumbnail, and re-encodes it as WebP (JPEG fallback). Re-encoding through a + canvas **strips EXIF, including GPS location**. +3. Each image is encrypted with `encKey` (fresh IV) and uploaded as a blob. +4. The expense references the blob IDs. Viewing downloads, decrypts and caches. +5. Deleting/replacing the photo leaves the old blob in place (history can + restore it); blobs are garbage-collected only when the group is deleted. + +--- + +## 10. Client / UX + +### 10.1 Platform + +- Single-page PWA: installable, offline-capable (service worker caches the + app shell; IndexedDB caches events, rates and thumbnails). +- Offline edits are queued and synced when the device comes back online. +- Responsive: single column on phones; on desktop, a two-pane layout (group + list / expenses on the left, detail/balances on the right). +- Minimum targets: last 2 versions of Safari iOS, Chrome Android, Chrome, + Firefox, Safari, Edge. + +### 10.2 Screens + +1. **Home**: groups saved on this device, each showing my balance. "New + group", "Open link/scan QR". +2. **Group**: tabs: Expenses · Balances (settle up) · Stats · Activity. + Floating "+" button for a new expense. +3. **Expense editor** (sheet on mobile, dialog on desktop). +4. **Expense detail**: photo, split breakdown, comments, history. +5. **Group settings**. +6. **App settings**: language, theme, notifications. + +### 10.3 Language + +- English (default) and Czech. +- Auto-detect: if the browser's preferred language (`navigator.languages`) + is Czech (`cs`, `cs-CZ`, …) use Czech; **anything else uses English**. + The user can override this in settings (remembered on the device). +- Numbers, currencies and dates are formatted with `Intl` for the active + locale (`1 234,50 Kč` vs `CZK 1,234.50`); Czech plural forms via + `Intl.PluralRules`. + +### 10.4 Theme + +Dark and light, following the system setting by default with a manual +override. Starting palette (to be validated for WCAG AA contrast): + +| Token | Dark | Light | +|---|---|---| +| background | `#0B2E22` | `#F2F7F4` | +| surface | `#123D2E` | `#FFFFFF` | +| surface-raised | `#1A4D3A` | `#E4EFE9` | +| text | `#E8F3EC` | `#0B2E22` | +| text-muted | `#9FBFAE` | `#4A6B5B` | +| accent / you are owed | `#3DDC97` | `#16865A` | +| you owe | `#F2A65A` | `#B5541C` | +| highlight (sparingly) | `#D4AF37` | `#9A7B12` | + +Positive/negative amounts also differ by sign and icon, never by colour alone. + +--- + +## 11. Security & threat model + +| Threat | Outcome | +|---|---| +| Server/database compromise or leak | Attacker sees group IDs, event counts, sizes, timestamps, IPs. **No content.** | +| Malicious server operator | Could withhold, reorder or delete events (clients detect seq rollback against their local cache and warn), or **serve modified JavaScript** — an inherent limit of web-delivered E2E. Mitigation: self-hosting, strict CSP, SRI on all assets, reproducible builds. | +| Leaked group link | Full read/write access to that group. No revocation in v1 (future: key rotation = re-encrypt into a new group). | +| Vandalising group member | Everything is reversible via history/rewind. | +| Lost link on all devices | Data unrecoverable (by design). Mitigated by backups and remembered groups. | +| Device access | Remembered groups are readable from an unlocked browser profile. | + +Hardening: + +- Strict CSP (`default-src 'self'`), no third-party scripts, fonts or + analytics; self-hosted assets only. +- `Referrer-Policy: no-referrer`, HSTS, `X-Content-Type-Options: nosniff`. +- The secret never appears in a query string, path, log or error report. + Server logs exclude `Authorization` headers. +- WebCrypto only (AES-256-GCM, HKDF-SHA-256); no custom crypto. + +--- + +## 12. Tech stack + +| Layer | Choice | Why | +|---|---|---| +| Frontend | **SvelteKit** (static adapter, SPA) + TypeScript | Small bundles (fast on phones), simple reactivity | +| PWA | Vite PWA plugin (Workbox) | Service worker, offline cache, push handling | +| Local storage | IndexedDB (via `idb`) | Groups, events, blobs cache | +| Charts | Lightweight library (e.g. Chart.js or LayerCake) | Stats tab | +| i18n | `svelte-i18n` or a small typed dictionary | EN/CS | +| Backend | **Bun + Hono** + TypeScript | Tiny, fast, shares types with the frontend | +| DB | SQLite (`bun:sqlite`) | Zero-ops, single file | +| Tests | Vitest (money math, replay, crypto), Playwright (E2E on mobile + desktop viewports) | Rounding and replay must be bulletproof | +| Proxy/TLS | **Caddy** | Automatic HTTPS (required for WebCrypto, service workers and push) | + +Repo layout (monorepo): + +``` +apps/web SvelteKit client +apps/server Bun + Hono API +packages/core shared: types, event schema, money math, replay, crypto +deploy/ compose.yaml, Caddyfile, .env.example +``` + +--- + +## 13. Deployment (VPS, podman compose) + +`deploy/compose.yaml` runs two services: + +- `app`: the Bun server, which also serves the built static client. Listens + on the internal network only. +- `caddy`: TLS termination + reverse proxy, the only service publishing + ports (80/443). + +Volumes: `oweme-data` (SQLite + blobs), `caddy-data` (certificates). + +Deploy steps (documented in `deploy/README.md`): + +1. Point a DNS A/AAAA record at the VPS. +2. `cp deploy/.env.example deploy/.env && chmod 600 deploy/.env`, then set + `DOMAIN`. Generate VAPID keys with the provided script, which writes them + into `.env` without printing them. +3. Rootless Podman cannot bind ports < 1024 by default: either set + `net.ipv4.ip_unprivileged_port_start=80` via sysctl, or publish 8080/8443 and + redirect with the firewall — both documented. +4. `podman compose up -d`. Updates: `git pull && podman compose up -d --build`. +5. Backups: copy the data volume. All contents are already encrypted, so + backups can be stored anywhere. + +Development (on the dev box): servers bind `127.0.0.1` only; preview over an +SSH tunnel. Ports and commands go in `AGENTS.md`. + +--- + +## 14. Milestones + +1. **Core**: crypto, event log, sync, groups (link + QR), members, identity, + expenses with all split modes in a single currency, balances, settle-up, + transfers, remembered groups, EN/CS, dark/light theme, PWA + offline, + podman compose deploy. +2. **Money & media**: multiple currencies + rates service, photos. +3. **History**: activity feed, per-expense history, restore, group rewind. +4. **Extras**: comments, categories, statistics, recurring expenses, CSV + export, encrypted backup/restore. +5. **Notifications & import**: Web Push, Settle Up / Splitwise import. + +--- + +## 15. Open questions + +- **Settle Up import:** need a sample export file to define the mapping. +- **Domain name** for the VPS deployment. +- **Storage limits:** are 2 MB per photo and 200 MB per group right? +- **Base currency change:** convert existing balances via a rate at switch + time (current proposal), or forbid changing the base currency once + expenses exist?