From 1382e533596e0c681751f397209b67113d3b0c25 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 20:45:28 +0000 Subject: [PATCH 01/12] Move compose.yaml and .env.example to the repo root Deploy is now `podman compose up -d` from the root. Add .containerignore so node_modules, local data and .env stay out of the build context, and mount only .env (not the whole tree) when generating VAPID keys. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- .containerignore | 8 ++++++++ deploy/.env.example => .env.example | 7 ++++--- .gitignore | 1 - AGENTS.md | 5 +++-- SPEC.md | 11 ++++++----- apps/server/src/config.ts | 2 +- apps/server/src/gen-vapid.ts | 2 +- deploy/compose.yaml => compose.yaml | 8 ++++---- deploy/README.md | 8 ++++---- 9 files changed, 31 insertions(+), 21 deletions(-) create mode 100644 .containerignore rename deploy/.env.example => .env.example (72%) rename deploy/compose.yaml => compose.yaml (86%) diff --git a/.containerignore b/.containerignore new file mode 100644 index 0000000..bef5e74 --- /dev/null +++ b/.containerignore @@ -0,0 +1,8 @@ +# Keep the image build context small and free of secrets/local data. +**/node_modules +**/dist +data +.env +test-results +playwright-report +.git diff --git a/deploy/.env.example b/.env.example similarity index 72% rename from deploy/.env.example rename to .env.example index d40ace4..d9cc843 100644 --- a/deploy/.env.example +++ b/.env.example @@ -1,11 +1,12 @@ -# Copy to deploy/.env and `chmod 600 deploy/.env`. Never commit .env. +# Copy to .env (repo root, next to compose.yaml) and `chmod 600 .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) +# podman run --rm --user root -v ./.env:/out/.env:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env +# (or, with Node 24 installed: node apps/server/src/gen-vapid.ts .env) # Leave empty to disable notifications. VAPID_SUBJECT=mailto:you@example.com VAPID_PUBLIC_KEY= diff --git a/.gitignore b/.gitignore index a5781f9..d9fff82 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ node_modules/ dist/ data/ .env -deploy/.env test-results/ playwright-report/ *.log diff --git a/AGENTS.md b/AGENTS.md index 1ea0527..3c8a211 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,8 @@ End-to-end encrypted group expense splitter (a Settle Up clone). Read 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. +- `compose.yaml` + `.env.example` (repo root) — the podman compose deployment. +- `deploy/` — Containerfile, Caddyfile, deploy docs. - `e2e/` — Playwright tests against the production build. ## Run @@ -56,4 +57,4 @@ notifications. 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`). + (`BIND_ADDR=127.0.0.1` in `.env`). diff --git a/SPEC.md b/SPEC.md index 4ba86e8..b575d88 100644 --- a/SPEC.md +++ b/SPEC.md @@ -496,7 +496,8 @@ 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 +compose.yaml podman compose deployment (with .env.example) +deploy/ Containerfile, Caddyfile, README e2e/ Playwright tests ``` @@ -504,7 +505,7 @@ e2e/ Playwright tests ## 13. Deployment (VPS, podman compose) -`deploy/compose.yaml` runs two services: +`compose.yaml` (repo root) runs two services: - `app`: the Node server, which also serves the built static client. Listens on the internal network only. @@ -516,7 +517,7 @@ 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 +2. `cp .env.example .env && chmod 600 .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 @@ -525,11 +526,11 @@ Deploy steps (documented in `deploy/README.md`): 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`. +4. `podman compose up -d` from the repo root. 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`): +Environment variables (`.env`, read by `compose.yaml`): | Variable | Required | Default | Purpose | |---|---|---|---| diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index c50144e..b86aee1 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -1,4 +1,4 @@ -// All configuration comes from environment variables (see deploy/.env.example). +// All configuration comes from environment variables (see .env.example). import { resolve } from 'node:path'; function int(env: NodeJS.ProcessEnv, name: string, def: number): number { diff --git a/apps/server/src/gen-vapid.ts b/apps/server/src/gen-vapid.ts index 091d1e7..273fe79 100644 --- a/apps/server/src/gen-vapid.ts +++ b/apps/server/src/gen-vapid.ts @@ -1,5 +1,5 @@ // Generate VAPID keys and write them into an env file without printing the -// private key: `node apps/server/src/gen-vapid.ts deploy/.env`. +// private key: `node apps/server/src/gen-vapid.ts .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'; diff --git a/deploy/compose.yaml b/compose.yaml similarity index 86% rename from deploy/compose.yaml rename to compose.yaml index c5ccc90..1d1461d 100644 --- a/deploy/compose.yaml +++ b/compose.yaml @@ -1,11 +1,11 @@ -# podman compose up -d --build (run from this directory; reads ./.env) +# podman compose up -d --build (run from the repo root; reads ./.env) # See deploy/README.md for the full deploy steps. name: oweme services: app: build: - context: .. + context: . dockerfile: deploy/Containerfile image: localhost/oweme:latest restart: unless-stopped @@ -31,7 +31,7 @@ services: depends_on: - app environment: - DOMAIN: ${DOMAIN:?set DOMAIN in deploy/.env} + DOMAIN: ${DOMAIN:?set DOMAIN in .env} ports: # BIND_ADDR defaults to all interfaces (a public VPS). Rootless Podman # can't bind ports below 1024 by default; see README "Ports". @@ -39,7 +39,7 @@ services: - "${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 + - ./deploy/Caddyfile:/etc/caddy/Caddyfile:ro,Z - caddy-data:/data - caddy-config:/config diff --git a/deploy/README.md b/deploy/README.md index d07d670..e13d598 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -12,7 +12,7 @@ web client) and **caddy** (HTTPS and reverse proxy). Only Caddy publishes ports. ## First deploy ```sh -git clone oweme && cd oweme/deploy +git clone oweme && cd oweme cp .env.example .env chmod 600 .env @@ -20,7 +20,7 @@ $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 run --rm --user root -v ./.env:/out/.env: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 @@ -32,12 +32,12 @@ Open `https://$DOMAIN`. `curl https://$DOMAIN/api/health` should say `{"ok":true ```sh cd oweme && git pull -cd deploy && podman compose up -d --build +podman compose up -d --build ``` Data lives in the `oweme-data` volume and survives rebuilds. -## Configuration (`deploy/.env`) +## Configuration (`.env`) | Variable | Required | Default | Purpose | |---|---|---|---| From 04d952872da6e2d0e7680f1e721c13f01d763498 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 22:24:22 +0000 Subject: [PATCH 02/12] Make the deploy panel-friendly: zero-config compose, env vars with defaults - compose.yaml runs only the app by default; Caddy moved to the 'standalone' profile (the panel brings its own Caddy and routes). - No env_file: every setting is ${VAR:-default} in compose.yaml, so it can be set from the panel's Environment tab (or .env standalone). - VAPID keys are generated on first start and kept in the data volume; the push subject defaults to https://. gen-vapid.ts removed. - PUSH_DISABLED=1 turns push off. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- .env.example | 29 ++++---- AGENTS.md | 6 +- SPEC.md | 59 +++++++--------- apps/server/src/app.ts | 21 ++++-- apps/server/src/config.ts | 2 + apps/server/src/gen-vapid.ts | 28 -------- apps/server/src/main.ts | 2 +- apps/server/src/push.ts | 19 ++++++ apps/server/test/server.test.ts | 19 +++++- compose.yaml | 42 +++++++++--- deploy/README.md | 116 +++++++++++++++++--------------- 11 files changed, 191 insertions(+), 152 deletions(-) delete mode 100644 apps/server/src/gen-vapid.ts diff --git a/.env.example b/.env.example index d9cc843..0e0728e 100644 --- a/.env.example +++ b/.env.example @@ -1,24 +1,19 @@ -# Copy to .env (repo root, next to compose.yaml) and `chmod 600 .env`. -# Never commit .env. +# Optional settings for a standalone deploy (podman compose without the +# panel). Copy to .env next to compose.yaml and `chmod 600 .env`. Never +# commit .env. With the panel, set these in the app's Environment tab instead. +# Everything has a working default; see compose.yaml for what each one does. -# Required: public hostname, with a DNS A/AAAA record pointing at this server. +# Standalone HTTPS: public hostname with a DNS record pointing here. DOMAIN=oweme.example.com -# Web Push. Generate the keys with: -# podman run --rm --user root -v ./.env:/out/.env:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env -# (or, with Node 24 installed: node apps/server/src/gen-vapid.ts .env) -# Leave empty to disable notifications. -VAPID_SUBJECT=mailto:you@example.com -VAPID_PUBLIC_KEY= -VAPID_PRIVATE_KEY= +#VAPID_SUBJECT=mailto:you@example.com +#MAX_PHOTO_BYTES=2097152 +#MAX_EVENT_BYTES=65536 +#MAX_GROUP_BYTES=209715200 +#GROUP_CREATE_PER_HOUR=10 +#PUSH_DISABLED=0 -# 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. +# Where the standalone Caddy listens. Defaults: all interfaces, ports 80/443. #BIND_ADDR=0.0.0.0 #HTTP_PORT=80 #HTTPS_PORT=443 diff --git a/AGENTS.md b/AGENTS.md index 3c8a211..8e506b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,9 @@ End-to-end encrypted group expense splitter (a Settle Up clone). Read 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). -- `compose.yaml` + `.env.example` (repo root) — the podman compose deployment. +- `compose.yaml` (repo root) — the deployment; the panel needs it at the root. + Settings are `${VAR:-default}` there; push keys are generated into the volume. + Caddy is only in the `standalone` profile (the panel brings its own). - `deploy/` — Containerfile, Caddyfile, deploy docs. - `e2e/` — Playwright tests against the production build. @@ -57,4 +59,4 @@ notifications. 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 `.env`). + (`BIND_ADDR=127.0.0.1` in `.env` for the standalone profile). diff --git a/SPEC.md b/SPEC.md index b575d88..3915948 100644 --- a/SPEC.md +++ b/SPEC.md @@ -503,46 +503,33 @@ e2e/ Playwright tests --- -## 13. Deployment (VPS, podman compose) +## 13. Deployment (podman compose, with or without the panel) -`compose.yaml` (repo root) runs two services: +`compose.yaml` (repo root) runs the `app` service: the Node server, which +also serves the built static client, on port 8080 with its data in the +`oweme-data` volume. It works with **zero configuration**: VAPID keys are +generated on first start and stored in the volume (`vapid.json`, mode 600), +and the push contact defaults to `https://`. -- `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). +Every setting is an optional environment variable, written in `compose.yaml` +as `${VAR:-default}` so it is visible and documented in one place: +`MAX_PHOTO_BYTES`, `MAX_EVENT_BYTES`, `MAX_GROUP_BYTES`, +`GROUP_CREATE_PER_HOUR`, `VAPID_SUBJECT`, `VAPID_PUBLIC_KEY` / +`VAPID_PRIVATE_KEY` (pin keys), `PUSH_DISABLED`. -Volumes: `oweme-data` (SQLite + blobs), `caddy-data` (certificates). +- **With the panel** (the main target): the panel clones the repo, finds + `compose.yaml` at the root, routes the app's domain to `app:8080` through + its own Caddy (HTTPS) and passes the Environment tab's variables to + compose for `${VAR}` interpolation. "Pass to every container" must stay + off until the panel's injection override stops clashing with variables the + compose file sets (podman-compose: `can't merge value of [KEY]`). +- **Standalone**: `podman compose --profile standalone up -d` adds a Caddy + container with automatic HTTPS for `DOMAIN`, published on + `${BIND_ADDR}:${HTTP_PORT}/${HTTPS_PORT}` (defaults all interfaces, 80/443). + Settings come from `.env` next to `compose.yaml`. -Deploy steps (documented in `deploy/README.md`): - -1. Point a DNS A/AAAA record at the VPS. -2. `cp .env.example .env && chmod 600 .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. `podman compose up -d` from the repo root. 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 (`.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 | +Step-by-step instructions, the full settings table, ports for rootless Podman +and backups are in `deploy/README.md`. Development (on the dev box): servers bind `127.0.0.1` only; preview over an SSH tunnel. Ports and commands go in `AGENTS.md`. diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 428be2c..8d673a0 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -6,7 +6,7 @@ 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'; +import { isAllowedEndpoint, loadVapidKeys, 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}$/; @@ -114,10 +114,9 @@ export function createApp(cfg: Config, store: Store) { const streams = new Map>(); 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 keys = cfg.pushEnabled ? loadVapidKeys(cfg.dataDir, cfg.vapidPublicKey, cfg.vapidPrivateKey) : null; + if (keys) console.log(`push: VAPID keys from ${keys.source}`); + const vapid: Vapid | null = keys ? { publicKey: keys.publicKey, privateKey: keys.privateKey, subject: cfg.vapidSubject } : null; const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g); function clientIp(req: IncomingMessage): string { @@ -141,9 +140,18 @@ export function createApp(cfg: Config, store: Store) { return g; } + // Push services want a contact URL in the VAPID token. Without + // VAPID_SUBJECT, use the public site address the requests arrive on. + function rememberOrigin(req: IncomingMessage) { + if (!vapid || cfg.vapidSubject) return; + const fwd = cfg.trustProxy ? req.headers['x-forwarded-host'] : undefined; + const host = String(fwd ?? req.headers.host ?? '').split(',')[0].trim().toLowerCase(); + if (/^[a-z0-9.-]+\.[a-z]{2,}(:\d+)?$/.test(host) && !host.startsWith('localhost')) vapid.subject = `https://${host}`; + } + 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; + if (!vapid?.subject) return; for (const sub of store.pushSubs(groupId)) { if (sub.deviceId === deviceId) continue; void sendPush(sub, { g: groupId }, vapid).then((r) => { @@ -336,6 +344,7 @@ export function createApp(cfg: Config, store: Store) { 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); + rememberOrigin(req); const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p); if (g) { diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index b86aee1..c9f0f9c 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -23,6 +23,7 @@ export interface Config { vapidPublicKey: string; vapidPrivateKey: string; vapidSubject: string; + pushEnabled: boolean; ratesEnabled: boolean; ratesBaseUrl: string; } @@ -41,6 +42,7 @@ export function loadConfig(env = process.env): Config { vapidPublicKey: env.VAPID_PUBLIC_KEY || '', vapidPrivateKey: env.VAPID_PRIVATE_KEY || '', vapidSubject: env.VAPID_SUBJECT || '', + pushEnabled: env.PUSH_DISABLED !== '1', ratesEnabled: env.RATES_DISABLED !== '1', ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', }; diff --git a/apps/server/src/gen-vapid.ts b/apps/server/src/gen-vapid.ts deleted file mode 100644 index 273fe79..0000000 --- a/apps/server/src/gen-vapid.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Generate VAPID keys and write them into an env file without printing the -// private key: `node apps/server/src/gen-vapid.ts .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 [--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).`); diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index f06049e..3a43c48 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -16,7 +16,7 @@ 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'); + if (!cfg.pushEnabled) console.log('push notifications disabled (PUSH_DISABLED=1)'); }); for (const sig of ['SIGINT', 'SIGTERM'] as const) { diff --git a/apps/server/src/push.ts b/apps/server/src/push.ts index c37b77f..fdc41b6 100644 --- a/apps/server/src/push.ts +++ b/apps/server/src/push.ts @@ -3,6 +3,8 @@ // 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 { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import type { PushSub } from './db.ts'; const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url'); @@ -35,6 +37,23 @@ export function generateVapidKeys(): { publicKey: string; privateKey: string } { return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) }; } +/** + * VAPID keys from the environment if both are set, otherwise generated once + * and kept in the data directory, so push works without any configuration. + * Deleting vapid.json rotates them (and invalidates every subscription). + */ +export function loadVapidKeys(dataDir: string, envPublic: string, envPrivate: string): { publicKey: string; privateKey: string; source: string } { + if (envPublic && envPrivate) return { publicKey: envPublic, privateKey: envPrivate, source: 'environment' }; + const file = join(dataDir, 'vapid.json'); + if (existsSync(file)) { + const k = JSON.parse(readFileSync(file, 'utf8')); + if (typeof k.publicKey === 'string' && typeof k.privateKey === 'string') return { ...k, source: file }; + } + const k = generateVapidKeys(); + writeFileSync(file, JSON.stringify(k), { mode: 0o600, flag: 'wx' }); + return { ...k, source: `${file} (new)` }; +} + export interface Vapid { publicKey: string; privateKey: string; diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts index e8bfe0c..5728658 100644 --- a/apps/server/test/server.test.ts +++ b/apps/server/test/server.test.ts @@ -8,7 +8,7 @@ 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 { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.ts'; import { parseEcbXml } from '../src/rates.ts'; const b64u = (b: Buffer) => b.toString('base64url'); @@ -161,6 +161,23 @@ describe('rates and static', () => { }); }); +describe('vapid keys', () => { + it('generates keys once and keeps them in the data dir', () => { + const d = mkdtempSync(join(tmpdir(), 'oweme-vapid-')); + const a = loadVapidKeys(d, '', ''); + const b = loadVapidKeys(d, '', ''); + assert.equal(a.publicKey, b.publicKey); + assert.match(a.publicKey, /^[A-Za-z0-9_-]{87}$/); + assert.equal(loadVapidKeys(d, 'pub', 'priv').publicKey, 'pub'); // env wins + rmSync(d, { recursive: true, force: true }); + }); + + it('exposes the public key without any configuration', async () => { + const r = await api('GET', '/api/config'); + assert.match(r.data.vapidPublicKey, /^[A-Za-z0-9_-]{87}$/); + }); +}); + 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. diff --git a/compose.yaml b/compose.yaml index 1d1461d..89d7c22 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,5 +1,12 @@ -# podman compose up -d --build (run from the repo root; reads ./.env) -# See deploy/README.md for the full deploy steps. +# OweMe. Works as-is with zero configuration; every setting below can be +# overridden with an environment variable (in the panel's Environment tab, +# or in a .env file next to this file). +# +# With the panel: point the app's domain at service `app`, port 8080. +# The panel's Caddy provides HTTPS. +# Standalone (no panel): set DOMAIN and run +# podman compose --profile standalone up -d --build +# which adds a Caddy container with automatic HTTPS. See deploy/README.md. name: oweme services: @@ -9,9 +16,25 @@ services: dockerfile: deploy/Containerfile image: localhost/oweme:latest restart: unless-stopped - env_file: .env environment: - # fixed inside the container; everything else comes from .env + # Max size of one uploaded (encrypted) photo, in bytes. Default 2 MB. + MAX_PHOTO_BYTES: ${MAX_PHOTO_BYTES:-2097152} + # Max size of one encrypted event, in bytes. Default 64 KB. + MAX_EVENT_BYTES: ${MAX_EVENT_BYTES:-65536} + # Storage cap per group (events + photos), in bytes. Default 200 MB. + MAX_GROUP_BYTES: ${MAX_GROUP_BYTES:-209715200} + # New groups per client IP per hour. + GROUP_CREATE_PER_HOUR: ${GROUP_CREATE_PER_HOUR:-10} + # Contact sent to push services, e.g. mailto:you@example.com. + # Empty = https://. + VAPID_SUBJECT: ${VAPID_SUBJECT:-} + # Push keys. Empty = generated on first start and kept in the data + # volume (recommended). Set both only to pin specific keys. + VAPID_PUBLIC_KEY: ${VAPID_PUBLIC_KEY:-} + VAPID_PRIVATE_KEY: ${VAPID_PRIVATE_KEY:-} + # 1 = turn push notifications off. + PUSH_DISABLED: ${PUSH_DISABLED:-0} + # Fixed for the container; no need to change these. HOST: 0.0.0.0 PORT: "8080" DATA_DIR: /data @@ -23,18 +46,21 @@ services: 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 + # No ports: the panel publishes 8080 for its routes; standalone, only + # Caddy reaches the app. caddy: + profiles: [standalone] image: docker.io/library/caddy:2.10.2-alpine restart: unless-stopped depends_on: - app environment: - DOMAIN: ${DOMAIN:?set DOMAIN in .env} + # Public hostname for standalone HTTPS (needs a DNS record). + DOMAIN: ${DOMAIN:-localhost} ports: - # BIND_ADDR defaults to all interfaces (a public VPS). Rootless Podman - # can't bind ports below 1024 by default; see README "Ports". + # Rootless Podman can't bind ports below 1024 by default; see + # deploy/README.md "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" diff --git a/deploy/README.md b/deploy/README.md index e13d598..41c1809 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,60 +1,48 @@ -# Deploying OweMe on a VPS +# Deploying OweMe -Two containers via `podman compose`: **app** (the Node server plus the built -web client) and **caddy** (HTTPS and reverse proxy). Only Caddy publishes ports. +`compose.yaml` (repo root) runs the **app** container: the Node server plus +the built web client, listening on port 8080, with its data in the +`oweme-data` volume. It needs **no configuration**: push keys are generated +on first start and kept in the volume. Every setting is an optional +environment variable, listed with its default in `compose.yaml`. -## Requirements +HTTPS comes either from the panel's Caddy or, standalone, from a Caddy +container enabled with the `standalone` profile. -- 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 +## With the panel -## First deploy +1. **New app → Git repository**: this repo, branch `main`. The panel finds + `compose.yaml` in the repository root. +2. **Domain**: point it at service **`app`**, port **`8080`**. The panel + publishes the port on 127.0.0.1 and its Caddy serves HTTPS. +3. **Environment** (optional): any variable from `compose.yaml`, for example + `MAX_PHOTO_BYTES=5242880` or `VAPID_SUBJECT=mailto:you@example.com`. + Untick **Pass to every container**. `compose.yaml` already passes each + setting to the app, and the panel's per-container copy currently makes + podman-compose fail with `can't merge value of [KEY] …` for variables the + compose file also sets. +4. **Deploy.** Check `https:///api/health` → `{"ok":true}`. + +Changing a variable takes effect on the next deploy. Volume backups in the +panel include the `oweme-data` volume (database, encrypted photos, push keys). + +## Standalone (no panel) + +Requirements: Podman ≥ 4 with podman-compose ≥ 1.1 (for profiles), a domain +with an A/AAAA record pointing at the server, and ports 80 and 443 (TCP, plus +UDP 443 for HTTP/3) open. ```sh git clone oweme && cd oweme - -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 ./.env:/out/.env: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 +cp .env.example .env && chmod 600 .env +$EDITOR .env # set DOMAIN +podman compose --profile standalone up -d --build +podman compose logs -f # Caddy gets the certificate on the first request ``` -Open `https://$DOMAIN`. `curl https://$DOMAIN/api/health` should say `{"ok":true}`. +Updating: `git pull && podman compose --profile standalone up -d --build`. -## Updating - -```sh -cd oweme && git pull -podman compose up -d --build -``` - -Data lives in the `oweme-data` volume and survives rebuilds. - -## Configuration (`.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) +### Ports (rootless Podman) Rootless Podman can't bind ports below 1024 by default. Pick one: @@ -63,30 +51,52 @@ Rootless Podman can't bind ports below 1024 by default. Pick one: 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). +2. Or publish high ports (`HTTP_PORT=8080`, `HTTPS_PORT=8443` in `.env`) and + redirect 80→8080 / 443→8443 in your firewall. 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. +## Settings + +All optional. Set them in the panel's Environment tab, or in `.env` for a +standalone deploy. + +| Variable | Default | Purpose | +|---|---|---| +| `MAX_PHOTO_BYTES` | `2097152` | Max size of one uploaded (encrypted) photo | +| `MAX_EVENT_BYTES` | `65536` | Max size of one encrypted event | +| `MAX_GROUP_BYTES` | `209715200` | Storage cap per group (events + photos) | +| `GROUP_CREATE_PER_HOUR` | `10` | Group creations per client IP per hour | +| `VAPID_SUBJECT` | `https://` | Contact sent to push services | +| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | generated | Pin push keys (set both); otherwise kept in the volume as `vapid.json` | +| `PUSH_DISABLED` | `0` | `1` turns push notifications off | +| `DOMAIN` | `localhost` | Standalone only: Caddy's site address and certificate | +| `BIND_ADDR` | `0.0.0.0` | Standalone only: address Caddy's ports are published on | +| `HTTP_PORT` / `HTTPS_PORT` | `80` / `443` | Standalone only: host ports for Caddy | + +Deleting `vapid.json` from the volume (or changing pinned keys) invalidates +every push subscription; people then turn notifications off and on again. + ## Backups -Back up the `oweme-data` volume (SQLite database + encrypted photos): +The `oweme-data` volume holds everything (SQLite database, encrypted photos, +push keys). Its contents are end-to-end encrypted, so backups can be stored +anywhere. Standalone: ```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. +People 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 +npm ci && E2E_BASE_URL=https:// npx playwright test e2e/app.spec.ts ``` This creates a throwaway group on that server. From 0217d62bf03e9d96b2ff1b81bfc3653221a57781 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 22:49:54 +0000 Subject: [PATCH 03/12] Make the app's port configurable with PORT (default 8080) compose.yaml passes ${PORT:-8080} to the app, its healthcheck and the standalone Caddy (APP_PORT in the Caddyfile). Docs note that the panel's domain must target the same port. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- SPEC.md | 6 +++--- compose.yaml | 13 +++++++++---- deploy/Caddyfile | 2 +- deploy/Containerfile | 1 + deploy/README.md | 6 ++++-- 5 files changed, 18 insertions(+), 10 deletions(-) diff --git a/SPEC.md b/SPEC.md index 3915948..499517b 100644 --- a/SPEC.md +++ b/SPEC.md @@ -506,7 +506,7 @@ e2e/ Playwright tests ## 13. Deployment (podman compose, with or without the panel) `compose.yaml` (repo root) runs the `app` service: the Node server, which -also serves the built static client, on port 8080 with its data in the +also serves the built static client, on port 8080 (`PORT`) with its data in the `oweme-data` volume. It works with **zero configuration**: VAPID keys are generated on first start and stored in the volume (`vapid.json`, mode 600), and the push contact defaults to `https://`. @@ -514,11 +514,11 @@ and the push contact defaults to `https://`. Every setting is an optional environment variable, written in `compose.yaml` as `${VAR:-default}` so it is visible and documented in one place: `MAX_PHOTO_BYTES`, `MAX_EVENT_BYTES`, `MAX_GROUP_BYTES`, -`GROUP_CREATE_PER_HOUR`, `VAPID_SUBJECT`, `VAPID_PUBLIC_KEY` / +`GROUP_CREATE_PER_HOUR`, `PORT`, `VAPID_SUBJECT`, `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` (pin keys), `PUSH_DISABLED`. - **With the panel** (the main target): the panel clones the repo, finds - `compose.yaml` at the root, routes the app's domain to `app:8080` through + `compose.yaml` at the root, routes the app's domain to `app:$PORT` through its own Caddy (HTTPS) and passes the Environment tab's variables to compose for `${VAR}` interpolation. "Pass to every container" must stay off until the panel's injection override stops clashing with variables the diff --git a/compose.yaml b/compose.yaml index 89d7c22..6d1d2b5 100644 --- a/compose.yaml +++ b/compose.yaml @@ -2,7 +2,8 @@ # overridden with an environment variable (in the panel's Environment tab, # or in a .env file next to this file). # -# With the panel: point the app's domain at service `app`, port 8080. +# With the panel: point the app's domain at service `app`, port $PORT +# (8080 unless you set PORT). # The panel's Caddy provides HTTPS. # Standalone (no panel): set DOMAIN and run # podman compose --profile standalone up -d --build @@ -34,19 +35,21 @@ services: VAPID_PRIVATE_KEY: ${VAPID_PRIVATE_KEY:-} # 1 = turn push notifications off. PUSH_DISABLED: ${PUSH_DISABLED:-0} + # Port the app listens on inside the container. If you change it, + # point the panel's domain at the new port too. + PORT: ${PORT:-8080} # Fixed for the container; no need to change these. 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"] + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:${PORT:-8080}/api/health"] interval: 30s timeout: 5s - # No ports: the panel publishes 8080 for its routes; standalone, only + # No ports: the panel publishes $PORT for its routes; standalone, only # Caddy reaches the app. caddy: @@ -58,6 +61,8 @@ services: environment: # Public hostname for standalone HTTPS (needs a DNS record). DOMAIN: ${DOMAIN:-localhost} + # Where Caddy finds the app (same as the app's PORT). + APP_PORT: ${PORT:-8080} ports: # Rootless Podman can't bind ports below 1024 by default; see # deploy/README.md "Ports". diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 171291f..1d7e375 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -3,7 +3,7 @@ # Security headers (CSP etc.) are set by the app itself. {$DOMAIN} { encode zstd gzip - reverse_proxy app:8080 { + reverse_proxy app:{$APP_PORT:8080} { # Server-Sent Events: don't buffer flush_interval -1 } diff --git a/deploy/Containerfile b/deploy/Containerfile index f5d4127..1cdc50c 100644 --- a/deploy/Containerfile +++ b/deploy/Containerfile @@ -25,5 +25,6 @@ COPY --from=build /src/apps/web/dist ./web RUN mkdir -p /data && chown node:node /data USER node VOLUME /data +# Default port; compose sets PORT (see compose.yaml). EXPOSE 8080 CMD ["node", "--disable-warning=ExperimentalWarning", "server/main.ts"] diff --git a/deploy/README.md b/deploy/README.md index 41c1809..2729754 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -1,7 +1,7 @@ # Deploying OweMe `compose.yaml` (repo root) runs the **app** container: the Node server plus -the built web client, listening on port 8080, with its data in the +the built web client, listening on port 8080 (or `PORT`), with its data in the `oweme-data` volume. It needs **no configuration**: push keys are generated on first start and kept in the volume. Every setting is an optional environment variable, listed with its default in `compose.yaml`. @@ -13,7 +13,8 @@ container enabled with the `standalone` profile. 1. **New app → Git repository**: this repo, branch `main`. The panel finds `compose.yaml` in the repository root. -2. **Domain**: point it at service **`app`**, port **`8080`**. The panel +2. **Domain**: point it at service **`app`**, port **`8080`** (or the + `PORT` you set in the Environment tab). The panel publishes the port on 127.0.0.1 and its Caddy serves HTTPS. 3. **Environment** (optional): any variable from `compose.yaml`, for example `MAX_PHOTO_BYTES=5242880` or `VAPID_SUBJECT=mailto:you@example.com`. @@ -72,6 +73,7 @@ standalone deploy. | `VAPID_SUBJECT` | `https://` | Contact sent to push services | | `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | generated | Pin push keys (set both); otherwise kept in the volume as `vapid.json` | | `PUSH_DISABLED` | `0` | `1` turns push notifications off | +| `PORT` | `8080` | Port the app listens on inside the container (the panel's domain must target it) | | `DOMAIN` | `localhost` | Standalone only: Caddy's site address and certificate | | `BIND_ADDR` | `0.0.0.0` | Standalone only: address Caddy's ports are published on | | `HTTP_PORT` / `HTTPS_PORT` | `80` / `443` | Standalone only: host ports for Caddy | From 6b0c80bb50dd2f6202944f9610e663e79c430764 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 6 Nov 2026 18:13:31 +0000 Subject: [PATCH 04/12] Offer only ISO 4217 currencies in circulation in the picker Browsers' Intl.supportedValuesOf('currency') includes long-withdrawn codes (ATS, DEM, ...). Use a hand-maintained ACTIVE_CURRENCIES list in core instead, which also drops recently replaced ones (BGN, HRK, ANG, ZWL, SLL, CUC) and non-cash units (XDR, XSU). A withdrawn currency already in use stays selectable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x --- apps/web/src/components/CurrencySelect.svelte | 15 +++++---- packages/core/src/currencies.ts | 32 +++++++++++++++++++ packages/core/src/index.ts | 1 + packages/core/test/core.test.ts | 11 +++++++ 4 files changed, 52 insertions(+), 7 deletions(-) create mode 100644 packages/core/src/currencies.ts diff --git a/apps/web/src/components/CurrencySelect.svelte b/apps/web/src/components/CurrencySelect.svelte index e289571..a50aef7 100644 --- a/apps/web/src/components/CurrencySelect.svelte +++ b/apps/web/src/components/CurrencySelect.svelte @@ -1,9 +1,10 @@ @@ -26,11 +27,11 @@ {#each recent as c}{/each} {/if} - - {#each ecb as c}{/each} + + {#each rated as c}{/each} {#if lists.other.length} - + {#each lists.other as c}{/each} {/if} diff --git a/packages/core/src/currencies.ts b/packages/core/src/currencies.ts new file mode 100644 index 0000000..d7cc409 --- /dev/null +++ b/packages/core/src/currencies.ts @@ -0,0 +1,32 @@ +// Currencies offered in the picker. Hardcoded rather than read from +// Intl.supportedValuesOf('currency'), which in browsers also returns +// historical codes (ATS, DEM, YUM, …) that nobody can spend any more. + +/** + * ISO 4217 currencies in circulation today. Excludes fund codes (CLF, USN, …), + * precious metals and other non-cash units (XAU, XDR, XSU), and codes that + * have been replaced: ANG → XCG (2025), BGN → EUR (2026), CUC (2021), + * HRK → EUR (2023), SLL → SLE (2024), ZWL → ZWG (2024). + * Update this list when ISO 4217 changes. + */ +export const ACTIVE_CURRENCIES: readonly string[] = [ + 'AED', 'AFN', 'ALL', 'AMD', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', + 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYN', 'BZD', 'CAD', + 'CDF', 'CHF', 'CLP', 'CNY', 'COP', 'CRC', 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', + 'DZD', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', + 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', + 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', + 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', + 'MNT', 'MOP', 'MRU', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', + 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', + 'RON', 'RSD', 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLE', + 'SOS', 'SRD', 'SSP', 'STN', 'SVC', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', + 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VES', 'VND', 'VUV', + 'WST', 'XAF', 'XCD', 'XCG', 'XOF', 'XPF', 'YER', 'ZAR', 'ZMW', 'ZWG', +]; + +const ACTIVE = new Set(ACTIVE_CURRENCIES); + +export function isActiveCurrency(code: string): boolean { + return ACTIVE.has(code); +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 77e1e1b..8b1ce45 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -6,3 +6,4 @@ export * from './settle.ts'; export * from './recurring.ts'; export * from './stats.ts'; export * from './csv.ts'; +export * from './currencies.ts'; diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.ts index dc56547..8d8e003 100644 --- a/packages/core/test/core.test.ts +++ b/packages/core/test/core.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { ACTIVE_CURRENCIES, isActiveCurrency } from '../src/index.ts'; import { allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence, occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats, @@ -230,3 +231,13 @@ describe('stats and csv', () => { expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`); }); }); + +describe('ACTIVE_CURRENCIES', () => { + it('is sorted, unique ISO codes without replaced currencies', () => { + expect([...ACTIVE_CURRENCIES].sort()).toEqual(ACTIVE_CURRENCIES); + expect(new Set(ACTIVE_CURRENCIES).size).toBe(ACTIVE_CURRENCIES.length); + expect(ACTIVE_CURRENCIES.every((c) => /^[A-Z]{3}$/.test(c))).toBe(true); + for (const gone of ['ANG', 'BGN', 'CUC', 'HRK', 'SLL', 'ZWL', 'DEM', 'XDR']) expect(isActiveCurrency(gone)).toBe(false); + for (const c of ['ALL', 'CZK', 'EUR', 'XCG', 'ZWG']) expect(isActiveCurrency(c)).toBe(true); + }); +}); From 62c19192a726bc42480d39ba2f4b45cc4c6e64e0 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 6 Nov 2026 18:13:31 +0000 Subject: [PATCH 05/12] Add a supplementary rate feed for currencies the ECB lacks (e.g. ALL) The server also fetches ExchangeRate-API's free EUR-based endpoint (RATES_EXTRA_URL, empty = off), stored apart from ECB rates; ECB always wins for a currency both publish. /api/rates returns sources for supplementary rates, expenses record them as xr:, and the editor shows the required attribution link. Snapshots older than a week before the requested date are not used. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x --- README.md | 3 +- SPEC.md | 22 ++++++++- apps/server/src/app.ts | 2 +- apps/server/src/config.ts | 4 ++ apps/server/src/db.ts | 44 ++++++++++++++++-- apps/server/src/main.ts | 2 +- apps/server/src/rates.ts | 49 ++++++++++++++++++-- apps/server/test/server.test.ts | 24 +++++++++- apps/web/src/components/ExpenseEditor.svelte | 4 +- apps/web/src/lib/api.ts | 2 +- apps/web/src/lib/locales/cs.ts | 3 ++ apps/web/src/lib/locales/en.ts | 3 ++ apps/web/src/lib/rates.ts | 25 +++++----- 13 files changed, 160 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index b0038dd..6a770a6 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,8 @@ 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) +- Multiple currencies with daily rates — ECB, plus ExchangeRate-API for the + rest (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) diff --git a/SPEC.md b/SPEC.md index 499517b..e476394 100644 --- a/SPEC.md +++ b/SPEC.md @@ -156,7 +156,7 @@ entity fully defines it. Conflicts resolve **last-writer-wins by server "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" + "rateSource": "ecb:2026-10-08", // or "xr:", "manual" (see 8.2) "payers": [ { "member": "m1", "amount": 12050 } ], // sums to amount "split": { "mode": "equal", // equal | shares | exact | percent @@ -370,9 +370,27 @@ which group ids exist. 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. +- For currencies the ECB doesn't publish (e.g. ALL), the server also fetches + a **supplementary EUR-based feed** on the same schedule: ExchangeRate-API's + free endpoint (`RATES_EXTRA_URL`, default + `https://open.er-api.com/v6/latest/EUR`; empty turns it off). It has no + history, so its daily snapshots accumulate from when the server starts + fetching them; one older than a week before the requested date is not + used. It is stored apart from the ECB rates, and **the ECB rate always wins** + for a currency both publish. `GET /api/rates` merges the two and returns + `sources: { CODE: "xr:" }` for every supplementary rate. +- An expense's `rateSource` is `ecb:`, or `xr:` when either side + of the conversion came from the supplementary feed. The editor labels `xr:` + rates with a link to exchangerate-api.com (the free tier's attribution + requirement). - 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. +- The currency picker offers only **ISO 4217 currencies in circulation** + (`ACTIVE_CURRENCIES` in `packages/core/src/currencies.ts`, hand-maintained; + browsers' `Intl.supportedValuesOf('currency')` includes long-gone codes). + Those with a daily rate come first; the rest can be used with a manually + entered rate. A group or recent currency that has since been withdrawn + stays selectable. - Behind an interface so a paid intraday provider can be swapped in later. ### 8.3 Storage and limits diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index 8d673a0..67e156b 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -292,7 +292,7 @@ export function createApp(cfg: Config, store: Store) { 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'); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(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. diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index c9f0f9c..3d3b04b 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -26,6 +26,8 @@ export interface Config { pushEnabled: boolean; ratesEnabled: boolean; ratesBaseUrl: string; + /** supplementary EUR-based rates for currencies the ECB doesn't publish; empty = off */ + ratesExtraUrl: string; } export function loadConfig(env = process.env): Config { @@ -45,5 +47,7 @@ export function loadConfig(env = process.env): Config { pushEnabled: env.PUSH_DISABLED !== '1', ratesEnabled: env.RATES_DISABLED !== '1', ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', + // `??`, not `||`: an explicitly empty value turns the extra source off. + ratesExtraUrl: env.RATES_EXTRA_URL ?? 'https://open.er-api.com/v6/latest/EUR', }; } diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index c550794..c23b618 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -19,6 +19,12 @@ export interface PushSub { deviceId: string; } +export interface RatesDay { + date: string; + rates: Record; + sources: Record; +} + export class Store { readonly db: DatabaseSync; @@ -65,6 +71,13 @@ export class Store { date TEXT PRIMARY KEY, json TEXT NOT NULL ); + -- Supplementary rates (see rates.ts), kept apart so ECB refreshes never + -- overwrite them and ECB always wins for currencies both publish. + CREATE TABLE IF NOT EXISTS rates_extra ( + date TEXT PRIMARY KEY, + source TEXT NOT NULL, + json TEXT NOT NULL + ); `); } @@ -160,12 +173,37 @@ export class Store { 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 } | undefined { + saveExtraRates(date: string, source: string, rates: Record): void { + this.db + .prepare('INSERT OR REPLACE INTO rates_extra (date, source, json) VALUES (?, ?, ?)') + .run(date, source, JSON.stringify(rates)); + } + + /** + * ECB rates for the latest published date on or before `date`, plus + * supplementary rates for currencies the ECB doesn't publish. `sources` + * names the origin of each supplementary rate (":"). + * Supplementary rates older than a week before `date` are not used. + */ + ratesOn(date: string): RatesDay | 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) }; + if (!r) return undefined; + const rates: Record = JSON.parse(r.json); + const sources: Record = {}; + const weekBefore = new Date(Date.parse(date) - 7 * 86400_000).toISOString().slice(0, 10); + const x = this.db + .prepare('SELECT date, source, json FROM rates_extra WHERE date <= ? AND date >= ? ORDER BY date DESC LIMIT 1') + .get(date, weekBefore) as { date: string; source: string; json: string } | undefined; + if (x) { + for (const [code, rate] of Object.entries(JSON.parse(x.json) as Record)) { + if (code in rates) continue; + rates[code] = rate; + sources[code] = `${x.source}:${x.date}`; + } + } + return { date: r.date, rates, sources }; } latestRatesDate(): string | undefined { diff --git a/apps/server/src/main.ts b/apps/server/src/main.ts index 3a43c48..e2fdbe1 100644 --- a/apps/server/src/main.ts +++ b/apps/server/src/main.ts @@ -11,7 +11,7 @@ const server = createServer(createApp(cfg, store)); server.requestTimeout = 0; server.headersTimeout = 30_000; -const rates = new RatesService(store, cfg.ratesBaseUrl); +const rates = new RatesService(store, cfg.ratesBaseUrl, cfg.ratesExtraUrl); if (cfg.ratesEnabled) rates.start(); server.listen(cfg.port, cfg.host, () => { diff --git a/apps/server/src/rates.ts b/apps/server/src/rates.ts index e0bc450..792ead0 100644 --- a/apps/server/src/rates.ts +++ b/apps/server/src/rates.ts @@ -1,7 +1,35 @@ -// ECB daily reference rates (EUR-based). Fetched by the server so that -// clients never contact a third party (SPEC.md §8.2). +// Exchange rates, fetched by the server so that clients never contact a +// third party (SPEC.md §8.2): +// - ECB daily reference rates (EUR-based, ~30 currencies, history to 1999); +// - a supplementary EUR-based feed for everything else (e.g. ALL), in the +// format of ExchangeRate-API's free endpoint. It has no history, so its +// daily snapshots accumulate from the day the server starts fetching. import type { Store } from './db.ts'; +/** Short name stored with supplementary rates; the client labels it. */ +export const EXTRA_SOURCE = 'xr'; + +const DECIMAL_RE = /^\d{1,12}(?:\.\d{1,12})?$/; + +/** + * Parse an ExchangeRate-API style response + * (`{ result, base_code, time_last_update_unix, rates: { CODE: number } }`) + * into its UTC date and decimal-string rates. + */ +export function parseExtraRates(json: unknown): { date: string; rates: Record } { + const d = json as { result?: unknown; base_code?: unknown; time_last_update_unix?: unknown; rates?: unknown }; + if (d?.result !== 'success' || d.base_code !== 'EUR') throw new Error('not a successful EUR-based response'); + if (typeof d.time_last_update_unix !== 'number' || typeof d.rates !== 'object' || !d.rates) throw new Error('malformed response'); + const rates: Record = {}; + for (const [code, value] of Object.entries(d.rates as Record)) { + if (!/^[A-Z]{3}$/.test(code) || typeof value !== 'number' || !(value > 0)) continue; + const str = String(value); // e.g. 1e-7 would not be a valid rate string; skip it + if (DECIMAL_RE.test(str)) rates[code] = str; + } + if (Object.keys(rates).length === 0) throw new Error('no rates parsed'); + return { date: new Date(d.time_last_update_unix * 1000).toISOString().slice(0, 10), rates }; +} + /** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ export function parseEcbXml(xml: string): Map> { const out = new Map>(); @@ -19,10 +47,12 @@ export class RatesService { private timer: NodeJS.Timeout | undefined; private readonly store: Store; private readonly baseUrl: string; + private readonly extraUrl: string; - constructor(store: Store, baseUrl: string) { + constructor(store: Store, baseUrl: string, extraUrl = '') { this.store = store; this.baseUrl = baseUrl; + this.extraUrl = extraUrl; } async refresh(): Promise { @@ -38,9 +68,20 @@ export class RatesService { console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); } + async refreshExtra(): Promise { + const res = await fetch(this.extraUrl, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) throw new Error(`extra rates: HTTP ${res.status}`); + const { date, rates } = parseExtraRates(await res.json()); + this.store.saveExtraRates(date, EXTRA_SOURCE, rates); + console.log(`rates: stored ${Object.keys(rates).length} extra rates for ${date}`); + } + /** 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}`)); + const run = () => { + this.refresh().catch((e) => console.error(`rates: ${e.message}`)); + if (this.extraUrl) this.refreshExtra().catch((e) => console.error(`rates: ${e.message}`)); + }; void run(); this.timer = setInterval(run, 6 * 3600_000); this.timer.unref(); diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts index 5728658..5f27381 100644 --- a/apps/server/test/server.test.ts +++ b/apps/server/test/server.test.ts @@ -9,7 +9,7 @@ import { createApp } from '../src/app.ts'; import { loadConfig } from '../src/config.ts'; import { Store } from '../src/db.ts'; import { encryptPayload, isAllowedEndpoint, loadVapidKeys } from '../src/push.ts'; -import { parseEcbXml } from '../src/rates.ts'; +import { parseEcbXml, parseExtraRates } from '../src/rates.ts'; const b64u = (b: Buffer) => b.toString('base64url'); const newGroup = () => { @@ -35,6 +35,7 @@ before(async () => { }); store = new Store(cfg.dataDir); store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); + store.saveExtraRates('2026-10-09', 'xr', { EUR: '1', CZK: '24.9', ALL: '98.38' }); server = createServer(createApp(cfg, store)); await new Promise((r) => server.listen(0, '127.0.0.1', r)); const addr = server.address() as { port: number }; @@ -142,6 +143,27 @@ describe('rates and static', () => { assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404); }); + it('fills in currencies the ECB lacks from the extra source, ECB first', async () => { + const r = await api('GET', '/api/rates?date=2026-10-11'); + assert.equal(r.data.rates.ALL, '98.38'); + assert.equal(r.data.rates.CZK, '24.4'); + assert.deepEqual(r.data.sources, { ALL: 'xr:2026-10-09' }); + // A snapshot more than a week old is not used; ECB rates still are. + const late = await api('GET', '/api/rates?date=2026-10-20'); + assert.equal(late.data.rates.ALL, undefined); + assert.equal(late.data.rates.CZK, '24.4'); + assert.equal((await api('GET', '/api/rates?date=2026-02-30x')).status, 400); + assert.equal((await api('GET', '/api/rates?date=2026-13-45')).status, 400); + }); + + it('parses the extra rates feed', () => { + const t = Date.UTC(2026, 10, 6, 0, 2) / 1000; + const p = parseExtraRates({ result: 'success', base_code: 'EUR', time_last_update_unix: t, rates: { EUR: 1, ALL: 98.38, BAD: -1, XYZ: 1e-9, lower: 2 } }); + assert.deepEqual(p, { date: '2026-11-06', rates: { EUR: '1', ALL: '98.38' } }); + assert.throws(() => parseExtraRates({ result: 'error' })); + assert.throws(() => parseExtraRates({ result: 'success', base_code: 'USD', time_last_update_unix: t, rates: { EUR: 1 } })); + }); + it('parses ECB XML', () => { const xml = ''; assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); diff --git a/apps/web/src/components/ExpenseEditor.svelte b/apps/web/src/components/ExpenseEditor.svelte index e434d20..73abe1f 100644 --- a/apps/web/src/components/ExpenseEditor.svelte +++ b/apps/web/src/components/ExpenseEditor.svelte @@ -138,7 +138,7 @@ return owedOriginal(e); }); - // Prefill the exchange rate from ECB rates. A rate typed by hand is kept + // Prefill the exchange rate from the server's daily 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); @@ -274,9 +274,11 @@ oninput={() => (rateSource = 'manual')} /> {base} +

