Compare commits

..

9 commits

Author SHA1 Message Date
41b3487a5a Merge pull request 'Implement OweMe v1' (#2) from feat/v1-app into main
Reviewed-on: #2
2026-10-09 22:28:30 +02:00
8c4e37ce4b Add podman compose deployment, dev script and docs
Containerfile + compose (app + Caddy with automatic HTTPS), env-driven
domain/limits/ports, VAPID key generation that never prints the key.
SPEC updated to match the implementation (Node stdlib server, Svelte SPA,
revert by event id, backup contents, push options).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:59:17 +00:00
a78d855886 Add Playwright end-to-end tests
Two devices (EN + CS) sharing a group through sync, photos, rates, rewind,
offline and settle-up; plus push delivery to the service worker via CDP.
Can target a running deployment with E2E_BASE_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:59:16 +00:00
8fbbb4933e 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
2026-10-09 19:59:16 +00:00
f67add3660 Server: count only newly stored events toward the group quota
Re-uploading existing events (retries, backup restore) is idempotent and
must not eat into MAX_GROUP_BYTES.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:59:16 +00:00
8dd25b93b0 Add server: encrypted event log API, blobs, SSE, ECB rates, Web Push
Node 24 standard library only (node:http, node:sqlite, node:crypto).
Push uses VAPID + RFC 8291 encryption with an allowlist of push services.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:33:28 +00:00
c2043b86bc Add core package: money math, event replay, settle-up, recurring, stats, CSV
Deterministic integer/BigInt arithmetic so every client computes identical
balances; replay validates events and supports rewind via snapshots.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:30:09 +00:00
747e49f46a Spec: drop import, lock base currency, env-configurable domain and limits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:19:21 +00:00
2e3604f70c Add v1 product and technical specification
Covers access model (key-in-fragment links), encrypted event log,
deterministic money math, currencies, photos, history/rewind,
i18n, theming, server API, threat model and podman compose deploy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF
2026-10-09 19:13:35 +00:00
88 changed files with 8966 additions and 1 deletions

8
.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
node_modules/
dist/
data/
.env
deploy/.env
test-results/
playwright-report/
*.log

59
AGENTS.md Normal file
View file

@ -0,0 +1,59 @@
# AGENTS.md — OweMe
End-to-end encrypted group expense splitter (a Settle Up clone). Read
`SPEC.md` first; it is the source of truth for behaviour and is kept current.
## Layout
- `packages/core/` — pure TypeScript shared by client and service worker:
event schema, validation, money math, replay/rewind, settle-up, recurring,
stats, CSV. **No I/O, no floats for money.**
- `apps/server/` — Node 24, **standard library only** (`node:http`,
`node:sqlite`, `node:crypto`), run directly as TypeScript (type stripping:
erasable syntax only, `.ts` import extensions). No npm dependencies; keep it
that way unless there's a strong reason.
- `apps/web/` — Svelte 5 SPA + service worker (`src/sw.ts`, built separately
by `vite.sw.config.ts` as a classic script).
- `deploy/` — Containerfile, compose.yaml, Caddyfile, `.env.example`, deploy docs.
- `e2e/` — Playwright tests against the production build.
## Run
Node lives at `~/.local/node/bin` on the dev box (not on PATH by default).
```sh
npm ci
npm run dev # API 127.0.0.1:8481 + Vite 127.0.0.1:8480
```
Preview from your machine: `ssh -p 14922 -L 8480:localhost:8480 <dev box>`,
then http://localhost:8480.
## Test
```sh
npm test # core (vitest) + server (node:test)
npm run check # tsc + svelte-check (must be 0 errors, 0 warnings)
npm run build && npm run test:e2e
```
E2E uses the Playwright browsers cached in `~/.cache/ms-playwright`
(`@playwright/test` is pinned to 1.63.0 to match them). `e2e/push.spec.ts`
needs full Chromium (`channel: 'chromium'`): the headless shell denies
notifications.
## Invariants — do not break
1. **The server never sees plaintext or keys.** The group secret exists only
in the URL fragment, IndexedDB and backup files. Never send it in a path,
query string, header or log line. The server stores `SHA-256(authToken)`.
2. **Every client computes identical balances.** Money is integer minor units;
rates are decimal strings; rounding is largest-remainder with ties to
member order, conversion is round-half-even (BigInt). Any change to money
math needs a test in `packages/core/test/`.
3. **The event log is append-only.** Undo is a new event (`revert`,
`expense.restored`, …), never a deletion. Replay must ignore invalid
events (`validateExpense`), not crash.
4. **New event types** go in `types.ts` (`EventBody`), `replay.ts` (with
validation), the activity text in `Activity.svelte` and both locale files.
5. **i18n:** every string in `locales/en.ts` and `locales/cs.ts` (the type
enforces it). English is the default; Czech only if the browser prefers it.
6. **Push endpoints** are restricted to the allowlist in `push.ts` (no SSRF).
Push payloads carry only the group id.
7. Strict CSP: no inline scripts, no third-party origins.
8. Containers: rootless Podman; for local testing publish to `127.0.0.1` only
(`BIND_ADDR=127.0.0.1` in `deploy/.env`).

View file

@ -1,3 +1,24 @@
# OweMe
End-to-end encrypted, mobile-first group expense splitter. See [SPEC.md](SPEC.md).
Split group expenses with friends: a mobile-first, **end-to-end encrypted**
Settle Up clone that runs in any browser and installs as an app.
- Groups you open via a link; the key travels in the `#fragment` and never reaches the server
- Equal, shares, exact-amount and percent splits; several payers; any member can be left out
- Multiple currencies with ECB daily rates (stored per expense, editable)
- One receipt photo per expense (resized, location data stripped, encrypted)
- Who-pays-whom settle-up suggestions, with "record payment"
- Full history: restore any version, or rewind the whole group (and undo that)
- Comments, categories, statistics, recurring expenses, CSV export, backup files
- Push notifications that the server can't read
- Works offline; English and Czech; dark and light money-green theme
See [SPEC.md](SPEC.md) for the design, [deploy/README.md](deploy/README.md)
to run it on a VPS with `podman compose`, and [AGENTS.md](AGENTS.md) for
development.
```sh
npm ci
npm run dev # http://127.0.0.1:8480
npm test
```

563
SPEC.md Normal file
View file

@ -0,0 +1,563 @@
# 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: **v1, implemented** · 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.
- Importing from other apps (Settle Up, Splitwise, …).
---
## 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://<domain>/g/<groupId>#<groupSecret>
```
- `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` | targetId (an event id) — 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 { targetId }`
event naming an earlier event. Replay replaces the state with a snapshot
taken right after that event, then applies later events normally. Nothing
is ever erased, so a rewind can itself be undone (revert to the event just
before the revert). Event ids rather than seqs are used so a restored
backup, which gets new seqs, keeps working.
- 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, members, "who am I", remove from device, export, delete
group (see 8.3).
- **Base currency is locked once the group has any expense or transfer.** It
can be changed freely while the group is empty; afterwards the setting is
read-only with a short explanation. Clients enforce this during replay too:
a `group.updated` that changes `baseCurrency` after the first expense event
is ignored.
### 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
(`rec-<templateId>-<occurrenceDate>`), so two clients doing it at once
produce the same ID; `expense.created` is first-wins on replay, so the
duplicate is ignored. Deleted occurrences are not recreated.
- 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
- **CSV export** of expenses (one row per expense, columns per member share)
and of current balances.
- **Backup file** (JSON): the encrypted event log and photos exactly as the
server stores them, **plus the group secret**, so a group can be restored
even if every link is lost. The file is therefore as sensitive as the link,
and the UI says so. Restoring creates the group on the server (or finds it
already there) and re-uploads everything; uploads are idempotent by id, so
an interrupted restore can simply be run again.
### 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 `{ g: groupId }` (itself encrypted to the browser per
RFC 8291). The service worker wakes, fetches new events, decrypts them
locally and shows "Anna: Dinner · 120.50 EUR". It stays quiet if that
group is open and focused.
- The server skips the device that created the event (`deviceId`).
- On/off per group only. An "only expenses involving me" option was dropped:
browsers require every push to show a notification, so the worker can't
silently discard irrelevant ones.
- The server only delivers to known push services (FCM, Mozilla, Apple,
Windows), so a registered endpoint can't make it call arbitrary hosts.
- 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 <authToken>`.
| Method & path | Purpose |
|---|---|
| `POST /api/groups` | Create: `{ groupId, authTokenHash }`. Rate-limited per IP. |
| `GET /api/groups/:id/events?after=<seq>` | 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/config` | Public settings: VAPID public key, size limits (no auth). |
| `GET /api/health` | Health check. |
Unknown groups and wrong tokens both answer `404`, so the API doesn't reveal
which group ids exist.
### 8.2 Exchange rates
- The server fetches **ECB daily reference rates** (~30 currencies, from the
ECB's own XML feed) every 6 hours and caches them in SQLite. The first run
loads the full history (back to 1999) for back-dated expenses; later runs
fetch the last 90 days.
- 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/<groupId>/<blobId>`.
- Limits (env variables, see 13): photo blob ≤ 2 MB (`MAX_PHOTO_BYTES`),
event ≤ 64 KB (`MAX_EVENT_BYTES`), per-group storage ≤ 200 MB
(`MAX_GROUP_BYTES`), group creation rate limit (`GROUP_CREATE_PER_HOUR`).
The server enforces the photo limit per uploaded blob; the client keeps a
photo and its thumbnail together under it.
- Inactive-group retention: none by default (configurable).
---
## 9. Photos
1. User picks/takes a photo (`<input type="file" accept="image/*" capture>`).
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 | **Svelte 5 + Vite** SPA, TypeScript, a ~60-line history router | Small bundle (~65 KB gzipped), simple reactivity; SvelteKit wasn't needed for a static SPA |
| PWA | Hand-written service worker, built as a classic script by a second Vite step | Offline shell, push handling; no Workbox dependency |
| Local storage | IndexedDB (small hand-written wrapper) | Groups, events, outbox, blobs cache; shared with the service worker |
| Charts | Hand-built HTML/CSS bars | Stats tab; no chart library |
| i18n | Small typed dictionary (`locales/en.ts`, `cs.ts`) | EN/CS; the type makes missing translations a compile error |
| Backend | **Node 24, standard library only** (`node:http`, `node:sqlite`, `node:crypto`), run as TypeScript via type stripping | No npm dependencies on the server; Node was already on the dev box (Bun would have meant another runtime) |
| DB | SQLite (`node: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 Svelte client + service worker
apps/server Node API (no dependencies)
packages/core shared: types, event schema, money math, replay, settle-up, recurring, stats, CSV
deploy/ Containerfile, compose.yaml, Caddyfile, .env.example, README
e2e/ Playwright tests
```
---
## 13. Deployment (VPS, podman compose)
`deploy/compose.yaml` runs two services:
- `app`: the Node 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` (e.g. `oweme.example.com`); Caddy uses it for the site address
and certificate. (The app itself needs no domain: share links use the
page's own origin and the CSP is `'self'`.) Generate VAPID keys with
`gen-vapid.ts` inside the built image, 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. `cd deploy && 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.
Environment variables (`deploy/.env`, read by `compose.yaml`):
| Variable | Required | Default | Purpose |
|---|---|---|---|
| `DOMAIN` | yes | — | Public hostname; Caddy site + TLS, share links |
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Web Push (generated by script); empty = notifications off |
| `VAPID_SUBJECT` | for push | — | `mailto:` contact for push services |
| `MAX_PHOTO_BYTES` | no | `2097152` | Per-photo upload cap |
| `MAX_EVENT_BYTES` | no | `65536` | Per-event cap |
| `MAX_GROUP_BYTES` | no | `209715200` | Per-group storage cap |
| `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per IP per hour |
| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on |
| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy |
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
All five milestones below shipped together in the first implementation
(2026-10-09):
1. **Core**: crypto, event log, sync, groups (link + QR), members, identity,
expenses with all split modes, 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, backup/restore.
5. **Notifications**: Web Push.

367
apps/server/src/app.ts Normal file
View file

@ -0,0 +1,367 @@
// HTTP API and static file server (SPEC.md §8.1). Plain node:http with a
// small hand-written router; no dependencies.
import { createHash, timingSafeEqual } from 'node:crypto';
import { createReadStream, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { extname, join, normalize, sep } from 'node:path';
import type { Config } from './config.ts';
import type { Store } from './db.ts';
import { isAllowedEndpoint, sendPush, type Vapid } from './push.ts';
const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url
const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/;
const BLOB_ID_RE = /^[A-Za-z0-9_-]{16,64}$/;
const DEVICE_RE = /^[A-Za-z0-9_-]{8,64}$/;
const B64U_RE = /^[A-Za-z0-9_-]+$/;
const HEX64_RE = /^[0-9a-f]{64}$/;
class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
const SECURITY_HEADERS: Record<string, string> = {
'Content-Security-Policy': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' blob: data:",
"connect-src 'self'",
"worker-src 'self'",
"manifest-src 'self'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; '),
'Referrer-Policy': 'no-referrer',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Permissions-Policy': 'camera=(self), geolocation=(), microphone=()',
'Cross-Origin-Opener-Policy': 'same-origin',
};
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json',
'.webmanifest': 'application/manifest+json',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
function send(res: ServerResponse, status: number, body: unknown, headers: Record<string, string> = {}): void {
const json = JSON.stringify(body);
res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers });
res.end(json);
}
async function readBody(req: IncomingMessage, limit: number): Promise<Buffer> {
const declared = Number(req.headers['content-length'] ?? 0);
if (declared > limit) throw new HttpError(413, 'too large');
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req) {
size += (chunk as Buffer).length;
if (size > limit) throw new HttpError(413, 'too large');
chunks.push(chunk as Buffer);
}
return Buffer.concat(chunks);
}
async function readJson(req: IncomingMessage, limit: number): Promise<any> {
if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new HttpError(415, 'expected JSON');
try {
return JSON.parse((await readBody(req, limit)).toString('utf8'));
} catch (e) {
if (e instanceof HttpError) throw e;
throw new HttpError(400, 'bad JSON');
}
}
const sha256hex = (s: string) => createHash('sha256').update(s).digest('hex');
/** Fixed-window rate limiter keyed by client IP. */
class RateLimiter {
private hits = new Map<string, { n: number; reset: number }>();
private readonly max: number;
private readonly windowMs: number;
constructor(max: number, windowMs: number) {
this.max = max;
this.windowMs = windowMs;
}
allow(key: string): boolean {
const now = Date.now();
if (this.hits.size > 10_000) for (const [k, v] of this.hits) if (v.reset < now) this.hits.delete(k);
const h = this.hits.get(key);
if (!h || h.reset < now) {
this.hits.set(key, { n: 1, reset: now + this.windowMs });
return true;
}
h.n += 1;
return h.n <= this.max;
}
}
export function createApp(cfg: Config, store: Store) {
const streams = new Map<string, Set<ServerResponse>>();
const createLimiter = new RateLimiter(cfg.groupCreatePerHour, 3600_000);
const pushLimiter = new RateLimiter(60, 3600_000);
const vapid: Vapid | null =
cfg.vapidPublicKey && cfg.vapidPrivateKey && cfg.vapidSubject
? { publicKey: cfg.vapidPublicKey, privateKey: cfg.vapidPrivateKey, subject: cfg.vapidSubject }
: null;
const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g);
function clientIp(req: IncomingMessage): string {
if (cfg.trustProxy) {
// Caddy appends the real client address as the last entry.
const xff = String(req.headers['x-forwarded-for'] ?? '').split(',').map((s) => s.trim()).filter(Boolean);
if (xff.length) return xff[xff.length - 1];
}
return req.socket.remoteAddress ?? '?';
}
/** Check the bearer token for a group. Unknown group and wrong token both
* give 404, so the API doesn't reveal which group ids exist. */
function authorize(req: IncomingMessage, groupId: string) {
if (!ID_RE.test(groupId)) throw new HttpError(404, 'not found');
const g = store.getGroup(groupId);
const m = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(String(req.headers.authorization ?? ''));
const given = Buffer.from(sha256hex(m?.[1] ?? ''), 'hex');
const expected = Buffer.from(g?.authHash ?? '0'.repeat(64), 'hex');
if (!g || !m || !timingSafeEqual(given, expected)) throw new HttpError(404, 'not found');
return g;
}
function notify(groupId: string, seq: number, deviceId: string): void {
for (const res of streams.get(groupId) ?? []) res.write(`data: ${seq}\n\n`);
if (!vapid) return;
for (const sub of store.pushSubs(groupId)) {
if (sub.deviceId === deviceId) continue;
void sendPush(sub, { g: groupId }, vapid).then((r) => {
if (r === 'gone') store.deletePush(groupId, sub.endpoint);
});
}
}
// ---- route handlers --------------------------------------------------
async function createGroup(req: IncomingMessage, res: ServerResponse) {
if (!createLimiter.allow(clientIp(req))) throw new HttpError(429, 'too many groups created, try later');
const body = await readJson(req, 1024);
if (!ID_RE.test(body?.id) || !HEX64_RE.test(body?.authHash)) throw new HttpError(400, 'bad group');
if (!store.createGroup(body.id, body.authHash)) throw new HttpError(409, 'exists');
send(res, 201, { id: body.id });
}
function getEvents(req: IncomingMessage, res: ServerResponse, groupId: string, url: URL) {
authorize(req, groupId);
const after = Math.max(0, Number(url.searchParams.get('after') ?? 0) || 0);
const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get('limit') ?? 500) || 500));
send(res, 200, { events: store.eventsAfter(groupId, after, limit), latest: store.latestSeq(groupId) });
}
async function postEvents(req: IncomingMessage, res: ServerResponse, groupId: string) {
const g = authorize(req, groupId);
const body = await readJson(req, 200 * (cfg.maxEventBytes * 1.4 + 512));
const events = body?.events;
if (!Array.isArray(events) || events.length === 0 || events.length > 200) throw new HttpError(400, 'events must be 1..200');
let incoming = 0;
for (const e of events) {
if (!EVENT_ID_RE.test(e?.id) || !DEVICE_RE.test(e?.deviceId) || !B64U_RE.test(e?.iv) || !B64U_RE.test(e?.ct) || e.iv.length !== 16)
throw new HttpError(400, 'bad event');
const size = Math.floor((e.ct.length * 3) / 4);
if (size > cfg.maxEventBytes) throw new HttpError(413, 'event too large');
incoming += size;
}
if (g.bytes + incoming > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full');
const seqs = store.tx(() => {
let next = store.latestSeq(groupId);
let bytes = 0;
const out: number[] = [];
for (const e of events) {
const existing = store.seqOf(groupId, e.id);
if (existing !== undefined) {
out.push(existing);
continue;
}
next += 1;
store.insertEvent(groupId, next, { id: e.id, deviceId: e.deviceId, iv: e.iv, ct: e.ct });
bytes += Math.floor((e.ct.length * 3) / 4);
out.push(next);
}
store.addBytes(groupId, bytes);
return out;
});
send(res, 200, { seqs });
notify(groupId, Math.max(...seqs), events[0].deviceId);
}
function stream(req: IncomingMessage, res: ServerResponse, groupId: string) {
authorize(req, groupId);
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-store',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write(`data: ${store.latestSeq(groupId)}\n\n`);
let set = streams.get(groupId);
if (!set) streams.set(groupId, (set = new Set()));
set.add(res);
const ping = setInterval(() => res.write(': ping\n\n'), 25_000);
req.on('close', () => {
clearInterval(ping);
set!.delete(res);
if (set!.size === 0) streams.delete(groupId);
});
}
async function putBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) {
const g = authorize(req, groupId);
if (!BLOB_ID_RE.test(blobId)) throw new HttpError(400, 'bad blob id');
if (store.hasBlob(groupId, blobId)) return send(res, 200, { ok: true }); // immutable; retries are fine
const data = await readBody(req, cfg.maxPhotoBytes);
if (data.length === 0) throw new HttpError(400, 'empty');
if (g.bytes + data.length > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full');
mkdirSync(blobDir(groupId), { recursive: true });
writeFileSync(join(blobDir(groupId), blobId), data, { flag: 'wx' });
store.tx(() => {
store.insertBlob(groupId, blobId, data.length);
store.addBytes(groupId, data.length);
});
send(res, 201, { ok: true });
}
function getBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) {
authorize(req, groupId);
if (!BLOB_ID_RE.test(blobId) || !store.hasBlob(groupId, blobId)) throw new HttpError(404, 'not found');
const path = join(blobDir(groupId), blobId);
res.writeHead(200, {
'Content-Type': 'application/octet-stream',
'Content-Length': String(statSync(path).size),
'Cache-Control': 'private, max-age=31536000, immutable',
});
createReadStream(path).pipe(res);
}
async function postPush(req: IncomingMessage, res: ServerResponse, groupId: string) {
authorize(req, groupId);
if (!vapid) throw new HttpError(501, 'push not configured');
if (!pushLimiter.allow(clientIp(req))) throw new HttpError(429, 'slow down');
const b = await readJson(req, 4096);
if (!isAllowedEndpoint(b?.endpoint) || b.endpoint.length > 1000) throw new HttpError(400, 'unsupported push service');
if (!B64U_RE.test(b?.keys?.p256dh) || !B64U_RE.test(b?.keys?.auth) || !DEVICE_RE.test(b?.deviceId))
throw new HttpError(400, 'bad subscription');
store.upsertPush(groupId, { endpoint: b.endpoint, p256dh: b.keys.p256dh, auth: b.keys.auth, deviceId: b.deviceId });
send(res, 200, { ok: true });
}
async function deletePush(req: IncomingMessage, res: ServerResponse, groupId: string) {
authorize(req, groupId);
const b = await readJson(req, 4096);
if (typeof b?.endpoint !== 'string') throw new HttpError(400, 'bad endpoint');
store.deletePush(groupId, b.endpoint);
send(res, 200, { ok: true });
}
function deleteGroup(req: IncomingMessage, res: ServerResponse, groupId: string) {
authorize(req, groupId);
store.deleteGroup(groupId);
rmSync(blobDir(groupId), { recursive: true, force: true });
for (const s of streams.get(groupId) ?? []) s.end();
streams.delete(groupId);
send(res, 200, { ok: true });
}
function rates(res: ServerResponse, url: URL) {
const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpError(400, 'bad date');
const r = store.ratesOn(date);
if (!r) throw new HttpError(404, 'no rates');
// Past dates never change; today's may still be published later.
const final = r.date < date || date < new Date().toISOString().slice(0, 10);
send(res, 200, { base: 'EUR', ...r }, { 'Cache-Control': final ? 'public, max-age=86400' : 'public, max-age=900' });
}
function serveStatic(req: IncomingMessage, res: ServerResponse, url: URL) {
if (!cfg.staticDir) throw new HttpError(404, 'not found');
let rel: string;
try {
rel = decodeURIComponent(url.pathname);
} catch {
throw new HttpError(400, 'bad path');
}
let path = normalize(join(cfg.staticDir, rel));
if (!path.startsWith(cfg.staticDir + sep) && path !== cfg.staticDir) throw new HttpError(404, 'not found');
let isFile = existsSync(path) && statSync(path).isFile();
if (!isFile) {
// SPA fallback for app routes; real missing assets stay 404.
if (extname(rel) !== '') throw new HttpError(404, 'not found');
rel = '/index.html';
path = join(cfg.staticDir, 'index.html');
isFile = true;
}
const cache = rel.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache';
res.writeHead(200, {
'Content-Type': MIME[extname(path)] ?? 'application/octet-stream',
'Content-Length': String(statSync(path).size),
'Cache-Control': cache,
...(rel === '/sw.js' ? { 'Service-Worker-Allowed': '/' } : {}),
});
if (req.method === 'HEAD') return res.end();
createReadStream(path).pipe(res);
}
// ---- router ----------------------------------------------------------
async function route(req: IncomingMessage, res: ServerResponse) {
const url = new URL(req.url ?? '/', 'http://x');
const p = url.pathname;
const m = req.method ?? 'GET';
if (!p.startsWith('/api/')) {
if (m !== 'GET' && m !== 'HEAD') throw new HttpError(405, 'method not allowed');
return serveStatic(req, res, url);
}
if (p === '/api/health' && m === 'GET') return send(res, 200, { ok: true });
if (p === '/api/config' && m === 'GET')
return send(res, 200, { vapidPublicKey: vapid?.publicKey ?? null, maxPhotoBytes: cfg.maxPhotoBytes, maxGroupBytes: cfg.maxGroupBytes });
if (p === '/api/rates' && m === 'GET') return rates(res, url);
if (p === '/api/groups' && m === 'POST') return createGroup(req, res);
const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p);
if (g) {
const [, id, rest = ''] = g;
if (rest === '' && m === 'DELETE') return deleteGroup(req, res, id);
if (rest === '/events' && m === 'GET') return getEvents(req, res, id, url);
if (rest === '/events' && m === 'POST') return postEvents(req, res, id);
if (rest === '/stream' && m === 'GET') return stream(req, res, id);
if (rest === '/push' && m === 'POST') return postPush(req, res, id);
if (rest === '/push' && m === 'DELETE') return deletePush(req, res, id);
const b = /^\/blobs\/([^/]+)$/.exec(rest);
if (b && m === 'PUT') return putBlob(req, res, id, b[1]);
if (b && m === 'GET') return getBlob(req, res, id, b[1]);
}
throw new HttpError(404, 'not found');
}
return async function handler(req: IncomingMessage, res: ServerResponse) {
for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v);
try {
await route(req, res);
} catch (e) {
const status = e instanceof HttpError ? e.status : 500;
if (status === 500) console.error(`${req.method} ${new URL(req.url ?? '/', 'http://x').pathname}:`, e);
if (!res.headersSent) send(res, status, { error: e instanceof HttpError ? e.message : 'internal error' });
else res.end();
}
};
}

47
apps/server/src/config.ts Normal file
View file

@ -0,0 +1,47 @@
// All configuration comes from environment variables (see deploy/.env.example).
import { resolve } from 'node:path';
function int(env: NodeJS.ProcessEnv, name: string, def: number): number {
const raw = env[name];
if (raw === undefined || raw === '') return def;
const n = Number(raw);
if (!Number.isSafeInteger(n) || n < 0) throw new Error(`${name} must be a non-negative integer, got "${raw}"`);
return n;
}
export interface Config {
host: string;
port: number;
dataDir: string;
/** built web client; empty = API only (dev, where Vite serves the client) */
staticDir: string;
trustProxy: boolean;
maxPhotoBytes: number;
maxEventBytes: number;
maxGroupBytes: number;
groupCreatePerHour: number;
vapidPublicKey: string;
vapidPrivateKey: string;
vapidSubject: string;
ratesEnabled: boolean;
ratesBaseUrl: string;
}
export function loadConfig(env = process.env): Config {
return {
host: env.HOST || '127.0.0.1',
port: int(env, 'PORT', 8481),
dataDir: resolve(env.DATA_DIR || './data'),
staticDir: env.STATIC_DIR ? resolve(env.STATIC_DIR) : '',
trustProxy: env.TRUST_PROXY === '1',
maxPhotoBytes: int(env, 'MAX_PHOTO_BYTES', 2 * 1024 * 1024),
maxEventBytes: int(env, 'MAX_EVENT_BYTES', 64 * 1024),
maxGroupBytes: int(env, 'MAX_GROUP_BYTES', 200 * 1024 * 1024),
groupCreatePerHour: int(env, 'GROUP_CREATE_PER_HOUR', 10),
vapidPublicKey: env.VAPID_PUBLIC_KEY || '',
vapidPrivateKey: env.VAPID_PRIVATE_KEY || '',
vapidSubject: env.VAPID_SUBJECT || '',
ratesEnabled: env.RATES_DISABLED !== '1',
ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref',
};
}

175
apps/server/src/db.ts Normal file
View file

@ -0,0 +1,175 @@
// SQLite storage. Everything group-related is ciphertext the server cannot
// read; the only plaintext is ids, sizes, timestamps and push endpoints.
import { DatabaseSync } from 'node:sqlite';
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
export interface StoredEvent {
seq: number;
id: string;
deviceId: string;
iv: string;
ct: string;
}
export interface PushSub {
endpoint: string;
p256dh: string;
auth: string;
deviceId: string;
}
export class Store {
readonly db: DatabaseSync;
constructor(dataDir: string) {
mkdirSync(dataDir, { recursive: true });
this.db = new DatabaseSync(join(dataDir, 'oweme.sqlite'));
this.db.exec(`
PRAGMA journal_mode = WAL;
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS groups (
id TEXT PRIMARY KEY,
auth_hash TEXT NOT NULL,
bytes INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS events (
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
seq INTEGER NOT NULL,
id TEXT NOT NULL,
device_id TEXT NOT NULL,
iv TEXT NOT NULL,
ct TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (group_id, seq),
UNIQUE (group_id, id)
);
CREATE TABLE IF NOT EXISTS blobs (
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
id TEXT NOT NULL,
size INTEGER NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (group_id, id)
);
CREATE TABLE IF NOT EXISTS push_subs (
group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
endpoint TEXT NOT NULL,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
device_id TEXT NOT NULL,
created_at INTEGER NOT NULL,
PRIMARY KEY (group_id, endpoint)
);
CREATE TABLE IF NOT EXISTS rates (
date TEXT PRIMARY KEY,
json TEXT NOT NULL
);
`);
}
tx<T>(fn: () => T): T {
this.db.exec('BEGIN IMMEDIATE');
try {
const r = fn();
this.db.exec('COMMIT');
return r;
} catch (e) {
this.db.exec('ROLLBACK');
throw e;
}
}
createGroup(id: string, authHash: string): boolean {
const r = this.db
.prepare('INSERT OR IGNORE INTO groups (id, auth_hash, created_at) VALUES (?, ?, ?)')
.run(id, authHash, Date.now());
return r.changes === 1;
}
getGroup(id: string): { authHash: string; bytes: number } | undefined {
const r = this.db.prepare('SELECT auth_hash, bytes FROM groups WHERE id = ?').get(id) as
| { auth_hash: string; bytes: number }
| undefined;
return r && { authHash: r.auth_hash, bytes: r.bytes };
}
deleteGroup(id: string): void {
this.db.prepare('DELETE FROM groups WHERE id = ?').run(id);
}
addBytes(id: string, n: number): void {
this.db.prepare('UPDATE groups SET bytes = bytes + ? WHERE id = ?').run(n, id);
}
latestSeq(groupId: string): number {
const r = this.db.prepare('SELECT MAX(seq) AS s FROM events WHERE group_id = ?').get(groupId) as { s: number | null };
return r.s ?? 0;
}
eventsAfter(groupId: string, after: number, limit: number): StoredEvent[] {
return this.db
.prepare('SELECT seq, id, device_id AS deviceId, iv, ct FROM events WHERE group_id = ? AND seq > ? ORDER BY seq LIMIT ?')
.all(groupId, after, limit) as unknown as StoredEvent[];
}
/** Existing seq for an event id (idempotent retries), if any. */
seqOf(groupId: string, id: string): number | undefined {
const r = this.db.prepare('SELECT seq FROM events WHERE group_id = ? AND id = ?').get(groupId, id) as { seq: number } | undefined;
return r?.seq;
}
insertEvent(groupId: string, seq: number, e: Omit<StoredEvent, 'seq'>): void {
this.db
.prepare('INSERT INTO events (group_id, seq, id, device_id, iv, ct, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
.run(groupId, seq, e.id, e.deviceId, e.iv, e.ct, Date.now());
}
hasBlob(groupId: string, id: string): boolean {
return !!this.db.prepare('SELECT 1 FROM blobs WHERE group_id = ? AND id = ?').get(groupId, id);
}
insertBlob(groupId: string, id: string, size: number): void {
this.db.prepare('INSERT INTO blobs (group_id, id, size, created_at) VALUES (?, ?, ?, ?)').run(groupId, id, size, Date.now());
}
upsertPush(groupId: string, s: PushSub): void {
this.db
.prepare(
`INSERT INTO push_subs (group_id, endpoint, p256dh, auth, device_id, created_at) VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (group_id, endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, device_id = excluded.device_id`,
)
.run(groupId, s.endpoint, s.p256dh, s.auth, s.deviceId, Date.now());
}
deletePush(groupId: string, endpoint: string): void {
this.db.prepare('DELETE FROM push_subs WHERE group_id = ? AND endpoint = ?').run(groupId, endpoint);
}
deletePushEverywhere(endpoint: string): void {
this.db.prepare('DELETE FROM push_subs WHERE endpoint = ?').run(endpoint);
}
pushSubs(groupId: string): PushSub[] {
return this.db
.prepare('SELECT endpoint, p256dh, auth, device_id AS deviceId FROM push_subs WHERE group_id = ?')
.all(groupId) as unknown as PushSub[];
}
saveRates(date: string, rates: Record<string, string>): void {
this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates));
}
/** Rates for the latest published date on or before `date`. */
ratesOn(date: string): { date: string; rates: Record<string, string> } | undefined {
const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as
| { date: string; json: string }
| undefined;
return r && { date: r.date, rates: JSON.parse(r.json) };
}
latestRatesDate(): string | undefined {
const r = this.db.prepare('SELECT MAX(date) AS d FROM rates').get() as { d: string | null };
return r.d ?? undefined;
}
}