{#if rateMissing && rateSource !== 'manual'}{t('rate_unavailable')} {:else if rateSource.startsWith('ecb:')}{t('rate_source_ecb', { date: fmtDate(rateSource.slice(4)) })} + {:else if rateSource.startsWith('xr:')}{t('rate_source_xr', { date: fmtDate(rateSource.slice(3)) })} {: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}

diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index 1c4c8e3..9397dc5 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -62,7 +62,7 @@ export const api = { 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 }>('GET', `/api/rates?date=${date}`), + rates: (date: string) => req<{ base: string; date: string; rates: Record; sources?: Record }>('GET', `/api/rates?date=${date}`), }; /** diff --git a/apps/web/src/lib/locales/cs.ts b/apps/web/src/lib/locales/cs.ts index af00839..367e4b2 100644 --- a/apps/web/src/lib/locales/cs.ts +++ b/apps/web/src/lib/locales/cs.ts @@ -101,6 +101,9 @@ const cs: Messages = { rate: 'Směnný kurz', rate_source_ecb: 'Kurz ECB ze dne {date}', rate_source_manual: 'Zadáno ručně', + rate_source_xr: 'Kurz od Exchange Rate API ze dne {date}', + currencies_rated: 'Denní kurz', + currencies_manual: 'Kurz zadáte 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í', diff --git a/apps/web/src/lib/locales/en.ts b/apps/web/src/lib/locales/en.ts index c60c641..7db3eb5 100644 --- a/apps/web/src/lib/locales/en.ts +++ b/apps/web/src/lib/locales/en.ts @@ -109,6 +109,9 @@ const en = { rate: 'Exchange rate', rate_source_ecb: 'ECB rate from {date}', rate_source_manual: 'Entered manually', + rate_source_xr: 'Rates By Exchange Rate API, {date}', + currencies_rated: 'Daily rate', + currencies_manual: 'Enter rate manually', rate_unavailable: 'No rate available for this currency, please enter it.', paid_by_label: 'Paid by', multiple_payers: 'Several people paid', diff --git a/apps/web/src/lib/rates.ts b/apps/web/src/lib/rates.ts index 7a7aed4..f31b1a4 100644 --- a/apps/web/src/lib/rates.ts +++ b/apps/web/src/lib/rates.ts @@ -1,6 +1,7 @@ -// Exchange rates from our own server (ECB daily, EUR-based). Cached in +// Exchange rates from our own server (EUR-based: ECB daily, plus a +// supplementary source for currencies the ECB doesn't publish). Cached in // IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2). -import { rateToString } from '@oweme/core'; +import { ACTIVE_CURRENCIES, isActiveCurrency, rateToString } from '@oweme/core'; import { api } from './api.ts'; import { kvGet, kvSet } from './idb.ts'; import { today } from './format.ts'; @@ -8,6 +9,8 @@ import { today } from './format.ts'; export interface RatesDay { date: string; rates: Record; + /** ":" for rates not from the ECB (absent in older caches) */ + sources?: Record; } const memory = new Map>(); @@ -23,7 +26,7 @@ export function ratesOn(date: string): Promise { if (cached && date < today()) return cached; try { const r = await api.rates(date); - const day = { date: r.date, rates: r.rates }; + const day: RatesDay = { date: r.date, rates: r.rates, sources: r.sources ?? {} }; await kvSet(key, day); await kvSet('rates:latest', day); return day; @@ -44,7 +47,9 @@ export async function suggestRate(from: string, to: string, date: string): Promi 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}` }; + // A cross rate is only as good as its weaker leg, so name that leg's source. + const source = day.sources?.[from] ?? day.sources?.[to] ?? `ecb:${day.date}`; + return { rate: rateToString(tt / f), source }; } /** Float conversion for display only (never stored). */ @@ -56,13 +61,9 @@ export async function displayRate(from: string, to: string): Promise 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[] }> { +/** Active currencies with a known rate first, then the rest (manual rate). */ +export async function currencyList(): Promise<{ rated: 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)) }; + const rated = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).filter(isActiveCurrency).sort(); + return { rated, other: ACTIVE_CURRENCIES.filter((c) => !rated.includes(c)) }; } From 769b76857aac58081d150ff435457ff57499a232 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 6 Nov 2026 19:55:42 +0000 Subject: [PATCH 06/12] Neutral dark, black and light themes with a modern look Replace the green-tinted palette with neutral near-black (Dark), true black (Black, new, opt-in) and light grey (Light); green is the accent only. System (default) follows the OS between Dark and Light. All text colours keep >= 4.5:1 contrast on every surface. Stylesheet-only restyle to match the approved mock: hairline card borders (--line, separate from control --border), 20px corners, pill buttons and segmented controls, round icon buttons and FAB, floating pill tab bar. Browser theme-color follows the effective theme. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x --- SPEC.md | 31 ++++-- apps/web/index.html | 2 +- apps/web/public/manifest.webmanifest | 4 +- apps/web/src/app.css | 123 ++++++++++++--------- apps/web/src/components/AppSettings.svelte | 1 + apps/web/src/lib/locales/cs.ts | 1 + apps/web/src/lib/locales/en.ts | 1 + apps/web/src/lib/settings.svelte.ts | 13 ++- 8 files changed, 103 insertions(+), 73 deletions(-) diff --git a/SPEC.md b/SPEC.md index e476394..9c41991 100644 --- a/SPEC.md +++ b/SPEC.md @@ -454,19 +454,26 @@ which group ids exist. ### 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): +Three themes, chosen per device in app settings: **System** (default: +follows the OS between soft dark and light), **Dark** (soft near-black), +**Black** (true black, for OLED screens) and **Light**. Neutral backgrounds; +green is the accent only. Tokens live in `apps/web/src/app.css`: -| 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` | +| Token | Dark | Black | Light | +|---|---|---|---| +| background | `#0A0B0D` | `#000000` | `#F2F3F5` | +| surface | `#16181C` | `#121316` | `#FFFFFF` | +| surface-raised | `#1F2227` | `#1B1D21` | `#E9EBEE` | +| text | `#F5F6F7` | same as Dark | `#0D0F12` | +| text-muted | `#8B9099` | same as Dark | `#5F6670` | +| accent / you are owed | `#3DDC97` | same as Dark | `#0B7549` | +| you owe | `#FF9466` | same as Dark | `#B53C0A` | +| highlight (sparingly) | `#D4AF37` | same as Dark | `#9A7B12` | + +Text, muted, accent, owe and danger colours have at least 4.5:1 contrast on +every background and surface in each theme. Cards and lists are separated by +shade with hairline dividers; controls are pill-shaped; the phone tab bar +floats as a pill above the content. Positive/negative amounts also differ by sign and icon, never by colour alone. diff --git a/apps/web/index.html b/apps/web/index.html index 79f2dd9..7584991 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -3,7 +3,7 @@ - + OweMe diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifest index 4b616eb..c9a26ed 100644 --- a/apps/web/public/manifest.webmanifest +++ b/apps/web/public/manifest.webmanifest @@ -5,8 +5,8 @@ "start_url": "/", "scope": "/", "display": "standalone", - "background_color": "#0B2E22", - "theme_color": "#0B2E22", + "background_color": "#0a0b0d", + "theme_color": "#0a0b0d", "icons": [ { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" }, { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" }, diff --git a/apps/web/src/app.css b/apps/web/src/app.css index c13151f..1d00059 100644 --- a/apps/web/src/app.css +++ b/apps/web/src/app.css @@ -1,59 +1,71 @@ -/* OweMe theme: dark & light "money green" (SPEC.md §10.4). */ +/* OweMe theme (SPEC.md §10.4): soft dark (default), black and light. + "System" follows the OS between soft dark and light; black is opt-in. + Contrast of text, muted, accent, owe and danger against bg, surface and + surface-2 is ≥ 4.5:1 in every theme. */ :root { - --bg: #0b2e22; - --surface: #123d2e; - --surface-2: #1a4d3a; - --border: #255c46; - --text: #e8f3ec; - --muted: #9fbfae; + --bg: #0a0b0d; + --surface: #16181c; + --surface-2: #1f2227; + --border: #3a3e45; /* controls: inputs, buttons */ + --line: #ffffff0f; /* quiet dividers: cards, lists */ + --text: #f5f6f7; + --muted: #8b9099; --accent: #3ddc97; - --accent-ink: #062016; - --owe: #f2a65a; + --accent-ink: #04140d; + --owe: #ff9466; --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; + --shadow: 0 10px 30px rgb(0 0 0 / 0.45); + --radius: 20px; --gutter: 16px; color-scheme: dark; } +:root[data-theme='black'] { + --bg: #000000; + --surface: #121316; + --surface-2: #1b1d21; + --border: #363a40; +} @media (prefers-color-scheme: light) { - :root:not([data-theme='dark']) { - --bg: #f2f7f4; + :root:not([data-theme]) { + --bg: #f2f3f5; --surface: #ffffff; - --surface-2: #e4efe9; - --border: #cfe0d6; - --text: #0b2e22; - --muted: #4a6b5b; - --accent: #16865a; + --surface-2: #e9ebee; + --border: #c9cdd3; + --line: #0000000f; + --text: #0d0f12; + --muted: #5f6670; + --accent: #0b7549; --accent-ink: #ffffff; - --owe: #b5541c; + --owe: #b53c0a; --danger: #c0392b; --gold: #9a7b12; --chart-1: #16865a; --chart-2: #2f6fb0; - --shadow: 0 8px 30px rgb(11 46 34 / 0.12); + --shadow: 0 8px 24px rgb(13 15 18 / 0.08); color-scheme: light; } } :root[data-theme='light'] { - --bg: #f2f7f4; + --bg: #f2f3f5; --surface: #ffffff; - --surface-2: #e4efe9; - --border: #cfe0d6; - --text: #0b2e22; - --muted: #4a6b5b; - --accent: #16865a; + --surface-2: #e9ebee; + --border: #c9cdd3; + --line: #0000000f; + --text: #0d0f12; + --muted: #5f6670; + --accent: #0b7549; --accent-ink: #ffffff; - --owe: #b5541c; + --owe: #b53c0a; --danger: #c0392b; --gold: #9a7b12; --chart-1: #16865a; --chart-2: #2f6fb0; - --shadow: 0 8px 30px rgb(11 46 34 / 0.12); + --shadow: 0 8px 24px rgb(13 15 18 / 0.08); color-scheme: light; } @@ -101,12 +113,12 @@ p { margin: 0; } .card { background: var(--surface); - border: 1px solid var(--border); + border: 1px solid var(--line); 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); } +.list { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; } +.list > * + * { border-top: 1px solid var(--line); } .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; @@ -124,7 +136,7 @@ button, .btn { } .btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; - min-height: 44px; padding: 0 16px; border-radius: 12px; + min-height: 44px; padding: 0 18px; border-radius: 999px; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-weight: 600; text-decoration: none; white-space: nowrap; } @@ -133,19 +145,19 @@ button, .btn { .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.small { min-height: 34px; padding: 0 14px; font-size: 0.9rem; } .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); + border-radius: 50%; 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; + border: 1px solid var(--border); border-radius: 12px; 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 { @@ -154,16 +166,16 @@ input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-vi 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 { display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; 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; + flex: 1; min-height: 38px; border: 0; border-radius: 999px; 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; + border-radius: 999px; border: 1px solid var(--line); 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)); } @@ -174,34 +186,37 @@ input[type='date'] { min-width: 0; } } .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; + width: 40px; height: 40px; border-radius: 50%; 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 { padding: 10px 14px; border-radius: 14px; font-size: 0.9rem; background: var(--surface-2); border: 1px solid var(--line); } .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; + position: fixed; right: max(var(--gutter), calc(50% - 360px + var(--gutter))); bottom: calc(96px + env(safe-area-inset-bottom)); z-index: 30; + width: 60px; height: 60px; border-radius: 50%; border: 0; background: var(--accent); color: var(--accent-ink); box-shadow: var(--shadow); display: grid; place-items: center; } +/* floating pill tab bar */ .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); + position: fixed; z-index: 25; + left: var(--gutter); right: var(--gutter); bottom: calc(12px + env(safe-area-inset-bottom)); + max-width: 560px; margin: 0 auto; + display: flex; justify-content: center; padding: 5px; border-radius: 999px; + background: color-mix(in srgb, var(--surface-2) 90%, transparent); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + border: 1px solid var(--line); + box-shadow: var(--shadow); } .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; + flex: 1; display: flex; flex-direction: column; align-items: center; gap: 2px; border-radius: 999px; + padding: 7px 4px; color: var(--muted); text-decoration: none; font-size: 0.72rem; font-weight: 600; } -.tabbar a[aria-current='page'] { color: var(--accent); } +.tabbar a[aria-current='page'] { color: var(--text); background: var(--surface); } /* dialogs: full-screen sheet on phones, centered on desktop */ dialog.sheet { @@ -212,7 +227,7 @@ 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); + margin: auto; border-radius: 24px; border: 1px solid var(--line); box-shadow: var(--shadow); } } .sheet-body { padding: 0 var(--gutter) calc(24px + env(safe-area-inset-bottom)); } @@ -233,7 +248,7 @@ dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); } /* 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 { position: static; justify-content: flex-start; gap: 4px; background: none; border: 0; box-shadow: none; backdrop-filter: none; padding: 0; margin: 0; max-width: none; } .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)); } diff --git a/apps/web/src/components/AppSettings.svelte b/apps/web/src/components/AppSettings.svelte index 86643e1..f2b729e 100644 --- a/apps/web/src/components/AppSettings.svelte +++ b/apps/web/src/components/AppSettings.svelte @@ -23,6 +23,7 @@
+
diff --git a/apps/web/src/lib/locales/cs.ts b/apps/web/src/lib/locales/cs.ts index 367e4b2..5187d63 100644 --- a/apps/web/src/lib/locales/cs.ts +++ b/apps/web/src/lib/locales/cs.ts @@ -26,6 +26,7 @@ const cs: Messages = { theme: 'Vzhled', theme_system: 'Podle systému', theme_dark: 'Tmavý', + theme_black: 'Černý', theme_light: 'Světlý', create_group: 'Vytvořit skupinu', diff --git a/apps/web/src/lib/locales/en.ts b/apps/web/src/lib/locales/en.ts index 7db3eb5..4ff4cca 100644 --- a/apps/web/src/lib/locales/en.ts +++ b/apps/web/src/lib/locales/en.ts @@ -28,6 +28,7 @@ const en = { theme: 'Theme', theme_system: 'System', theme_dark: 'Dark', + theme_black: 'Black', theme_light: 'Light', // new group diff --git a/apps/web/src/lib/settings.svelte.ts b/apps/web/src/lib/settings.svelte.ts index c48eec9..dfc8277 100644 --- a/apps/web/src/lib/settings.svelte.ts +++ b/apps/web/src/lib/settings.svelte.ts @@ -4,7 +4,10 @@ import { detectLang, localeOf, translate, type Lang, type MsgKey } from './i18n. import { kvSet } from './idb.ts'; type LangPref = 'auto' | Lang; -type ThemePref = 'system' | 'dark' | 'light'; +type ThemePref = 'system' | 'dark' | 'black' | 'light'; + +/** Browser/OS chrome colour per theme; matches --bg in app.css. */ +const THEME_COLOR = { dark: '#0a0b0d', black: '#000000', light: '#f2f3f5' } as const; function load(key: string, allowed: readonly T[], def: T): T { try { @@ -22,7 +25,7 @@ function save(key: string, v: string) { class Settings { langPref = $state(load('oweme.lang', ['auto', 'en', 'cs'], 'auto')); - themePref = $state(load('oweme.theme', ['system', 'dark', 'light'], 'system')); + themePref = $state(load('oweme.theme', ['system', 'dark', 'black', 'light'], 'system')); lang = $derived(this.langPref === 'auto' ? detectLang() : this.langPref); locale = $derived(localeOf(this.lang)); @@ -45,8 +48,10 @@ class Settings { 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'); + // "System" follows the OS between soft dark and light. + const effective = this.themePref !== 'system' ? this.themePref + : matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'; + document.querySelector('meta[name=theme-color]')?.setAttribute('content', THEME_COLOR[effective]); } } From c12fd64f0942920605fb501fe9cfbd97292ec466 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 6 Nov 2026 20:36:33 +0000 Subject: [PATCH 07/12] Core: per-group default category (group.updated defaultCategory) SPEC listed defaultCategory on group.updated but nothing implemented it. Replay accepts one of CATEGORIES and ignores the whole event otherwise, validating before any field is applied. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x --- packages/core/src/replay.ts | 8 +++++++- packages/core/src/types.ts | 2 ++ packages/core/test/core.test.ts | 9 +++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/core/src/replay.ts b/packages/core/src/replay.ts index a7bd259..d1552c1 100644 --- a/packages/core/src/replay.ts +++ b/packages/core/src/replay.ts @@ -4,7 +4,9 @@ // 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'; +import { CATEGORIES, type Activity, type GroupEvent, type GroupState, type Recurring } from './types.ts'; + +const isCategory = (c: unknown): c is (typeof CATEGORIES)[number] => (CATEGORIES as readonly unknown[]).includes(c); export function emptyState(): GroupState { return { group: null, members: [], expenses: {}, comments: {}, recurring: {} }; @@ -40,18 +42,22 @@ function apply(s: GroupState, ev: GroupEvent, snapshots: Map 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) : '' }; + if (isCategory(d.defaultCategory)) s.group.defaultCategory = d.defaultCategory; act.after = { ...s.group }; break; } case 'group.updated': { if (!s.group) return ignore(); const d = ev.data ?? {}; + // Validate before changing anything, so an invalid event has no effect. + if (d.defaultCategory !== undefined && !isCategory(d.defaultCategory)) return ignore(); 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.defaultCategory !== undefined) s.group.defaultCategory = d.defaultCategory; 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(); diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index ae550d7..4bec556 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -81,6 +81,8 @@ export interface GroupInfo { name: string; baseCurrency: string; icon: string; + /** category new expenses start with; absent = 'other' */ + defaultCategory?: (typeof CATEGORIES)[number]; } export type EventBody = diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.ts index 8d8e003..a24f498 100644 --- a/packages/core/test/core.test.ts +++ b/packages/core/test/core.test.ts @@ -149,6 +149,15 @@ describe('replay', () => { expect(replay(locked).state.group!.baseCurrency).toBe('CZK'); }); + it('sets a default category and ignores invalid ones', () => { + const set = [...baseGroup(), ev({ type: 'group.updated', data: { defaultCategory: 'travel' } })]; + expect(replay(set).state.group!.defaultCategory).toBe('travel'); + const bad = [...set, ev({ type: 'group.updated', data: { defaultCategory: 'transfer' as never, name: 'Renamed' } })]; + const g = replay(bad).state.group!; + expect(g.defaultCategory).toBe('travel'); + expect(g.name).not.toBe('Renamed'); // the whole invalid event is ignored + }); + 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')); From b3b57c156ef3c283d73618f32e4933612fd95ec7 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 6 Nov 2026 20:36:33 +0000 Subject: [PATCH 08/12] Group page redesign and visual bug fixes Layout, from the approved mock: - Group header on Expenses/Balances: my balance as the headline number (Money component de-emphasises currency and decimals), total spent, and round quick actions Add / Payment / Settle up / Share. The floating + shows only once those scroll off screen. - Expense rows on two lines (title | amount, payer | my part) with round icons tinted per category; sentence-case section headings. - Balances: larger avatars, paired avatars on settle-up rows, tinted button. Bugs found in a screenshot pass (phone 320/390, desktop 1280; dark, black, light; English and Czech): - A long title or member name widened the group page past the screen and phones zoomed out (grid tracks without minmax(0, ...)); same in Stats. - Long titles were clipped mid-word with no ellipsis. - Category emoji nearly invisible on its grey circle in the light theme. - Stats period labels wrapped (en) or ran off screen (cs); shortened. - Icons next to wrapping text were squashed (lock on Home/App settings). - Dialogs opened with a focus ring on the close button after a tap. - New expenses always defaulted to Food & drink; now the group's default category (settable in group settings), else Other. e2e: the Balances check now targets the Settle up heading, which the new quick action shares its text with. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HA82gVKYyo9BHLHPW4qr4x --- SPEC.md | 18 +++-- apps/web/src/app.css | 22 +++++- apps/web/src/components/Balances.svelte | 19 +++-- apps/web/src/components/ExpenseDetail.svelte | 4 +- apps/web/src/components/ExpenseEditor.svelte | 2 +- apps/web/src/components/ExpenseList.svelte | 66 +++++++++-------- apps/web/src/components/GroupHeader.svelte | 74 ++++++++++++++++++++ apps/web/src/components/GroupPage.svelte | 22 +++++- apps/web/src/components/GroupSettings.svelte | 21 ++++-- apps/web/src/components/Icon.svelte | 1 + apps/web/src/components/Money.svelte | 10 +++ apps/web/src/components/Sheet.svelte | 5 ++ apps/web/src/components/Stats.svelte | 7 +- apps/web/src/lib/format.ts | 35 ++++++++- apps/web/src/lib/locales/cs.ts | 17 ++++- apps/web/src/lib/locales/en.ts | 15 +++- e2e/app.spec.ts | 2 +- 17 files changed, 275 insertions(+), 65 deletions(-) create mode 100644 apps/web/src/components/GroupHeader.svelte create mode 100644 apps/web/src/components/Money.svelte diff --git a/SPEC.md b/SPEC.md index 9c41991..1851532 100644 --- a/SPEC.md +++ b/SPEC.md @@ -262,8 +262,8 @@ the minimum in practice, and is easy to reason about. - 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). +- Settings: rename, members, "who am I", default category, 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: @@ -288,6 +288,12 @@ Fixed v1 set with icons: food & drink, groceries, transport, accommodation, entertainment, shopping, utilities, rent, travel, gifts, health, other. Transfers have their own implicit category. +Each group has a **default category** (`group.updated` → `defaultCategory`, +one of the set above; absent means "other") that new expenses start with. +Replay ignores a `group.updated` whose `defaultCategory` isn't in the set, +without applying any other field of that event. Each category has an icon +colour (`CATEGORY_COLORS` in `apps/web/src/lib/format.ts`). + ### 7.4 Recurring expenses - A template (expense object + rule: weekly / monthly / yearly, interval, @@ -435,8 +441,12 @@ which group ids exist. 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. +2. **Group**: on Expenses and Balances, a header with my balance as the + headline number ("You're owed / You owe / settled up"; the group total if + "who am I" isn't set), the group's total spent, and round quick actions: + Add · Payment · Settle up · Share. Tabs: Expenses · Balances (settle up) · + Stats · Activity. A floating "+" appears only once the quick actions have + scrolled off screen. 3. **Expense editor** (sheet on mobile, dialog on desktop). 4. **Expense detail**: photo, split breakdown, comments, history. 5. **Group settings**. diff --git a/apps/web/src/app.css b/apps/web/src/app.css index 1d00059..b3484a8 100644 --- a/apps/web/src/app.css +++ b/apps/web/src/app.css @@ -70,6 +70,7 @@ } * { box-sizing: border-box; } +svg { flex-shrink: 0; } /* icons beside wrapping text must not be squashed */ html { -webkit-text-size-adjust: 100%; } body { margin: 0; @@ -82,7 +83,8 @@ body { 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; } +h3 { font-size: 1.05rem; font-weight: 700; letter-spacing: -0.01em; } +h3.day { font-size: 0.85rem; font-weight: 600; letter-spacing: 0; color: var(--muted); padding-left: 4px; } a { color: var(--accent); } p { margin: 0; } .muted { color: var(--muted); } @@ -145,6 +147,8 @@ button, .btn { .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.tint { background: color-mix(in srgb, var(--accent) 15%, var(--surface)); border-color: transparent; color: var(--accent); } +.btn.tint:hover { background: color-mix(in srgb, var(--accent) 24%, var(--surface)); } .btn.small { min-height: 34px; padding: 0 14px; font-size: 0.9rem; } .btn.block { width: 100%; } .btn:disabled { opacity: 0.5; cursor: not-allowed; } @@ -166,9 +170,13 @@ input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-vi 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(--line); border-radius: 999px; padding: 3px; gap: 3px; } +.seg { + display: flex; background: var(--surface); border: 1px solid var(--line); border-radius: 999px; padding: 3px; gap: 3px; + overflow-x: auto; scrollbar-width: none; /* very narrow screens scroll rather than wrap */ +} +.seg::-webkit-scrollbar { display: none; } .seg button { - flex: 1; min-height: 38px; border: 0; border-radius: 999px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px; + flex: 1 0 auto; white-space: nowrap; min-height: 38px; border: 0; border-radius: 999px; 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); } @@ -223,6 +231,7 @@ 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:focus { outline: none; } dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); } @media (min-width: 760px) { dialog.sheet { @@ -254,3 +263,10 @@ dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); } .fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); } .page { padding-bottom: 48px; } } + +/* round category icon tinted with its category colour (set --cat inline) */ +.cat-icon { background: color-mix(in srgb, var(--cat, var(--muted)) 24%, var(--surface-2)); } + +/* money with the whole number emphasised (see moneyParts) */ +.money .cur, .money .frac { color: var(--muted); font-size: 0.82em; font-weight: inherit; } +.pos .money .cur, .pos .money .frac, .neg .money .cur, .neg .money .frac { color: inherit; opacity: 0.8; } diff --git a/apps/web/src/components/Balances.svelte b/apps/web/src/components/Balances.svelte index a07095b..563eeb0 100644 --- a/apps/web/src/components/Balances.svelte +++ b/apps/web/src/components/Balances.svelte @@ -42,14 +42,14 @@
{#each members as { m, i, bal } (m.id)}
- + {m.name}{m.id === session.me ? ` (${t('you')})` : ''} - + {bal === 0 ? t('settled') : (bal > 0 ? '+' : '−') + conv(Math.abs(bal))}
@@ -62,12 +62,18 @@ {:else}
{#each transfers as tr} + {@const from = session.state.members.findIndex((m) => m.id === tr.from)} + {@const to = session.state.members.findIndex((m) => m.id === tr.to)}
+ {session.memberName(tr.from)} → {session.memberName(tr.to)} - {conv(tr.amount)} + {conv(tr.amount)} - +
{/each}
@@ -85,7 +91,10 @@
diff --git a/apps/web/src/components/GroupHeader.svelte b/apps/web/src/components/GroupHeader.svelte new file mode 100644 index 0000000..c27d346 --- /dev/null +++ b/apps/web/src/components/GroupHeader.svelte @@ -0,0 +1,74 @@ + + +
+ {#if mine === null} +
{t('total_spent')}
+
+ {:else} +
{mine > 0 ? t('hero_owed') : mine < 0 ? t('hero_owe') : t('hero_settled')}
+
+
{t('total_spent')}
+ {/if} +
+ + + + diff --git a/apps/web/src/components/GroupPage.svelte b/apps/web/src/components/GroupPage.svelte index 5ecd727..4115412 100644 --- a/apps/web/src/components/GroupPage.svelte +++ b/apps/web/src/components/GroupPage.svelte @@ -9,6 +9,7 @@ import ExpenseDetail from './ExpenseDetail.svelte'; import ExpenseEditor from './ExpenseEditor.svelte'; import ExpenseList from './ExpenseList.svelte'; + import GroupHeader from './GroupHeader.svelte'; import GroupSettings from './GroupSettings.svelte'; import Icon from './Icon.svelte'; import IdentityPicker from './IdentityPicker.svelte'; @@ -19,12 +20,16 @@ const id = untrack(() => props.id); let session = $state(undefined); let skippedIdentity = $state(false); + // The floating Add button only appears once the header's actions scroll away. + // Starts true so the button doesn't flash before the observer reports. + let actionsVisible = $state(true); openSession(id).then((s) => (session = s)); onDestroy(() => closeSession(id)); const route = $derived(router.route); const tab = $derived(route.name === 'group' ? route.tab : 'expenses'); + const withHeader = $derived(tab === 'expenses' || tab === 'balances'); const base = `/g/${id}`; const tabs = [ { key: 'expenses', path: base, icon: 'list', label: 'expenses' }, @@ -62,7 +67,8 @@ {@const s = session}
-

{s.state.group?.name ?? s.local.name}

+ {#if s.state.group?.icon}{/if} +

{s.state.group?.name ?? s.local.name}

nav(e, `${base}/settings`)} aria-label={t('group_settings')}>
@@ -80,6 +86,10 @@ {/if} {#if s.rollback}{/if} + {#if withHeader && s.status !== 'gone'} + (actionsVisible = v)} /> + {/if} +