View file

@ -0,0 +1,28 @@
// Generate VAPID keys and write them into an env file without printing the
// private key: `node apps/server/src/gen-vapid.ts deploy/.env`.
// Existing VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY lines are kept unless
// --force is given (rotating keys invalidates every push subscription).
import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
import { generateVapidKeys } from './push.ts';
const file = process.argv[2];
const force = process.argv.includes('--force');
if (!file) {
console.error('usage: node gen-vapid.ts <env-file> [--force]');
process.exit(2);
}
const lines = existsSync(file) ? readFileSync(file, 'utf8').split('\n') : [];
const has = (k: string) => lines.some((l) => l.startsWith(`${k}=`) && l.length > k.length + 1);
if (has('VAPID_PUBLIC_KEY') && has('VAPID_PRIVATE_KEY') && !force) {
console.error(`${file} already has VAPID keys; leaving them alone (use --force to rotate).`);
process.exit(0);
}
const { publicKey, privateKey } = generateVapidKeys();
const kept = lines.filter((l) => !l.startsWith('VAPID_PUBLIC_KEY=') && !l.startsWith('VAPID_PRIVATE_KEY='));
while (kept.length && kept[kept.length - 1] === '') kept.pop();
kept.push(`VAPID_PUBLIC_KEY=${publicKey}`, `VAPID_PRIVATE_KEY=${privateKey}`, '');
writeFileSync(file, kept.join('\n'), { mode: 0o600 });
chmodSync(file, 0o600);
console.error(`Wrote VAPID keys to ${file} (private key ${privateKey.length} chars, not shown).`);

30
apps/server/src/main.ts Normal file
View file

@ -0,0 +1,30 @@
import { createServer } from 'node:http';
import { createApp } from './app.ts';
import { loadConfig } from './config.ts';
import { Store } from './db.ts';
import { RatesService } from './rates.ts';
const cfg = loadConfig();
const store = new Store(cfg.dataDir);
const server = createServer(createApp(cfg, store));
// SSE connections are long-lived; don't let the default timeouts cut them.
server.requestTimeout = 0;
server.headersTimeout = 30_000;
const rates = new RatesService(store, cfg.ratesBaseUrl);
if (cfg.ratesEnabled) rates.start();
server.listen(cfg.port, cfg.host, () => {
console.log(`oweme server on http://${cfg.host}:${cfg.port}` + (cfg.staticDir ? ` serving ${cfg.staticDir}` : ' (API only)'));
if (!cfg.vapidPublicKey) console.log('push notifications disabled: VAPID_* not set');
});
for (const sig of ['SIGINT', 'SIGTERM'] as const) {
process.on(sig, () => {
rates.stop();
server.close();
server.closeAllConnections();
store.db.close();
process.exit(0);
});
}

105
apps/server/src/push.ts Normal file
View file

@ -0,0 +1,105 @@
// Web Push sender: VAPID (RFC 8292) + aes128gcm payload encryption
// (RFC 8291), using only node:crypto. The payload is just { g: groupId };
// the service worker fetches and decrypts the actual events itself, so the
// push service never sees content (SPEC.md §7.7).
import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto';
import type { PushSub } from './db.ts';
const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url');
const fromB64u = (s: string) => Buffer.from(s, 'base64url');
/** Push services we deliver to. Anything else is refused, so a registered
* "endpoint" can't make the server send requests to arbitrary hosts. */
const ALLOWED_PUSH_HOSTS = [
'fcm.googleapis.com',
'updates.push.services.mozilla.com',
'push.services.mozilla.com',
'web.push.apple.com',
'notify.windows.com',
];
export function isAllowedEndpoint(endpoint: string): boolean {
let u: URL;
try {
u = new URL(endpoint);
} catch {
return false;
}
if (u.protocol !== 'https:' || u.port !== '') return false;
return ALLOWED_PUSH_HOSTS.some((h) => u.hostname === h || u.hostname.endsWith(`.${h}`));
}
export function generateVapidKeys(): { publicKey: string; privateKey: string } {
const ecdh = createECDH('prime256v1');
ecdh.generateKeys();
return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) };
}
export interface Vapid {
publicKey: string;
privateKey: string;
subject: string;
}
function vapidAuthHeader(endpoint: string, v: Vapid): string {
const pub = fromB64u(v.publicKey);
const key = createPrivateKey({
key: { kty: 'EC', crv: 'P-256', d: v.privateKey, x: b64u(pub.subarray(1, 33)), y: b64u(pub.subarray(33, 65)) },
format: 'jwk',
});
const header = b64u(Buffer.from(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
const claims = b64u(
Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: v.subject })),
);
const sig = sign('sha256', Buffer.from(`${header}.${claims}`), { key, dsaEncoding: 'ieee-p1363' });
return `vapid t=${header}.${claims}.${b64u(sig)}, k=${v.publicKey}`;
}
/** RFC 8291 aes128gcm encryption of `plaintext` for one subscription. */
export function encryptPayload(sub: Pick<PushSub, 'p256dh' | 'auth'>, plaintext: Buffer): Buffer {
const uaPublic = fromB64u(sub.p256dh);
const authSecret = fromB64u(sub.auth);
const ecdh = createECDH('prime256v1');
const asPublic = ecdh.generateKeys();
const shared = ecdh.computeSecret(uaPublic);
const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]);
const ikm = Buffer.from(hkdfSync('sha256', shared, authSecret, keyInfo, 32));
const salt = randomBytes(16);
const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
const cipher = createCipheriv('aes-128-gcm', cek, nonce);
// 0x02 = padding delimiter for the last (only) record.
const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]);
const rs = Buffer.alloc(4);
rs.writeUInt32BE(4096);
return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]);
}
/** Send one push. Returns 'gone' if the subscription should be deleted. */
export async function sendPush(sub: PushSub, payload: object, v: Vapid): Promise<'ok' | 'gone' | 'error'> {
if (!isAllowedEndpoint(sub.endpoint)) return 'gone';
try {
const res = await fetch(sub.endpoint, {
method: 'POST',
headers: {
Authorization: vapidAuthHeader(sub.endpoint, v),
'Content-Encoding': 'aes128gcm',
'Content-Type': 'application/octet-stream',
TTL: String(24 * 3600),
Urgency: 'normal',
},
body: encryptPayload(sub, Buffer.from(JSON.stringify(payload))),
redirect: 'error',
signal: AbortSignal.timeout(15_000),
});
if (res.status === 404 || res.status === 410) return 'gone';
if (!res.ok) {
console.error(`push: ${new URL(sub.endpoint).hostname} HTTP ${res.status}`);
return 'error';
}
return 'ok';
} catch (e) {
console.error(`push: ${(e as Error).message}`);
return 'error';
}
}

52
apps/server/src/rates.ts Normal file
View file

@ -0,0 +1,52 @@
// ECB daily reference rates (EUR-based). Fetched by the server so that
// clients never contact a third party (SPEC.md §8.2).
import type { Store } from './db.ts';
/** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */
export function parseEcbXml(xml: string): Map<string, Record<string, string>> {
const out = new Map<string, Record<string, string>>();
const dayRe = /<Cube time="(\d{4}-\d{2}-\d{2})">([\s\S]*?)<\/Cube>/g;
const rateRe = /<Cube currency="([A-Z]{3})" rate="(\d+(?:\.\d+)?)"\s*\/>/g;
for (const day of xml.matchAll(dayRe)) {
const rates: Record<string, string> = { EUR: '1' };
for (const r of day[2].matchAll(rateRe)) rates[r[1]] = r[2];
out.set(day[1], rates);
}
return out;
}
export class RatesService {
private timer: NodeJS.Timeout | undefined;
private readonly store: Store;
private readonly baseUrl: string;
constructor(store: Store, baseUrl: string) {
this.store = store;
this.baseUrl = baseUrl;
}
async refresh(): Promise<void> {
// Full history the first time (≈8 MB), the last 90 days afterwards.
const file = this.store.latestRatesDate() ? 'eurofxref-hist-90d.xml' : 'eurofxref-hist.xml';
const res = await fetch(`${this.baseUrl}/${file}`, { signal: AbortSignal.timeout(60_000) });
if (!res.ok) throw new Error(`ECB ${file}: HTTP ${res.status}`);
const days = parseEcbXml(await res.text());
if (days.size === 0) throw new Error(`ECB ${file}: no rates parsed`);
this.store.tx(() => {
for (const [date, rates] of days) this.store.saveRates(date, rates);
});
console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`);
}
/** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */
start(): void {
const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`));
void run();
this.timer = setInterval(run, 6 * 3600_000);
this.timer.unref();
}
stop(): void {
clearInterval(this.timer);
}
}

View file

@ -0,0 +1,186 @@
import assert from 'node:assert/strict';
import { createDecipheriv, createECDH, createHash, hkdfSync, randomBytes } from 'node:crypto';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { after, before, describe, it } from 'node:test';
import { createApp } from '../src/app.ts';
import { loadConfig } from '../src/config.ts';
import { Store } from '../src/db.ts';
import { encryptPayload, isAllowedEndpoint } from '../src/push.ts';
import { parseEcbXml } from '../src/rates.ts';
const b64u = (b: Buffer) => b.toString('base64url');
const newGroup = () => {
const id = b64u(randomBytes(16));
const token = b64u(randomBytes(32));
return { id, token, authHash: createHash('sha256').update(token).digest('hex') };
};
let server: Server;
let base: string;
let dir: string;
let store: Store;
before(async () => {
dir = mkdtempSync(join(tmpdir(), 'oweme-test-'));
const web = join(dir, 'web');
mkdirSync(join(web, 'assets'), { recursive: true });
writeFileSync(join(web, 'index.html'), '<!doctype html><title>OweMe</title>');
writeFileSync(join(web, 'assets', 'app-abc.js'), 'console.log(1)');
const cfg = loadConfig({
DATA_DIR: join(dir, 'data'), STATIC_DIR: web, MAX_PHOTO_BYTES: '1000', MAX_EVENT_BYTES: '300',
MAX_GROUP_BYTES: '5000', GROUP_CREATE_PER_HOUR: '50',
});
store = new Store(cfg.dataDir);
store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' });
server = createServer(createApp(cfg, store));
await new Promise<void>((r) => server.listen(0, '127.0.0.1', r));
const addr = server.address() as { port: number };
base = `http://127.0.0.1:${addr.port}`;
});
after(() => {
server.closeAllConnections();
server.close();
store.db.close();
rmSync(dir, { recursive: true, force: true });
});
async function api(method: string, path: string, opts: { token?: string; json?: unknown; body?: Buffer } = {}) {
const headers: Record<string, string> = {};
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
if (opts.json !== undefined) headers['Content-Type'] = 'application/json';
const res = await fetch(base + path, { method, headers, body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body });
const text = await res.text();
let data: any = text;
try { data = JSON.parse(text); } catch { /* not JSON */ }
return { status: res.status, data, headers: res.headers };
}
const event = (id: string, size = 20) => ({ id, deviceId: 'device-123', iv: b64u(randomBytes(12)), ct: b64u(randomBytes(size)) });
describe('groups and events', () => {
it('creates a group, rejects duplicates and bad input', async () => {
const g = newGroup();
assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 201);
assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 409);
assert.equal((await api('POST', '/api/groups', { json: { id: 'short', authHash: g.authHash } })).status, 400);
});
it('requires the right token, answering 404 either way', async () => {
const g = newGroup();
await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } });
assert.equal((await api('GET', `/api/groups/${g.id}/events`)).status, 404);
assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: newGroup().token })).status, 404);
assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 200);
});
it('appends idempotently and pages by seq', async () => {
const g = newGroup();
await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } });
const r1 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-aaaa'), event('evt-bbbb')] } });
assert.deepEqual(r1.data.seqs, [1, 2]);
const r2 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-bbbb'), event('evt-cccc')] } });
assert.deepEqual(r2.data.seqs, [2, 3]);
const r3 = await api('GET', `/api/groups/${g.id}/events?after=1`, { token: g.token });
assert.deepEqual(r3.data.events.map((e: any) => e.id), ['evt-bbbb', 'evt-cccc']);
assert.equal(r3.data.latest, 3);
});
it('enforces event and group size limits', async () => {
const g = newGroup();
await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } });
assert.equal((await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-big1', 400)] } })).status, 413);
for (let i = 0; i < 17; i++) await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event(`evt-fill${i}`, 290)] } });
const r = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-over', 290)] } });
assert.equal(r.status, 507);
});
it('streams new seqs over SSE', async () => {
const g = newGroup();
await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } });
const ac = new AbortController();
const res = await fetch(`${base}/api/groups/${g.id}/stream`, { headers: { Authorization: `Bearer ${g.token}` }, signal: ac.signal });
const reader = res.body!.getReader();
const first = new TextDecoder().decode((await reader.read()).value);
assert.match(first, /data: 0/);
await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-live')] } });
const next = new TextDecoder().decode((await reader.read()).value);
assert.match(next, /data: 1/);
ac.abort();
});
it('stores immutable blobs with a size cap, and deletes everything with the group', async () => {
const g = newGroup();
await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } });
const blob = randomBytes(500);
assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { token: g.token, body: blob })).status, 201);
assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdee`, { token: g.token, body: randomBytes(1001) })).status, 413);
const res = await fetch(`${base}/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { headers: { Authorization: `Bearer ${g.token}` } });
assert.deepEqual(Buffer.from(await res.arrayBuffer()), blob);
assert.equal((await api('DELETE', `/api/groups/${g.id}`, { token: g.token })).status, 200);
assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 404);
});
it('refuses push endpoints outside known push services', async () => {
assert.equal(isAllowedEndpoint('https://fcm.googleapis.com/fcm/send/abc'), true);
assert.equal(isAllowedEndpoint('https://web.push.apple.com/xyz'), true);
assert.equal(isAllowedEndpoint('https://169.254.169.254/latest'), false);
assert.equal(isAllowedEndpoint('http://fcm.googleapis.com/x'), false);
assert.equal(isAllowedEndpoint('https://fcm.googleapis.com.evil.example/x'), false);
});
});
describe('rates and static', () => {
it('returns the latest rates on or before a date', async () => {
const r = await api('GET', '/api/rates?date=2026-10-11');
assert.equal(r.status, 200);
assert.equal(r.data.date, '2026-10-08');
assert.equal(r.data.rates.CZK, '24.4');
assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404);
});
it('parses ECB XML', () => {
const xml = '<Cube><Cube time="2026-10-09"><Cube currency="USD" rate="1.1206"/><Cube currency="CZK" rate="24.369"/></Cube></Cube>';
assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' });
});
it('serves the SPA with security headers and blocks traversal', async () => {
const r = await api('GET', '/g/abc');
assert.equal(r.status, 200);
assert.match(r.data, /OweMe/);
assert.match(r.headers.get('content-security-policy')!, /default-src 'self'/);
assert.equal(r.headers.get('referrer-policy'), 'no-referrer');
assert.equal((await api('GET', '/assets/app-abc.js')).headers.get('cache-control'), 'public, max-age=31536000, immutable');
assert.equal((await api('GET', '/assets/missing.js')).status, 404);
assert.equal((await api('GET', '/assets/..%2f..%2f..%2f..%2fetc%2fpasswd')).status, 404);
const dots = await api('GET', '/%2e%2e/%2e%2e/etc/passwd'); // URL parser collapses these → SPA fallback
assert.match(dots.data, /OweMe/);
});
});
describe('web push encryption', () => {
it('produces an RFC 8291 payload the browser side can decrypt', () => {
// Play the browser: generate a subscription key pair and auth secret.
const ua = createECDH('prime256v1');
const uaPublic = ua.generateKeys();
const auth = randomBytes(16);
const body = encryptPayload({ p256dh: b64u(uaPublic), auth: b64u(auth) }, Buffer.from('{"g":"x"}'));
const salt = body.subarray(0, 16);
const idlen = body[20];
const asPublic = body.subarray(21, 21 + idlen);
const ct = body.subarray(21 + idlen);
const shared = ua.computeSecret(asPublic);
const ikm = Buffer.from(hkdfSync('sha256', shared, auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]), 32));
const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16));
const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12));
const d = createDecipheriv('aes-128-gcm', cek, nonce);
d.setAuthTag(ct.subarray(ct.length - 16));
const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]);
assert.equal(plain.subarray(0, -1).toString(), '{"g":"x"}');
assert.equal(plain[plain.length - 1], 2);
});
});

16
apps/server/tsconfig.json Normal file
View file

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src", "test"]
}

18
apps/web/index.html Normal file
View file

@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0B2E22" />
<meta name="referrer" content="no-referrer" />
<meta name="description" content="Split group expenses, end-to-end encrypted." />
<title>OweMe</title>
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="/icon-192.png" />
<link rel="manifest" href="/manifest.webmanifest" />
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

21
apps/web/package.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "@oweme/web",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build && vite build -c vite.sw.config.ts",
"preview": "vite preview",
"check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings"
},
"dependencies": {
"@oweme/core": "*",
"uqr": "0.1.3"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "7.3.1",
"svelte": "5.57.1",
"svelte-check": "4.7.6",
"vite": "8.3.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

5
apps/web/public/icon.svg Normal file
View file

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="112" fill="#0B2E22"/>
<circle cx="256" cy="256" r="150" fill="none" stroke="#3DDC97" stroke-width="28"/>
<path d="M256 160v192M298 196c-10-14-26-20-44-20-26 0-44 13-44 32 0 46 92 26 92 74 0 20-19 34-46 34-20 0-38-8-48-24" fill="none" stroke="#3DDC97" stroke-width="26" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 429 B

View file

@ -0,0 +1,16 @@
{
"name": "OweMe",
"short_name": "OweMe",
"description": "Split group expenses, end-to-end encrypted.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#0B2E22",
"theme_color": "#0B2E22",
"icons": [
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" },
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" },
{ "src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
]
}

View file

@ -0,0 +1,2 @@
User-agent: *
Disallow: /g/

61
apps/web/src/App.svelte Normal file
View file

@ -0,0 +1,61 @@
<script lang="ts">
import { isGroupId, isGroupSecret } from './lib/crypto.ts';
import { router } from './lib/router.svelte.ts';
import { addGroup } from './lib/session.svelte.ts';
import { t } from './lib/settings.svelte.ts';
import { ui } from './lib/ui.svelte.ts';
import Home from './components/Home.svelte';
import NewGroup from './components/NewGroup.svelte';
import AppSettings from './components/AppSettings.svelte';
import Restore from './components/Restore.svelte';
import GroupPage from './components/GroupPage.svelte';
// Opening a link: /g/<id>#<secret>. Save the group on this device, then
// drop the secret from the address bar (and from history).
let ready = $state(false);
(async () => {
const m = /^\/g\/([^/]+)/.exec(location.pathname);
const secret = location.hash.slice(1);
if (m && isGroupId(m[1]) && isGroupSecret(secret)) {
await addGroup(m[1], secret);
history.replaceState(null, '', location.pathname + location.search);
}
ready = true;
})();
const groupId = $derived('id' in router.route ? router.route.id : null);
</script>
{#if ready}
{#if router.route.name === 'home'}
<Home />
{:else if router.route.name === 'new'}
<NewGroup />
{:else if router.route.name === 'settings'}
<AppSettings />
{:else if router.route.name === 'restore'}
<Restore />
{:else if groupId}
{#key groupId}
<GroupPage id={groupId} />
{/key}
{:else}
<main class="page">
<div class="empty stack">
<p>404</p>
<a class="btn" href="/" onclick={(e) => { e.preventDefault(); router.go('/'); }}>{t('back')}</a>
</div>
</main>
{/if}
{/if}
{#if ui.toast}
<div class="toast" role="status">{ui.toast}</div>
{/if}
{#if ui.updateReady}
<div class="toast row" role="status">
{t('update_available')}
<button class="btn small primary" onclick={() => location.reload()}>{t('reload')}</button>
</div>
{/if}

241
apps/web/src/app.css Normal file
View file

@ -0,0 +1,241 @@
/* OweMe theme: dark & light "money green" (SPEC.md §10.4). */
:root {
--bg: #0b2e22;
--surface: #123d2e;
--surface-2: #1a4d3a;
--border: #255c46;
--text: #e8f3ec;
--muted: #9fbfae;
--accent: #3ddc97;
--accent-ink: #062016;
--owe: #f2a65a;
--danger: #f87171;
--gold: #d4af37;
/* chart series, validated for CVD separation on --surface */
--chart-1: #22a66e;
--chart-2: #4a8fd0;
--shadow: 0 8px 30px rgb(0 0 0 / 0.35);
--radius: 14px;
--gutter: 16px;
color-scheme: dark;
}
@media (prefers-color-scheme: light) {
:root:not([data-theme='dark']) {
--bg: #f2f7f4;
--surface: #ffffff;
--surface-2: #e4efe9;
--border: #cfe0d6;
--text: #0b2e22;
--muted: #4a6b5b;
--accent: #16865a;
--accent-ink: #ffffff;
--owe: #b5541c;
--danger: #c0392b;
--gold: #9a7b12;
--chart-1: #16865a;
--chart-2: #2f6fb0;
--shadow: 0 8px 30px rgb(11 46 34 / 0.12);
color-scheme: light;
}
}
:root[data-theme='light'] {
--bg: #f2f7f4;
--surface: #ffffff;
--surface-2: #e4efe9;
--border: #cfe0d6;
--text: #0b2e22;
--muted: #4a6b5b;
--accent: #16865a;
--accent-ink: #ffffff;
--owe: #b5541c;
--danger: #c0392b;
--gold: #9a7b12;
--chart-1: #16865a;
--chart-2: #2f6fb0;
--shadow: 0 8px 30px rgb(11 46 34 / 0.12);
color-scheme: light;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 16px/1.45 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
-webkit-font-smoothing: antialiased;
min-height: 100dvh;
}
h1, h2, h3 { line-height: 1.2; margin: 0; }
h1 { font-size: 1.35rem; }
h2 { font-size: 1.05rem; }
h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); font-weight: 600; }
a { color: var(--accent); }
p { margin: 0; }
.muted { color: var(--muted); }
.small { font-size: 0.85rem; }
.pos { color: var(--accent); }
.neg { color: var(--owe); }
.num { font-variant-numeric: tabular-nums; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
/* layout */
.page { max-width: 720px; margin: 0 auto; padding: 0 var(--gutter) calc(96px + env(safe-area-inset-bottom)); }
.page.wide { max-width: 1120px; }
.stack { display: flex; flex-direction: column; gap: 12px; }
.row { display: flex; align-items: center; gap: 10px; }
.row.wrap { flex-wrap: wrap; }
.spacer { flex: 1; }
.section { margin-top: 24px; display: flex; flex-direction: column; gap: 10px; }
.topbar {
position: sticky; top: 0; z-index: 20;
display: flex; align-items: center; gap: 8px;
padding: calc(10px + env(safe-area-inset-top)) var(--gutter) 10px;
background: color-mix(in srgb, var(--bg) 88%, transparent);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
}
.topbar h1 { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card {
background: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 14px 16px;
}
.list { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
.list > * + * { border-top: 1px solid var(--border); }
.item {
display: flex; align-items: center; gap: 12px; padding: 12px 14px; width: 100%;
background: none; border: 0; color: inherit; font: inherit; text-align: left; text-decoration: none;
}
button.item, a.item { cursor: pointer; }
button.item:hover, a.item:hover { background: var(--surface-2); }
.item .grow { flex: 1; min-width: 0; }
.item .title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.item .sub { font-size: 0.85rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.item .end { text-align: right; flex-shrink: 0; }
/* controls */
button, .btn {
font: inherit; color: inherit; cursor: pointer;
}
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 8px;
min-height: 44px; padding: 0 16px; border-radius: 12px;
border: 1px solid var(--border); background: var(--surface); color: var(--text);
font-weight: 600; text-decoration: none; white-space: nowrap;
}
.btn:hover { background: var(--surface-2); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover { filter: brightness(1.08); }
.btn.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 40%, var(--border)); }
.btn.ghost { background: transparent; border-color: transparent; }
.btn.small { min-height: 34px; padding: 0 12px; font-size: 0.9rem; border-radius: 10px; }
.btn.block { width: 100%; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.icon-btn {
display: inline-grid; place-items: center; width: 44px; height: 44px; flex-shrink: 0;
border-radius: 12px; border: 0; background: transparent; color: var(--text);
}
.icon-btn:hover { background: var(--surface-2); }
label.field { display: flex; flex-direction: column; gap: 6px; font-size: 0.9rem; color: var(--muted); }
input, select, textarea {
font: inherit; color: var(--text); background: var(--surface); width: 100%;
border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; min-height: 44px;
}
textarea { min-height: 80px; resize: vertical; }
input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-visible, .icon-btn:focus-visible, .item:focus-visible, .chip:focus-visible {
outline: 2px solid var(--accent); outline-offset: 1px;
}
input[type='checkbox'] { width: 22px; height: 22px; min-height: 0; accent-color: var(--accent); flex-shrink: 0; }
input[type='date'] { min-width: 0; }
.seg { display: flex; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 3px; gap: 3px; }
.seg button {
flex: 1; min-height: 38px; border: 0; border-radius: 9px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px;
}
.seg button[aria-pressed='true'] { background: var(--surface-2); color: var(--text); }
.chips { display: flex; flex-wrap: wrap; gap: 8px; }
.chip {
display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px;
border-radius: 999px; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-size: 0.9rem;
}
.chip[aria-pressed='true'] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, var(--surface)); }
.avatar {
display: inline-grid; place-items: center; flex-shrink: 0;
width: 36px; height: 36px; border-radius: 50%;
font-weight: 700; font-size: 0.9rem; color: #062016;
}
.cat-icon {
display: inline-grid; place-items: center; flex-shrink: 0;
width: 40px; height: 40px; border-radius: 12px; background: var(--surface-2); font-size: 1.2rem;
}
.banner { padding: 10px 14px; border-radius: 12px; font-size: 0.9rem; background: var(--surface-2); border: 1px solid var(--border); }
.banner.warn { border-color: color-mix(in srgb, var(--owe) 60%, var(--border)); }
.banner.danger { border-color: color-mix(in srgb, var(--danger) 60%, var(--border)); }
.fab {
position: fixed; right: max(var(--gutter), calc(50% - 360px + var(--gutter))); bottom: calc(80px + env(safe-area-inset-bottom)); z-index: 30;
width: 60px; height: 60px; border-radius: 20px; border: 0;
background: var(--accent); color: var(--accent-ink); box-shadow: var(--shadow);
display: grid; place-items: center;
}
.tabbar {
position: fixed; left: 0; right: 0; bottom: 0; z-index: 25;
display: flex; justify-content: center;
background: color-mix(in srgb, var(--surface) 94%, transparent);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
border-top: 1px solid var(--border);
padding-bottom: env(safe-area-inset-bottom);
}
.tabbar a {
flex: 1; max-width: 180px; display: flex; flex-direction: column; align-items: center; gap: 2px;
padding: 8px 4px; color: var(--muted); text-decoration: none; font-size: 0.75rem; font-weight: 600;
}
.tabbar a[aria-current='page'] { color: var(--accent); }
/* dialogs: full-screen sheet on phones, centered on desktop */
dialog.sheet {
padding: 0; border: 0; color: var(--text); background: var(--bg);
width: 100%; max-width: 100%; height: 100%; max-height: 100%; margin: 0;
}
dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); }
@media (min-width: 760px) {
dialog.sheet {
width: min(640px, calc(100% - 48px)); height: auto; max-height: calc(100dvh - 64px);
margin: auto; border-radius: 20px; border: 1px solid var(--border); box-shadow: var(--shadow);
}
}
.sheet-body { padding: 0 var(--gutter) calc(24px + env(safe-area-inset-bottom)); }
.toast {
position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(150px + env(safe-area-inset-bottom)); z-index: 100;
background: var(--text); color: var(--bg); padding: 10px 16px; border-radius: 12px; font-weight: 600; box-shadow: var(--shadow);
max-width: calc(100% - 32px);
}
.amount-input {
font-size: 2rem; font-weight: 700; text-align: center; border: 0; background: transparent; padding: 4px 0; min-height: 56px;
}
.amount-input:focus-visible { outline: none; border-bottom: 2px solid var(--accent); border-radius: 0; }
.empty { text-align: center; color: var(--muted); padding: 40px 16px; }
.photo-thumb { width: 100%; max-height: 320px; object-fit: contain; border-radius: 12px; background: var(--surface-2); display: block; }
/* desktop: group page with a side column */
@media (min-width: 960px) {
.tabbar { position: static; justify-content: flex-start; gap: 4px; background: none; border: 0; backdrop-filter: none; padding: 0; }
.tabbar a { flex: 0 0 auto; flex-direction: row; gap: 8px; font-size: 0.95rem; padding: 10px 14px; border-radius: 10px; }
.tabbar a[aria-current='page'] { background: var(--surface); }
.fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); }
.page { padding-bottom: 48px; }
}

View file

@ -0,0 +1,100 @@
<script lang="ts">
import type { Activity, Expense } from '@oweme/core';
import { fmtDateTime, money } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
let { session }: { session: GroupSession } = $props();
let limit = $state(100);
const entries = $derived(session.activity.filter((a) => !a.ignored).reverse());
const all = $derived(session.activity);
function expenseTitle(a: Activity): string {
const e = (a.after ?? a.before) as Expense | null;
const fromState = a.entityId ? session.state.expenses[a.entityId]?.expense : undefined;
const x = e && 'amount' in e ? e : fromState;
if (!x) return '…';
const label = x.kind === 'transfer'
? t('transfer_line', { from: session.memberName(x.payers[0]?.member), to: session.memberName(x.split.entries.find((s) => s.value > 0)?.member) })
: x.title;
return `${label} (${money(x.amount, x.currency)})`;
}
function describe(a: Activity): string {
const actor = a.actor && session.memberName(a.actor) !== '?' ? session.memberName(a.actor) : t('someone');
const key = `act_${a.type.replace('.', '_')}` as MsgKey;
const after = (a.after ?? {}) as { name?: string; template?: Expense };
const before = (a.before ?? {}) as { name?: string; template?: Expense };
switch (a.type) {
case 'member.added':
return t(key, { actor, name: after.name ?? '' });
case 'member.updated':
return t(key, { actor, old: before.name ?? '', name: after.name ?? '' });
case 'member.archived':
case 'member.restored':
return t(key, { actor, name: session.memberName(a.entityId) });
case 'recurring.created':
case 'recurring.updated':
case 'recurring.deleted':
return t(key, { actor, title: (after.template ?? before.template)?.title ?? '' });
case 'comment.added':
case 'comment.deleted': {
const ex = a.entityId ? session.state.expenses[a.entityId]?.expense : undefined;
return t(key, { actor, title: ex ? (ex.title || t('kind_transfer')) : '…' });
}
case 'revert': {
const target = all.find((x) => x.eventId === a.entityId);
return t(key, { actor, time: target ? fmtDateTime(target.at) : '?' });
}
case 'group.created':
case 'group.updated':
return t(key, { actor });
default:
return t(key, { actor, title: expenseTitle(a) });
}
}
async function rewindTo(eventId: string) {
if (!confirm(t('confirm_rewind'))) return;
await session.emit({ type: 'revert', data: { targetId: eventId } });
}
/** Undo a rewind = rewind to the event just before it. */
function beforeOf(eventId: string): string | null {
const i = all.findIndex((x) => x.eventId === eventId);
return i > 0 ? all[i - 1].eventId : null;
}
</script>
<div class="stack">
{#if entries.length === 0}
<p class="empty">{t('no_activity')}</p>
{:else}
<div class="list">
{#each entries.slice(0, limit) as a, i (a.eventId)}
<div class="item" style:align-items="flex-start">
<span class="grow">
<span style:display="block">{describe(a)}</span>
<span class="small muted">{fmtDateTime(a.at)}{a.seq === null ? ' · ⏳' : ''}</span>
</span>
{#if a.type === 'revert'}
{@const prev = beforeOf(a.eventId)}
{#if prev}
<button class="btn small" onclick={() => rewindTo(prev)}><Icon name="undo" size={16} /> {t('undo_rewind')}</button>
{/if}
{:else if i > 0}
<button class="btn small ghost" onclick={() => rewindTo(a.eventId)} title={t('rewind_here')}>
<Icon name="undo" size={16} /><span class="sr-only">{t('rewind_here')}</span>
</button>
{/if}
</div>
{/each}
</div>
{#if entries.length > limit}
<button class="btn" onclick={() => (limit += 100)}>…</button>
{/if}
{/if}
</div>

View file

@ -0,0 +1,32 @@
<script lang="ts">
import { router } from '../lib/router.svelte.ts';
import { settings, t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
</script>
<header class="topbar">
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1>{t('app_settings')}</h1>
</header>
<main class="page stack">
<div class="section">
<h3>{t('language')}</h3>
<div class="seg" role="group" aria-label={t('language')}>
<button aria-pressed={settings.langPref === 'auto'} onclick={() => settings.setLang('auto')}>{t('lang_auto')}</button>
<button aria-pressed={settings.langPref === 'en'} onclick={() => settings.setLang('en')}>English</button>
<button aria-pressed={settings.langPref === 'cs'} onclick={() => settings.setLang('cs')}>Čeština</button>
</div>
</div>
<div class="section">
<h3>{t('theme')}</h3>
<div class="seg" role="group" aria-label={t('theme')}>
<button aria-pressed={settings.themePref === 'system'} onclick={() => settings.setTheme('system')}>{t('theme_system')}</button>
<button aria-pressed={settings.themePref === 'dark'} onclick={() => settings.setTheme('dark')}>{t('theme_dark')}</button>
<button aria-pressed={settings.themePref === 'light'} onclick={() => settings.setTheme('light')}>{t('theme_light')}</button>
</div>
</div>
<p class="muted small row" style:align-items="flex-start" style:margin-top="24px">
<Icon name="lock" size={16} /> <span>{t('e2e_note')}</span>
</p>
</main>

View file

@ -0,0 +1,12 @@
<script lang="ts">
import type { Member } from '@oweme/core';
import { MEMBER_COLORS } from '../lib/format.ts';
let { member, index = 0, size = 36 }: { member: Member | undefined; index?: number; size?: number } = $props();
const initials = $derived(
(member?.name ?? '?').split(/\s+/).filter(Boolean).slice(0, 2).map((w) => w[0]!.toUpperCase()).join('') || '?',
);
const color = $derived(member?.color || MEMBER_COLORS[index % MEMBER_COLORS.length]);
</script>
<span class="avatar" style:background={color} style:width="{size}px" style:height="{size}px" style:font-size="{size * 0.38}px" aria-hidden="true">{initials}</span>

View file

@ -0,0 +1,92 @@
<script lang="ts">
import { untrack } from 'svelte';
import { exponent, settleUp } from '@oweme/core';
import { money } from '../lib/format.ts';
import { displayRate } from '../lib/rates.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Avatar from './Avatar.svelte';
import CurrencySelect from './CurrencySelect.svelte';
let { session, compact = false }: { session: GroupSession; compact?: boolean } = $props();
// Optional display in another currency at today's rate (never stored).
let showIn = $state(untrack(() => session.base));
let factor = $state<number | null>(1);
$effect(() => {
const target = showIn || session.base;
displayRate(session.base, target).then((r) => (factor = r));
});
const cur = $derived(factor === null ? session.base : showIn || session.base);
const conv = (v: number) => {
if (!showIn || showIn === session.base || factor === null) return money(v, session.base);
// display only: float maths is fine here
return money(Math.round(v * factor * 10 ** (exponent(cur) - exponent(session.base))), cur);
};
const members = $derived(session.state.members.map((m, i) => ({ m, i, bal: session.balances[m.id] ?? 0 })).filter((x) => !x.m.archived || x.bal !== 0));
const maxAbs = $derived(Math.max(1, ...members.map((x) => Math.abs(x.bal))));
const transfers = $derived(settleUp(session.balances, session.state.members.map((m) => m.id)));
function record(from: string, to: string, amount: number) {
const p = new URLSearchParams({ kind: 'transfer', from, to, amount: String(amount) });
router.go(`/g/${session.id}/e/new?${p}`);
}
</script>
<div class="stack">
{#if !compact}
<h3>{t('balances')}</h3>
{/if}
<div class="list">
{#each members as { m, i, bal } (m.id)}
<div class="item">
<Avatar member={m} index={i} size={32} />
<span class="grow">
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
<span class="bar" aria-hidden="true">
<span class={bal >= 0 ? 'fill pos-fill' : 'fill neg-fill'} style:width="{(Math.abs(bal) / maxAbs) * 100}%"></span>
</span>
</span>
<span class="end num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : 'muted'}">
{bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))}
</span>
</div>
{/each}
</div>
<h3 style:margin-top="12px">{t('settle_up')}</h3>
{#if transfers.length === 0}
<p class="card muted">{t('all_settled')}</p>
{:else}
<div class="list">
{#each transfers as tr}
<div class="item">
<span class="grow">
<span class="title" style:display="block">{session.memberName(tr.from)} → {session.memberName(tr.to)}</span>
<span class="num" style:font-weight="700">{conv(tr.amount)}</span>
</span>
<button class="btn small" onclick={() => record(tr.from, tr.to, tr.amount)}>{t('mark_paid')}</button>
</div>
{/each}
</div>
{/if}
{#if !compact}
<label class="field" style:margin-top="12px">
{t('show_in')}
<CurrencySelect bind:value={showIn} />
{#if showIn && showIn !== session.base}
<span class="small">{factor === null ? t('rate_unavailable') : t('display_only_rate')}</span>
{/if}
</label>
{/if}
</div>
<style>
.bar { display: block; height: 6px; margin-top: 6px; background: var(--surface-2); border-radius: 3px; overflow: hidden; }
.fill { display: block; height: 100%; border-radius: 3px; }
.pos-fill { background: var(--accent); }
.neg-fill { background: var(--owe); }
</style>

View file

@ -0,0 +1,37 @@
<script lang="ts">
import { currencyList } from '../lib/rates.ts';
import { currencyName } from '../lib/format.ts';
let { value = $bindable(), disabled = false, id }: { value: string; disabled?: boolean; id?: string } = $props();
let lists = $state<{ ecb: string[]; other: string[] }>({ ecb: [], other: [] });
currencyList().then((l) => (lists = l));
const recent = (() => {
try {
return JSON.parse(localStorage.getItem('oweme.recentCurrencies') ?? '[]') as string[];
} catch {
return [];
}
})();
// Keep the current value selectable even before the lists load, or if
// it's a code this browser doesn't know.
const ecb = $derived(
[...lists.ecb, ...lists.other, ...recent].includes(value) ? lists.ecb : [value, ...lists.ecb],
);
</script>
<select bind:value {disabled} {id}>
{#if recent.length}
<optgroup label="★">
{#each recent as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup>
{/if}
<optgroup label="ECB">
{#each ecb as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup>
{#if lists.other.length}
<optgroup label="…">
{#each lists.other as c}<option value={c}>{c} · {currencyName(c)}</option>{/each}
</optgroup>
{/if}
</select>

View file

@ -0,0 +1,161 @@
<script lang="ts">
import { inBase, owedOriginal, type Expense } from '@oweme/core';
import { randomId } from '../lib/crypto.ts';
import { CATEGORY_ICONS, fmtDate, fmtDateTime, money } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Avatar from './Avatar.svelte';
import Icon from './Icon.svelte';
import PhotoView from './PhotoView.svelte';
import Sheet from './Sheet.svelte';
let { session, eid }: { session: GroupSession; eid: string } = $props();
let comment = $state('');
const rec = $derived(session.state.expenses[eid]);
const e = $derived(rec?.expense);
const b = $derived(e ? inBase(e, session.base) : null);
const orig = $derived(e ? owedOriginal(e) : {});
const comments = $derived(Object.values(session.state.comments).filter((c) => c.expenseId === eid).sort((a, b) => a.at.localeCompare(b.at)));
const versions = $derived(
session.activity
.filter((a) => a.entityId === eid && !a.ignored && (a.type === 'expense.created' || a.type === 'expense.updated'))
.map((a) => ({ ...a, exp: a.after as Expense }))
.reverse(),
);
const memberIdx = (id: string) => session.state.members.findIndex((m) => m.id === id);
const member = (id: string) => session.state.members.find((m) => m.id === id);
const close = () => router.back(`/g/${session.id}`);
const edit = () => router.go(`/g/${session.id}/e/${encodeURIComponent(eid)}/edit`, { replace: true });
async function remove() {
if (!confirm(t('confirm_delete'))) return;
await session.emit({ type: 'expense.deleted', data: { id: eid } });
close();
}
async function restoreVersion(v: Expense) {
const events = [];
if (rec?.deleted) events.push({ type: 'expense.restored' as const, data: { id: eid } });
events.push({ type: 'expense.updated' as const, data: v });
await session.emit(...events);
}
async function addComment(ev: SubmitEvent) {
ev.preventDefault();
const text = comment.trim();
if (!text) return;
comment = '';
await session.emit({ type: 'comment.added', data: { id: randomId(9), expenseId: eid, text } });
}
/** Field names that differ between two versions, for the history list. */
function changed(a: Expense | undefined, bb: Expense): string {
if (!a) return '';
const labels: [keyof Expense, MsgKey][] = [
['title', 'title'], ['amount', 'amount'], ['currency', 'currency'], ['rate', 'rate'], ['date', 'date'],
['category', 'category'], ['payers', 'paid_by_label'], ['split', 'split'], ['note', 'note'], ['photo', 'photo'],
];
const out = labels.filter(([k]) => JSON.stringify(a[k]) !== JSON.stringify(bb[k])).map(([, l]) => t(l).replace(/[?:]$/, ''));
return out.length ? t('changed_fields', { fields: out.join(', ') }) : '';
}
</script>
{#if !e || !b}
<Sheet title="…" onclose={close}><p class="empty">{t('loading')}</p></Sheet>
{:else}
<Sheet title={e.kind === 'transfer' ? t('kind_transfer') : e.title} onclose={close}>
{#snippet actions()}
{#if !rec.deleted}
<button class="icon-btn" onclick={edit} aria-label={t('edit')}><Icon name="edit" /></button>
{/if}
{/snippet}
<div class="stack">
{#if rec.deleted}
<div class="banner warn row">
<span class="grow" style:flex="1">{t('deleted_banner')}</span>
<button class="btn small" onclick={() => session.emit({ type: 'expense.restored', data: { id: eid } })}>{t('restore')}</button>
</div>
{/if}
<div class="card stack" style:align-items="center" style:text-align="center">
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category]}</span>
<div class="num" style:font-size="2rem" style:font-weight="700">{money(e.amount, e.currency)}</div>
{#if e.currency !== session.base}
<div class="muted small num">{t('converted', { amount: money(b.total, session.base), rate: e.rate })}</div>
{/if}
<div class="muted small">
{fmtDate(e.date, 'long')} · {t(`cat_${e.category}` as MsgKey)}
{#if e.recurringId} · <Icon name="repeat" size={12} /> {t('recurring_badge')}{/if}
</div>
</div>
{#if e.photo}<PhotoView {session} photo={e.photo} />{/if}
{#if e.note}<p class="card" style:white-space="pre-wrap">{e.note}</p>{/if}
<h3>{t('split_details')}</h3>
<div class="list">
{#each session.state.members.filter((m) => b.paid[m.id] || b.owed[m.id]) as m (m.id)}
<div class="item">
<Avatar member={m} index={memberIdx(m.id)} size={32} />
<span class="grow">
<span class="title" style:display="block">{m.name}{m.id === session.me ? ` (${t('you')})` : ''}</span>
{#if b.paid[m.id]}<span class="sub pos" style:display="block">{t('paid', { amount: money(e.payers.find((p) => p.member === m.id)!.amount, e.currency) })}</span>{/if}
</span>
{#if b.owed[m.id]}
<span class="end num small">
{t('owes_share', { amount: money(orig[m.id] ?? 0, e.currency) })}
{#if e.currency !== session.base}<span class="muted" style:display="block">{money(b.owed[m.id], session.base)}</span>{/if}
</span>
{/if}
</div>
{/each}
</div>
<h3>{t('comments')}</h3>
{#if comments.length}
<div class="list">
{#each comments as c (c.id)}
<div class="item" style:align-items="flex-start">
<Avatar member={member(c.author ?? '')} index={memberIdx(c.author ?? '')} size={28} />
<span class="grow">
<span class="small muted">{session.memberName(c.author)} · {fmtDateTime(c.at)}</span>
<span style:display="block" style:white-space="pre-wrap">{c.text}</span>
</span>
<button class="icon-btn" onclick={() => session.emit({ type: 'comment.deleted', data: { id: c.id } })} aria-label={t('delete')}><Icon name="trash" size={16} /></button>
</div>
{/each}
</div>
{/if}
<form class="row" onsubmit={addComment}>
<input bind:value={comment} placeholder={t('add_comment')} maxlength="2000" aria-label={t('add_comment')} />
<button class="btn" type="submit" disabled={!comment.trim()}>{t('send')}</button>
</form>
<h3>{t('history')}</h3>
<div class="list">
{#each versions as v, i (v.eventId)}
<div class="item">
<span class="grow">
<span class="small muted" style:display="block">{session.memberName(v.actor) === '?' ? t('someone') : session.memberName(v.actor)} · {fmtDateTime(v.at)}</span>
<span style:display="block">{v.exp.title || t('kind_transfer')} · <span class="num">{money(v.exp.amount, v.exp.currency)}</span></span>
<span class="small muted">{changed(versions[i + 1]?.exp, v.exp)}</span>
</span>
{#if !rec.deleted && JSON.stringify(v.exp) === JSON.stringify(e)}
<span class="small muted">{t('current_version')}</span>
{:else}
<button class="btn small" onclick={() => restoreVersion(v.exp)}>{t('restore')}</button>
{/if}
</div>
{/each}
</div>
{#if !rec.deleted}
<button class="btn danger" onclick={remove}><Icon name="trash" size={18} /> {t('delete')}</button>
{/if}
</div>
</Sheet>
{/if}

View file

@ -0,0 +1,422 @@
<script lang="ts">
import { untrack } from 'svelte';
import {
CATEGORIES, exponent, isValidRate, owedOriginal, parseAmount, validateExpense,
type Category, type Expense, type Freq, type Photo, type SplitMode,
} from '@oweme/core';
import { serverConfig } from '../lib/api.ts';
import { randomId } from '../lib/crypto.ts';
import { amountInput, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { processPhoto, type ProcessedPhoto } from '../lib/photo.ts';
import { suggestRate } from '../lib/rates.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { settings, t } from '../lib/settings.svelte.ts';
import type { MsgKey } from '../lib/i18n.ts';
import Avatar from './Avatar.svelte';
import CurrencySelect from './CurrencySelect.svelte';
import PhotoView from './PhotoView.svelte';
import Sheet from './Sheet.svelte';
// Read once: the editor is keyed by route, so a new expense remounts it.
const props: { session: GroupSession; eid: string | null; params: URLSearchParams } = $props();
const { session, eid, params } = untrack(() => props);
const existing: Expense | null = eid ? (session.state.expenses[eid]?.expense ?? null) : null;
const base = session.base;
const me = session.me;
const allMembers = session.state.members;
// Archived members only show up if this expense already involves them.
const involved = new Set([...(existing?.payers.map((p) => p.member) ?? []), ...(existing?.split.entries.map((s) => s.member) ?? [])]);
const members = allMembers.filter((m) => !m.archived || involved.has(m.id));
const memberIndex = (id: string) => allMembers.findIndex((m) => m.id === id);
const defaultPayer = me ?? members[0]?.id ?? '';
// ---- form state ----------------------------------------------------
const pAmount = Number(params.get('amount'));
let kind = $state<'expense' | 'transfer'>(existing?.kind ?? (params.get('kind') === 'transfer' ? 'transfer' : 'expense'));
let currency = $state(existing?.currency ?? base);
let amountText = $state(existing ? amountInput(existing.amount, existing.currency) : pAmount > 0 ? amountInput(pAmount, base) : '');
let title = $state(existing?.title ?? '');
let category = $state<Category>(existing?.category === 'transfer' ? 'other' : (existing?.category ?? 'food'));
let date = $state(existing?.date ?? today());
let note = $state(existing?.note ?? '');
let rateText = $state(existing && existing.currency !== base ? existing.rate : '1');
let rateSource = $state(existing?.rateSource ?? 'same');
let rateMissing = $state(false);
let multiPayer = $state((existing?.payers.length ?? 1) > 1);
let payer = $state(existing?.payers[0]?.member ?? params.get('from') ?? defaultPayer);
let payerAmounts = $state<Record<string, string>>(
Object.fromEntries(members.map((m) => {
const p = existing?.payers.find((x) => x.member === m.id);
return [m.id, p ? amountInput(p.amount, existing!.currency) : ''];
})),
);
let transferTo = $state(
existing?.kind === 'transfer' ? (existing.split.entries.find((s) => s.value > 0)?.member ?? '') : (params.get('to') ?? members.find((m) => m.id !== payer)?.id ?? ''),
);
let mode = $state<SplitMode>(existing?.kind === 'expense' ? existing.split.mode : 'equal');
const initValue = (id: string): string => {
const e = existing?.kind === 'expense' ? existing.split.entries.find((s) => s.member === id) : undefined;
if (!e) return mode === 'equal' ? '1' : mode === 'shares' ? '1' : '';
if (mode === 'exact') return e.value ? amountInput(e.value, existing!.currency) : '';
if (mode === 'percent') return e.value ? String(e.value / 100).replace('.', settings.lang === 'cs' ? ',' : '.') : '';
return String(e.value);
};
let values = $state<Record<string, string>>(Object.fromEntries(members.map((m) => [m.id, initValue(m.id)])));
let included = $state<Record<string, boolean>>(
Object.fromEntries(members.map((m) => {
const e = existing?.kind === 'expense' ? existing.split.entries.find((s) => s.member === m.id) : undefined;
return [m.id, existing?.kind === 'expense' ? !!e && e.value > 0 : !m.archived];
})),
);
let photo = $state<Photo | null>(existing?.photo ?? null);
let newPhoto = $state<ProcessedPhoto | null>(null);
let newPhotoUrl = $state<string | null>(null);
let photoBusy = $state(false);
let repeat = $state<'none' | Freq>('none');
let error = $state('');
let saving = $state(false);
// ---- derived -------------------------------------------------------
const amount = $derived(parseAmount(amountText, currency));
const exp = $derived(exponent(currency));
/** Parse a member's split value into the integer the event stores. */
function splitValue(id: string): number | null {
const raw = (values[id] ?? '').trim();
if (mode === 'equal') return included[id] ? 1 : 0;
if (!included[id] || raw === '' || raw === '0') return 0;
if (mode === 'shares') return /^\d{1,6}$/.test(raw) ? Number(raw) : null;
if (mode === 'exact') return parseAmount(raw, currency);
const m = /^(\d{1,3})(?:[.,](\d{1,2}))?$/.exec(raw); // percent → basis points
return m ? Number(m[1]) * 100 + Number((m[2] ?? '').padEnd(2, '0')) : null;
}
const splitEntries = $derived(members.map((m) => ({ member: m.id, value: splitValue(m.id) })));
const splitSum = $derived(splitEntries.reduce((a, e) => a + (e.value ?? 0), 0));
const remaining = $derived(mode === 'exact' ? (amount ?? 0) - splitSum : mode === 'percent' ? 10000 - splitSum : 0);
const payers = $derived.by(() => {
if (!multiPayer || kind === 'transfer') return amount ? [{ member: payer, amount }] : [];
return members
.map((m) => ({ member: m.id, amount: parseAmount(payerAmounts[m.id] ?? '', currency) ?? 0 }))
.filter((p) => p.amount > 0);
});
const payersRemaining = $derived((amount ?? 0) - payers.reduce((a, p) => a + p.amount, 0));
function build(): Expense | null {
if (!amount) return null;
const isTransfer = kind === 'transfer';
return {
id: existing?.id ?? randomId(12),
kind,
title: isTransfer ? '' : title.trim(),
category: isTransfer ? 'transfer' : category,
date,
currency,
amount,
rate: currency === base ? '1' : rateText.trim().replace(',', '.'),
rateSource: currency === base ? 'same' : rateSource,
payers,
split: isTransfer
? { mode: 'equal', entries: [{ member: transferTo, value: 1 }] }
: { mode, entries: splitEntries.filter((e) => e.value !== null && (mode === 'equal' || e.value > 0 || included[e.member])).map((e) => ({ member: e.member, value: e.value ?? 0 })) },
note: note.trim(),
photo,
...(existing?.recurringId ? { recurringId: existing.recurringId } : {}),
};
}
/** Live per-member preview of the split, in the expense currency. */
const preview = $derived.by(() => {
const e = build();
if (!e || kind === 'transfer' || validateExpense({ ...e, photo: null }, allMembers) !== null) return {} as Record<string, number>;
return owedOriginal(e);
});
// Prefill the exchange rate from ECB rates. A rate typed by hand is kept
// when the date changes, but not when the currency does. An existing
// expense keeps its stored rate until one of them changes.
let lastCurrency = untrack(() => currency);
let firstRun = true;
$effect(() => {
const c = currency;
const d = date;
const currencyChanged = c !== lastCurrency;
lastCurrency = c;
const keepStored = firstRun && !!existing;
firstRun = false;
if (c === base) {
rateText = '1';
rateSource = 'same';
rateMissing = false;
return;
}
if (keepStored || (!currencyChanged && untrack(() => rateSource) === 'manual')) return;
suggestRate(c, base, d).then((r) => {
if (c !== currency || d !== date) return;
rateMissing = !r;
if (r) {
rateText = r.rate;
rateSource = r.source;
} else if (currencyChanged) {
rateText = '';
rateSource = 'manual';
}
});
});
function setMode(m: SplitMode) {
mode = m;
for (const mem of members) values[mem.id] = m === 'shares' ? '1' : '';
}
async function pickPhoto(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
photoBusy = true;
error = '';
try {
const cfg = await serverConfig().catch(() => ({ maxPhotoBytes: 2 * 1024 * 1024 }));
newPhoto = await processPhoto(file, cfg.maxPhotoBytes);
if (newPhotoUrl) URL.revokeObjectURL(newPhotoUrl);
newPhotoUrl = URL.createObjectURL(newPhoto.full);
photo = null;
} catch (err) {
error = (err as Error).message === 'too large' ? t('photo_too_large') : t('error_generic', { msg: (err as Error).message });
} finally {
photoBusy = false;
}
}
function removePhoto() {
photo = null;
newPhoto = null;
if (newPhotoUrl) URL.revokeObjectURL(newPhotoUrl);
newPhotoUrl = null;
}
const ERRORS: Record<string, MsgKey> = {
amount: 'invalid_amount', 'payers sum': 'invalid_payers', 'payer amount': 'invalid_payers', payers: 'invalid_payers',
'exact sum': 'invalid_split', 'percent sum': 'invalid_split', equal: 'invalid_split', shares: 'invalid_split',
'split value': 'invalid_split', split: 'invalid_split', transfer: 'invalid_split', rate: 'rate_unavailable',
};
async function save(e: SubmitEvent) {
e.preventDefault();
error = '';
if (!members.length) return (error = t('need_members'));
if (kind === 'expense' && !title.trim()) return (error = t('need_title'));
if (currency !== base && !isValidRate(rateText.trim().replace(',', '.'))) return (error = t('rate_unavailable'));
const exp = build();
if (!exp) return (error = t('invalid_amount'));
const reason = validateExpense({ ...exp, photo: null }, allMembers);
if (reason) return (error = t(ERRORS[reason] ?? 'invalid_split'));
saving = true;
try {
if (newPhoto) {
const blobId = await session.addBlob(await newPhoto.full.arrayBuffer());
const thumbBlobId = await session.addBlob(await newPhoto.thumb.arrayBuffer());
exp.photo = { blobId, thumbBlobId, w: newPhoto.w, h: newPhoto.h };
}
if (existing) {
await session.emit({ type: 'expense.updated', data: exp });
} else if (repeat !== 'none' && kind === 'expense') {
const { id: _id, date: start, photo: _p, recurringId: _r, ...template } = exp;
await session.emit({ type: 'recurring.created', data: { id: randomId(9), template, rule: { freq: repeat, interval: 1, start, end: null } } });
await session.createDueOccurrences();
} else {
await session.emit({ type: 'expense.created', data: exp });
}
try {
const recent = JSON.parse(localStorage.getItem('oweme.recentCurrencies') ?? '[]') as string[];
localStorage.setItem('oweme.recentCurrencies', JSON.stringify([currency, ...recent.filter((c) => c !== currency)].slice(0, 4)));
} catch { /* per-device nicety only */ }
close();
} catch (err) {
error = t('error_generic', { msg: (err as Error).message });
saving = false;
}
}
function close() {
router.back(`/g/${session.id}`);
}
const heading = $derived(existing ? t('edit_expense') : kind === 'transfer' ? t('new_transfer') : t('new_expense'));
</script>
<Sheet title={heading} onclose={close}>
<form class="stack" onsubmit={save} novalidate>
{#if !existing}
<div class="seg" role="group">
<button type="button" aria-pressed={kind === 'expense'} onclick={() => (kind = 'expense')}>{t('kind_expense')}</button>
<button type="button" aria-pressed={kind === 'transfer'} onclick={() => (kind = 'transfer')}>{t('kind_transfer')}</button>
</div>
{/if}
<div class="card stack" style:gap="4px">
<label class="sr-only" for="amount">{t('amount')}</label>
<input id="amount" class="amount-input num" bind:value={amountText} inputmode="decimal" placeholder={exp === 0 ? '0' : `0${settings.lang === 'cs' ? ',' : '.'}${'0'.repeat(exp)}`} autocomplete="off" />
<div class="row" style:justify-content="center">
<label class="sr-only" for="currency">{t('currency')}</label>
<div style:max-width="260px" style:width="100%"><CurrencySelect id="currency" bind:value={currency} /></div>
</div>
{#if currency !== base}
<div class="row small" style:justify-content="center" style:margin-top="6px">
<label for="rate" class="muted">1 {currency} =</label>
<input id="rate" class="num" style:width="120px" style:min-height="36px" inputmode="decimal" bind:value={rateText}
oninput={() => (rateSource = 'manual')} />
<span class="muted">{base}</span>
</div>
<p class="small muted" style:text-align="center">
{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')}
{:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })}
{:else}{t('rate_source_manual')}{/if}
{#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if}
</p>
{/if}
</div>
{#if kind === 'expense'}
<label class="field">{t('title')}<input bind:value={title} placeholder={t('title_ph')} maxlength="200" /></label>
<div class="field">
<span class="small muted">{t('category')}</span>
<div class="chips">
{#each CATEGORIES as c}
<button type="button" class="chip" aria-pressed={category === c} onclick={() => (category = c)}>
<span aria-hidden="true">{CATEGORY_ICONS[c]}</span> {t(`cat_${c}` as MsgKey)}
</button>
{/each}
</div>
</div>
{/if}
<label class="field">{t('date')}<input type="date" bind:value={date} required /></label>
<!-- who paid -->
{#if kind === 'transfer'}
<div class="row">
<label class="field" style:flex="1">{t('from_label')}
<select bind:value={payer}>{#each members as m}<option value={m.id}>{m.name}</option>{/each}</select>
</label>
<label class="field" style:flex="1">{t('to_label')}
<select bind:value={transferTo}>{#each members.filter((m) => m.id !== payer) as m}<option value={m.id}>{m.name}</option>{/each}</select>
</label>
</div>
{:else}
<div class="field">
<span class="row small muted">
<span class="grow" style:flex="1">{t('paid_by_label')}</span>
<label class="row" style:gap="6px"><input type="checkbox" bind:checked={multiPayer} /> {t('multiple_payers')}</label>
</span>
{#if multiPayer}
<div class="list">
{#each members as m (m.id)}
<div class="item">
<Avatar member={m} index={memberIndex(m.id)} size={30} />
<span class="grow">{m.name}</span>
<input class="num" style:width="120px" inputmode="decimal" bind:value={payerAmounts[m.id]} aria-label="{t('paid_by_label')}: {m.name}" />
</div>
{/each}
</div>
{#if payersRemaining !== 0 && amount}
<span class="small {payersRemaining < 0 ? 'neg' : 'muted'}">
{payersRemaining > 0 ? t('remaining', { amount: money(payersRemaining, currency) }) : t('over_by', { amount: money(-payersRemaining, currency) })}
</span>
{/if}
{:else}
<select bind:value={payer} aria-label={t('paid_by_label')}>
{#each members as m}<option value={m.id}>{m.name}{m.id === me ? ` (${t('you')})` : ''}</option>{/each}
</select>
{/if}
</div>
<!-- split -->
<div class="field">
<span class="small muted">{t('split')}</span>
<div class="seg" role="group" aria-label={t('split')}>
{#each [['equal', 'split_equal'], ['shares', 'split_shares'], ['exact', 'split_exact'], ['percent', 'split_percent']] as const as [m, label]}
<button type="button" aria-pressed={mode === m} onclick={() => setMode(m)}>{t(label)}</button>
{/each}
</div>
<div class="row small" style:justify-content="flex-end">
<button type="button" class="btn ghost small" onclick={() => members.forEach((m) => (included[m.id] = true))}>{t('select_all')}</button>
<button type="button" class="btn ghost small" onclick={() => members.forEach((m) => (included[m.id] = false))}>{t('select_none')}</button>
</div>
<div class="list">
{#each members as m (m.id)}
<div class="item">
<input type="checkbox" bind:checked={included[m.id]} aria-label={m.name} />
<Avatar member={m} index={memberIndex(m.id)} size={30} />
<span class="grow">
<span style:display="block">{m.name}</span>
{#if preview[m.id]}<span class="small muted num">{money(preview[m.id], currency)}</span>{/if}
</span>
{#if mode !== 'equal'}
<span class="row" style:gap="4px">
<input class="num" style:width={mode === 'exact' ? '110px' : '72px'} inputmode={mode === 'shares' ? 'numeric' : 'decimal'}
bind:value={values[m.id]} disabled={!included[m.id]} aria-label="{t('split')}: {m.name}" />
{#if mode === 'percent'}<span class="muted">%</span>{/if}
</span>
{/if}
</div>
{/each}
</div>
{#if (mode === 'exact' || mode === 'percent') && remaining !== 0}
<span class="small {remaining < 0 ? 'neg' : 'muted'}">
{#if mode === 'exact'}
{remaining > 0 ? t('remaining', { amount: money(remaining, currency) }) : t('over_by', { amount: money(-remaining, currency) })}
{:else}
{remaining > 0 ? t('remaining', { amount: `${remaining / 100} %` }) : t('over_by', { amount: `${-remaining / 100} %` })}
{/if}
</span>
{/if}
</div>
{/if}
<!-- photo -->
{#if repeat === 'none'}
<div class="field">
<span class="small muted">{t('photo')}</span>
{#if newPhotoUrl}
<img class="photo-thumb" src={newPhotoUrl} alt={t('photo')} />
{:else if photo}
<PhotoView {session} {photo} />
{/if}
<div class="row">
<label class="btn small">
{photo || newPhoto ? t('replace_photo') : t('add_photo')}
<input class="sr-only" type="file" accept="image/*" onchange={pickPhoto} disabled={photoBusy} />
</label>
{#if photo || newPhoto}<button type="button" class="btn small ghost" onclick={removePhoto}>{t('remove_photo')}</button>{/if}
{#if photoBusy}<span class="small muted">{t('processing_photo')}</span>{/if}
</div>
</div>
{/if}
<label class="field">{t('note')}<textarea bind:value={note} maxlength="2000"></textarea></label>
{#if !existing && kind === 'expense'}
<label class="field">{t('repeat')}
<select bind:value={repeat}>
<option value="none">{t('repeat_none')}</option>
<option value="weekly">{t('repeat_weekly')}</option>
<option value="monthly">{t('repeat_monthly')}</option>
<option value="yearly">{t('repeat_yearly')}</option>
</select>
</label>
{/if}
{#if error}<p class="neg" role="alert">{error}</p>{/if}
<div class="row">
<button type="button" class="btn" style:flex="1" onclick={close}>{t('cancel')}</button>
<button type="submit" class="btn primary" style:flex="2" disabled={saving || photoBusy}>{t('save')}</button>
</div>
</form>
</Sheet>

View file

@ -0,0 +1,103 @@
<script lang="ts">
import { inBase } from '@oweme/core';
import { addDays, CATEGORY_ICONS, fmtDate, money, today } from '../lib/format.ts';
import { router } from '../lib/router.svelte.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
let { session }: { session: GroupSession } = $props();
let query = $state('');
const rows = $derived.by(() => {
const q = query.trim().toLowerCase();
const recs = Object.values(session.state.expenses)
.filter((r) => !r.deleted)
.filter((r) => !q || r.expense.title.toLowerCase().includes(q) || r.expense.note.toLowerCase().includes(q))
.sort((a, b) => b.expense.date.localeCompare(a.expense.date) || b.createdAt.localeCompare(a.createdAt));
const groups: { date: string; items: typeof recs }[] = [];
for (const r of recs) {
const last = groups[groups.length - 1];
if (last?.date === r.expense.date) last.items.push(r);
else groups.push({ date: r.expense.date, items: [r] });
}
return groups;
});
const total = $derived(
Object.values(session.state.expenses)
.filter((r) => !r.deleted && r.expense.kind === 'expense')
.reduce((a, r) => a + inBase(r.expense, session.base).total, 0),
);
function dayLabel(d: string) {
if (d === today()) return t('today');
if (d === addDays(today(), -1)) return t('yesterday');
return fmtDate(d, 'long');
}
function mine(e: (typeof rows)[number]['items'][number]['expense']) {
const me = session.me;
if (!me) return null;
const b = inBase(e, session.base);
const net = (b.paid[me] ?? 0) - (b.owed[me] ?? 0);
if (net > 0) return { cls: 'pos', text: t('you_lent', { amount: money(net, session.base) }) };
if (net < 0) return { cls: 'neg', text: t('you_borrowed', { amount: money(-net, session.base) }) };
return { cls: 'muted', text: b.owed[me] ? t('your_share', { amount: money(b.owed[me], session.base) }) : t('not_involved') };
}
function open(e: MouseEvent, id: string) {
e.preventDefault();
router.go(`/g/${session.id}/e/${encodeURIComponent(id)}`);
}
</script>
<div class="stack">
<div class="card row">
<div class="grow">
<div class="muted small">{t('total_spent')}</div>
<div class="num" style:font-size="1.6rem" style:font-weight="700">{money(total, session.base)}</div>
</div>
</div>
{#if Object.keys(session.state.expenses).length > 6}
<input type="search" bind:value={query} placeholder={t('search')} aria-label={t('search')} />
{/if}
{#if rows.length === 0}
<p class="empty">{session.status === 'loading' ? t('loading') : t('no_expenses')}</p>
{/if}
{#each rows as day (day.date)}
<section class="stack" style:gap="6px">
<h3>{dayLabel(day.date)}</h3>
<div class="list">
{#each day.items as r (r.expense.id)}
{@const e = r.expense}
{@const m = mine(e)}
<a class="item" href="/g/{session.id}/e/{encodeURIComponent(e.id)}" onclick={(ev) => open(ev, e.id)}>
<span class="cat-icon" aria-hidden="true">{CATEGORY_ICONS[e.category] ?? '🧾'}</span>
<span class="grow">
<span class="title row" style:gap="6px">
{#if e.kind === 'transfer'}
{t('transfer_line', { from: session.memberName(e.payers[0]?.member), to: session.memberName(e.split.entries.find((x) => x.value > 0)?.member) })}
{:else}
{e.title}
{/if}
{#if e.recurringId}<Icon name="repeat" size={14} />{/if}
{#if e.photo}<Icon name="camera" size={14} />{/if}
</span>
<span class="sub" style:display="block">
{e.payers.length === 1 ? t('paid_by', { name: session.memberName(e.payers[0].member) }) : t('paid_by_many', { n: e.payers.length })}
</span>
</span>
<span class="end">
<span class="num" style:display="block" style:font-weight="600">{money(e.amount, e.currency)}</span>
{#if m}<span class="small num {m.cls}" style:display="block">{m.text}</span>{/if}
</span>
</a>
{/each}
</div>
</section>
{/each}
</div>

View file

@ -0,0 +1,132 @@
<script lang="ts">
import { onDestroy, untrack } from 'svelte';
import { forgetGroup } from '../lib/idb.ts';
import { router } from '../lib/router.svelte.ts';
import { closeSession, openSession, type GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Activity from './Activity.svelte';
import Balances from './Balances.svelte';
import ExpenseDetail from './ExpenseDetail.svelte';
import ExpenseEditor from './ExpenseEditor.svelte';
import ExpenseList from './ExpenseList.svelte';
import GroupSettings from './GroupSettings.svelte';
import Icon from './Icon.svelte';
import IdentityPicker from './IdentityPicker.svelte';
import Stats from './Stats.svelte';
// Keyed by group id in App.svelte, so reading it once is enough.
const props: { id: string } = $props();
const id = untrack(() => props.id);
let session = $state<GroupSession | null | undefined>(undefined);
let skippedIdentity = $state(false);
openSession(id).then((s) => (session = s));
onDestroy(() => closeSession(id));
const route = $derived(router.route);
const tab = $derived(route.name === 'group' ? route.tab : 'expenses');
const base = `/g/${id}`;
const tabs = [
{ key: 'expenses', path: base, icon: 'list', label: 'expenses' },
{ key: 'balances', path: `${base}/balances`, icon: 'scale', label: 'balances' },
{ key: 'stats', path: `${base}/stats`, icon: 'chart', label: 'stats' },
{ key: 'activity', path: `${base}/activity`, icon: 'clock', label: 'activity' },
] as const;
function nav(e: MouseEvent, path: string, replace = false) {
e.preventDefault();
router.go(path, { replace });
}
const needsIdentity = $derived(
!!session && session.status !== 'loading' && session.state.members.length > 0 && !session.me && !skippedIdentity,
);
async function remove() {
await forgetGroup(id);
router.go('/', { replace: true });
}
</script>
{#if session === undefined}
<main class="page"><p class="empty">{t('loading')}</p></main>
{:else if session === null}
<header class="topbar">
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1>{t('app_name')}</h1>
</header>
<main class="page"><p class="card">{t('group_not_on_device')}</p></main>
{:else if route.name === 'group-settings'}
<GroupSettings {session} />
{:else}
{@const s = session}
<header class="topbar">
<button class="icon-btn" onclick={() => router.go('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1><span aria-hidden="true">{s.state.group?.icon}</span> {s.state.group?.name ?? s.local.name}</h1>
<a class="icon-btn" href="{base}/settings" onclick={(e) => nav(e, `${base}/settings`)} aria-label={t('group_settings')}><Icon name="settings" /></a>
</header>
<main class="page wide stack">
{#if s.status === 'gone'}
<div class="banner danger stack">
<p>{t('not_found_group')}</p>
<button class="btn small danger" onclick={remove}>{t('remove_from_device')}</button>
</div>
{:else if s.status === 'offline'}
<p class="banner">{t('offline')}</p>
{/if}
{#if s.pending.length && s.status !== 'online'}
<p class="muted small">{t('pending', { n: s.pending.length })}</p>
{/if}
{#if s.rollback}<p class="banner warn">{t('rollback_warning')}</p>{/if}
<nav class="tabbar" aria-label={s.state.group?.name}>
{#each tabs as tb}
<a href={tb.path} aria-current={tab === tb.key ? 'page' : undefined} onclick={(e) => nav(e, tb.path, true)}>
<Icon name={tb.icon} size={20} />
{t(tb.label)}
</a>
{/each}
</nav>
<div class="layout" class:with-side={tab === 'expenses'}>
<div class="main-col">
{#if tab === 'expenses'}
<ExpenseList session={s} />
{:else if tab === 'balances'}
<Balances session={s} />
{:else if tab === 'stats'}
<Stats session={s} />
{:else}
<Activity session={s} />
{/if}
</div>
{#if tab === 'expenses'}
<aside class="side-col"><Balances session={s} compact /></aside>
{/if}
</div>
</main>
{#if s.status !== 'gone' && (tab === 'expenses' || tab === 'balances')}
<a class="fab" href="{base}/e/new" onclick={(e) => nav(e, `${base}/e/new`)} aria-label={t('add_expense')}><Icon name="plus" size={28} /></a>
{/if}
{#if route.name === 'expense'}
<ExpenseDetail session={s} eid={route.eid} />
{:else if route.name === 'expense-edit'}
{#key route.eid}
<ExpenseEditor session={s} eid={route.eid} params={route.params} />
{/key}
{:else if needsIdentity}
<IdentityPicker session={s} onskip={() => (skippedIdentity = true)} />
{/if}
{/if}
<style>
.layout { display: grid; gap: 24px; }
.side-col { display: none; }
@media (min-width: 960px) {
.layout.with-side { grid-template-columns: minmax(0, 1fr) 340px; }
.side-col { display: block; position: sticky; top: 80px; align-self: start; }
}
</style>

View file

@ -0,0 +1,257 @@
<script lang="ts">
import { untrack } from 'svelte';
import { balancesCsv, expensesCsv, nextOccurrence } from '@oweme/core';
import { renderSVG } from 'uqr';
import { api } from '../lib/api.ts';
import { makeBackup } from '../lib/backup.ts';
import { randomId } from '../lib/crypto.ts';
import { download, fmtDate, MEMBER_COLORS, money, slug, today } from '../lib/format.ts';
import { forgetGroup } from '../lib/idb.ts';
import { disablePush, enablePush, pushSupport, type PushSupport } from '../lib/push.ts';
import { router } from '../lib/router.svelte.ts';
import { closeSession, type GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import { ui } from '../lib/ui.svelte.ts';
import Avatar from './Avatar.svelte';
import CurrencySelect from './CurrencySelect.svelte';
import Icon from './Icon.svelte';
const props: { session: GroupSession } = $props();
const s = untrack(() => props.session);
const justCreated = new URLSearchParams(location.search).has('share');
const link = `${location.origin}/g/${s.id}#${s.local.secret}`;
let showQr = $state(justCreated);
const qr = renderSVG(link, { border: 2, whiteColor: '#ffffff', blackColor: '#0B2E22' });
let name = $state(s.state.group?.name ?? '');
let icon = $state(s.state.group?.icon ?? '');
let baseCurrency = $state(s.base);
let newMember = $state('');
let deleteConfirm = $state('');
let push = $state<PushSupport | null>(null);
let pushBusy = $state(false);
pushSupport().then((p) => (push = p));
const locked = $derived(Object.keys(s.state.expenses).length > 0);
const dirty = $derived(name.trim() !== s.state.group?.name || icon !== s.state.group?.icon || baseCurrency !== s.base);
async function copy() {
await navigator.clipboard.writeText(link);
ui.show(t('copied'));
}
async function nativeShare() {
try {
await navigator.share({ title: s.state.group?.name, url: link });
} catch { /* cancelled */ }
}
async function saveGroup(e: SubmitEvent) {
e.preventDefault();
if (!name.trim()) return;
const data: { name?: string; icon?: string; baseCurrency?: string } = {};
if (name.trim() !== s.state.group?.name) data.name = name.trim();
if (icon !== s.state.group?.icon) data.icon = icon;
if (!locked && baseCurrency !== s.base) data.baseCurrency = baseCurrency;
await s.emit({ type: 'group.updated', data });
ui.show(t('saved'));
}
async function addMember(e: SubmitEvent) {
e.preventDefault();
const n = newMember.trim();
if (!n) return;
newMember = '';
await s.emit({ type: 'member.added', data: { id: randomId(9), name: n, color: MEMBER_COLORS[s.state.members.length % MEMBER_COLORS.length] } });
}
async function rename(id: string, old: string) {
const n = prompt(t('rename'), old)?.trim();
if (n && n !== old) await s.emit({ type: 'member.updated', data: { id, name: n.slice(0, 60) } });
}
async function togglePush() {
pushBusy = true;
try {
if (s.local.push) await disablePush(s);
else if (!(await enablePush(s))) push = await pushSupport();
} catch (e) {
ui.show(t('error_generic', { msg: (e as Error).message }), 4000);
} finally {
pushBusy = false;
}
}
const fileBase = () => `oweme-${slug(s.state.group?.name ?? 'group')}-${today()}`;
async function backup() {
download(`${fileBase()}.json`, await makeBackup(s), 'application/json');
}
async function removeFromDevice() {
if (s.local.push) await disablePush(s).catch(() => {});
closeSession(s.id);
await forgetGroup(s.id);
router.go('/', { replace: true });
}
async function deleteGroup() {
if (deleteConfirm.trim() !== s.state.group?.name) return;
await api.deleteGroup(s.id, s.keys.authToken);
closeSession(s.id);
await forgetGroup(s.id);
router.go('/', { replace: true });
}
</script>
<header class="topbar">
<button class="icon-btn" onclick={() => (justCreated ? router.go(`/g/${s.id}`, { replace: true }) : router.back(`/g/${s.id}`))} aria-label={t('back')}><Icon name="back" /></button>
<h1>{t('group_settings')}</h1>
</header>
<main class="page stack">
<!-- share -->
<section class="section">
<h3>{t('share_group')}</h3>
<div class="card stack">
{#if justCreated}<p class="banner warn">{t('save_link_warning')}</p>{/if}
<p class="small muted">{t('share_intro')}</p>
<div class="row wrap">
<button class="btn primary" onclick={copy}><Icon name="copy" size={18} /> {t('copy_link')}</button>
{#if 'share' in navigator}<button class="btn" onclick={nativeShare}><Icon name="share" size={18} /> {t('share')}</button>{/if}
<button class="btn ghost" onclick={() => (showQr = !showQr)}>QR</button>
</div>
{#if showQr}
<div class="qr">{@html qr}</div>
{/if}
</div>
</section>
<!-- group -->
<section class="section">
<h3>{t('group_settings')}</h3>
<form class="card stack" onsubmit={saveGroup}>
<div class="row">
<label class="field" style:width="80px">{t('icon')}<input bind:value={icon} maxlength="8" /></label>
<label class="field" style:flex="1">{t('group_name')}<input bind:value={name} maxlength="100" required /></label>
</div>
<label class="field">
{t('base_currency')}
<CurrencySelect bind:value={baseCurrency} disabled={locked} />
<span class="small">{locked ? t('base_currency_locked') : t('base_currency_hint')}</span>
</label>
<button class="btn primary" type="submit" disabled={!dirty || !name.trim()}>{t('save')}</button>
</form>
</section>
<!-- identity -->
<section class="section">
<h3>{t('identity')}</h3>
<select value={s.me ?? ''} onchange={(e) => s.setMe((e.target as HTMLSelectElement).value || null)} aria-label={t('identity')}>
<option value="">{t('not_set')}</option>
{#each s.state.members.filter((m) => !m.archived) as m}<option value={m.id}>{m.name}</option>{/each}
</select>
</section>
<!-- members -->
<section class="section">
<h3>{t('members')}</h3>
<div class="list">
{#each s.state.members as m, i (m.id)}
{@const bal = s.balances[m.id] ?? 0}
<div class="item">
<Avatar member={m} index={i} size={32} />
<span class="grow">
<span class="title" style:display="block">{m.name}{m.archived ? ` · ${t('archived')}` : ''}</span>
<span class="sub num {bal > 0 ? 'pos' : bal < 0 ? 'neg' : ''}">{bal === 0 ? t('settled') : money(bal, s.base, { sign: true })}</span>
</span>
<button class="btn small ghost" onclick={() => rename(m.id, m.name)}>{t('rename')}</button>
{#if m.archived}
<button class="btn small ghost" onclick={() => s.emit({ type: 'member.restored', data: { id: m.id } })}>{t('unarchive')}</button>
{:else}
<button class="btn small ghost" disabled={bal !== 0} title={bal !== 0 ? t('archive_needs_zero') : ''}
onclick={() => s.emit({ type: 'member.archived', data: { id: m.id } })}>{t('archive')}</button>
{/if}
</div>
{/each}
</div>
<form class="row" onsubmit={addMember}>
<input bind:value={newMember} placeholder={t('member_name')} maxlength="60" aria-label={t('member_name')} />
<button class="btn" type="submit" disabled={!newMember.trim()}><Icon name="plus" size={18} /> {t('add_member')}</button>
</form>
</section>
<!-- notifications -->
<section class="section">
<h3>{t('notifications')}</h3>
<div class="card stack">
{#if push === 'ok' || s.local.push}
<label class="row">
<input type="checkbox" checked={s.local.push} disabled={pushBusy} onchange={togglePush} />
<span>{t('notifications_hint')}</span>
</label>
{:else if push === 'needs-install'}
<p class="small">{t('notifications_ios')}</p>
{:else if push === 'denied'}
<p class="small">{t('notifications_denied')}</p>
{:else if push}
<p class="small muted">{t('notifications_unavailable')}</p>
{/if}
</div>
</section>
<!-- recurring -->
<section class="section">
<h3>{t('recurring')}</h3>
{#if Object.keys(s.state.recurring).length === 0}
<p class="card small muted">{t('no_recurring')}</p>
{:else}
<div class="list">
{#each Object.values(s.state.recurring) as r (r.id)}
{@const next = nextOccurrence(r.rule, today())}
<div class="item">
<Icon name="repeat" size={18} />
<span class="grow">
<span class="title" style:display="block">{r.template.title} · <span class="num">{money(r.template.amount, r.template.currency)}</span></span>
<span class="sub">{t(`repeat_${r.rule.freq}`)}{next ? ` · ${t('next_on', { date: fmtDate(next) })}` : ''}</span>
</span>
<button class="btn small ghost" onclick={() => s.emit({ type: 'recurring.deleted', data: { id: r.id } })}>{t('stop')}</button>
</div>
{/each}
</div>
{/if}
</section>
<!-- export -->
<section class="section">
<h3>{t('export')}</h3>
<div class="row wrap">
<button class="btn" onclick={() => download(`${fileBase()}-expenses.csv`, '' + expensesCsv(s.state), 'text/csv')}>{t('export_expenses')}</button>
<button class="btn" onclick={() => download(`${fileBase()}-balances.csv`, '' + balancesCsv(s.state), 'text/csv')}>{t('export_balances')}</button>
<button class="btn" onclick={backup}>{t('backup')}</button>
</div>
<p class="small muted">{t('backup_hint')}</p>
</section>
<!-- danger -->
<section class="section">
<h3>{t('danger_zone')}</h3>
<div class="card stack">
<p class="small muted">{t('remove_from_device_hint')}</p>
<button class="btn" onclick={removeFromDevice}>{t('remove_from_device')}</button>
</div>
<div class="card stack">
<p class="small muted">{t('delete_group_hint')}</p>
<input bind:value={deleteConfirm} placeholder={s.state.group?.name} aria-label={t('group_name')} />
<button class="btn danger" disabled={deleteConfirm.trim() !== s.state.group?.name} onclick={deleteGroup}>
<Icon name="trash" size={18} /> {t('delete_group')}
</button>
</div>
</section>
</main>
<style>
.qr { width: min(260px, 100%); margin: 0 auto; background: #fff; border-radius: 12px; padding: 8px; }
.qr :global(svg) { width: 100%; height: auto; display: block; }
</style>

View file

@ -0,0 +1,95 @@
<script lang="ts">
import { getAll, type LocalGroup } from '../lib/idb.ts';
import { isGroupId, isGroupSecret } from '../lib/crypto.ts';
import { money } from '../lib/format.ts';
import { router } from '../lib/router.svelte.ts';
import { addGroup } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Icon from './Icon.svelte';
let groups = $state<LocalGroup[] | null>(null);
let link = $state('');
let linkError = $state(false);
let showLink = $state(false);
getAll<LocalGroup>('groups').then((g) => (groups = g.sort((a, b) => b.lastOpened - a.lastOpened)));
async function openLink(e: SubmitEvent) {
e.preventDefault();
const m = /\/g\/([A-Za-z0-9_-]{22})#([A-Za-z0-9_-]{43})\s*$/.exec(link.trim());
if (!m || !isGroupId(m[1]) || !isGroupSecret(m[2])) {
linkError = true;
return;
}
await addGroup(m[1], m[2]);
router.go(`/g/${m[1]}`);
}
function nav(e: MouseEvent, path: string) {
e.preventDefault();
router.go(path);
}
</script>
<header class="topbar">
<h1><span aria-hidden="true">💸</span> {t('app_name')}</h1>
<a class="icon-btn" href="/settings" onclick={(e) => nav(e, '/settings')} aria-label={t('settings')}><Icon name="settings" /></a>
</header>
<main class="page stack">
<p class="muted">{t('tagline')}</p>
<div class="section">
<h3>{t('your_groups')}</h3>
{#if groups === null}
<p class="muted">{t('loading')}</p>
{:else if groups.length === 0}
<p class="card muted">{t('no_groups')}</p>
{:else}
<div class="list">
{#each groups as g (g.id)}
<a class="item" href="/g/{g.id}" onclick={(e) => nav(e, `/g/${g.id}`)}>
<span class="cat-icon" aria-hidden="true">{g.icon || '👥'}</span>
<span class="grow">
<span class="title" style:display="block">{g.name || '…'}</span>
<span class="sub" style:display="block">
{#if g.gone}
{t('group_gone')}
{:else if g.myBalance === null}
{t('pick_identity_hint')}
{:else if g.myBalance > 0}
<span class="pos">{t('you_are_owed', { amount: money(g.myBalance, g.baseCurrency) })}</span>
{:else if g.myBalance < 0}
<span class="neg">{t('you_owe', { amount: money(-g.myBalance, g.baseCurrency) })}</span>
{:else}
{t('settled')}
{/if}
</span>
</span>
</a>
{/each}
</div>
{/if}
</div>
<div class="section">
<a class="btn primary block" href="/new" onclick={(e) => nav(e, '/new')}><Icon name="plus" /> {t('new_group')}</a>
{#if showLink}
<form class="stack card" onsubmit={openLink}>
<label class="field">
{t('paste_link')}
<input bind:value={link} oninput={() => (linkError = false)} placeholder="https://…/g/…#…" autocomplete="off" spellcheck="false" />
</label>
{#if linkError}<p class="neg small" role="alert">{t('invalid_link')}</p>{/if}
<button class="btn" type="submit">{t('open')}</button>
</form>
{:else}
<button class="btn block" onclick={() => (showLink = true)}><Icon name="link" /> {t('open_link')}</button>
{/if}
<a class="btn ghost block" href="/restore" onclick={(e) => nav(e, '/restore')}><Icon name="upload" /> {t('restore_backup')}</a>
</div>
<p class="muted small row" style:align-items="flex-start" style:margin-top="24px">
<Icon name="lock" size={16} /> <span>{t('e2e_note')}</span>
</p>
</main>

View file

@ -0,0 +1,29 @@
<script lang="ts">
// Inline SVG icons (no icon font: keeps the CSP strict and works offline).
const paths = {
plus: 'M12 5v14M5 12h14',
back: 'M15 18l-6-6 6-6',
close: 'M18 6L6 18M6 6l12 12',
settings: 'M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z',
share: 'M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8M16 6l-4-4-4 4M12 2v13',
camera: 'M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2zM12 17a4 4 0 1 0 0-8 4 4 0 0 0 0 8z',
list: 'M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01',
scale: 'M12 3v18M5 7h14M5 7l-3 7a4 4 0 0 0 6 0L5 7zM19 7l-3 7a4 4 0 0 0 6 0l-3-7z',
chart: 'M3 3v18h18M8 17V11M13 17V7M18 17v-4',
clock: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20zM12 6v6l4 2',
trash: 'M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6',
edit: 'M12 20h9M16.5 3.5a2.1 2.1 0 1 1 3 3L7 19l-4 1 1-4z',
copy: 'M9 9h11v11H9zM5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1',
lock: 'M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4',
repeat: 'M17 1l4 4-4 4M3 11V9a4 4 0 0 1 4-4h14M7 23l-3-4 3-4M21 13v2a4 4 0 0 1-4 4H3',
undo: 'M3 7v6h6M21 17a9 9 0 0 0-15-6.7L3 13',
link: 'M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7',
upload: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12',
} as const;
let { name, size = 22 }: { name: keyof typeof paths; size?: number } = $props();
</script>
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d={paths[name]} />
</svg>

View file

@ -0,0 +1,50 @@
<script lang="ts">
import { randomId } from '../lib/crypto.ts';
import { MEMBER_COLORS } from '../lib/format.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import Avatar from './Avatar.svelte';
import Sheet from './Sheet.svelte';
let { session, onskip }: { session: GroupSession; onskip: () => void } = $props();
let newName = $state('');
let adding = $state(false);
const members = $derived(session.state.members.filter((m) => !m.archived));
async function pick(id: string) {
await session.setMe(id);
}
async function addMe(e: SubmitEvent) {
e.preventDefault();
const name = newName.trim();
if (!name) return;
const id = randomId(9);
await session.emit({ type: 'member.added', data: { id, name, color: MEMBER_COLORS[session.state.members.length % MEMBER_COLORS.length] } });
await session.setMe(id);
}
</script>
<Sheet title={t('who_are_you')} onclose={onskip}>
<div class="stack">
<p class="muted">{t('who_are_you_hint')}</p>
<div class="list">
{#each members as m, i (m.id)}
<button class="item" onclick={() => pick(m.id)}>
<Avatar member={m} index={i} />
<span class="grow title">{m.name}</span>
</button>
{/each}
</div>
{#if adding}
<form class="row" onsubmit={addMe}>
<input bind:value={newName} placeholder={t('your_name')} maxlength="60" aria-label={t('your_name')} />
<button class="btn primary" type="submit" disabled={!newName.trim()}>{t('save')}</button>
</form>
{:else}
<button class="btn" onclick={() => (adding = true)}>{t('im_new')}</button>
{/if}
<button class="btn ghost" onclick={onskip}>{t('just_looking')}</button>
</div>
</Sheet>

View file

@ -0,0 +1,105 @@
<script lang="ts">
import type { EventBody } from '@oweme/core';
import { api } from '../lib/api.ts';
import { deriveKeys, randomId, sha256hex } from '../lib/crypto.ts';
import { MEMBER_COLORS } from '../lib/format.ts';
import { router } from '../lib/router.svelte.ts';
import { addGroup, openSession } from '../lib/session.svelte.ts';
import { settings, t } from '../lib/settings.svelte.ts';
import CurrencySelect from './CurrencySelect.svelte';
import Icon from './Icon.svelte';
const ICONS = ['👥', '🏔️', '🏖️', '🏠', '🍻', '🚗', '🎉', '⛺', '🎿', '✈️', '🍕', '💼'];
let name = $state('');
let icon = $state(ICONS[0]);
let currency = $state(settings.lang === 'cs' ? 'CZK' : 'EUR');
let me = $state('');
let others = $state<string[]>(['']);
let busy = $state(false);
let error = $state('');
async function create(e: SubmitEvent) {
e.preventDefault();
if (!name.trim() || !me.trim()) return;
busy = true;
error = '';
try {
const id = randomId(16);
const secret = randomId(32);
const keys = await deriveKeys(secret);
await api.createGroup(id, await sha256hex(keys.authToken));
const meId = randomId(9);
await addGroup(id, secret, { name: name.trim(), icon, baseCurrency: currency, me: meId });
const s = await openSession(id);
if (!s) throw new Error('could not open group');
const names = [me, ...others].map((n) => n.trim()).filter(Boolean);
const events: EventBody[] = [
{ type: 'group.created', data: { name: name.trim(), baseCurrency: currency, icon } },
...names.map((n, i) => ({
type: 'member.added' as const,
data: { id: i === 0 ? meId : randomId(9), name: n.slice(0, 60), color: MEMBER_COLORS[i % MEMBER_COLORS.length] },
})),
];
await s.emit(...events);
router.go(`/g/${id}/settings?share=1`, { replace: true });
} catch (err) {
error = t('error_generic', { msg: (err as Error).message });
busy = false;
}
}
</script>
<header class="topbar">
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1>{t('new_group')}</h1>
</header>
<main class="page">
<form class="stack" onsubmit={create}>
<label class="field">
{t('group_name')}
<input bind:value={name} placeholder={t('group_name_ph')} maxlength="100" required />
</label>
<div class="field">
<span class="small muted">{t('icon')}</span>
<div class="chips">
{#each ICONS as i}
<button type="button" class="chip" aria-pressed={icon === i} onclick={() => (icon = i)}>{i}</button>
{/each}
</div>
</div>
<label class="field">
{t('base_currency')}
<CurrencySelect bind:value={currency} />
<span class="small">{t('base_currency_hint')}</span>
</label>
<label class="field">
{t('your_name')}
<input bind:value={me} maxlength="60" required autocomplete="given-name" />
</label>
<div class="field">
<span class="small muted">{t('other_members')}</span>
{#each others as _, i}
<div class="row">
<input bind:value={others[i]} placeholder={t('member_name')} maxlength="60" aria-label={t('member_name')} />
{#if others.length > 1}
<button type="button" class="icon-btn" onclick={() => others.splice(i, 1)} aria-label={t('delete')}><Icon name="close" /></button>
{/if}
</div>
{/each}
<button type="button" class="btn small ghost" style:align-self="flex-start" onclick={() => others.push('')}>
<Icon name="plus" size={18} /> {t('add_member')}
</button>
</div>
{#if error}<p class="neg" role="alert">{error}</p>{/if}
<button class="btn primary block" type="submit" disabled={busy || !name.trim() || !me.trim()}>
{busy ? t('creating') : t('create_group')}
</button>
</form>
</main>

View file

@ -0,0 +1,50 @@
<script lang="ts">
import type { Photo } from '@oweme/core';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
let { session, photo }: { session: GroupSession; photo: Photo } = $props();
let thumb = $state<string | null>(null);
let full = $state<string | null>(null);
let failed = $state(false);
let open = $state(false);
let dialog = $state<HTMLDialogElement>();
$effect(() => {
const p = photo;
thumb = null;
session.blobUrl(p.thumbBlobId).then((u) => (thumb = u)).catch(() => (failed = true));
});
async function show() {
open = true;
full ??= await session.blobUrl(photo.blobId).catch(() => null);
}
$effect(() => {
if (open) dialog?.showModal();
});
</script>
{#if failed}
<p class="small muted">📷 …</p>
{:else}
<button type="button" class="thumb-btn" onclick={show} aria-label={t('photo')}>
{#if thumb}<img class="photo-thumb" src={thumb} alt={t('photo')} style:aspect-ratio="{photo.w} / {photo.h}" />
{:else}<span class="photo-thumb placeholder" style:aspect-ratio="{photo.w} / {photo.h}"></span>{/if}
</button>
{/if}
{#if open}
<dialog class="viewer" bind:this={dialog} onclose={() => (open = false)} onclick={() => dialog?.close()}>
<img src={full ?? thumb ?? ''} alt={t('photo')} />
</dialog>
{/if}
<style>
.thumb-btn { padding: 0; border: 0; background: none; width: 100%; display: block; cursor: zoom-in; }
.placeholder { display: block; max-height: 240px; }
.viewer { padding: 0; border: 0; background: transparent; max-width: 100vw; max-height: 100dvh; }
.viewer::backdrop { background: rgb(0 0 0 / 0.9); }
.viewer img { max-width: 100vw; max-height: 100dvh; object-fit: contain; display: block; }
</style>

View file

@ -0,0 +1,40 @@
<script lang="ts">
import { restoreBackup } from '../lib/backup.ts';
import { router } from '../lib/router.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
import { ui } from '../lib/ui.svelte.ts';
import Icon from './Icon.svelte';
let busy = $state(false);
let error = $state('');
async function pick(e: Event) {
const file = (e.target as HTMLInputElement).files?.[0];
if (!file) return;
busy = true;
error = '';
try {
const { id, existed } = await restoreBackup(await file.text());
if (existed) ui.show(t('restore_exists'), 4000);
router.go(`/g/${id}`, { replace: true });
} catch (err) {
error = (err as Error).message === 'bad file' ? t('restore_bad_file') : t('error_generic', { msg: (err as Error).message });
} finally {
busy = false;
}
}
</script>
<header class="topbar">
<button class="icon-btn" onclick={() => router.back('/')} aria-label={t('back')}><Icon name="back" /></button>
<h1>{t('restore_title')}</h1>
</header>
<main class="page stack">
<label class="field">
{t('restore_pick')}
<input type="file" accept="application/json,.json" onchange={pick} disabled={busy} />
</label>
{#if busy}<p class="muted">{t('restoring')}</p>{/if}
{#if error}<p class="neg" role="alert">{error}</p>{/if}
</main>

View file

@ -0,0 +1,32 @@
<script lang="ts">
// Modal sheet: full screen on phones, a centered dialog on desktop.
// Uses <dialog> for focus trapping and Escape handling.
import type { Snippet } from 'svelte';
import Icon from './Icon.svelte';
import { t } from '../lib/settings.svelte.ts';
let { title, onclose, children, actions }: { title: string; onclose: () => void; children: Snippet; actions?: Snippet } = $props();
let dialog: HTMLDialogElement;
$effect(() => {
dialog.showModal();
return () => dialog.close();
});
</script>
<dialog
class="sheet"
bind:this={dialog}
aria-label={title}
oncancel={(e) => { e.preventDefault(); onclose(); }}
onclick={(e) => { if (e.target === dialog) onclose(); }}
>
<header class="topbar">
<button class="icon-btn" onclick={onclose} aria-label={t('close')}><Icon name="close" /></button>
<h1>{title}</h1>
{@render actions?.()}
</header>
<div class="sheet-body">
{@render children()}
</div>
</dialog>

View file

@ -0,0 +1,143 @@
<script lang="ts">
import { computeStats } from '@oweme/core';
import { addDays, CATEGORY_ICONS, fmtMonth, money, today } from '../lib/format.ts';
import type { MsgKey } from '../lib/i18n.ts';
import type { GroupSession } from '../lib/session.svelte.ts';
import { t } from '../lib/settings.svelte.ts';
let { session }: { session: GroupSession } = $props();
type Range = 'all' | 'month' | '30' | 'year';
let range = $state<Range>('all');
let hoverMonth = $state<string | null>(null);
const bounds = $derived.by((): [string | null, string | null] => {
const d = today();
if (range === 'month') return [`${d.slice(0, 7)}-01`, d];
if (range === '30') return [addDays(d, -29), d];
if (range === 'year') return [`${d.slice(0, 4)}-01-01`, d];
return [null, null];
});
const st = $derived(computeStats(session.state, bounds[0], bounds[1]));
const base = $derived(session.base);
const maxCat = $derived(Math.max(1, ...st.byCategory.map((c) => c.amount)));
const maxMonth = $derived(Math.max(1, ...st.byMonth.map((m) => m.amount)));
const peakMonth = $derived(st.byMonth.reduce((a, m) => (m.amount > (a?.amount ?? -1) ? m : a), null as null | { month: string; amount: number }));
const shownMonth = $derived(st.byMonth.find((m) => m.month === hoverMonth) ?? peakMonth);
const members = $derived(st.perMember.filter((p) => p.paid || p.consumed));
const maxMember = $derived(Math.max(1, ...members.flatMap((p) => [p.paid, p.consumed])));
const mine = $derived(st.perMember.find((p) => p.member === session.me));
// Label every month on short ranges, fewer on long ones, so labels never collide.
const labelEvery = $derived(Math.ceil(st.byMonth.length / 8));
</script>
<div class="stack">
<div class="seg" role="group" aria-label={t('stats')}>
{#each [['all', 'range_all'], ['year', 'range_year'], ['month', 'range_month'], ['30', 'range_30']] as const as [r, label]}
<button aria-pressed={range === r} onclick={() => (range = r)}>{t(label)}</button>
{/each}
</div>
<div class="tiles">
<div class="card">
<div class="muted small">{t('total_spent')}</div>
<div class="hero num">{money(st.total, base)}</div>
</div>
{#if mine}
<div class="card">
<div class="muted small">{t('my_spending')}</div>
<div class="hero num">{money(mine.consumed, base)}</div>
</div>
{/if}
</div>
{#if st.total === 0}
<p class="empty">{t('no_data')}</p>
{:else}
<section class="card stack">
<h2>{t('by_category')}</h2>
<ul class="bars">
{#each st.byCategory as c (c.category)}
<li title="{t(`cat_${c.category}` as MsgKey)}: {money(c.amount, base)}">
<span class="label"><span aria-hidden="true">{CATEGORY_ICONS[c.category]}</span> {t(`cat_${c.category}` as MsgKey)}</span>
<span class="track"><span class="hbar s1" style:width="{(c.amount / maxCat) * 100}%"></span></span>
<span class="value num">{money(c.amount, base)}</span>
</li>
{/each}
</ul>
</section>
{#if st.byMonth.length > 1}
<section class="card stack">
<div class="row">
<h2 class="grow" style:flex="1">{t('by_month')}</h2>
{#if shownMonth}<span class="small num" aria-live="polite">{fmtMonth(shownMonth.month)}: <strong>{money(shownMonth.amount, base)}</strong></span>{/if}
</div>
<div class="months">
{#each st.byMonth as m, i (m.month)}
<button
type="button" class="month"
aria-label="{fmtMonth(m.month)}: {money(m.amount, base)}"
onmouseenter={() => (hoverMonth = m.month)} onmouseleave={() => (hoverMonth = null)}
onfocus={() => (hoverMonth = m.month)} onblur={() => (hoverMonth = null)}
>
<span class="col"><span class="vbar s1" class:active={shownMonth?.month === m.month} style:height="{(m.amount / maxMonth) * 100}%"></span></span>
<span class="mlabel small muted">{i % labelEvery === 0 ? fmtMonth(m.month) : ''}</span>
</button>
{/each}
</div>
</section>
{/if}
{#if members.length}
<section class="card stack">
<h2>{t('per_member')}</h2>
<div class="legend small muted row">
<span class="row" style:gap="6px"><span class="swatch s1"></span>{t('legend_paid')}</span>
<span class="row" style:gap="6px"><span class="swatch s2"></span>{t('legend_share')}</span>
</div>
<ul class="bars grouped">
{#each members as p (p.member)}
<li>
<span class="label">{session.memberName(p.member)}</span>
<span class="pair">
<span class="line" title="{t('legend_paid')}: {money(p.paid, base)}">
<span class="track"><span class="hbar s1" style:width="{(p.paid / maxMember) * 100}%"></span></span>
<span class="value num">{money(p.paid, base)}</span>
</span>
<span class="line" title="{t('legend_share')}: {money(p.consumed, base)}">
<span class="track"><span class="hbar s2" style:width="{(p.consumed / maxMember) * 100}%"></span></span>
<span class="value num">{money(p.consumed, base)}</span>
</span>
</span>
</li>
{/each}
</ul>
</section>
{/if}
{/if}
</div>
<style>
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; }
.hero { font-size: 1.6rem; font-weight: 700; }
.s1 { background: var(--chart-1); }
.s2 { background: var(--chart-2); }
.bars { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.bars li { display: grid; grid-template-columns: minmax(90px, 34%) 1fr auto; align-items: center; gap: 10px; }
.label { font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.track { display: block; height: 12px; }
.hbar { display: block; height: 100%; min-width: 2px; border-radius: 0 4px 4px 0; }
.value { font-size: 0.85rem; color: var(--text); text-align: right; }
.grouped li { grid-template-columns: minmax(70px, 28%) 1fr; }
.pair { display: flex; flex-direction: column; gap: 2px; }
.line { display: grid; grid-template-columns: 1fr auto; gap: 10px; align-items: center; }
.legend { gap: 16px; }
.swatch { width: 12px; height: 12px; border-radius: 3px; display: inline-block; }
.months { display: flex; align-items: stretch; gap: 2px; height: 160px; }
.month { flex: 1; display: flex; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: default; flex-direction: column; min-width: 0; outline-offset: 2px; }
.month:focus-visible { outline: 2px solid var(--accent); border-radius: 4px; }
.col { flex: 1; display: flex; align-items: flex-end; border-bottom: 1px solid var(--border); }
.vbar { display: block; width: 100%; max-width: 28px; margin: 0 auto; min-height: 2px; border-radius: 4px 4px 0 0; opacity: 0.85; }
.vbar.active { opacity: 1; }
.mlabel { text-align: center; white-space: nowrap; overflow: visible; height: 1.4em; font-size: 0.7rem; }
</style>

90
apps/web/src/lib/api.ts Normal file
View file

@ -0,0 +1,90 @@
// Thin wrappers around the server API (SPEC.md §8.1).
import type { StoredEvent } from './idb.ts';
export class ApiError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
/** True for errors that mean "try again later" rather than "this is wrong". */
export const isOffline = (e: unknown) => !(e instanceof ApiError) || e.status >= 500 || e.status === 429;
async function req<T>(method: string, path: string, opts: { token?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal } = {}): Promise<T> {
const headers: Record<string, string> = {};
if (opts.token) headers.Authorization = `Bearer ${opts.token}`;
if (opts.json !== undefined) headers['Content-Type'] = 'application/json';
const res = await fetch(path, {
method,
headers,
body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body,
signal: opts.signal,
cache: 'no-store',
});
if (!res.ok) {
let msg = res.statusText;
try {
msg = (await res.json()).error ?? msg;
} catch { /* not JSON */ }
throw new ApiError(res.status, msg);
}
const type = res.headers.get('content-type') ?? '';
return (type.includes('application/json') ? res.json() : res.arrayBuffer()) as Promise<T>;
}
export interface ServerConfig {
vapidPublicKey: string | null;
maxPhotoBytes: number;
maxGroupBytes: number;
}
let configP: Promise<ServerConfig> | null = null;
export function serverConfig(): Promise<ServerConfig> {
configP ??= req<ServerConfig>('GET', '/api/config').catch((e) => {
configP = null;
throw e;
});
return configP;
}
export const api = {
createGroup: (id: string, authHash: string) => req('POST', '/api/groups', { json: { id, authHash } }),
deleteGroup: (id: string, token: string) => req('DELETE', `/api/groups/${id}`, { token }),
events: (id: string, token: string, after: number) =>
req<{ events: Omit<StoredEvent, 'g'>[]; latest: number }>('GET', `/api/groups/${id}/events?after=${after}&limit=500`, { token }),
append: (id: string, token: string, events: Omit<StoredEvent, 'g' | 'seq'>[]) =>
req<{ seqs: number[] }>('POST', `/api/groups/${id}/events`, { token, json: { events } }),
putBlob: (id: string, token: string, blobId: string, data: ArrayBuffer) =>
req('PUT', `/api/groups/${id}/blobs/${blobId}`, { token, body: data }),
getBlob: (id: string, token: string, blobId: string) => req<ArrayBuffer>('GET', `/api/groups/${id}/blobs/${blobId}`, { token }),
pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) =>
req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }),
pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }),
rates: (date: string) => req<{ base: string; date: string; rates: Record<string, string> }>('GET', `/api/rates?date=${date}`),
};
/**
* Listen for "new seq" pings on the group's SSE stream. EventSource can't
* send an Authorization header, so this reads the stream with fetch.
* Resolves when the stream ends; throws on errors.
*/
export async function listen(id: string, token: string, signal: AbortSignal, onSeq: (seq: number) => void): Promise<void> {
const res = await fetch(`/api/groups/${id}/stream`, { headers: { Authorization: `Bearer ${token}` }, signal, cache: 'no-store' });
if (!res.ok || !res.body) throw new ApiError(res.status, 'stream failed');
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
let buf = '';
for (;;) {
const { value, done } = await reader.read();
if (done) return;
buf += value;
let i: number;
while ((i = buf.indexOf('\n\n')) >= 0) {
const msg = buf.slice(0, i);
buf = buf.slice(i + 2);
const m = /^data: (\d+)$/m.exec(msg);
if (m) onSeq(Number(m[1]));
}
}
}

View file

@ -0,0 +1,84 @@
// 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<string>();
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<string> {
await s.sync();
const raw = await s.rawEvents();
const blobs: BackupFile['blobs'] = [];
for (const id of photoIds(s.synced)) {
let rec = await get<StoredBlob>('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 };
}

View file

@ -0,0 +1,77 @@
// Client-side encryption (SPEC.md §3.1, §11). WebCrypto only:
// AES-256-GCM for data, HKDF-SHA-256 to derive keys from the group secret.
const te = new TextEncoder();
const td = new TextDecoder();
export function b64uEncode(bytes: Uint8Array): string {
let s = '';
for (const b of bytes) s += String.fromCharCode(b);
return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
export function b64uDecode(str: string): Uint8Array<ArrayBuffer> {
const s = atob(str.replace(/-/g, '+').replace(/_/g, '/'));
const out = new Uint8Array(s.length);
for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
return out;
}
export function randomBytes(n: number): Uint8Array<ArrayBuffer> {
return crypto.getRandomValues(new Uint8Array(n));
}
/** Random base64url id; 16 bytes → 22 chars. */
export function randomId(bytes = 16): string {
return b64uEncode(randomBytes(bytes));
}
export const isGroupId = (s: string) => /^[A-Za-z0-9_-]{22}$/.test(s);
export const isGroupSecret = (s: string) => /^[A-Za-z0-9_-]{43}$/.test(s);
export interface GroupKeys {
encKey: CryptoKey;
/** bearer token for the API; the server only stores its SHA-256 */
authToken: string;
}
export async function deriveKeys(secret: string): Promise<GroupKeys> {
const ikm = await crypto.subtle.importKey('raw', b64uDecode(secret), 'HKDF', false, ['deriveKey', 'deriveBits']);
const params = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: te.encode(info) });
const encKey = await crypto.subtle.deriveKey(params('oweme/enc/v1'), ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
const auth = new Uint8Array(await crypto.subtle.deriveBits(params('oweme/auth/v1'), ikm, 256));
return { encKey, authToken: b64uEncode(auth) };
}
export async function sha256hex(s: string): Promise<string> {
const d = new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s)));
return [...d].map((b) => b.toString(16).padStart(2, '0')).join('');
}
/** Encrypt JSON for an event. `aad` binds the ciphertext to its group and id,
* so the server can't swap events between groups or ids. */
export async function encryptJson(key: CryptoKey, value: unknown, aad: string): Promise<{ iv: string; ct: string }> {
const iv = randomBytes(12);
const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, te.encode(JSON.stringify(value)));
return { iv: b64uEncode(iv), ct: b64uEncode(new Uint8Array(ct)) };
}
export async function decryptJson<T>(key: CryptoKey, iv: string, ct: string, aad: string): Promise<T> {
const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64uDecode(iv), additionalData: te.encode(aad) }, key, b64uDecode(ct));
return JSON.parse(td.decode(pt));
}
/** Encrypt bytes for a blob: output is iv (12 bytes) || ciphertext. */
export async function encryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise<ArrayBuffer> {
const iv = randomBytes(12);
const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, data));
const out = new Uint8Array(12 + ct.length);
out.set(iv);
out.set(ct, 12);
return out.buffer;
}
export async function decryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise<ArrayBuffer> {
const bytes = new Uint8Array(data);
return crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: te.encode(aad) }, key, bytes.subarray(12));
}

View file

@ -0,0 +1,17 @@
// Decrypting a stored event. Plain module (no runes) so the service worker
// can use it too.
import type { EventPlaintext, GroupEvent } from '@oweme/core';
import { decryptJson, type GroupKeys } from './crypto.ts';
export async function decryptEvent(
keys: GroupKeys,
groupId: string,
e: { id: string; seq: number | null; deviceId: string; iv: string; ct: string },
): Promise<GroupEvent | null> {
try {
const p = await decryptJson<EventPlaintext>(keys.encKey, e.iv, e.ct, `${groupId}|${e.id}`);
return { ...p, id: e.id, seq: e.seq, deviceId: e.deviceId };
} catch {
return null; // wrong key or tampered: skip it
}
}

View file

@ -0,0 +1,87 @@
import { exponent, toDecimalString } from '@oweme/core';
import { settings } from './settings.svelte.ts';
const cache = new Map<string, Intl.NumberFormat>();
/** Format minor units as money in the current locale ("1 234,50 Kč"). */
export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string {
const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`;
let f = cache.get(key);
if (!f) {
const e = exponent(currency);
try {
f = new Intl.NumberFormat(settings.locale, {
style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e,
signDisplay: opts.sign ? 'exceptZero' : 'auto',
});
} catch {
f = new Intl.NumberFormat(settings.locale, { minimumFractionDigits: e, maximumFractionDigits: e });
}
cache.set(key, f);
}
return f.format(minor / 10 ** exponent(currency));
}
/** Editable amount text for an input, in the user's decimal style. */
export function amountInput(minor: number, currency: string): string {
const s = toDecimalString(minor, currency);
return settings.lang === 'cs' ? s.replace('.', ',') : s;
}
export function fmtDate(d: string, style: 'short' | 'long' = 'short'): string {
const date = new Date(`${d}T12:00:00`);
return date.toLocaleDateString(settings.locale, style === 'long'
? { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' }
: { day: 'numeric', month: 'short', year: date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric' });
}
export function fmtDateTime(iso: string): string {
return new Date(iso).toLocaleString(settings.locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });
}
export function fmtMonth(ym: string): string {
return new Date(`${ym}-15T12:00:00`).toLocaleDateString(settings.locale, { month: 'short', year: '2-digit' });
}
/** Today as YYYY-MM-DD in local time. */
export function today(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}
export function addDays(d: string, n: number): string {
const x = new Date(`${d}T12:00:00`);
x.setDate(x.getDate() + n);
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, '0')}-${String(x.getDate()).padStart(2, '0')}`;
}
export function currencyName(code: string): string {
try {
return new Intl.DisplayNames(settings.locale, { type: 'currency' }).of(code) ?? code;
} catch {
return code;
}
}
export const CATEGORY_ICONS: Record<string, string> = {
food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️',
shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊',
other: '🧾', transfer: '💸',
};
export const MEMBER_COLORS = ['#3DDC97', '#F2A65A', '#6CB4EE', '#E879A6', '#C9A227', '#9B8CF2', '#4FD1C5', '#F87171', '#A3E635', '#FB923C'];
export function download(filename: string, content: BlobPart, type: string) {
const url = URL.createObjectURL(new Blob([content], { type }));
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
export function slug(s: string): string {
return s.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'group';
}

25
apps/web/src/lib/i18n.ts Normal file
View file

@ -0,0 +1,25 @@
// Tiny i18n. English is the default; Czech is used when the browser's
// preferred language is Czech, unless the user picks one in settings
// (SPEC.md §10.3). Plain module (no runes) so the service worker can use it.
import cs from './locales/cs.ts';
import en, { type Messages, type Plural } from './locales/en.ts';
export type Lang = 'en' | 'cs';
export type MsgKey = keyof Messages;
const dicts: Record<Lang, Messages> = { en, cs };
export function detectLang(languages: readonly string[] = navigator.languages ?? [navigator.language]): Lang {
const first = (languages[0] ?? '').toLowerCase();
return first === 'cs' || first.startsWith('cs-') ? 'cs' : 'en';
}
export const localeOf = (lang: Lang) => (lang === 'cs' ? 'cs-CZ' : 'en');
export function translate(lang: Lang, key: MsgKey, vars: Record<string, string | number> = {}): string {
let msg: string | Plural = dicts[lang][key] ?? en[key];
if (typeof msg !== 'string') {
const form = new Intl.PluralRules(localeOf(lang)).select(Number(vars.n ?? 0));
msg = form === 'one' ? msg.one : form === 'few' ? msg.few : msg.other;
}
return msg.replace(/\{(\w+)\}/g, (_, k) => (k in vars ? String(vars[k]) : `{${k}}`));
}

150
apps/web/src/lib/idb.ts Normal file
View file

@ -0,0 +1,150 @@
// IndexedDB storage, shared by the page and the service worker.
// Events are kept as the server's ciphertext and decrypted when loaded.
export interface LocalGroup {
id: string;
/** the key from the link; anyone with this has full access */
secret: string;
name: string;
icon: string;
baseCurrency: string;
/** "who am I" on this device */
me: string | null;
/** my balance in base minor units, cached for the home screen */
myBalance: number | null;
lastSeq: number;
lastOpened: number;
push: boolean;
/** highest seq the service worker has notified about */
notifiedSeq: number;
/** set when the server says the group no longer exists */
gone?: boolean;
}
export interface StoredEvent {
g: string;
seq: number;
id: string;
deviceId: string;
iv: string;
ct: string;
}
export interface OutboxItem {
n?: number;
g: string;
id: string;
deviceId: string;
iv: string;
ct: string;
}
export interface StoredBlob {
g: string;
id: string;
/** encrypted bytes */
data: ArrayBuffer;
uploaded: boolean;
}
let dbp: Promise<IDBDatabase> | null = null;
export function openDb(): Promise<IDBDatabase> {
if (dbp) return dbp;
dbp = new Promise((resolve, reject) => {
const req = indexedDB.open('oweme', 1);
req.onupgradeneeded = () => {
const db = req.result;
db.createObjectStore('groups', { keyPath: 'id' });
db.createObjectStore('events', { keyPath: ['g', 'seq'] });
db.createObjectStore('outbox', { keyPath: 'n', autoIncrement: true }).createIndex('g', 'g');
db.createObjectStore('blobs', { keyPath: ['g', 'id'] });
db.createObjectStore('kv');
};
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
return dbp;
}
type StoreName = 'groups' | 'events' | 'outbox' | 'blobs' | 'kv';
function wrap<T>(req: IDBRequest<T>): Promise<T> {
return new Promise((resolve, reject) => {
req.onsuccess = () => resolve(req.result);
req.onerror = () => reject(req.error);
});
}
async function store(name: StoreName, mode: IDBTransactionMode = 'readonly'): Promise<IDBObjectStore> {
return (await openDb()).transaction(name, mode).objectStore(name);
}
export async function get<T>(name: StoreName, key: IDBValidKey): Promise<T | undefined> {
return wrap((await store(name)).get(key));
}
export async function put(name: StoreName, value: unknown, key?: IDBValidKey): Promise<void> {
await wrap((await store(name, 'readwrite')).put(value, key));
}
export async function del(name: StoreName, key: IDBValidKey | IDBKeyRange): Promise<void> {
await wrap((await store(name, 'readwrite')).delete(key));
}
export async function getAll<T>(name: StoreName, query?: IDBKeyRange): Promise<T[]> {
return wrap((await store(name)).getAll(query)) as Promise<T[]>;
}
export const groupRange = (g: string) => IDBKeyRange.bound([g, -Infinity], [g, Infinity]);
export const groupBlobRange = (g: string) => IDBKeyRange.bound([g, ''], [g, '￿']);
export async function putEvents(events: StoredEvent[]): Promise<void> {
if (!events.length) return;
const tx = (await openDb()).transaction('events', 'readwrite');
for (const e of events) tx.objectStore('events').put(e);
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
}
export async function outboxFor(g: string): Promise<OutboxItem[]> {
const s = await store('outbox');
return wrap(s.index('g').getAll(g)) as Promise<OutboxItem[]>;
}
export async function updateGroup(id: string, patch: Partial<LocalGroup>): Promise<LocalGroup | undefined> {
const tx = (await openDb()).transaction('groups', 'readwrite');
const s = tx.objectStore('groups');
const g = (await wrap(s.get(id))) as LocalGroup | undefined;
if (!g) return undefined;
const next = { ...g, ...patch };
s.put(next);
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
return next;
}
/** Remove a group and everything cached for it from this device. */
export async function forgetGroup(id: string): Promise<void> {
const db = await openDb();
const tx = db.transaction(['groups', 'events', 'outbox', 'blobs'], 'readwrite');
tx.objectStore('groups').delete(id);
tx.objectStore('events').delete(groupRange(id));
tx.objectStore('blobs').delete(groupBlobRange(id));
const ob = tx.objectStore('outbox');
const keys = await wrap(ob.index('g').getAllKeys(id));
for (const k of keys) ob.delete(k);
await new Promise<void>((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error))));
}
export async function kvGet<T>(k: string): Promise<T | undefined> {
return get<T>('kv', k);
}
export async function kvSet(k: string, v: unknown): Promise<void> {
await put('kv', v, k);
}
/** Stable random id for this browser, so it can skip notifying itself. */
export async function deviceId(): Promise<string> {
let id = await kvGet<string>('deviceId');
if (!id) {
id = Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(36).padStart(2, '0')).join('');
await kvSet('deviceId', id);
}
return id;
}

View file

@ -0,0 +1,253 @@
import type { Messages } from './en.ts';
const cs: Messages = {
app_name: 'OweMe',
tagline: 'Dělte společné výdaje. Šifrováno end-to-end.',
your_groups: 'Vaše skupiny',
no_groups: 'Na tomto zařízení zatím nejsou žádné skupiny. Vytvořte novou, nebo otevřete odkaz, který vám někdo poslal.',
new_group: 'Nová skupina',
open_link: 'Otevřít odkaz na skupinu',
restore_backup: 'Obnovit zálohu',
paste_link: 'Vložte odkaz na skupinu',
open: 'Otevřít',
invalid_link: 'Tohle nevypadá jako úplný odkaz na skupinu OweMe.',
you_are_owed: 'dluží vám {amount}',
you_owe: 'dlužíte {amount}',
settled: 'vyrovnáno',
pick_identity_hint: 'vyberte, kdo jste',
group_gone: 'smazáno',
e2e_note: 'Vše se šifruje přímo ve vašem zařízení. Server ukládá jen data, která nedokáže přečíst. Odkazy na skupiny si proto dobře uschovejte: ztracený odkaz nelze obnovit.',
settings: 'Nastavení',
app_settings: 'Nastavení aplikace',
language: 'Jazyk',
lang_auto: 'Automaticky',
theme: 'Vzhled',
theme_system: 'Podle systému',
theme_dark: 'Tmavý',
theme_light: 'Světlý',
create_group: 'Vytvořit skupinu',
group_name: 'Název skupiny',
group_name_ph: 'Výlet do Prahy',
base_currency: 'Hlavní měna',
base_currency_hint: 'V této měně se zobrazují zůstatky. Jakmile má skupina výdaje, nelze ji změnit.',
base_currency_locked: 'Uzamčeno, protože skupina už má výdaje.',
icon: 'Ikona',
your_name: 'Vaše jméno',
other_members: 'Další členové',
add_member: 'Přidat člena',
member_name: 'Jméno',
creating: 'Vytvářím…',
share_group: 'Sdílet skupinu',
share_intro: 'Kdokoli s tímto odkazem může skupinu vidět i upravovat. Posílejte ho jen členům.',
save_link_warning: 'Uložte si tento odkaz na bezpečné místo. Pokud se ztratí všechny kopie, skupinu nepůjde obnovit.',
copy_link: 'Kopírovat odkaz',
copied: 'Zkopírováno',
share: 'Sdílet…',
done: 'Hotovo',
who_are_you: 'Kdo jste?',
who_are_you_hint: 'Zapamatuje se na tomto zařízení, takže výdaje budou předvyplněné na vás.',
im_new: 'Nejsem v seznamu',
just_looking: 'Přeskočit',
change_identity: 'Nejsem {name}',
you: 'vy',
expenses: 'Výdaje',
balances: 'Zůstatky',
stats: 'Statistiky',
activity: 'Aktivita',
add_expense: 'Přidat výdaj',
no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.',
total_spent: 'Celkem utraceno',
paid_by: 'Platil(a) {name}',
paid_by_many: 'Platilo {n} lidí',
your_share: 'váš podíl {amount}',
you_lent: 'půjčili jste {amount}',
you_borrowed: 'dlužíte {amount}',
not_involved: 'netýká se vás',
transfer_line: '{from} → {to}',
offline: 'Jste offline. Změny se uloží v zařízení a synchronizují se později.',
pending: { one: '{n} změna čeká na synchronizaci', few: '{n} změny čekají na synchronizaci', other: '{n} změn čeká na synchronizaci' },
rollback_warning: 'Server vrátil starší data, než toto zařízení už vidělo. Mohl s nimi někdo manipulovat, nebo byla obnovena ze zálohy.',
not_found_group: 'Tato skupina už na serveru neexistuje.',
remove_from_device: 'Odebrat z tohoto zařízení',
group_not_on_device: 'Tato skupina není uložená v tomto zařízení. Otevřete celý odkaz (včetně části za #).',
loading: 'Načítám…',
search: 'Hledat',
settle_up: 'Vyrovnání',
all_settled: 'Všichni jsou vyrovnaní. 🎉',
mark_paid: 'Zaznamenat platbu',
show_in: 'Zobrazit v',
display_only_rate: 'Přepočteno dnešním kurzem, jen pro zobrazení.',
is_owed: 'má dostat {amount}',
owes: 'dluží {amount}',
new_expense: 'Nový výdaj',
edit_expense: 'Upravit výdaj',
new_transfer: 'Zaznamenat platbu',
kind_expense: 'Výdaj',
kind_transfer: 'Platba',
amount: 'Částka',
title: 'Za co?',
title_ph: 'Večeře',
category: 'Kategorie',
date: 'Datum',
currency: 'Měna',
rate: 'Směnný kurz',
rate_source_ecb: 'Kurz ECB ze dne {date}',
rate_source_manual: 'Zadáno ručně',
rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.',
paid_by_label: 'Platil(a)',
multiple_payers: 'Platilo více lidí',
from_label: 'Od',
to_label: 'Komu',
split: 'Rozdělení',
split_equal: 'Rovným dílem',
split_shares: 'Podíly',
split_exact: 'Částky',
split_percent: 'Procenta',
remaining: 'Zbývá: {amount}',
over_by: 'Přebývá: {amount}',
select_all: 'Všichni',
select_none: 'Nikdo',
note: 'Poznámka',
photo: 'Fotka',
add_photo: 'Přidat fotku',
replace_photo: 'Vyměnit',
remove_photo: 'Odebrat',
processing_photo: 'Zpracovávám fotku…',
photo_too_large: 'Fotka je i po zmenšení příliš velká.',
repeat: 'Opakovat',
repeat_none: 'Nikdy',
repeat_weekly: 'Každý týden',
repeat_monthly: 'Každý měsíc',
repeat_yearly: 'Každý rok',
save: 'Uložit',
cancel: 'Zrušit',
invalid_amount: 'Zadejte platnou částku.',
invalid_split: 'Rozdělení nesedí.',
invalid_payers: 'Platby nedávají dohromady celou částku.',
need_title: 'Doplňte popis.',
need_members: 'Nejdřív do skupiny přidejte členy.',
delete: 'Smazat',
restore: 'Obnovit',
edit: 'Upravit',
deleted_banner: 'Tento výdaj byl smazán.',
split_details: 'Rozdělení',
paid: 'zaplatil(a) {amount}',
owes_share: 'podíl {amount}',
converted: '{amount} při kurzu {rate}',
comments: 'Komentáře',
add_comment: 'Napište komentář…',
send: 'Odeslat',
history: 'Historie',
restore_version: 'Obnovit tuto verzi',
current_version: 'Aktuální verze',
recurring_badge: 'Opakuje se',
confirm_delete: 'Smazat tento výdaj? Později ho můžete obnovit z historie.',
rewind_here: 'Vrátit skupinu sem',
undo_rewind: 'Zrušit toto vrácení',
confirm_rewind: 'Vrátit celou skupinu do stavu po této změně? Nic se neztratí: vrácení lze zase zrušit.',
act_group_created: '{actor} vytvořil(a) skupinu',
act_group_updated: '{actor} změnil(a) nastavení skupiny',
act_member_added: '{actor} přidal(a) člena {name}',
act_member_updated: '{actor} přejmenoval(a) {old} na {name}',
act_member_archived: '{actor} archivoval(a) člena {name}',
act_member_restored: '{actor} obnovil(a) člena {name}',
act_expense_created: '{actor} přidal(a) {title}',
act_expense_updated: '{actor} upravil(a) {title}',
act_expense_deleted: '{actor} smazal(a) {title}',
act_expense_restored: '{actor} obnovil(a) {title}',
act_comment_added: '{actor} okomentoval(a) {title}',
act_comment_deleted: '{actor} smazal(a) komentář u {title}',
act_recurring_created: '{actor} nastavil(a) opakování {title}',
act_recurring_updated: '{actor} změnil(a) opakování {title}',
act_recurring_deleted: '{actor} zrušil(a) opakování {title}',
act_revert: '{actor} vrátil(a) skupinu do stavu z {time}',
someone: 'Někdo',
changed_fields: 'Změněno: {fields}',
no_activity: 'Zatím žádná aktivita.',
range_all: 'Celé období',
range_month: 'Tento měsíc',
range_30: 'Posledních 30 dní',
range_year: 'Tento rok',
by_category: 'Podle kategorie',
by_month: 'Podle měsíce',
per_member: 'Zaplaceno vs. podíl',
legend_paid: 'Zaplaceno',
legend_share: 'Podíl',
my_spending: 'Můj podíl na útratě',
no_data: 'Za toto období tu nic není.',
group_settings: 'Nastavení skupiny',
members: 'Členové',
rename: 'Přejmenovat',
archive: 'Archivovat',
archived: 'archivován(a)',
unarchive: 'Obnovit',
archive_needs_zero: 'Archivovat lze jen členy s nulovým zůstatkem.',
identity: 'Jste',
not_set: 'Nenastaveno',
change: 'Změnit',
notifications: 'Oznámení',
notifications_hint: 'Dostanete oznámení, když skupinu změní někdo jiný.',
notifications_ios: 'Na iPhonu a iPadu nejdřív přidejte OweMe na plochu (Sdílet → Přidat na plochu).',
notifications_denied: 'Oznámení jsou pro tento web zablokovaná v nastavení prohlížeče.',
notifications_unavailable: 'Oznámení nejsou na tomto serveru nebo v tomto prohlížeči k dispozici.',
recurring: 'Opakované výdaje',
no_recurring: 'Žádné. Při přidání výdaje zvolte „Opakovat“.',
next_on: 'příště {date}',
stop: 'Zrušit',
export: 'Export',
export_expenses: 'Výdaje (CSV)',
export_balances: 'Zůstatky (CSV)',
backup: 'Soubor se zálohou',
backup_hint: 'Obsahuje klíč skupiny: kdokoli se souborem skupinu otevře. Uložte ho bezpečně.',
danger_zone: 'Nebezpečná zóna',
remove_from_device_hint: 'Skupina zůstane na serveru i v ostatních zařízeních.',
delete_group: 'Smazat skupinu pro všechny',
delete_group_hint: 'Smaže ze serveru všechny výdaje a fotky. Pro potvrzení napište název skupiny.',
confirm: 'Potvrdit',
saved: 'Uloženo',
restore_title: 'Obnovit zálohu',
restore_pick: 'Vyberte soubor se zálohou OweMe (.json).',
restore_bad_file: 'Tohle není platná záloha OweMe.',
restore_exists: 'Tato skupina na serveru už existuje, takže byla jen přidána do tohoto zařízení.',
restoring: 'Obnovuji…',
back: 'Zpět',
close: 'Zavřít',
error_generic: 'Něco se pokazilo: {msg}',
update_available: 'Je k dispozici nová verze.',
reload: 'Načíst znovu',
today: 'Dnes',
yesterday: 'Včera',
n_members: { one: '{n} člen', few: '{n} členové', other: '{n} členů' },
cat_food: 'Jídlo a pití',
cat_groceries: 'Potraviny',
cat_transport: 'Doprava',
cat_accommodation: 'Ubytování',
cat_entertainment: 'Zábava',
cat_shopping: 'Nákupy',
cat_utilities: 'Energie a služby',
cat_rent: 'Nájem',
cat_travel: 'Cestování',
cat_gifts: 'Dárky',
cat_health: 'Zdraví',
cat_other: 'Ostatní',
cat_transfer: 'Platba',
notif_new_activity: { one: '{n} nová změna', few: '{n} nové změny', other: '{n} nových změn' },
};
export default cs;

View file

@ -0,0 +1,270 @@
// English strings. `{name}` placeholders are filled by t(); entries with
// one/few/other are plural forms chosen by Intl.PluralRules on `{n}`.
const en = {
app_name: 'OweMe',
tagline: 'Split group expenses. End-to-end encrypted.',
// home
your_groups: 'Your groups',
no_groups: 'No groups on this device yet. Create one, or open a group link someone sent you.',
new_group: 'New group',
open_link: 'Open a group link',
restore_backup: 'Restore a backup',
paste_link: 'Paste the group link',
open: 'Open',
invalid_link: "That doesn't look like a complete OweMe group link.",
you_are_owed: 'you are owed {amount}',
you_owe: 'you owe {amount}',
settled: 'settled up',
pick_identity_hint: 'choose who you are',
group_gone: 'deleted',
e2e_note: 'Everything is encrypted on your device. The server only stores data it cannot read, so keep your group links safe: lost links cannot be recovered.',
// settings
settings: 'Settings',
app_settings: 'App settings',
language: 'Language',
lang_auto: 'Automatic',
theme: 'Theme',
theme_system: 'System',
theme_dark: 'Dark',
theme_light: 'Light',
// new group
create_group: 'Create group',
group_name: 'Group name',
group_name_ph: 'Prague trip',
base_currency: 'Main currency',
base_currency_hint: 'Balances are shown in this currency. It can’t be changed once the group has expenses.',
base_currency_locked: 'Locked because the group has expenses.',
icon: 'Icon',
your_name: 'Your name',
other_members: 'Other members',
add_member: 'Add member',
member_name: 'Name',
creating: 'Creating…',
// share
share_group: 'Share group',
share_intro: 'Anyone with this link can see and edit the group. Send it only to group members.',
save_link_warning: 'Save this link somewhere safe. If every copy is lost, the group can’t be recovered.',
copy_link: 'Copy link',
copied: 'Copied',
share: 'Share…',
done: 'Done',
// identity
who_are_you: 'Who are you?',
who_are_you_hint: 'This is remembered on this device, so expenses default to you.',
im_new: 'I’m not on the list',
just_looking: 'Skip',
change_identity: 'I’m not {name}',
you: 'you',
// group tabs
expenses: 'Expenses',
balances: 'Balances',
stats: 'Stats',
activity: 'Activity',
add_expense: 'Add expense',
no_expenses: 'No expenses yet. Tap + to add the first one.',
total_spent: 'Total spent',
paid_by: 'Paid by {name}',
paid_by_many: 'Paid by {n} people',
your_share: 'your share {amount}',
you_lent: 'you lent {amount}',
you_borrowed: 'you borrowed {amount}',
not_involved: 'not involved',
transfer_line: '{from} → {to}',
offline: 'Offline. Changes are saved on this device and will sync later.',
pending: { one: '{n} change waiting to sync', few: '{n} changes waiting to sync', other: '{n} changes waiting to sync' },
rollback_warning: 'The server returned older data than this device has seen. Someone may have tampered with it, or it was restored from a backup.',
not_found_group: 'This group no longer exists on the server.',
remove_from_device: 'Remove from this device',
group_not_on_device: 'This group isn’t saved on this device. Open the full link (with the part after #) to add it.',
loading: 'Loading…',
search: 'Search',
// balances
settle_up: 'Settle up',
all_settled: 'Everyone is settled up. 🎉',
mark_paid: 'Record payment',
show_in: 'Show in',
display_only_rate: 'Converted at today’s rate, for display only.',
is_owed: 'is owed {amount}',
owes: 'owes {amount}',
// expense editor
new_expense: 'New expense',
edit_expense: 'Edit expense',
new_transfer: 'Record payment',
kind_expense: 'Expense',
kind_transfer: 'Payment',
amount: 'Amount',
title: 'What was it for?',
title_ph: 'Dinner',
category: 'Category',
date: 'Date',
currency: 'Currency',
rate: 'Exchange rate',
rate_source_ecb: 'ECB rate from {date}',
rate_source_manual: 'Entered manually',
rate_unavailable: 'No rate available for this currency, please enter it.',
paid_by_label: 'Paid by',
multiple_payers: 'Several people paid',
from_label: 'From',
to_label: 'To',
split: 'Split',
split_equal: 'Equally',
split_shares: 'Shares',
split_exact: 'Amounts',
split_percent: 'Percent',
remaining: 'Remaining: {amount}',
over_by: 'Over by: {amount}',
select_all: 'All',
select_none: 'None',
note: 'Note',
photo: 'Photo',
add_photo: 'Add photo',
replace_photo: 'Replace',
remove_photo: 'Remove',
processing_photo: 'Processing photo…',
photo_too_large: 'The photo is too large even after compressing.',
repeat: 'Repeat',
repeat_none: 'Never',
repeat_weekly: 'Every week',
repeat_monthly: 'Every month',
repeat_yearly: 'Every year',
save: 'Save',
cancel: 'Cancel',
invalid_amount: 'Enter a valid amount.',
invalid_split: 'The split doesn’t add up.',
invalid_payers: 'The payers don’t add up to the amount.',
need_title: 'Add a description.',
need_members: 'Add members to the group first.',
// expense detail
delete: 'Delete',
restore: 'Restore',
edit: 'Edit',
deleted_banner: 'This expense was deleted.',
split_details: 'Split',
paid: 'paid {amount}',
owes_share: 'share {amount}',
converted: '{amount} at {rate}',
comments: 'Comments',
add_comment: 'Write a comment…',
send: 'Send',
history: 'History',
restore_version: 'Restore this version',
current_version: 'Current version',
recurring_badge: 'Repeats',
confirm_delete: 'Delete this expense? You can restore it later from its history.',
// activity
rewind_here: 'Rewind group to here',
undo_rewind: 'Undo this rewind',
confirm_rewind: 'Restore the whole group to how it was after this change? Nothing is lost: the rewind itself can be undone.',
act_group_created: '{actor} created the group',
act_group_updated: '{actor} changed group settings',
act_member_added: '{actor} added {name}',
act_member_updated: '{actor} renamed {old} to {name}',
act_member_archived: '{actor} archived {name}',
act_member_restored: '{actor} restored {name}',
act_expense_created: '{actor} added {title}',
act_expense_updated: '{actor} edited {title}',
act_expense_deleted: '{actor} deleted {title}',
act_expense_restored: '{actor} restored {title}',
act_comment_added: '{actor} commented on {title}',
act_comment_deleted: '{actor} deleted a comment on {title}',
act_recurring_created: '{actor} set up repeating {title}',
act_recurring_updated: '{actor} changed repeating {title}',
act_recurring_deleted: '{actor} stopped repeating {title}',
act_revert: '{actor} rewound the group to {time}',
someone: 'Someone',
changed_fields: 'Changed: {fields}',
no_activity: 'No activity yet.',
// stats
range_all: 'All time',
range_month: 'This month',
range_30: 'Last 30 days',
range_year: 'This year',
by_category: 'By category',
by_month: 'By month',
per_member: 'Paid vs. share',
legend_paid: 'Paid',
legend_share: 'Share',
my_spending: 'My share of spending',
no_data: 'Nothing to show for this period.',
// group settings
group_settings: 'Group settings',
members: 'Members',
rename: 'Rename',
archive: 'Archive',
archived: 'archived',
unarchive: 'Restore',
archive_needs_zero: 'Only members with a zero balance can be archived.',
identity: 'You are',
not_set: 'Not set',
change: 'Change',
notifications: 'Notifications',
notifications_hint: 'Get a notification when someone else changes this group.',
notifications_ios: 'On iPhone and iPad, add OweMe to your home screen first (Share → Add to Home Screen).',
notifications_denied: 'Notifications are blocked for this site in your browser settings.',
notifications_unavailable: 'Notifications aren’t available on this server or in this browser.',
recurring: 'Repeating expenses',
no_recurring: 'None. Choose “Repeat” when adding an expense.',
next_on: 'next on {date}',
stop: 'Stop',
export: 'Export',
export_expenses: 'Expenses (CSV)',
export_balances: 'Balances (CSV)',
backup: 'Backup file',
backup_hint: 'Contains the group key: anyone with the file can open the group. Store it safely.',
danger_zone: 'Danger zone',
remove_from_device_hint: 'The group stays on the server and on other devices.',
delete_group: 'Delete group for everyone',
delete_group_hint: 'Deletes all expenses and photos from the server. Type the group name to confirm.',
confirm: 'Confirm',
saved: 'Saved',
// backup restore
restore_title: 'Restore a backup',
restore_pick: 'Choose an OweMe backup file (.json).',
restore_bad_file: 'That isn’t a valid OweMe backup.',
restore_exists: 'This group already exists on the server, so it was added to this device.',
restoring: 'Restoring…',
// misc
back: 'Back',
close: 'Close',
error_generic: 'Something went wrong: {msg}',
update_available: 'A new version is available.',
reload: 'Reload',
today: 'Today',
yesterday: 'Yesterday',
n_members: { one: '{n} member', few: '{n} members', other: '{n} members' },
cat_food: 'Food & drink',
cat_groceries: 'Groceries',
cat_transport: 'Transport',
cat_accommodation: 'Accommodation',
cat_entertainment: 'Entertainment',
cat_shopping: 'Shopping',
cat_utilities: 'Utilities',
cat_rent: 'Rent',
cat_travel: 'Travel',
cat_gifts: 'Gifts',
cat_health: 'Health',
cat_other: 'Other',
cat_transfer: 'Payment',
// notifications (service worker)
notif_new_activity: { one: '{n} new change', few: '{n} new changes', other: '{n} new changes' },
};
export type Plural = { one: string; few: string; other: string };
export type Messages = { [K in keyof typeof en]: (typeof en)[K] extends string ? string : Plural };
export default en satisfies Messages as Messages;

49
apps/web/src/lib/photo.ts Normal file
View file

@ -0,0 +1,49 @@
// Receipt photos (SPEC.md §9): shrink and re-encode on the device, which
// also strips EXIF metadata including GPS location, then encrypt.
export interface ProcessedPhoto {
full: Blob;
thumb: Blob;
w: number;
h: number;
}
async function encode(canvas: HTMLCanvasElement, quality: number): Promise<Blob> {
const webp = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/webp', quality));
// Browsers that can't encode WebP silently return PNG; use JPEG instead.
if (webp && webp.type === 'image/webp') return webp;
const jpeg = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/jpeg', quality));
if (!jpeg) throw new Error('could not encode image');
return jpeg;
}
function draw(img: ImageBitmap, maxEdge: number): HTMLCanvasElement {
const scale = Math.min(1, maxEdge / Math.max(img.width, img.height));
const c = document.createElement('canvas');
c.width = Math.round(img.width * scale);
c.height = Math.round(img.height * scale);
c.getContext('2d')!.drawImage(img, 0, 0, c.width, c.height);
return c;
}
/**
* Photo + thumbnail, together under `maxBytes` (minus encryption overhead).
* Tries lower quality, then smaller sizes, before giving up.
*/
export async function processPhoto(file: Blob, maxBytes: number): Promise<ProcessedPhoto> {
const img = await createImageBitmap(file, { imageOrientation: 'from-image' });
try {
const thumb = await encode(draw(img, 320), 0.7);
const budget = maxBytes - thumb.size - 1024;
for (const edge of [1600, 1280, 1024, 800]) {
const canvas = draw(img, edge);
for (const q of [0.82, 0.7, 0.55]) {
const full = await encode(canvas, q);
if (full.size <= budget) return { full, thumb, w: canvas.width, h: canvas.height };
}
}
throw new Error('too large');
} finally {
img.close();
}
}

52
apps/web/src/lib/push.ts Normal file
View file

@ -0,0 +1,52 @@
// Web Push opt-in per group (SPEC.md §7.7). One browser subscription is
// shared by all groups; each group registers it with the server separately.
import { api, serverConfig } from './api.ts';
import { b64uDecode } from './crypto.ts';
import { deviceId, getAll, updateGroup, type LocalGroup } from './idb.ts';
import type { GroupSession } from './session.svelte.ts';
export type PushSupport = 'ok' | 'unsupported' | 'needs-install' | 'denied' | 'no-server';
export async function pushSupport(): Promise<PushSupport> {
const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
const standalone = matchMedia('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true;
if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) {
return ios && !standalone ? 'needs-install' : 'unsupported';
}
if (Notification.permission === 'denied') return 'denied';
try {
if (!(await serverConfig()).vapidPublicKey) return 'no-server';
} catch {
return 'no-server';
}
return 'ok';
}
async function subscription(create: boolean): Promise<PushSubscription | null> {
const reg = await navigator.serviceWorker.ready;
const existing = await reg.pushManager.getSubscription();
if (existing || !create) return existing;
const key = (await serverConfig()).vapidPublicKey;
if (!key) throw new Error('push not configured');
return reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uDecode(key) });
}
export async function enablePush(s: GroupSession): Promise<boolean> {
if ((await Notification.requestPermission()) !== 'granted') return false;
const sub = await subscription(true);
if (!sub) return false;
await api.pushSubscribe(s.id, s.keys.authToken, sub.toJSON(), await deviceId());
// Don't notify about everything that happened before opting in.
s.local = { ...s.local, push: true, notifiedSeq: s.local.lastSeq };
await updateGroup(s.id, { push: true, notifiedSeq: s.local.lastSeq });
return true;
}
export async function disablePush(s: GroupSession): Promise<void> {
const sub = await subscription(false);
if (sub) await api.pushUnsubscribe(s.id, s.keys.authToken, sub.endpoint).catch(() => {});
s.local = { ...s.local, push: false };
await updateGroup(s.id, { push: false });
const others = (await getAll<LocalGroup>('groups')).filter((g) => g.push && g.id !== s.id);
if (sub && others.length === 0) await sub.unsubscribe();
}

68
apps/web/src/lib/rates.ts Normal file
View file

@ -0,0 +1,68 @@
// Exchange rates from our own server (ECB daily, EUR-based). Cached in
// IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2).
import { rateToString } from '@oweme/core';
import { api } from './api.ts';
import { kvGet, kvSet } from './idb.ts';
import { today } from './format.ts';
export interface RatesDay {
date: string;
rates: Record<string, string>;
}
const memory = new Map<string, Promise<RatesDay | null>>();
/** Rates for a date (the latest published on or before it). */
export function ratesOn(date: string): Promise<RatesDay | null> {
let p = memory.get(date);
if (!p) {
p = (async () => {
const key = `rates:${date}`;
const cached = await kvGet<RatesDay>(key);
// A past date's rates never change; today's might still be published.
if (cached && date < today()) return cached;
try {
const r = await api.rates(date);
const day = { date: r.date, rates: r.rates };
await kvSet(key, day);
await kvSet('rates:latest', day);
return day;
} catch {
memory.delete(date);
return cached ?? (await kvGet<RatesDay>('rates:latest')) ?? null;
}
})();
memory.set(date, p);
}
return p;
}
/** Suggested rate string for 1 `from` = x `to`, or null if unknown. */
export async function suggestRate(from: string, to: string, date: string): Promise<{ rate: string; source: string } | null> {
if (from === to) return { rate: '1', source: 'same' };
const day = await ratesOn(date);
const f = Number(day?.rates[from]);
const tt = Number(day?.rates[to]);
if (!day || !(f > 0) || !(tt > 0)) return null;
return { rate: rateToString(tt / f), source: `ecb:${day.date}` };
}
/** Float conversion for display only (never stored). */
export async function displayRate(from: string, to: string): Promise<number | null> {
if (from === to) return 1;
const day = await ratesOn(today());
const f = Number(day?.rates[from]);
const tt = Number(day?.rates[to]);
return f > 0 && tt > 0 ? tt / f : null;
}
/** Currencies with ECB rates first, then every other ISO currency. */
export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> {
const day = await ratesOn(today());
const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort();
let all: string[] = [];
try {
all = Intl.supportedValuesOf('currency');
} catch { /* old browser */ }
return { ecb, other: all.filter((c) => !ecb.includes(c)) };
}

View file

@ -0,0 +1,66 @@
// Minimal history-API router. The group secret lives only in the URL
// fragment and is stripped from the address bar as soon as it's saved.
export type Route =
| { name: 'home' }
| { name: 'new' }
| { name: 'settings' }
| { name: 'restore' }
| { name: 'group'; id: string; tab: 'expenses' | 'balances' | 'stats' | 'activity' }
| { name: 'group-settings'; id: string }
| { name: 'expense'; id: string; eid: string }
| { name: 'expense-edit'; id: string; eid: string | null; params: URLSearchParams }
| { name: 'notfound' };
function parse(path: string, search: string): Route {
const parts = path.split('/').filter(Boolean);
if (parts.length === 0) return { name: 'home' };
if (parts[0] === 'new' && parts.length === 1) return { name: 'new' };
if (parts[0] === 'settings' && parts.length === 1) return { name: 'settings' };
if (parts[0] === 'restore' && parts.length === 1) return { name: 'restore' };
if (parts[0] === 'g' && parts[1]) {
const id = parts[1];
const rest = parts.slice(2);
if (rest.length === 0) return { name: 'group', id, tab: 'expenses' };
if (rest.length === 1 && ['balances', 'stats', 'activity'].includes(rest[0]))
return { name: 'group', id, tab: rest[0] as 'balances' | 'stats' | 'activity' };
if (rest.length === 1 && rest[0] === 'settings') return { name: 'group-settings', id };
if (rest[0] === 'e' && rest[1] === 'new' && rest.length === 2)
return { name: 'expense-edit', id, eid: null, params: new URLSearchParams(search) };
if (rest[0] === 'e' && rest[1] && rest.length === 2) return { name: 'expense', id, eid: rest[1] };
if (rest[0] === 'e' && rest[1] && rest[2] === 'edit') return { name: 'expense-edit', id, eid: rest[1], params: new URLSearchParams(search) };
}
return { name: 'notfound' };
}
class Router {
route = $state<Route>(parse(location.pathname, location.search));
/** how many entries we pushed, so "back" can stay inside the app */
private depth = 0;
constructor() {
addEventListener('popstate', () => {
this.depth = Math.max(0, this.depth - 1);
this.route = parse(location.pathname, location.search);
});
}
go(path: string, opts: { replace?: boolean } = {}) {
const url = new URL(path, location.origin);
if (opts.replace) history.replaceState(null, '', url.pathname + url.search);
else {
history.pushState(null, '', url.pathname + url.search);
this.depth += 1;
}
this.route = parse(url.pathname, url.search);
window.scrollTo(0, 0);
}
/** Back within the app, or to `fallback` if this is the first page. */
back(fallback: string) {
if (this.depth > 0) history.back();
else this.go(fallback, { replace: true });
}
}
export const router = new Router();

View 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);
}

View file

@ -0,0 +1,58 @@
// App-wide, per-device preferences: language and theme. Stored in
// localStorage (a per-device convenience; failures just mean defaults).
import { detectLang, localeOf, translate, type Lang, type MsgKey } from './i18n.ts';
import { kvSet } from './idb.ts';
type LangPref = 'auto' | Lang;
type ThemePref = 'system' | 'dark' | 'light';
function load<T extends string>(key: string, allowed: readonly T[], def: T): T {
try {
const v = localStorage.getItem(key) as T | null;
return v && allowed.includes(v) ? v : def;
} catch {
return def;
}
}
function save(key: string, v: string) {
try {
localStorage.setItem(key, v);
} catch { /* private mode etc. */ }
}
class Settings {
langPref = $state<LangPref>(load('oweme.lang', ['auto', 'en', 'cs'], 'auto'));
themePref = $state<ThemePref>(load('oweme.theme', ['system', 'dark', 'light'], 'system'));
lang = $derived<Lang>(this.langPref === 'auto' ? detectLang() : this.langPref);
locale = $derived(localeOf(this.lang));
setLang(v: LangPref) {
this.langPref = v;
save('oweme.lang', v);
document.documentElement.lang = this.lang;
// the service worker reads this to localise notifications
void kvSet('lang', this.lang).catch(() => {});
}
setTheme(v: ThemePref) {
this.themePref = v;
save('oweme.theme', v);
this.applyTheme();
}
applyTheme() {
const root = document.documentElement;
if (this.themePref === 'system') delete root.dataset.theme;
else root.dataset.theme = this.themePref;
const dark = this.themePref === 'dark' || (this.themePref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches);
document.querySelector('meta[name=theme-color]')?.setAttribute('content', dark ? '#0B2E22' : '#F2F7F4');
}
}
export const settings = new Settings();
/** Translate in the current language. Reactive inside components. */
export function t(key: MsgKey, vars?: Record<string, string | number>): string {
return translate(settings.lang, key, vars);
}

View file

@ -0,0 +1,14 @@
// Small bits of global UI state: toasts and the "new version" prompt.
class Ui {
toast = $state<string | null>(null);
updateReady = $state(false);
private timer: ReturnType<typeof setTimeout> | undefined;
show(msg: string, ms = 2500) {
this.toast = msg;
clearTimeout(this.timer);
this.timer = setTimeout(() => (this.toast = null), ms);
}
}
export const ui = new Ui();

25
apps/web/src/main.ts Normal file
View file

@ -0,0 +1,25 @@
import { mount } from 'svelte';
import App from './App.svelte';
import './app.css';
import { kvSet } from './lib/idb.ts';
import { settings } from './lib/settings.svelte.ts';
import { ui } from './lib/ui.svelte.ts';
settings.applyTheme();
document.documentElement.lang = settings.lang;
void kvSet('lang', settings.lang).catch(() => {});
matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => settings.applyTheme());
if ('serviceWorker' in navigator && import.meta.env.PROD) {
void navigator.serviceWorker.register('/sw.js').then((reg) => {
reg.addEventListener('updatefound', () => {
const sw = reg.installing;
sw?.addEventListener('statechange', () => {
// A new version installed while an old one controls the page.
if (sw.state === 'installed' && navigator.serviceWorker.controller) ui.updateReady = true;
});
});
});
}
mount(App, { target: document.getElementById('app')! });

117
apps/web/src/sw.ts Normal file
View file

@ -0,0 +1,117 @@
/// <reference lib="webworker" />
// Service worker: offline app shell + push notifications (SPEC.md §7.7, §10.1).
// A push only says "group X changed"; this worker fetches the new events,
// decrypts them on the device and writes the notification text itself.
import { exponent, logOrder, replay, type GroupEvent } from '@oweme/core';
import { deriveKeys } from './lib/crypto.ts';
import { translate, type Lang } from './lib/i18n.ts';
import { deviceId, get, getAll, groupRange, kvGet, putEvents, updateGroup, type LocalGroup, type StoredEvent } from './lib/idb.ts';
import { decryptEvent } from './lib/events.ts';
declare const __PRECACHE__: string[];
declare const __VERSION__: string;
const sw = self as unknown as ServiceWorkerGlobalScope;
const CACHE = `oweme-${__VERSION__}`;
sw.addEventListener('install', (e) => {
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(__PRECACHE__)).then(() => sw.skipWaiting()));
});
sw.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((k) => k.startsWith('oweme-') && k !== CACHE).map((k) => caches.delete(k))))
.then(() => sw.clients.claim()),
);
});
sw.addEventListener('fetch', (e) => {
const url = new URL(e.request.url);
if (e.request.method !== 'GET' || url.origin !== location.origin || url.pathname.startsWith('/api/')) return;
if (e.request.mode === 'navigate') {
// Network first so deploys show up; the cached shell when offline.
e.respondWith(fetch(e.request).catch(async () => (await caches.match('/index.html')) ?? Response.error()));
return;
}
e.respondWith(caches.match(e.request).then((hit) => hit ?? fetch(e.request)));
});
function fmtMoney(minor: number, currency: string, locale: string): string {
const e = exponent(currency);
try {
return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e }).format(minor / 10 ** e);
} catch {
return `${(minor / 10 ** e).toFixed(e)} ${currency}`;
}
}
async function handlePush(groupId: string): Promise<void> {
const lang: Lang = (await kvGet<Lang>('lang')) ?? 'en';
const locale = lang === 'cs' ? 'cs-CZ' : 'en';
const tr = (k: Parameters<typeof translate>[1], v?: Record<string, string | number>) => translate(lang, k, v);
const group = await get<LocalGroup>('groups', groupId);
const fallback = () => sw.registration.showNotification('OweMe', { body: tr('notif_new_activity', { n: 1 }), tag: groupId, icon: '/icon-192.png' });
if (!group) return fallback();
const keys = await deriveKeys(group.secret);
let lastSeq = group.lastSeq;
try {
for (;;) {
const res = await fetch(`/api/groups/${groupId}/events?after=${lastSeq}&limit=500`, { headers: { Authorization: `Bearer ${keys.authToken}` } });
if (!res.ok) break;
const { events, latest } = (await res.json()) as { events: Omit<StoredEvent, 'g'>[]; latest: number };
if (!events.length) break;
await putEvents(events.map((e) => ({ ...e, g: groupId })));
lastSeq = events[events.length - 1].seq;
if (lastSeq >= latest) break;
}
await updateGroup(groupId, { lastSeq });
} catch { /* offline: notify with what we have */ }
const stored = await getAll<StoredEvent>('events', groupRange(groupId));
const all = (await Promise.all(stored.map((e) => decryptEvent(keys, groupId, e)))).filter((e): e is GroupEvent => !!e);
const { state, activity } = replay(logOrder(all, []));
const me = await deviceId();
const fresh = activity.filter((a) => !a.ignored && (a.seq ?? 0) > group.notifiedSeq && all.find((e) => e.id === a.eventId)?.deviceId !== me);
await updateGroup(groupId, { notifiedSeq: lastSeq });
// Skip if the user is looking at this group right now.
const windows = await sw.clients.matchAll({ type: 'window' });
if (windows.some((w) => w.focused && w.visibilityState === 'visible' && new URL(w.url).pathname.startsWith(`/g/${groupId}`))) return;
if (!fresh.length && group.notifiedSeq >= lastSeq) return fallback();
const name = (id: string | null) => state.members.find((m) => m.id === id)?.name ?? tr('someone');
const lines = fresh.slice(-4).map((a) => {
const ev = all.find((e) => e.id === a.eventId)!;
if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'expense')
return `${name(ev.actor)}: ${ev.data.title} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`;
if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'transfer')
return `${name(ev.data.payers[0]?.member ?? null)} → ${name(ev.data.split.entries[0]?.member ?? null)} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`;
if (ev.type === 'comment.added') return `${name(ev.actor)}: “${ev.data.text.slice(0, 80)}”`;
return `${name(ev.actor)}: ${tr('notif_new_activity', { n: 1 })}`;
});
const body = fresh.length > 4 ? [tr('notif_new_activity', { n: fresh.length }), ...lines].join('\n') : lines.join('\n') || tr('notif_new_activity', { n: 1 });
await sw.registration.showNotification(`${state.group?.icon ?? ''} ${state.group?.name ?? 'OweMe'}`.trim(), {
body, tag: groupId, icon: '/icon-192.png', badge: '/badge-96.png', data: { url: `/g/${groupId}` },
});
}
sw.addEventListener('push', (e) => {
let groupId = '';
try {
groupId = (e.data?.json() as { g?: string })?.g ?? '';
} catch { /* empty payload */ }
e.waitUntil(handlePush(groupId).catch(() => sw.registration.showNotification('OweMe', { tag: groupId || 'oweme' })));
});
sw.addEventListener('notificationclick', (e) => {
e.notification.close();
const url = (e.notification.data as { url?: string } | null)?.url ?? '/';
e.waitUntil(
sw.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => {
const existing = list.find((c) => new URL(c.url).origin === location.origin);
if (existing) return existing.focus().then((c) => c.navigate(url));
return sw.clients.openWindow(url);
}),
);
});

View file

@ -0,0 +1 @@
export default {};

16
apps/web/tsconfig.json Normal file
View file

@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
"types": ["svelte", "vite/client"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"isolatedModules": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts", "src/**/*.svelte"]
}

15
apps/web/vite.config.ts Normal file
View file

@ -0,0 +1,15 @@
import { svelte } from '@sveltejs/vite-plugin-svelte';
import { defineConfig } from 'vite';
// Dev: the client on 127.0.0.1:8480, proxying /api to the server on 8481.
// Preview from your machine with: ssh -p 14922 -L 8480:localhost:8480 <dev box>
export default defineConfig({
plugins: [svelte()],
server: {
host: '127.0.0.1',
port: 8480,
strictPort: true,
proxy: { '/api': 'http://127.0.0.1:8481' },
},
build: { target: 'es2022', sourcemap: false },
});

View file

@ -0,0 +1,35 @@
// Second build step: the service worker, as one classic script at /sw.js
// (module service workers aren't supported everywhere yet). It precaches
// whatever the first step put in dist/, so this must run after it.
import { createHash } from 'node:crypto';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { defineConfig } from 'vite';
const dist = join(import.meta.dirname, 'dist');
function listFiles(dir: string): string[] {
return readdirSync(dir).flatMap((f) => {
const p = join(dir, f);
return statSync(p).isDirectory() ? listFiles(p) : [p];
});
}
const files = listFiles(dist)
.map((p) => '/' + relative(dist, p).split('\\').join('/'))
.filter((p) => p !== '/sw.js' && !p.endsWith('.map'));
const hash = createHash('sha256');
for (const f of files.sort()) hash.update(f).update(readFileSync(join(dist, f)));
export default defineConfig({
define: {
__PRECACHE__: JSON.stringify(files),
__VERSION__: JSON.stringify(hash.digest('hex').slice(0, 12)),
},
build: {
outDir: 'dist',
emptyOutDir: false,
target: 'es2022',
lib: { entry: 'src/sw.ts', formats: ['iife'], name: 'sw', fileName: () => 'sw.js' },
},
});

23
deploy/.env.example Normal file
View file

@ -0,0 +1,23 @@
# Copy to deploy/.env and `chmod 600 deploy/.env`. Never commit .env.
# Required: public hostname, with a DNS A/AAAA record pointing at this server.
DOMAIN=oweme.example.com
# Web Push. Generate the keys with:
# podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env
# (or, with Node 24 installed: node apps/server/src/gen-vapid.ts deploy/.env)
# Leave empty to disable notifications.
VAPID_SUBJECT=mailto:you@example.com
VAPID_PUBLIC_KEY=
VAPID_PRIVATE_KEY=
# Limits (bytes). Defaults shown.
MAX_PHOTO_BYTES=2097152
MAX_EVENT_BYTES=65536
MAX_GROUP_BYTES=209715200
GROUP_CREATE_PER_HOUR=10
# Where Caddy listens. Defaults: all interfaces, ports 80/443.
#BIND_ADDR=0.0.0.0
#HTTP_PORT=80
#HTTPS_PORT=443

10
deploy/Caddyfile Normal file
View file

@ -0,0 +1,10 @@
# Automatic HTTPS for $DOMAIN (Let's Encrypt / ZeroSSL). HTTPS is required:
# WebCrypto, service workers and push only work in a secure context.
# Security headers (CSP etc.) are set by the app itself.
{$DOMAIN} {
encode zstd gzip
reverse_proxy app:8080 {
# Server-Sent Events: don't buffer
flush_interval -1
}
}

29
deploy/Containerfile Normal file
View file

@ -0,0 +1,29 @@
# OweMe: one image with the server (Node standard library only, no
# node_modules) and the built web client. Build context: the repo root.
FROM docker.io/library/node:24.21.0-alpine AS build
WORKDIR /src
COPY package.json package-lock.json ./
COPY packages/core/package.json packages/core/
COPY apps/web/package.json apps/web/
# --ignore-scripts: no install hooks from dependencies run during the build.
RUN npm ci --no-audit --no-fund --ignore-scripts
COPY packages/core packages/core
COPY apps/web apps/web
RUN npm run build -w apps/web
FROM docker.io/library/node:24.21.0-alpine
WORKDIR /app
ENV NODE_ENV=production \
HOST=0.0.0.0 \
PORT=8080 \
DATA_DIR=/data \
STATIC_DIR=/app/web \
TRUST_PROXY=1
COPY apps/server/src ./server
COPY --from=build /src/apps/web/dist ./web
RUN mkdir -p /data && chown node:node /data
USER node
VOLUME /data
EXPOSE 8080
CMD ["node", "--disable-warning=ExperimentalWarning", "server/main.ts"]

92
deploy/README.md Normal file
View file

@ -0,0 +1,92 @@
# Deploying OweMe on a VPS
Two containers via `podman compose`: **app** (the Node server plus the built
web client) and **caddy** (HTTPS and reverse proxy). Only Caddy publishes ports.
## Requirements
- Podman ≥ 4 with `podman compose` (podman-compose or docker-compose as the provider)
- A domain with an A/AAAA record pointing at the VPS
- Ports 80 and 443 (TCP, plus UDP 443 for HTTP/3) open in the firewall
## First deploy
```sh
git clone <repo> oweme && cd oweme/deploy
cp .env.example .env
chmod 600 .env
$EDITOR .env # set DOMAIN and VAPID_SUBJECT (mailto:)
podman compose build # builds localhost/oweme:latest
# Web Push keys: written into .env, private key never printed.
podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env
podman compose up -d
podman compose logs -f # Caddy obtains the certificate on first request
```
Open `https://$DOMAIN`. `curl https://$DOMAIN/api/health` should say `{"ok":true}`.
## Updating
```sh
cd oweme && git pull
cd deploy && podman compose up -d --build
```
Data lives in the `oweme-data` volume and survives rebuilds.
## Configuration (`deploy/.env`)
| Variable | Required | Default | Purpose |
|---|---|---|---|
| `DOMAIN` | yes | — | Public hostname; Caddy's site address and certificate |
| `VAPID_SUBJECT` | for push | — | `mailto:` contact sent to push services |
| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Generated by `gen-vapid.ts`; empty = notifications off |
| `MAX_PHOTO_BYTES` | no | `2097152` | Max size of one uploaded (encrypted) photo |
| `MAX_EVENT_BYTES` | no | `65536` | Max size of one encrypted event |
| `MAX_GROUP_BYTES` | no | `209715200` | Storage cap per group (events + photos) |
| `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per client IP per hour |
| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on |
| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy |
Rotating the VAPID keys (`gen-vapid.ts … --force`) silently invalidates every
push subscription; users have to toggle notifications off and on again.
## Ports (rootless Podman)
Rootless Podman can't bind ports below 1024 by default. Pick one:
1. Allow it (simplest):
```sh
echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee /etc/sysctl.d/90-unprivileged-ports.conf
sudo sysctl --system
```
2. Or publish high ports (`HTTP_PORT=8080`, `HTTPS_PORT=8443`) and redirect
80→8080 / 443→8443 in your firewall (e.g. nftables/UFW `nat` rules).
With rootless Podman, published ports go through `rootlessport` and are
subject to the host firewall. Rootful container networking can add its own
firewall rules around UFW, so don't rely on UFW alone if you run rootful.
## Backups
Back up the `oweme-data` volume (SQLite database + encrypted photos):
```sh
podman volume export oweme_oweme-data > oweme-data-$(date +%F).tar
```
Everything in it is already end-to-end encrypted, so the backup can be stored
anywhere. Users can also download per-group backup files in the app.
## Testing a deployment
From a machine with the repo and Node 24:
```sh
npm ci && E2E_BASE_URL=https://$DOMAIN npx playwright test e2e/app.spec.ts
```
This creates a throwaway group on that server.

49
deploy/compose.yaml Normal file
View file

@ -0,0 +1,49 @@
# podman compose up -d --build (run from this directory; reads ./.env)
# See deploy/README.md for the full deploy steps.
name: oweme
services:
app:
build:
context: ..
dockerfile: deploy/Containerfile
image: localhost/oweme:latest
restart: unless-stopped
env_file: .env
environment:
# fixed inside the container; everything else comes from .env
HOST: 0.0.0.0
PORT: "8080"
DATA_DIR: /data
STATIC_DIR: /app/web
TRUST_PROXY: "1"
volumes:
- oweme-data:/data
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/api/health"]
interval: 30s
timeout: 5s
# no published ports: only Caddy can reach the app
caddy:
image: docker.io/library/caddy:2.10.2-alpine
restart: unless-stopped
depends_on:
- app
environment:
DOMAIN: ${DOMAIN:?set DOMAIN in deploy/.env}
ports:
# BIND_ADDR defaults to all interfaces (a public VPS). Rootless Podman
# can't bind ports below 1024 by default; see README "Ports".
- "${BIND_ADDR:-0.0.0.0}:${HTTP_PORT:-80}:80"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443"
- "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro,Z
- caddy-data:/data
- caddy-config:/config
volumes:
oweme-data:
caddy-data:
caddy-config:

145
e2e/app.spec.ts Normal file
View file

@ -0,0 +1,145 @@
import { expect, test, type Browser, type Page } from '@playwright/test';
import { deflateSync } from 'node:zlib';
/** A small valid PNG (solid colour), for the photo upload. */
function png(w = 64, h = 48): Buffer {
const crcTable = Array.from({ length: 256 }, (_, n) => {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
return c >>> 0;
});
const crc = (b: Buffer) => { let c = 0xffffffff; for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; };
const chunk = (type: string, data: Buffer) => {
const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
const td = Buffer.concat([Buffer.from(type), data]);
const c = Buffer.alloc(4); c.writeUInt32BE(crc(td));
return Buffer.concat([len, td, c]);
};
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
const raw = Buffer.alloc((w * 3 + 1) * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([61, 220, 151], y * (w * 3 + 1) + 1 + x * 3);
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
}
async function device(browser: Browser, locale: string): Promise<Page> {
const ctx = await browser.newContext({ locale, viewport: { width: 412, height: 915 }, isMobile: true, hasTouch: true });
await ctx.grantPermissions(['clipboard-read', 'clipboard-write']);
return ctx.newPage();
}
test('two devices share a group end to end', async ({ browser }) => {
// ---- Anna creates a group (English device) --------------------------
const anna = await device(browser, 'en-US');
await anna.goto('/');
await expect(anna.getByText('No groups on this device yet')).toBeVisible();
await anna.getByRole('link', { name: 'New group' }).click();
await anna.getByLabel('Group name').fill('Prague trip');
await anna.getByLabel('Main currency').selectOption('CZK');
await anna.getByLabel('Your name').fill('Anna');
await anna.getByPlaceholder('Name').fill('Petr');
await anna.getByRole('button', { name: 'Add member' }).click();
await anna.getByPlaceholder('Name').nth(1).fill('Jana');
await anna.getByRole('button', { name: 'Create group' }).click();
// Lands on settings with the "save this link" warning; copy the link.
await expect(anna.getByText('Save this link somewhere safe')).toBeVisible();
await anna.getByRole('button', { name: 'Copy link' }).click();
const link = await anna.evaluate(() => navigator.clipboard.readText());
expect(link).toMatch(/\/g\/[A-Za-z0-9_-]{22}#[A-Za-z0-9_-]{43}$/);
await anna.getByRole('button', { name: 'Back', exact: true }).click();
// ---- An equal split in the base currency ----------------------------
await anna.getByRole('link', { name: 'Add expense' }).click();
await anna.getByLabel('Amount').fill('300');
await anna.getByLabel('What was it for?').fill('Dinner');
await anna.getByRole('button', { name: 'Save', exact: true }).click();
await expect(anna.getByRole('link', { name: /Dinner/ })).toBeVisible();
await expect(anna.getByText('you lent CZK 200.00')).toBeVisible();
// ---- Petr opens the link on a Czech device --------------------------
const petr = await device(browser, 'cs-CZ');
await petr.goto(link);
await expect(petr.getByRole('heading', { name: 'Kdo jste?' })).toBeVisible();
// The secret is dropped from the address bar once saved.
expect(new URL(petr.url()).hash).toBe('');
await petr.getByRole('button', { name: 'Petr' }).click();
await expect(petr.getByRole('link', { name: /Dinner/ })).toBeVisible();
await expect(petr.getByText(/dlužíte 100,00\sKč/)).toBeVisible();
// ---- Petr adds a EUR expense with exact amounts and a photo ----------
await petr.getByRole('link', { name: 'Přidat výdaj' }).click();
await petr.getByLabel('Částka').fill('30');
await petr.getByLabel('Měna').selectOption('EUR');
// The ECB rate is prefilled by our server.
await expect(petr.getByText(/Kurz ECB ze dne/)).toBeVisible({ timeout: 30_000 });
const rate = Number((await petr.getByLabel('1 EUR =').inputValue()).replace(',', '.'));
expect(rate).toBeGreaterThan(15);
expect(rate).toBeLessThan(40);
await petr.getByLabel('Za co?').fill('Museum');
await petr.getByRole('button', { name: 'Částky' }).click();
await petr.getByLabel('Rozdělení: Anna').fill('10');
await petr.getByLabel('Rozdělení: Petr').fill('20');
await petr.getByLabel('Jana', { exact: true }).uncheck();
await petr.locator('input[type=file]').setInputFiles({ name: 'receipt.png', mimeType: 'image/png', buffer: png() });
await expect(petr.getByRole('img', { name: 'Fotka' })).toBeVisible();
await petr.getByRole('button', { name: 'Uložit' }).click();
await expect(petr.getByRole('link', { name: /Museum/ })).toBeVisible();
// ---- Anna sees it live (SSE), with the photo, without reloading -----
await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible({ timeout: 15_000 });
await anna.getByRole('link', { name: /Museum/ }).click();
await expect(anna.getByText('€30.00').first()).toBeVisible();
await expect(anna.getByRole('img', { name: 'Photo' })).toBeVisible({ timeout: 15_000 });
await anna.getByRole('button', { name: 'Close', exact: true }).click();
// ---- Balances and settle-up ------------------------------------------
await anna.getByRole('link', { name: 'Balances' }).click();
const annaBal = 20000 - Math.round(rate * 1000); // +200 Kč − €10
const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 });
const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`;
await expect(anna.getByText(shown).first()).toBeVisible();
await expect(anna.getByText('Settle up')).toBeVisible();
const recordButtons = anna.getByRole('button', { name: 'Record payment' });
const transfers = await recordButtons.count();
expect(transfers).toBeGreaterThan(0);
expect(transfers).toBeLessThanOrEqual(2);
// ---- Rewind and undo ------------------------------------------------
await anna.getByRole('link', { name: 'Activity' }).click();
await expect(anna.getByText(/Petr added Museum/)).toBeVisible();
anna.once('dialog', (d) => d.accept());
// Rewind to just after Dinner was added (the entry below "Museum").
await anna.getByRole('button', { name: 'Rewind group to here' }).first().click();
await expect(anna.getByText(/rewound the group/)).toBeVisible();
await anna.getByRole('link', { name: 'Expenses' }).click();
await expect(anna.getByRole('link', { name: /Museum/ })).toHaveCount(0);
await anna.getByRole('link', { name: 'Activity' }).click();
anna.once('dialog', (d) => d.accept());
await anna.getByRole('button', { name: 'Undo this rewind' }).click();
await expect(anna.getByText(/rewound the group/)).toHaveCount(2);
await anna.getByRole('link', { name: 'Expenses' }).click();
await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible();
// ---- Offline edits sync later ---------------------------------------
await anna.context().setOffline(true);
await anna.getByRole('link', { name: 'Add expense' }).click();
await anna.getByLabel('Amount').fill('90');
await anna.getByLabel('What was it for?').fill('Taxi');
await anna.getByRole('button', { name: 'Save', exact: true }).click();
await expect(anna.getByRole('link', { name: /Taxi/ })).toBeVisible();
await expect(anna.getByText(/Offline/)).toBeVisible({ timeout: 20_000 });
await anna.context().setOffline(false);
await expect(petr.getByRole('link', { name: /Taxi/ })).toBeVisible({ timeout: 30_000 });
// ---- Home lists the group with my balance after reload --------------
await anna.goto('/');
await expect(anna.getByRole('link', { name: /Prague trip/ })).toBeVisible();
await expect(anna.getByText(/you are owed/)).toBeVisible();
// ---- Stats render ---------------------------------------------------
await anna.getByRole('link', { name: /Prague trip/ }).click();
await anna.getByRole('link', { name: 'Stats' }).click();
await expect(anna.getByRole('heading', { name: 'By category' })).toBeVisible();
await expect(anna.getByRole('heading', { name: 'Paid vs. share' })).toBeVisible();
});

49
e2e/push.spec.ts Normal file
View file

@ -0,0 +1,49 @@
import { expect, test } from '@playwright/test';
// Delivers a push message straight to the service worker over CDP (no real
// push service involved) and checks that it decrypts the new events and
// shows a readable notification.
// The stripped-down headless shell always denies notifications; full
// Chromium in headless mode supports them.
test.use({ channel: 'chromium' });
test('service worker turns a push into a decrypted notification', async ({ browser, baseURL }) => {
const annaCtx = await browser.newContext({ locale: 'en-US' });
await annaCtx.grantPermissions(['clipboard-read', 'clipboard-write', 'notifications']);
const anna = await annaCtx.newPage();
await anna.goto('/new');
await anna.getByLabel('Group name').fill('Flat');
await anna.getByLabel('Your name').fill('Anna');
await anna.getByPlaceholder('Name').fill('Petr');
await anna.getByRole('button', { name: 'Create group' }).click();
await anna.getByRole('button', { name: 'Copy link' }).click();
const link = await anna.evaluate(() => navigator.clipboard.readText());
const groupId = /\/g\/([^#]+)#/.exec(link)![1];
await anna.evaluate(() => navigator.serviceWorker.ready);
// Petr adds an expense from another device.
const petr = await (await browser.newContext({ locale: 'en-US' })).newPage();
await petr.goto(link);
await petr.getByRole('button', { name: 'Petr' }).click();
await petr.getByRole('link', { name: 'Add expense' }).click();
await petr.getByLabel('Amount').fill('12.50');
await petr.getByLabel('What was it for?').fill('Pizza');
await petr.getByRole('button', { name: 'Save', exact: true }).click();
await expect(petr.getByRole('link', { name: /Pizza/ })).toBeVisible();
// Anna is on the home screen (not looking at the group) when the push arrives.
await anna.goto('/');
const cdp = await annaCtx.newCDPSession(anna);
const registrationId = await new Promise<string>((resolve) => {
cdp.on('ServiceWorker.workerRegistrationUpdated', ({ registrations }) => {
const r = registrations.find((x: { scopeURL: string; isDeleted: boolean }) => x.scopeURL.startsWith(baseURL!) && !x.isDeleted);
if (r) resolve(r.registrationId);
});
void cdp.send('ServiceWorker.enable');
});
await cdp.send('ServiceWorker.deliverPushMessage', { origin: new URL(baseURL!).origin, registrationId, data: JSON.stringify({ g: groupId }) });
await expect
.poll(async () => anna.evaluate(async () => (await (await navigator.serviceWorker.ready).getNotifications()).map((n) => `${n.title} | ${n.body}`)), { timeout: 15_000 })
.toContainEqual(expect.stringMatching(/Flat \| Petr: Pizza · \S*12\.50/));
});

1612
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

22
package.json Normal file
View file

@ -0,0 +1,22 @@
{
"name": "oweme",
"private": true,
"type": "module",
"workspaces": ["packages/core", "apps/web"],
"engines": { "node": ">=24" },
"scripts": {
"dev": "node scripts/dev.mjs",
"build": "npm run build -w apps/web",
"test": "npm run test:core && npm run test:server",
"test:core": "vitest run --root packages/core",
"test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/*.test.ts",
"test:e2e": "playwright test",
"check": "tsc -p packages/core && tsc -p apps/server && npm run check -w apps/web"
},
"devDependencies": {
"@playwright/test": "1.63.0",
"@types/node": "24.10.1",
"typescript": "6.0.2",
"vitest": "5.0.2"
}
}

View file

@ -0,0 +1,6 @@
{
"name": "@oweme/core",
"private": true,
"type": "module",
"exports": { ".": "./src/index.ts" }
}

46
packages/core/src/csv.ts Normal file
View file

@ -0,0 +1,46 @@
// CSV export (SPEC.md §7.6). Plain decimal numbers with "." so spreadsheets
// in any locale can import them.
import { inBase } from './expense.ts';
import { toDecimalString } from './money.ts';
import { balances } from './settle.ts';
import type { GroupState } from './types.ts';
function cell(v: string | number): string {
const s = String(v);
// Neutralise spreadsheet formula injection, then quote if needed.
const safe = /^[=+\-@\t\r]/.test(s) && typeof v === 'string' ? `'${s}` : s;
return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;
}
const row = (cells: (string | number)[]) => cells.map(cell).join(',');
export function expensesCsv(s: GroupState): string {
const base = s.group?.baseCurrency ?? 'EUR';
const name = (id: string) => s.members.find((m) => m.id === id)?.name ?? id;
const header = [
'date', 'title', 'type', 'category', 'currency', 'amount', 'rate', `amount_${base}`, 'paid_by', 'note',
...s.members.map((m) => `share_${base}:${m.name}`),
];
const lines = [row(header)];
const records = Object.values(s.expenses)
.filter((r) => !r.deleted)
.sort((a, b) => a.expense.date.localeCompare(b.expense.date));
for (const { expense: e } of records) {
const b = inBase(e, base);
lines.push(row([
e.date, e.title, e.kind, e.category, e.currency, toDecimalString(e.amount, e.currency),
e.currency === base ? '1' : e.rate, toDecimalString(b.total, base),
e.payers.map((p) => name(p.member)).join(' + '), e.note,
...s.members.map((m) => toDecimalString(b.owed[m.id] ?? 0, base)),
]));
}
return lines.join('\r\n') + '\r\n';
}
export function balancesCsv(s: GroupState): string {
const base = s.group?.baseCurrency ?? 'EUR';
const bal = balances(s);
const lines = [row(['member', `balance_${base}`])];
for (const m of s.members) lines.push(row([m.name, toDecimalString(bal[m.id] ?? 0, base)]));
return lines.join('\r\n') + '\r\n';
}

View file

@ -0,0 +1,117 @@
// Validating an expense and turning it into per-member amounts.
import { allocate, convert, isCurrencyCode, isValidRate, MAX_AMOUNT } from './money.ts';
import { CATEGORIES, type Expense, type Member } from './types.ts';
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
const isInt = (n: unknown): n is number => Number.isSafeInteger(n);
export function isValidDate(d: unknown): d is string {
if (typeof d !== 'string' || !DATE_RE.test(d)) return false;
const t = Date.parse(`${d}T00:00:00Z`);
return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === d;
}
/**
* Returns null if the expense is valid for the given members, otherwise a
* short reason. Events failing this are ignored on replay, so a buggy or
* malicious client can't corrupt everyone's balances.
*/
export function validateExpense(e: Expense, members: Member[]): string | null {
const ids = new Set(members.map((m) => m.id));
if (!e || typeof e !== 'object') return 'not an object';
if (typeof e.id !== 'string' || !e.id) return 'id';
if (e.kind !== 'expense' && e.kind !== 'transfer') return 'kind';
if (typeof e.title !== 'string' || e.title.length > 200) return 'title';
if (e.category !== 'transfer' && !(CATEGORIES as readonly string[]).includes(e.category)) return 'category';
if (!isValidDate(e.date)) return 'date';
if (!isCurrencyCode(e.currency)) return 'currency';
if (!isInt(e.amount) || e.amount <= 0 || e.amount > MAX_AMOUNT) return 'amount';
if (!isValidRate(e.rate)) return 'rate';
if (typeof e.note !== 'string' || e.note.length > 2000) return 'note';
if (!Array.isArray(e.payers) || e.payers.length === 0) return 'payers';
const payerIds = new Set<string>();
let paid = 0;
for (const p of e.payers) {
if (!ids.has(p.member) || payerIds.has(p.member)) return 'payer member';
if (!isInt(p.amount) || p.amount <= 0) return 'payer amount';
payerIds.add(p.member);
paid += p.amount;
}
if (paid !== e.amount) return 'payers sum';
const { mode, entries } = e.split ?? {};
if (!Array.isArray(entries) || entries.length === 0) return 'split';
const seen = new Set<string>();
let sum = 0;
for (const s of entries) {
if (!ids.has(s.member) || seen.has(s.member)) return 'split member';
if (!isInt(s.value) || s.value < 0) return 'split value';
seen.add(s.member);
sum += s.value;
}
switch (mode) {
case 'equal':
if (entries.some((s) => s.value > 1) || sum === 0) return 'equal';
break;
case 'shares':
if (sum === 0 || sum > 1_000_000) return 'shares';
break;
case 'exact':
if (sum !== e.amount) return 'exact sum';
break;
case 'percent':
if (sum !== 10000) return 'percent sum';
break;
default:
return 'mode';
}
if (e.kind === 'transfer' && entries.filter((s) => s.value > 0).length !== 1) return 'transfer';
if (e.photo !== null) {
const p = e.photo;
if (!p || typeof p.blobId !== 'string' || typeof p.thumbBlobId !== 'string') return 'photo';
}
return null;
}
/** What each member owes, in minor units of the expense's own currency. */
export function owedOriginal(e: Expense): Record<string, number> {
const entries = e.split.entries;
const parts =
e.split.mode === 'exact'
? entries.map((s) => s.value)
: allocate(e.amount, entries.map((s) => s.value));
const out: Record<string, number> = {};
entries.forEach((s, i) => {
if (parts[i] !== 0) out[s.member] = parts[i];
});
return out;
}
export interface ExpenseInBase {
/** total in base currency minor units */
total: number;
paid: Record<string, number>;
owed: Record<string, number>;
}
/**
* Express an expense in the base currency. The total is converted once, and
* both the payer vector and the split vector are re-allocated onto it, so
* paid and owed each sum to exactly `total`.
*/
export function inBase(e: Expense, baseCurrency: string): ExpenseInBase {
const total = convert(e.amount, e.currency, baseCurrency, e.rate);
const owedOrig = owedOriginal(e);
const owedIds = Object.keys(owedOrig);
const paidIds = e.payers.map((p) => p.member);
const sameCurrency = e.currency === baseCurrency;
const paidParts = sameCurrency ? e.payers.map((p) => p.amount) : allocate(total, e.payers.map((p) => p.amount));
const owedParts = sameCurrency ? owedIds.map((id) => owedOrig[id]) : allocate(total, owedIds.map((id) => owedOrig[id]));
const paid: Record<string, number> = {};
const owed: Record<string, number> = {};
paidIds.forEach((id, i) => (paid[id] = paidParts[i]));
owedIds.forEach((id, i) => (owed[id] = owedParts[i]));
return { total, paid, owed };
}

View file

@ -0,0 +1,8 @@
export * from './types.ts';
export * from './money.ts';
export * from './expense.ts';
export * from './replay.ts';
export * from './settle.ts';
export * from './recurring.ts';
export * from './stats.ts';
export * from './csv.ts';

134
packages/core/src/money.ts Normal file
View file

@ -0,0 +1,134 @@
// Integer money math. Every client must produce identical numbers from the
// same events, so nothing here uses floating point: amounts are integers in
// minor units, rates are exact decimal strings, and intermediate values are
// BigInt.
/** ISO 4217 exponents that differ from the default of 2. Hardcoded rather
* than read from Intl, because Intl data can differ between browsers. */
const EXPONENTS: Record<string, number> = {
BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0,
RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0,
BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3,
};
export const MAX_AMOUNT = 1e13; // minor units; keeps everything well inside 2^53
export function isCurrencyCode(code: unknown): code is string {
return typeof code === 'string' && /^[A-Z]{3}$/.test(code);
}
export function exponent(currency: string): number {
return EXPONENTS[currency] ?? 2;
}
const RATE_RE = /^(\d{1,12})(?:\.(\d{1,12}))?$/;
/** A rate is a positive decimal string, e.g. "25.214". */
export function isValidRate(rate: unknown): rate is string {
if (typeof rate !== 'string') return false;
const m = RATE_RE.exec(rate);
if (!m) return false;
return BigInt(m[1] + (m[2] ?? '')) > 0n;
}
function parseRate(rate: string): { num: bigint; scale: number } {
const m = RATE_RE.exec(rate);
if (!m) throw new Error(`invalid rate ${rate}`);
const frac = m[2] ?? '';
return { num: BigInt(m[1] + frac), scale: frac.length };
}
/** n / d rounded half to even, for n >= 0, d > 0. */
function divRoundHalfEven(n: bigint, d: bigint): bigint {
const q = n / d;
const r = n % d;
const twice = r * 2n;
if (twice > d || (twice === d && q % 2n === 1n)) return q + 1n;
return q;
}
/** Convert an amount (minor units of `from`) into minor units of `to`. */
export function convert(amount: number, from: string, to: string, rate: string): number {
if (from === to) return amount;
const { num, scale } = parseRate(rate);
const n = BigInt(amount) * num * 10n ** BigInt(exponent(to));
const d = 10n ** BigInt(scale + exponent(from));
return Number(divRoundHalfEven(n, d));
}
/**
* Split `total` into integers proportional to `weights` that sum exactly to
* `total`. Each part is floored, then the leftover units go one at a time to
* the largest remainders; ties go to the lower index (member order).
*/
export function allocate(total: number, weights: number[]): number[] {
const W = weights.reduce((a, w) => a + BigInt(w), 0n);
if (W <= 0n) throw new Error('allocate: weights must sum to > 0');
const T = BigInt(total);
const parts = weights.map((w) => {
const raw = T * BigInt(w);
return { q: raw / W, r: raw % W };
});
let leftover = T - parts.reduce((a, p) => a + p.q, 0n);
const order = parts
.map((p, i) => ({ r: p.r, i }))
.sort((a, b) => (a.r === b.r ? a.i - b.i : a.r > b.r ? -1 : 1));
for (const { i } of order) {
if (leftover <= 0n) break;
parts[i].q += 1n;
leftover -= 1n;
}
return parts.map((p) => Number(p.q));
}
/** Minor units → plain decimal string ("1234.50"), no grouping. */
export function toDecimalString(minor: number, currency: string): string {
const e = exponent(currency);
const neg = minor < 0;
const s = String(Math.abs(minor)).padStart(e + 1, '0');
const out = e === 0 ? s : `${s.slice(0, -e)}.${s.slice(-e)}`;
return neg ? `-${out}` : out;
}
/**
* Parse user input ("1 234,5", "1234.50", "12") into minor units.
* Returns null for anything that isn't a positive number with at most the
* currency's number of decimals.
*/
export function parseAmount(input: string, currency: string): number | null {
const e = exponent(currency);
const s = input.replace(/[\s\u00a0\u202f']/g, '');
let intPart: string;
let frac = '';
const sep = Math.max(s.lastIndexOf('.'), s.lastIndexOf(','));
const before = s.slice(0, sep);
const after = s.slice(sep + 1);
if (/^\d+$/.test(s)) {
intPart = s;
} else if (
sep > 0 && !before.includes(s[sep]) && after.length >= 1 && after.length <= e && /^\d+$/.test(after) &&
/^(\d{1,3}([.,]\d{3})*|\d+)$/.test(before)
) {
// "12,5" / "1.234,50": the last separator is the decimal point
intPart = before.replace(/[.,]/g, '');
frac = after;
} else if (/^\d{1,3}([.,]\d{3})+$/.test(s)) {
// "1.234" in a 2-decimal currency: grouping only
intPart = s.replace(/[.,]/g, '');
} else {
return null;
}
const minor = Number(intPart + frac.padEnd(e, '0'));
if (!Number.isSafeInteger(minor) || minor <= 0 || minor > MAX_AMOUNT) return null;
return minor;
}
/** Turn a float rate (from the rates API) into a stored decimal string with
* 6 significant digits. Only used to prefill; the stored string is then exact. */
export function rateToString(rate: number): string {
if (!(rate > 0) || !Number.isFinite(rate)) throw new Error('bad rate');
const digits = Math.max(0, 6 - Math.floor(Math.log10(rate)) - 1);
let s = rate.toFixed(Math.min(12, digits));
if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, '');
return s === '0' ? rate.toFixed(12).replace(/0+$/, '') : s;
}

View file

@ -0,0 +1,69 @@
// Recurring expenses (SPEC.md §7.4). There's no server-side scheduler (the
// server can't read templates), so whichever client opens the group first
// creates the missing occurrences. Their ids are deterministic, so two
// clients doing it at once produce the same expense and replay keeps one.
import type { Expense, Recurring, RecurringRule, GroupState } from './types.ts';
const MAX_PER_RUN = 120;
function parse(d: string): Date {
return new Date(`${d}T00:00:00Z`);
}
function fmt(d: Date): string {
return d.toISOString().slice(0, 10);
}
function daysInMonth(y: number, m: number): number {
return new Date(Date.UTC(y, m + 1, 0)).getUTCDate();
}
/** The n-th occurrence date (n = 0 is `start`). Monthly/yearly clamp to month end. */
export function nthOccurrence(rule: RecurringRule, n: number): string {
const start = parse(rule.start);
if (rule.freq === 'weekly') return fmt(new Date(start.getTime() + n * rule.interval * 7 * 864e5));
const months = rule.freq === 'monthly' ? n * rule.interval : n * rule.interval * 12;
const y = start.getUTCFullYear() + Math.floor((start.getUTCMonth() + months) / 12);
const m = (start.getUTCMonth() + months) % 12;
const day = Math.min(start.getUTCDate(), daysInMonth(y, m));
return fmt(new Date(Date.UTC(y, m, day)));
}
/** All occurrence dates from start up to and including `today`. */
export function occurrencesUntil(rule: RecurringRule, today: string): string[] {
const out: string[] = [];
for (let n = 0; out.length < 10_000; n++) {
const d = nthOccurrence(rule, n);
if (d > today || (rule.end && d > rule.end)) break;
out.push(d);
}
return out;
}
export function occurrenceId(recurringId: string, date: string): string {
return `rec-${recurringId}-${date}`;
}
/**
* Occurrences that are due but don't exist yet. Deleted occurrences count
* as existing, so deleting one doesn't make it come back.
*/
export function dueOccurrences(s: GroupState, today: string): Expense[] {
const out: Expense[] = [];
for (const r of Object.values(s.recurring) as Recurring[]) {
for (const date of occurrencesUntil(r.rule, today)) {
const id = occurrenceId(r.id, date);
if (s.expenses[id]) continue;
out.push({ ...structuredClone(r.template), id, date, photo: null, recurringId: r.id });
if (out.length >= MAX_PER_RUN) return out;
}
}
return out;
}
export function nextOccurrence(rule: RecurringRule, today: string): string | null {
for (let n = 0; n < 10_000; n++) {
const d = nthOccurrence(rule, n);
if (rule.end && d > rule.end) return null;
if (d > today) return d;
}
return null;
}

197
packages/core/src/replay.ts Normal file
View file

@ -0,0 +1,197 @@
// Rebuild a group's state from its event log. Events are applied in log
// order (server seq, then the local outbox); for the same entity the later
// event wins. A `revert` event replaces the state with a snapshot taken right
// after its target event; nothing is ever erased from the log. See SPEC.md §6.
import { validateExpense } from './expense.ts';
import { isCurrencyCode } from './money.ts';
import type { Activity, GroupEvent, GroupState, Recurring } from './types.ts';
export function emptyState(): GroupState {
return { group: null, members: [], expenses: {}, comments: {}, recurring: {} };
}
const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length > 0 && v.length <= max;
function validRecurring(r: Recurring, s: GroupState): boolean {
if (!r || !str(r.id, 100) || !r.rule || !r.template) return false;
const { freq, interval, start, end } = r.rule;
if (!['weekly', 'monthly', 'yearly'].includes(freq)) return false;
if (!Number.isSafeInteger(interval) || interval < 1 || interval > 52) return false;
const probe = { ...r.template, id: r.id, date: start, photo: null };
if (validateExpense(probe, s.members) !== null) return false;
return end === null || (typeof end === 'string' && end >= start);
}
/**
* Apply one event to `s` in place. Returns the activity entry describing it.
* `snapshots` provides states for `revert` targets.
*/
function apply(s: GroupState, ev: GroupEvent, snapshots: Map<string, GroupState>): { state: GroupState; activity: Activity } {
const act: Activity = {
eventId: ev.id, seq: ev.seq, at: ev.at, actor: ev.actor, type: ev.type,
entityId: null, before: null, after: null,
};
const ignore = () => ((act.ignored = true), { state: s, activity: act });
const member = (id: string) => s.members.find((m) => m.id === id);
const hasExpenses = Object.keys(s.expenses).length > 0;
switch (ev.type) {
case 'group.created': {
const d = ev.data;
if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore();
s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' };
act.after = { ...s.group };
break;
}
case 'group.updated': {
if (!s.group) return ignore();
const d = ev.data ?? {};
act.before = { ...s.group };
if (d.name !== undefined) {
if (!str(d.name, 100)) return ignore();
s.group.name = d.name;
}
if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16);
if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) {
// Locked once the group has any expense (SPEC §7.1).
if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore();
s.group.baseCurrency = d.baseCurrency;
}
act.after = { ...s.group };
break;
}
case 'member.added': {
const d = ev.data;
if (!str(d?.id, 100) || !str(d.name, 60) || member(d.id)) return ignore();
s.members.push({ id: d.id, name: d.name, color: String(d.color ?? '').slice(0, 16), archived: false });
act.entityId = d.id;
act.after = { name: d.name };
break;
}
case 'member.updated': {
const m = member(ev.data?.id);
if (!m) return ignore();
act.entityId = m.id;
act.before = { name: m.name, color: m.color };
if (ev.data.name !== undefined) {
if (!str(ev.data.name, 60)) return ignore();
m.name = ev.data.name;
}
if (typeof ev.data.color === 'string') m.color = ev.data.color.slice(0, 16);
act.after = { name: m.name, color: m.color };
break;
}
case 'member.archived':
case 'member.restored': {
const m = member(ev.data?.id);
if (!m) return ignore();
act.entityId = m.id;
m.archived = ev.type === 'member.archived';
break;
}
case 'expense.created':
case 'expense.updated': {
const e = ev.data;
const existing = s.expenses[e?.id];
act.entityId = e?.id ?? null;
// Creation is idempotent (first wins): two clients generating the same
// recurring occurrence must not clobber each other.
if (ev.type === 'expense.created' && existing) return ignore();
if (ev.type === 'expense.updated' && !existing) return ignore();
if (validateExpense(e, s.members) !== null) return ignore();
const copy = structuredClone(e);
if (existing) {
act.before = existing.expense;
existing.expense = copy;
existing.updatedAt = ev.at;
} else {
s.expenses[e.id] = { expense: copy, deleted: false, createdBy: ev.actor, createdAt: ev.at, updatedAt: ev.at };
}
act.after = copy;
break;
}
case 'expense.deleted':
case 'expense.restored': {
const r = s.expenses[ev.data?.id];
if (!r) return ignore();
act.entityId = r.expense.id;
act.before = r.expense;
r.deleted = ev.type === 'expense.deleted';
break;
}
case 'comment.added': {
const d = ev.data;
if (!str(d?.id, 100) || !str(d.text, 2000) || !s.expenses[d.expenseId] || s.comments[d.id]) return ignore();
s.comments[d.id] = { id: d.id, expenseId: d.expenseId, text: d.text, author: ev.actor, at: ev.at };
act.entityId = d.expenseId;
act.after = { text: d.text };
break;
}
case 'comment.deleted': {
const c = s.comments[ev.data?.id];
if (!c) return ignore();
act.entityId = c.expenseId;
act.before = { text: c.text };
delete s.comments[c.id];
break;
}
case 'recurring.created':
case 'recurring.updated': {
const r = ev.data;
const existing = s.recurring[r?.id];
if ((ev.type === 'recurring.created') === !!existing) return ignore();
if (!validRecurring(r, s)) return ignore();
act.entityId = r.id;
act.before = existing ?? null;
s.recurring[r.id] = structuredClone(r);
act.after = s.recurring[r.id];
break;
}
case 'recurring.deleted': {
const r = s.recurring[ev.data?.id];
if (!r) return ignore();
act.entityId = r.id;
act.before = r;
delete s.recurring[r.id];
break;
}
case 'revert': {
const snap = snapshots.get(ev.data?.targetId);
if (!snap) return ignore();
act.entityId = ev.data.targetId;
return { state: structuredClone(snap), activity: act };
}
default:
return ignore();
}
return { state: s, activity: act };
}
export interface ReplayResult {
state: GroupState;
/** oldest first, one entry per event */
activity: Activity[];
}
/** Replay events (already in log order) into a state. */
export function replay(events: GroupEvent[]): ReplayResult {
const targets = new Set<string>();
for (const ev of events) if (ev.type === 'revert' && typeof ev.data?.targetId === 'string') targets.add(ev.data.targetId);
const snapshots = new Map<string, GroupState>();
const activity: Activity[] = [];
let state = emptyState();
for (const ev of events) {
const r = apply(state, ev, snapshots);
state = r.state;
activity.push(r.activity);
if (targets.has(ev.id) && !snapshots.has(ev.id)) snapshots.set(ev.id, structuredClone(state));
}
return { state, activity };
}
/** Sort events into log order: synced by seq, then pending in outbox order. */
export function logOrder(synced: GroupEvent[], pending: GroupEvent[]): GroupEvent[] {
const ids = new Set(synced.map((e) => e.id));
return [...synced].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)).concat(pending.filter((e) => !ids.has(e.id)));
}

View file

@ -0,0 +1,47 @@
// Balances and settle-up suggestions (SPEC.md §5.3–5.4).
import { inBase } from './expense.ts';
import type { GroupState } from './types.ts';
/** member id → balance in base minor units (positive = is owed money). */
export function balances(s: GroupState): Record<string, number> {
const out: Record<string, number> = {};
for (const m of s.members) out[m.id] = 0;
if (!s.group) return out;
for (const r of Object.values(s.expenses)) {
if (r.deleted) continue;
const b = inBase(r.expense, s.group.baseCurrency);
for (const [id, v] of Object.entries(b.paid)) out[id] = (out[id] ?? 0) + v;
for (const [id, v] of Object.entries(b.owed)) out[id] = (out[id] ?? 0) - v;
}
return out;
}
export interface Transfer {
from: string;
to: string;
amount: number;
}
/**
* Greedy settle-up: repeatedly pay the largest creditor from the largest
* debtor. At most n − 1 transfers. Ties go to the earlier member, so every
* client suggests the same transfers.
*/
export function settleUp(bal: Record<string, number>, memberOrder: string[]): Transfer[] {
const idx = new Map(memberOrder.map((id, i) => [id, i]));
const rank = (id: string) => idx.get(id) ?? Number.MAX_SAFE_INTEGER;
const debtors = Object.entries(bal).filter(([, v]) => v < 0).map(([id, v]) => ({ id, v: -v }));
const creditors = Object.entries(bal).filter(([, v]) => v > 0).map(([id, v]) => ({ id, v }));
const pick = (xs: { id: string; v: number }[]) =>
xs.reduce((best, x) => (x.v > best.v || (x.v === best.v && rank(x.id) < rank(best.id)) ? x : best));
const out: Transfer[] = [];
while (debtors.some((d) => d.v > 0) && creditors.some((c) => c.v > 0)) {
const d = pick(debtors.filter((x) => x.v > 0));
const c = pick(creditors.filter((x) => x.v > 0));
const amount = Math.min(d.v, c.v);
out.push({ from: d.id, to: c.id, amount });
d.v -= amount;
c.v -= amount;
}
return out;
}

View file

@ -0,0 +1,53 @@
// Spending statistics (SPEC.md §7.5). Transfers are not spending, so they
// are left out of every figure here.
import { inBase } from './expense.ts';
import type { GroupState } from './types.ts';
export interface Stats {
total: number;
byCategory: { category: string; amount: number }[];
/** YYYY-MM → amount, ascending, months with no spending included */
byMonth: { month: string; amount: number }[];
/** paid = put money in; consumed = their share of the spending */
perMember: { member: string; paid: number; consumed: number }[];
}
export function computeStats(s: GroupState, from: string | null, to: string | null): Stats {
const base = s.group?.baseCurrency ?? 'EUR';
const cat = new Map<string, number>();
const month = new Map<string, number>();
const paid = new Map<string, number>();
const consumed = new Map<string, number>();
let total = 0;
for (const r of Object.values(s.expenses)) {
const e = r.expense;
if (r.deleted || e.kind === 'transfer') continue;
if ((from && e.date < from) || (to && e.date > to)) continue;
const b = inBase(e, base);
total += b.total;
cat.set(e.category, (cat.get(e.category) ?? 0) + b.total);
const mk = e.date.slice(0, 7);
month.set(mk, (month.get(mk) ?? 0) + b.total);
for (const [id, v] of Object.entries(b.paid)) paid.set(id, (paid.get(id) ?? 0) + v);
for (const [id, v] of Object.entries(b.owed)) consumed.set(id, (consumed.get(id) ?? 0) + v);
}
const months = [...month.keys()].sort();
const byMonth: Stats['byMonth'] = [];
if (months.length) {
let [y, m] = months[0].split('-').map(Number);
const last = months[months.length - 1];
for (;;) {
const k = `${y}-${String(m).padStart(2, '0')}`;
byMonth.push({ month: k, amount: month.get(k) ?? 0 });
if (k >= last) break;
m += 1;
if (m > 12) (m = 1), (y += 1);
}
}
return {
total,
byCategory: [...cat].map(([category, amount]) => ({ category, amount })).sort((a, b) => b.amount - a.amount),
byMonth,
perMember: s.members.map((m) => ({ member: m.id, paid: paid.get(m.id) ?? 0, consumed: consumed.get(m.id) ?? 0 })),
};
}

161
packages/core/src/types.ts Normal file
View file

@ -0,0 +1,161 @@
// Event schema (decrypted plaintext) and the state derived by replaying it.
// See SPEC.md §4.
export const SCHEMA_VERSION = 1;
export type SplitMode = 'equal' | 'shares' | 'exact' | 'percent';
export type ExpenseKind = 'expense' | 'transfer';
export const CATEGORIES = [
'food', 'groceries', 'transport', 'accommodation', 'entertainment',
'shopping', 'utilities', 'rent', 'travel', 'gifts', 'health', 'other',
] as const;
export type Category = (typeof CATEGORIES)[number] | 'transfer';
export interface Member {
id: string;
name: string;
color: string;
archived: boolean;
}
export interface SplitEntry {
member: string;
/** equal: 1/0 · shares: weight · exact: minor units · percent: basis points */
value: number;
}
export interface Payer {
member: string;
amount: number;
}
export interface Photo {
blobId: string;
thumbBlobId: string;
w: number;
h: number;
}
export interface Expense {
id: string;
kind: ExpenseKind;
title: string;
category: Category;
/** YYYY-MM-DD */
date: string;
currency: string;
/** minor units of `currency` */
amount: number;
/** decimal string: 1 `currency` = rate × base currency */
rate: string;
rateSource: string;
payers: Payer[];
split: { mode: SplitMode; entries: SplitEntry[] };
note: string;
photo: Photo | null;
/** set on occurrences generated from a recurring template */
recurringId?: string;
}
export type Freq = 'weekly' | 'monthly' | 'yearly';
export interface RecurringRule {
freq: Freq;
interval: number;
/** YYYY-MM-DD, first occurrence */
start: string;
/** YYYY-MM-DD inclusive, or null */
end: string | null;
}
export type ExpenseTemplate = Omit<Expense, 'id' | 'date' | 'recurringId' | 'photo'>;
export interface Recurring {
id: string;
template: ExpenseTemplate;
rule: RecurringRule;
}
export interface GroupInfo {
name: string;
baseCurrency: string;
icon: string;
}
export type EventBody =
| { type: 'group.created'; data: GroupInfo }
| { type: 'group.updated'; data: Partial<GroupInfo> }
| { type: 'member.added'; data: { id: string; name: string; color: string } }
| { type: 'member.updated'; data: { id: string; name?: string; color?: string } }
| { type: 'member.archived'; data: { id: string } }
| { type: 'member.restored'; data: { id: string } }
| { type: 'expense.created'; data: Expense }
| { type: 'expense.updated'; data: Expense }
| { type: 'expense.deleted'; data: { id: string } }
| { type: 'expense.restored'; data: { id: string } }
| { type: 'comment.added'; data: { id: string; expenseId: string; text: string } }
| { type: 'comment.deleted'; data: { id: string } }
| { type: 'recurring.created'; data: Recurring }
| { type: 'recurring.updated'; data: Recurring }
| { type: 'recurring.deleted'; data: { id: string } }
| { type: 'revert'; data: { targetId: string } };
export type EventType = EventBody['type'];
/** What gets encrypted into an event's ciphertext. */
export type EventPlaintext = EventBody & {
v: number;
/** member id of whoever made the change, if they picked an identity */
actor: string | null;
/** client clock, ISO 8601 */
at: string;
};
/** A decrypted event as the client holds it. */
export type GroupEvent = EventPlaintext & {
id: string;
/** server-assigned; null while still in the local outbox */
seq: number | null;
deviceId: string;
};
export interface ExpenseRecord {
expense: Expense;
deleted: boolean;
createdBy: string | null;
createdAt: string;
updatedAt: string;
}
export interface Comment {
id: string;
expenseId: string;
text: string;
author: string | null;
at: string;
}
export interface GroupState {
group: GroupInfo | null;
/** in order of addition; order breaks rounding ties */
members: Member[];
expenses: Record<string, ExpenseRecord>;
comments: Record<string, Comment>;
recurring: Record<string, Recurring>;
}
/** One line of the group's activity feed. Not affected by rewinds. */
export interface Activity {
eventId: string;
seq: number | null;
at: string;
actor: string | null;
type: EventType;
/** id of the entity concerned (expense, member, comment, …) */
entityId: string | null;
before: unknown;
after: unknown;
/** set when the event was ignored as invalid or as a no-op */
ignored?: boolean;
}

View file

@ -0,0 +1,232 @@
import { describe, expect, it } from 'vitest';
import {
allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence,
occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats,
type EventBody, type Expense, type GroupEvent,
} from '../src/index.ts';
let seq = 0;
function ev(body: EventBody, actor: string | null = null, id?: string): GroupEvent {
seq += 1;
return { ...body, v: 1, actor, at: `2026-10-01T00:00:${String(seq % 60).padStart(2, '0')}Z`, id: id ?? `e${seq}`, seq, deviceId: 'd' } as GroupEvent;
}
function expense(over: Partial<Expense> = {}): Expense {
return {
id: 'x1', kind: 'expense', title: 'Dinner', category: 'food', date: '2026-10-01',
currency: 'CZK', amount: 10000, rate: '1', rateSource: 'manual',
payers: [{ member: 'a', amount: 10000 }],
split: { mode: 'equal', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 1 }, { member: 'c', value: 1 }] },
note: '', photo: null, ...over,
};
}
function baseGroup(): GroupEvent[] {
return [
ev({ type: 'group.created', data: { name: 'Trip', baseCurrency: 'CZK', icon: '🏔️' } }),
ev({ type: 'member.added', data: { id: 'a', name: 'Anna', color: '' } }),
ev({ type: 'member.added', data: { id: 'b', name: 'Petr', color: '' } }),
ev({ type: 'member.added', data: { id: 'c', name: 'Jana', color: '' } }),
];
}
describe('allocate', () => {
it('splits 100.00 three ways as 33.34 / 33.33 / 33.33', () => {
expect(allocate(10000, [1, 1, 1])).toEqual([3334, 3333, 3333]);
});
it('gives leftovers to the largest remainders, ties to the earlier index', () => {
expect(allocate(10, [1, 1, 1, 1])).toEqual([3, 3, 2, 2]);
expect(allocate(100, [1, 2])).toEqual([33, 67]);
});
it('always sums to the total', () => {
for (let t = 1; t < 500; t += 7) {
const w = [3, 0, 7, 1, 13];
expect(allocate(t, w).reduce((a, b) => a + b, 0)).toBe(t);
}
});
});
describe('convert', () => {
it('converts EUR to CZK with the stored rate', () => {
expect(convert(12050, 'EUR', 'CZK', '25.214')).toBe(303829); // 120.50 × 25.214 = 3038.287 → 3038.29
});
it('handles differing exponents', () => {
expect(convert(1000, 'JPY', 'CZK', '0.1567')).toBe(15670); // ¥1000 → 156.70 Kč
expect(convert(100, 'CZK', 'JPY', '6.38')).toBe(6); // 1 Kč → ¥6.38 → ¥6
});
it('rounds half to even', () => {
expect(convert(1, 'EUR', 'CZK', '0.5')).toBe(0); // 0.005 → 0.00
expect(convert(3, 'EUR', 'CZK', '0.5')).toBe(2); // 0.015 → 0.02
});
});
describe('parseAmount / toDecimalString', () => {
it('accepts comma or dot decimals and grouping', () => {
expect(parseAmount('12,5', 'CZK')).toBe(1250);
expect(parseAmount('1 234,50', 'CZK')).toBe(123450);
expect(parseAmount('1.234,5', 'EUR')).toBe(123450);
expect(parseAmount('1,234.56', 'USD')).toBe(123456);
expect(parseAmount('1.234', 'EUR')).toBe(123400);
expect(parseAmount('1.234', 'BHD')).toBe(1234);
expect(parseAmount('500', 'JPY')).toBe(500);
});
it('rejects junk, zero and too many decimals', () => {
for (const s of ['', 'abc', '0', '1.234.5', '12.3456', '-5', '1e5']) expect(parseAmount(s, 'EUR')).toBeNull();
expect(parseAmount('1.5', 'JPY')).toBeNull();
});
it('formats minor units', () => {
expect(toDecimalString(5, 'EUR')).toBe('0.05');
expect(toDecimalString(-123450, 'CZK')).toBe('-1234.50');
expect(toDecimalString(500, 'JPY')).toBe('500');
});
it('rateToString keeps 6 significant digits', () => {
expect(rateToString(25.21399999)).toBe('25.214');
expect(rateToString(0.0412345678)).toBe('0.0412346');
expect(rateToString(1)).toBe('1');
});
});
describe('inBase', () => {
it('paid and owed each sum to the converted total', () => {
const e = expense({ currency: 'EUR', amount: 1000, rate: '25.333', split: { mode: 'shares', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 2 }, { member: 'c', value: 0 }] } });
const b = inBase(e, 'CZK');
expect(b.total).toBe(25333);
expect(Object.values(b.owed).reduce((x, y) => x + y)).toBe(b.total);
expect(Object.values(b.paid).reduce((x, y) => x + y)).toBe(b.total);
expect(b.owed.c).toBeUndefined();
});
it('supports exact and percent splits', () => {
expect(inBase(expense({ split: { mode: 'exact', entries: [{ member: 'a', value: 2500 }, { member: 'b', value: 7500 }] } }), 'CZK').owed).toEqual({ a: 2500, b: 7500 });
expect(inBase(expense({ split: { mode: 'percent', entries: [{ member: 'a', value: 3333 }, { member: 'b', value: 6667 }] } }), 'CZK').owed).toEqual({ a: 3333, b: 6667 });
});
});
describe('replay', () => {
it('builds members and balances that sum to zero', () => {
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() })]);
const bal = balances(state);
expect(bal).toEqual({ a: 6666, b: -3333, c: -3333 });
expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0);
});
it('ignores invalid expenses (bad sums, unknown members)', () => {
const bad1 = expense({ id: 'x2', payers: [{ member: 'a', amount: 1 }] });
const bad2 = expense({ id: 'x3', split: { mode: 'equal', entries: [{ member: 'zzz', value: 1 }] } });
const r = replay([...baseGroup(), ev({ type: 'expense.created', data: bad1 }), ev({ type: 'expense.created', data: bad2 })]);
expect(Object.keys(r.state.expenses)).toEqual([]);
expect(r.activity.filter((a) => a.ignored)).toHaveLength(2);
});
it('last writer wins, and delete/restore toggle', () => {
const evs = [
...baseGroup(),
ev({ type: 'expense.created', data: expense() }),
ev({ type: 'expense.updated', data: expense({ title: 'Lunch' }) }),
ev({ type: 'expense.deleted', data: { id: 'x1' } }),
];
let { state } = replay(evs);
expect(state.expenses.x1.expense.title).toBe('Lunch');
expect(state.expenses.x1.deleted).toBe(true);
expect(balances(state)).toEqual({ a: 0, b: 0, c: 0 });
({ state } = replay([...evs, ev({ type: 'expense.restored', data: { id: 'x1' } })]));
expect(state.expenses.x1.deleted).toBe(false);
});
it('expense.created is first-wins (recurring dedupe)', () => {
const { state } = replay([
...baseGroup(),
ev({ type: 'expense.created', data: expense({ title: 'first' }) }),
ev({ type: 'expense.created', data: expense({ title: 'second' }) }),
]);
expect(state.expenses.x1.expense.title).toBe('first');
});
it('locks the base currency once there are expenses', () => {
const evs = [...baseGroup(), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })];
expect(replay(evs).state.group!.baseCurrency).toBe('EUR');
const locked = [...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })];
expect(replay(locked).state.group!.baseCurrency).toBe('CZK');
});
it('revert restores an earlier state, and can itself be reverted', () => {
const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')];
evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal'));
evs.push(ev({ type: 'member.added', data: { id: 'd', name: 'Dan', color: '' } }));
evs.push(ev({ type: 'revert', data: { targetId: 'keep' } }, 'a', 'rw'));
let r = replay(evs);
expect(r.state.expenses.x1.expense.amount).toBe(10000);
expect(r.state.members.map((m) => m.id)).toEqual(['a', 'b', 'c']);
expect(r.activity).toHaveLength(evs.length); // nothing erased from history
// Undo the rewind: revert to the event just before it.
const before = evs[evs.length - 2].id;
evs.push(ev({ type: 'revert', data: { targetId: before } }));
r = replay(evs);
expect(r.state.expenses.x1.expense.amount).toBe(99900);
expect(r.state.members).toHaveLength(4);
});
it('logOrder puts synced events by seq, then pending ones', () => {
const a = ev({ type: 'member.added', data: { id: 'q', name: 'Q', color: '' } });
const b = ev({ type: 'member.added', data: { id: 'r', name: 'R', color: '' } });
const p = { ...b, id: 'p1', seq: null };
expect(logOrder([b, a], [p, { ...a }]).map((e) => e.id)).toEqual([a.id, b.id, 'p1']);
});
});
describe('settleUp', () => {
it('produces transfers that zero all balances', () => {
const bal = { a: 5000, b: -2000, c: -2000, d: -1000 };
const t = settleUp(bal, ['a', 'b', 'c', 'd']);
expect(t).toEqual([
{ from: 'b', to: 'a', amount: 2000 },
{ from: 'c', to: 'a', amount: 2000 },
{ from: 'd', to: 'a', amount: 1000 },
]);
});
it('uses at most n-1 transfers', () => {
const bal = { a: 700, b: 300, c: -400, d: -600 };
const t = settleUp(bal, ['a', 'b', 'c', 'd']);
expect(t.length).toBeLessThanOrEqual(3);
const net: Record<string, number> = { ...bal };
for (const x of t) (net[x.from] += x.amount), (net[x.to] -= x.amount);
expect(Object.values(net).every((v) => v === 0)).toBe(true);
});
});
describe('recurring', () => {
it('clamps monthly occurrences to the month end', () => {
const rule = { freq: 'monthly' as const, interval: 1, start: '2026-01-31', end: null };
expect([0, 1, 2, 3].map((n) => nthOccurrence(rule, n))).toEqual(['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']);
});
it('creates missing occurrences once, and deleted ones stay deleted', () => {
const { template: _t, ...rest } = { template: null, ...expense() };
const tpl = { ...rest } as Partial<Expense>;
delete tpl.id; delete tpl.date; delete tpl.photo;
const rec = { id: 'r1', template: tpl as any, rule: { freq: 'weekly' as const, interval: 1, start: '2026-09-01', end: null } };
const evs = [...baseGroup(), ev({ type: 'recurring.created', data: rec })];
let { state } = replay(evs);
const due = dueOccurrences(state, '2026-09-20');
expect(due.map((e) => e.date)).toEqual(['2026-09-01', '2026-09-08', '2026-09-15']);
for (const e of due) evs.push(ev({ type: 'expense.created', data: e }));
evs.push(ev({ type: 'expense.deleted', data: { id: occurrenceId('r1', '2026-09-08') } }));
({ state } = replay(evs));
expect(dueOccurrences(state, '2026-09-20')).toEqual([]);
expect(dueOccurrences(state, '2026-09-22').map((e) => e.date)).toEqual(['2026-09-22']);
});
});
describe('stats and csv', () => {
it('excludes transfers from stats', () => {
const t = expense({ id: 't1', kind: 'transfer', category: 'transfer', amount: 500, payers: [{ member: 'b', amount: 500 }], split: { mode: 'equal', entries: [{ member: 'a', value: 1 }] } });
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'expense.created', data: t })]);
const st = computeStats(state, null, null);
expect(st.total).toBe(10000);
expect(st.byCategory).toEqual([{ category: 'food', amount: 10000 }]);
expect(balances(state)).toEqual({ a: 6166, b: -2833, c: -3333 });
});
it('escapes CSV and neutralises formulas', () => {
const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense({ title: '=HYPERLINK("x")' }) })]);
expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`);
});
});

View file

@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM"],
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true
},
"include": ["src", "test"]
}

27
playwright.config.ts Normal file
View file

@ -0,0 +1,27 @@
import { defineConfig, devices } from '@playwright/test';
// E2E against the production build served by the real server.
// Run `npm run build` first. Uses a throwaway data dir per run.
// Set E2E_BASE_URL to test an already running deployment instead (e.g. the
// compose stack: E2E_BASE_URL=https://localhost:8483).
const external = process.env.E2E_BASE_URL;
const port = 8490;
const dataDir = `${process.env.TMPDIR ?? '/tmp'}/oweme-e2e-${Date.now()}`;
export default defineConfig({
testDir: 'e2e',
timeout: 90_000,
fullyParallel: false,
workers: 1,
reporter: [['list']],
use: { baseURL: external ?? `http://127.0.0.1:${port}`, ignoreHTTPSErrors: !!external, trace: 'retain-on-failure' },
projects: [
{ name: 'mobile-chromium', use: { ...devices['Pixel 7'] } },
],
webServer: external ? undefined : {
command: 'node --disable-warning=ExperimentalWarning apps/server/src/main.ts',
url: `http://127.0.0.1:${port}/api/health`,
reuseExistingServer: false,
env: { PORT: String(port), DATA_DIR: dataDir, STATIC_DIR: 'apps/web/dist', GROUP_CREATE_PER_HOUR: '100' },
},
});

16
scripts/dev.mjs Normal file
View file

@ -0,0 +1,16 @@
// `npm run dev`: API server on 127.0.0.1:8481 (restarts on change) and the
// Vite dev server on 127.0.0.1:8480 (proxies /api). Data goes to ./data.
import { spawn } from 'node:child_process';
const procs = [
spawn(process.execPath, ['--watch', '--disable-warning=ExperimentalWarning', 'apps/server/src/main.ts'], {
stdio: 'inherit',
env: { ...process.env, PORT: '8481', DATA_DIR: process.env.DATA_DIR ?? 'data' },
}),
spawn('npm', ['run', 'dev', '-w', 'apps/web'], { stdio: 'inherit' }),
];
const stop = () => procs.forEach((p) => p.kill('SIGTERM'));
process.on('SIGINT', stop);
process.on('SIGTERM', stop);
for (const p of procs) p.on('exit', (code) => { stop(); process.exitCode = code ?? 0; });

29
scripts/render-icons.mjs Normal file
View file

@ -0,0 +1,29 @@
// Render the PNG app icons from apps/web/public/icon.svg with headless
// Chromium (Playwright). Run after changing the SVG: node scripts/render-icons.mjs
import { chromium } from '@playwright/test';
import { readFileSync } from 'node:fs';
const dir = new URL('../apps/web/public/', import.meta.url);
const svg = readFileSync(new URL('icon.svg', dir), 'utf8');
const b64 = Buffer.from(svg).toString('base64');
// Maskable: full-bleed background, artwork inside the 80% safe zone.
const maskable = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><rect width="512" height="512" fill="#0B2E22"/><image href="data:image/svg+xml;base64,${b64}" x="64" y="64" width="384" height="384"/></svg>`;
// Badge: white glyph on transparent (Android tints it).
const badge = svg.replace(/<rect[^>]*\/>/, '').replaceAll('#3DDC97', '#FFFFFF');
const jobs = [
['icon-192.png', svg, 192],
['icon-512.png', svg, 512],
['icon-maskable-512.png', maskable, 512],
['badge-96.png', badge, 96],
];
const browser = await chromium.launch();
const page = await browser.newPage();
for (const [name, src, size] of jobs) {
await page.setViewportSize({ width: size, height: size });
await page.setContent(`<style>html,body{margin:0;background:transparent}svg{width:${size}px;height:${size}px;display:block}</style>${src}`);
await page.screenshot({ path: new URL(name, dir).pathname, omitBackground: true });
}
await browser.close();
console.log('icons written');