From c2043b86bc90abc8a205d38b33bbd55fdd7d4012 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:30:09 +0000 Subject: [PATCH 01/18] Add core package: money math, event replay, settle-up, recurring, stats, CSV Deterministic integer/BigInt arithmetic so every client computes identical balances; replay validates events and supports rewind via snapshots. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- .gitignore | 8 + package-lock.json | 1241 +++++++++++++++++++++++++++++++ package.json | 22 + packages/core/package.json | 6 + packages/core/src/csv.ts | 46 ++ packages/core/src/expense.ts | 117 +++ packages/core/src/index.ts | 8 + packages/core/src/money.ts | 134 ++++ packages/core/src/recurring.ts | 69 ++ packages/core/src/replay.ts | 197 +++++ packages/core/src/settle.ts | 47 ++ packages/core/src/stats.ts | 53 ++ packages/core/src/types.ts | 161 ++++ packages/core/test/core.test.ts | 232 ++++++ packages/core/tsconfig.json | 14 + 15 files changed, 2355 insertions(+) create mode 100644 .gitignore create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 packages/core/package.json create mode 100644 packages/core/src/csv.ts create mode 100644 packages/core/src/expense.ts create mode 100644 packages/core/src/index.ts create mode 100644 packages/core/src/money.ts create mode 100644 packages/core/src/recurring.ts create mode 100644 packages/core/src/replay.ts create mode 100644 packages/core/src/settle.ts create mode 100644 packages/core/src/stats.ts create mode 100644 packages/core/src/types.ts create mode 100644 packages/core/test/core.test.ts create mode 100644 packages/core/tsconfig.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a5781f9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +node_modules/ +dist/ +data/ +.env +deploy/.env +test-results/ +playwright-report/ +*.log diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..a6ace43 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1241 @@ +{ + "name": "oweme", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "oweme", + "workspaces": [ + "packages/core", + "apps/web" + ], + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/node": "24.10.1", + "typescript": "6.0.2", + "vitest": "5.0.2" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oweme/core": { + "resolved": "packages/core", + "link": true + }, + "node_modules/@oxc-project/types": { + "version": "0.153.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", + "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", + "dev": true, + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@playwright/test": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.63.0.tgz", + "integrity": "sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", + "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", + "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", + "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", + "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", + "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", + "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", + "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", + "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", + "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", + "cpu": [ + "ppc64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", + "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", + "cpu": [ + "s390x" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", + "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", + "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", + "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", + "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT", + "peer": true + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.10.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", + "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/@vitest/mocker": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.2.tgz", + "integrity": "sha512-Z5FS00Q1SJHkB35xATsmWGdQ5WA1/0MV3CDjqyv7GavHv1OfOj145MNfHOlHk7QLes21dKFDHr8EO2zvL+9WGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.2", + "estree-walker": "^3.0.3", + "magic-string": "^1.2.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/spy": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.2.tgz", + "integrity": "sha512-Ijc7T1nT9efNb5LxvjaBrEqw3f/QwUv5EE0nKqZxgqsaV/FxAAZ8baGylA8X/Z2oS4Lp+K74Jr6dTJsDKxJDeg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "peer": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "peer": true, + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "peer": true, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", + "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC", + "peer": true + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "peer": true, + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/rolldown": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", + "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@oxc-project/types": "=0.153.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.13", + "@rolldown/binding-android-arm64": "1.2.13", + "@rolldown/binding-darwin-arm64": "1.2.13", + "@rolldown/binding-darwin-x64": "1.2.13", + "@rolldown/binding-freebsd-x64": "1.2.13", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", + "@rolldown/binding-linux-arm64-gnu": "1.2.13", + "@rolldown/binding-linux-arm64-musl": "1.2.13", + "@rolldown/binding-linux-ppc64-gnu": "1.2.13", + "@rolldown/binding-linux-s390x-gnu": "1.2.13", + "@rolldown/binding-linux-x64-gnu": "1.2.13", + "@rolldown/binding-linux-x64-musl": "1.2.13", + "@rolldown/binding-openharmony-arm64": "1.2.13", + "@rolldown/binding-win32-arm64-msvc": "1.2.13", + "@rolldown/binding-win32-x64-msvc": "1.2.13" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.1.tgz", + "integrity": "sha512-IAbQaPJIIdhVxi0mqy9lez1wEwje0UQf9F1vwtbelEG5Nbgn0nPOxCvU+mNeNS9gyJTAhrHp74CbUaSynQpZcQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/typescript": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.2.tgz", + "integrity": "sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==", + "dev": true, + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", + "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.29", + "rolldown": "~1.2.12", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.2.tgz", + "integrity": "sha512-7MQrx9pDv5aHiUcovIb/70Ys3tgtkUVgCtledvKdCmEO+/1Dicq5ZqoSxOW034m03oqC+oHOKui2dM6qtMLoJg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.2", + "chai": "^6.2.2", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.2.3", + "obug": "^2.1.4", + "picomatch": "^4.0.7", + "std-env": "^4.2.0", + "tinybench": "^6.1.4", + "tinyexec": "^1.3.0", + "tinyglobby": "^0.2.17", + "why-is-node-running": "^3.2.1" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.2", + "@vitest/browser-preview": "5.0.2", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.2", + "@vitest/coverage-v8": "5.0.2", + "@vitest/ui": "5.0.2", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/why-is-node-running": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.3.tgz", + "integrity": "sha512-b+aWTM7Zz5Q82TurMbr034vAmyJo2pJFVXzUzuhJK8lP+XI6xUfvzXizZINaERhH3KwybDLt6iqh7pOXaVxjnQ==", + "dev": true, + "license": "MIT", + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=20.11" + } + }, + "packages/core": { + "name": "@oweme/core" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..0a43455 --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "oweme", + "private": true, + "type": "module", + "workspaces": ["packages/core", "apps/web"], + "engines": { "node": ">=24" }, + "scripts": { + "dev": "node scripts/dev.mjs", + "build": "npm run build -w apps/web", + "test": "npm run test:core && npm run test:server", + "test:core": "vitest run --root packages/core", + "test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/", + "test:e2e": "playwright test", + "check": "tsc -p packages/core && tsc -p apps/server && npm run check -w apps/web" + }, + "devDependencies": { + "@playwright/test": "1.63.0", + "@types/node": "24.10.1", + "typescript": "6.0.2", + "vitest": "5.0.2" + } +} diff --git a/packages/core/package.json b/packages/core/package.json new file mode 100644 index 0000000..387152c --- /dev/null +++ b/packages/core/package.json @@ -0,0 +1,6 @@ +{ + "name": "@oweme/core", + "private": true, + "type": "module", + "exports": { ".": "./src/index.ts" } +} diff --git a/packages/core/src/csv.ts b/packages/core/src/csv.ts new file mode 100644 index 0000000..66202b2 --- /dev/null +++ b/packages/core/src/csv.ts @@ -0,0 +1,46 @@ +// CSV export (SPEC.md §7.6). Plain decimal numbers with "." so spreadsheets +// in any locale can import them. +import { inBase } from './expense.ts'; +import { toDecimalString } from './money.ts'; +import { balances } from './settle.ts'; +import type { GroupState } from './types.ts'; + +function cell(v: string | number): string { + const s = String(v); + // Neutralise spreadsheet formula injection, then quote if needed. + const safe = /^[=+\-@\t\r]/.test(s) && typeof v === 'string' ? `'${s}` : s; + return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe; +} + +const row = (cells: (string | number)[]) => cells.map(cell).join(','); + +export function expensesCsv(s: GroupState): string { + const base = s.group?.baseCurrency ?? 'EUR'; + const name = (id: string) => s.members.find((m) => m.id === id)?.name ?? id; + const header = [ + 'date', 'title', 'type', 'category', 'currency', 'amount', 'rate', `amount_${base}`, 'paid_by', 'note', + ...s.members.map((m) => `share_${base}:${m.name}`), + ]; + const lines = [row(header)]; + const records = Object.values(s.expenses) + .filter((r) => !r.deleted) + .sort((a, b) => a.expense.date.localeCompare(b.expense.date)); + for (const { expense: e } of records) { + const b = inBase(e, base); + lines.push(row([ + e.date, e.title, e.kind, e.category, e.currency, toDecimalString(e.amount, e.currency), + e.currency === base ? '1' : e.rate, toDecimalString(b.total, base), + e.payers.map((p) => name(p.member)).join(' + '), e.note, + ...s.members.map((m) => toDecimalString(b.owed[m.id] ?? 0, base)), + ])); + } + return lines.join('\r\n') + '\r\n'; +} + +export function balancesCsv(s: GroupState): string { + const base = s.group?.baseCurrency ?? 'EUR'; + const bal = balances(s); + const lines = [row(['member', `balance_${base}`])]; + for (const m of s.members) lines.push(row([m.name, toDecimalString(bal[m.id] ?? 0, base)])); + return lines.join('\r\n') + '\r\n'; +} diff --git a/packages/core/src/expense.ts b/packages/core/src/expense.ts new file mode 100644 index 0000000..00d24fc --- /dev/null +++ b/packages/core/src/expense.ts @@ -0,0 +1,117 @@ +// Validating an expense and turning it into per-member amounts. +import { allocate, convert, isCurrencyCode, isValidRate, MAX_AMOUNT } from './money.ts'; +import { CATEGORIES, type Expense, type Member } from './types.ts'; + +const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const isInt = (n: unknown): n is number => Number.isSafeInteger(n); + +export function isValidDate(d: unknown): d is string { + if (typeof d !== 'string' || !DATE_RE.test(d)) return false; + const t = Date.parse(`${d}T00:00:00Z`); + return Number.isFinite(t) && new Date(t).toISOString().slice(0, 10) === d; +} + +/** + * Returns null if the expense is valid for the given members, otherwise a + * short reason. Events failing this are ignored on replay, so a buggy or + * malicious client can't corrupt everyone's balances. + */ +export function validateExpense(e: Expense, members: Member[]): string | null { + const ids = new Set(members.map((m) => m.id)); + if (!e || typeof e !== 'object') return 'not an object'; + if (typeof e.id !== 'string' || !e.id) return 'id'; + if (e.kind !== 'expense' && e.kind !== 'transfer') return 'kind'; + if (typeof e.title !== 'string' || e.title.length > 200) return 'title'; + if (e.category !== 'transfer' && !(CATEGORIES as readonly string[]).includes(e.category)) return 'category'; + if (!isValidDate(e.date)) return 'date'; + if (!isCurrencyCode(e.currency)) return 'currency'; + if (!isInt(e.amount) || e.amount <= 0 || e.amount > MAX_AMOUNT) return 'amount'; + if (!isValidRate(e.rate)) return 'rate'; + if (typeof e.note !== 'string' || e.note.length > 2000) return 'note'; + + if (!Array.isArray(e.payers) || e.payers.length === 0) return 'payers'; + const payerIds = new Set(); + let paid = 0; + for (const p of e.payers) { + if (!ids.has(p.member) || payerIds.has(p.member)) return 'payer member'; + if (!isInt(p.amount) || p.amount <= 0) return 'payer amount'; + payerIds.add(p.member); + paid += p.amount; + } + if (paid !== e.amount) return 'payers sum'; + + const { mode, entries } = e.split ?? {}; + if (!Array.isArray(entries) || entries.length === 0) return 'split'; + const seen = new Set(); + let sum = 0; + for (const s of entries) { + if (!ids.has(s.member) || seen.has(s.member)) return 'split member'; + if (!isInt(s.value) || s.value < 0) return 'split value'; + seen.add(s.member); + sum += s.value; + } + switch (mode) { + case 'equal': + if (entries.some((s) => s.value > 1) || sum === 0) return 'equal'; + break; + case 'shares': + if (sum === 0 || sum > 1_000_000) return 'shares'; + break; + case 'exact': + if (sum !== e.amount) return 'exact sum'; + break; + case 'percent': + if (sum !== 10000) return 'percent sum'; + break; + default: + return 'mode'; + } + if (e.kind === 'transfer' && entries.filter((s) => s.value > 0).length !== 1) return 'transfer'; + + if (e.photo !== null) { + const p = e.photo; + if (!p || typeof p.blobId !== 'string' || typeof p.thumbBlobId !== 'string') return 'photo'; + } + return null; +} + +/** What each member owes, in minor units of the expense's own currency. */ +export function owedOriginal(e: Expense): Record { + const entries = e.split.entries; + const parts = + e.split.mode === 'exact' + ? entries.map((s) => s.value) + : allocate(e.amount, entries.map((s) => s.value)); + const out: Record = {}; + entries.forEach((s, i) => { + if (parts[i] !== 0) out[s.member] = parts[i]; + }); + return out; +} + +export interface ExpenseInBase { + /** total in base currency minor units */ + total: number; + paid: Record; + owed: Record; +} + +/** + * Express an expense in the base currency. The total is converted once, and + * both the payer vector and the split vector are re-allocated onto it, so + * paid and owed each sum to exactly `total`. + */ +export function inBase(e: Expense, baseCurrency: string): ExpenseInBase { + const total = convert(e.amount, e.currency, baseCurrency, e.rate); + const owedOrig = owedOriginal(e); + const owedIds = Object.keys(owedOrig); + const paidIds = e.payers.map((p) => p.member); + const sameCurrency = e.currency === baseCurrency; + const paidParts = sameCurrency ? e.payers.map((p) => p.amount) : allocate(total, e.payers.map((p) => p.amount)); + const owedParts = sameCurrency ? owedIds.map((id) => owedOrig[id]) : allocate(total, owedIds.map((id) => owedOrig[id])); + const paid: Record = {}; + const owed: Record = {}; + paidIds.forEach((id, i) => (paid[id] = paidParts[i])); + owedIds.forEach((id, i) => (owed[id] = owedParts[i])); + return { total, paid, owed }; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts new file mode 100644 index 0000000..77e1e1b --- /dev/null +++ b/packages/core/src/index.ts @@ -0,0 +1,8 @@ +export * from './types.ts'; +export * from './money.ts'; +export * from './expense.ts'; +export * from './replay.ts'; +export * from './settle.ts'; +export * from './recurring.ts'; +export * from './stats.ts'; +export * from './csv.ts'; diff --git a/packages/core/src/money.ts b/packages/core/src/money.ts new file mode 100644 index 0000000..e6ff665 --- /dev/null +++ b/packages/core/src/money.ts @@ -0,0 +1,134 @@ +// Integer money math. Every client must produce identical numbers from the +// same events, so nothing here uses floating point: amounts are integers in +// minor units, rates are exact decimal strings, and intermediate values are +// BigInt. + +/** ISO 4217 exponents that differ from the default of 2. Hardcoded rather + * than read from Intl, because Intl data can differ between browsers. */ +const EXPONENTS: Record = { + BIF: 0, CLP: 0, DJF: 0, GNF: 0, ISK: 0, JPY: 0, KMF: 0, KRW: 0, PYG: 0, + RWF: 0, UGX: 0, UYI: 0, VND: 0, VUV: 0, XAF: 0, XOF: 0, XPF: 0, + BHD: 3, IQD: 3, JOD: 3, KWD: 3, LYD: 3, OMR: 3, TND: 3, +}; + +export const MAX_AMOUNT = 1e13; // minor units; keeps everything well inside 2^53 + +export function isCurrencyCode(code: unknown): code is string { + return typeof code === 'string' && /^[A-Z]{3}$/.test(code); +} + +export function exponent(currency: string): number { + return EXPONENTS[currency] ?? 2; +} + +const RATE_RE = /^(\d{1,12})(?:\.(\d{1,12}))?$/; + +/** A rate is a positive decimal string, e.g. "25.214". */ +export function isValidRate(rate: unknown): rate is string { + if (typeof rate !== 'string') return false; + const m = RATE_RE.exec(rate); + if (!m) return false; + return BigInt(m[1] + (m[2] ?? '')) > 0n; +} + +function parseRate(rate: string): { num: bigint; scale: number } { + const m = RATE_RE.exec(rate); + if (!m) throw new Error(`invalid rate ${rate}`); + const frac = m[2] ?? ''; + return { num: BigInt(m[1] + frac), scale: frac.length }; +} + +/** n / d rounded half to even, for n >= 0, d > 0. */ +function divRoundHalfEven(n: bigint, d: bigint): bigint { + const q = n / d; + const r = n % d; + const twice = r * 2n; + if (twice > d || (twice === d && q % 2n === 1n)) return q + 1n; + return q; +} + +/** Convert an amount (minor units of `from`) into minor units of `to`. */ +export function convert(amount: number, from: string, to: string, rate: string): number { + if (from === to) return amount; + const { num, scale } = parseRate(rate); + const n = BigInt(amount) * num * 10n ** BigInt(exponent(to)); + const d = 10n ** BigInt(scale + exponent(from)); + return Number(divRoundHalfEven(n, d)); +} + +/** + * Split `total` into integers proportional to `weights` that sum exactly to + * `total`. Each part is floored, then the leftover units go one at a time to + * the largest remainders; ties go to the lower index (member order). + */ +export function allocate(total: number, weights: number[]): number[] { + const W = weights.reduce((a, w) => a + BigInt(w), 0n); + if (W <= 0n) throw new Error('allocate: weights must sum to > 0'); + const T = BigInt(total); + const parts = weights.map((w) => { + const raw = T * BigInt(w); + return { q: raw / W, r: raw % W }; + }); + let leftover = T - parts.reduce((a, p) => a + p.q, 0n); + const order = parts + .map((p, i) => ({ r: p.r, i })) + .sort((a, b) => (a.r === b.r ? a.i - b.i : a.r > b.r ? -1 : 1)); + for (const { i } of order) { + if (leftover <= 0n) break; + parts[i].q += 1n; + leftover -= 1n; + } + return parts.map((p) => Number(p.q)); +} + +/** Minor units → plain decimal string ("1234.50"), no grouping. */ +export function toDecimalString(minor: number, currency: string): string { + const e = exponent(currency); + const neg = minor < 0; + const s = String(Math.abs(minor)).padStart(e + 1, '0'); + const out = e === 0 ? s : `${s.slice(0, -e)}.${s.slice(-e)}`; + return neg ? `-${out}` : out; +} + +/** + * Parse user input ("1 234,5", "1234.50", "12") into minor units. + * Returns null for anything that isn't a positive number with at most the + * currency's number of decimals. + */ +export function parseAmount(input: string, currency: string): number | null { + const e = exponent(currency); + const s = input.replace(/[\s\u00a0\u202f']/g, ''); + let intPart: string; + let frac = ''; + const sep = Math.max(s.lastIndexOf('.'), s.lastIndexOf(',')); + const before = s.slice(0, sep); + const after = s.slice(sep + 1); + if (/^\d+$/.test(s)) { + intPart = s; + } else if ( + sep > 0 && !before.includes(s[sep]) && after.length >= 1 && after.length <= e && /^\d+$/.test(after) && + /^(\d{1,3}([.,]\d{3})*|\d+)$/.test(before) + ) { + // "12,5" / "1.234,50": the last separator is the decimal point + intPart = before.replace(/[.,]/g, ''); + frac = after; + } else if (/^\d{1,3}([.,]\d{3})+$/.test(s)) { + // "1.234" in a 2-decimal currency: grouping only + intPart = s.replace(/[.,]/g, ''); + } else { + return null; + } + const minor = Number(intPart + frac.padEnd(e, '0')); + if (!Number.isSafeInteger(minor) || minor <= 0 || minor > MAX_AMOUNT) return null; + return minor; +} + +/** Turn a float rate (from the rates API) into a stored decimal string with + * 6 significant digits. Only used to prefill; the stored string is then exact. */ +export function rateToString(rate: number): string { + if (!(rate > 0) || !Number.isFinite(rate)) throw new Error('bad rate'); + const digits = Math.max(0, 6 - Math.floor(Math.log10(rate)) - 1); + let s = rate.toFixed(Math.min(12, digits)); + if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, ''); + return s === '0' ? rate.toFixed(12).replace(/0+$/, '') : s; +} diff --git a/packages/core/src/recurring.ts b/packages/core/src/recurring.ts new file mode 100644 index 0000000..f1db5f7 --- /dev/null +++ b/packages/core/src/recurring.ts @@ -0,0 +1,69 @@ +// Recurring expenses (SPEC.md §7.4). There's no server-side scheduler (the +// server can't read templates), so whichever client opens the group first +// creates the missing occurrences. Their ids are deterministic, so two +// clients doing it at once produce the same expense and replay keeps one. +import type { Expense, Recurring, RecurringRule, GroupState } from './types.ts'; + +const MAX_PER_RUN = 120; + +function parse(d: string): Date { + return new Date(`${d}T00:00:00Z`); +} +function fmt(d: Date): string { + return d.toISOString().slice(0, 10); +} +function daysInMonth(y: number, m: number): number { + return new Date(Date.UTC(y, m + 1, 0)).getUTCDate(); +} + +/** The n-th occurrence date (n = 0 is `start`). Monthly/yearly clamp to month end. */ +export function nthOccurrence(rule: RecurringRule, n: number): string { + const start = parse(rule.start); + if (rule.freq === 'weekly') return fmt(new Date(start.getTime() + n * rule.interval * 7 * 864e5)); + const months = rule.freq === 'monthly' ? n * rule.interval : n * rule.interval * 12; + const y = start.getUTCFullYear() + Math.floor((start.getUTCMonth() + months) / 12); + const m = (start.getUTCMonth() + months) % 12; + const day = Math.min(start.getUTCDate(), daysInMonth(y, m)); + return fmt(new Date(Date.UTC(y, m, day))); +} + +/** All occurrence dates from start up to and including `today`. */ +export function occurrencesUntil(rule: RecurringRule, today: string): string[] { + const out: string[] = []; + for (let n = 0; out.length < 10_000; n++) { + const d = nthOccurrence(rule, n); + if (d > today || (rule.end && d > rule.end)) break; + out.push(d); + } + return out; +} + +export function occurrenceId(recurringId: string, date: string): string { + return `rec-${recurringId}-${date}`; +} + +/** + * Occurrences that are due but don't exist yet. Deleted occurrences count + * as existing, so deleting one doesn't make it come back. + */ +export function dueOccurrences(s: GroupState, today: string): Expense[] { + const out: Expense[] = []; + for (const r of Object.values(s.recurring) as Recurring[]) { + for (const date of occurrencesUntil(r.rule, today)) { + const id = occurrenceId(r.id, date); + if (s.expenses[id]) continue; + out.push({ ...structuredClone(r.template), id, date, photo: null, recurringId: r.id }); + if (out.length >= MAX_PER_RUN) return out; + } + } + return out; +} + +export function nextOccurrence(rule: RecurringRule, today: string): string | null { + for (let n = 0; n < 10_000; n++) { + const d = nthOccurrence(rule, n); + if (rule.end && d > rule.end) return null; + if (d > today) return d; + } + return null; +} diff --git a/packages/core/src/replay.ts b/packages/core/src/replay.ts new file mode 100644 index 0000000..a7bd259 --- /dev/null +++ b/packages/core/src/replay.ts @@ -0,0 +1,197 @@ +// Rebuild a group's state from its event log. Events are applied in log +// order (server seq, then the local outbox); for the same entity the later +// event wins. A `revert` event replaces the state with a snapshot taken right +// after its target event; nothing is ever erased from the log. See SPEC.md §6. +import { validateExpense } from './expense.ts'; +import { isCurrencyCode } from './money.ts'; +import type { Activity, GroupEvent, GroupState, Recurring } from './types.ts'; + +export function emptyState(): GroupState { + return { group: null, members: [], expenses: {}, comments: {}, recurring: {} }; +} + +const str = (v: unknown, max: number): v is string => typeof v === 'string' && v.length > 0 && v.length <= max; + +function validRecurring(r: Recurring, s: GroupState): boolean { + if (!r || !str(r.id, 100) || !r.rule || !r.template) return false; + const { freq, interval, start, end } = r.rule; + if (!['weekly', 'monthly', 'yearly'].includes(freq)) return false; + if (!Number.isSafeInteger(interval) || interval < 1 || interval > 52) return false; + const probe = { ...r.template, id: r.id, date: start, photo: null }; + if (validateExpense(probe, s.members) !== null) return false; + return end === null || (typeof end === 'string' && end >= start); +} + +/** + * Apply one event to `s` in place. Returns the activity entry describing it. + * `snapshots` provides states for `revert` targets. + */ +function apply(s: GroupState, ev: GroupEvent, snapshots: Map): { state: GroupState; activity: Activity } { + const act: Activity = { + eventId: ev.id, seq: ev.seq, at: ev.at, actor: ev.actor, type: ev.type, + entityId: null, before: null, after: null, + }; + const ignore = () => ((act.ignored = true), { state: s, activity: act }); + const member = (id: string) => s.members.find((m) => m.id === id); + const hasExpenses = Object.keys(s.expenses).length > 0; + + switch (ev.type) { + case 'group.created': { + const d = ev.data; + if (s.group || !str(d?.name, 100) || !isCurrencyCode(d.baseCurrency)) return ignore(); + s.group = { name: d.name, baseCurrency: d.baseCurrency, icon: typeof d.icon === 'string' ? d.icon.slice(0, 16) : '' }; + act.after = { ...s.group }; + break; + } + case 'group.updated': { + if (!s.group) return ignore(); + const d = ev.data ?? {}; + act.before = { ...s.group }; + if (d.name !== undefined) { + if (!str(d.name, 100)) return ignore(); + s.group.name = d.name; + } + if (typeof d.icon === 'string') s.group.icon = d.icon.slice(0, 16); + if (d.baseCurrency !== undefined && d.baseCurrency !== s.group.baseCurrency) { + // Locked once the group has any expense (SPEC §7.1). + if (hasExpenses || !isCurrencyCode(d.baseCurrency)) return ignore(); + s.group.baseCurrency = d.baseCurrency; + } + act.after = { ...s.group }; + break; + } + case 'member.added': { + const d = ev.data; + if (!str(d?.id, 100) || !str(d.name, 60) || member(d.id)) return ignore(); + s.members.push({ id: d.id, name: d.name, color: String(d.color ?? '').slice(0, 16), archived: false }); + act.entityId = d.id; + act.after = { name: d.name }; + break; + } + case 'member.updated': { + const m = member(ev.data?.id); + if (!m) return ignore(); + act.entityId = m.id; + act.before = { name: m.name, color: m.color }; + if (ev.data.name !== undefined) { + if (!str(ev.data.name, 60)) return ignore(); + m.name = ev.data.name; + } + if (typeof ev.data.color === 'string') m.color = ev.data.color.slice(0, 16); + act.after = { name: m.name, color: m.color }; + break; + } + case 'member.archived': + case 'member.restored': { + const m = member(ev.data?.id); + if (!m) return ignore(); + act.entityId = m.id; + m.archived = ev.type === 'member.archived'; + break; + } + case 'expense.created': + case 'expense.updated': { + const e = ev.data; + const existing = s.expenses[e?.id]; + act.entityId = e?.id ?? null; + // Creation is idempotent (first wins): two clients generating the same + // recurring occurrence must not clobber each other. + if (ev.type === 'expense.created' && existing) return ignore(); + if (ev.type === 'expense.updated' && !existing) return ignore(); + if (validateExpense(e, s.members) !== null) return ignore(); + const copy = structuredClone(e); + if (existing) { + act.before = existing.expense; + existing.expense = copy; + existing.updatedAt = ev.at; + } else { + s.expenses[e.id] = { expense: copy, deleted: false, createdBy: ev.actor, createdAt: ev.at, updatedAt: ev.at }; + } + act.after = copy; + break; + } + case 'expense.deleted': + case 'expense.restored': { + const r = s.expenses[ev.data?.id]; + if (!r) return ignore(); + act.entityId = r.expense.id; + act.before = r.expense; + r.deleted = ev.type === 'expense.deleted'; + break; + } + case 'comment.added': { + const d = ev.data; + if (!str(d?.id, 100) || !str(d.text, 2000) || !s.expenses[d.expenseId] || s.comments[d.id]) return ignore(); + s.comments[d.id] = { id: d.id, expenseId: d.expenseId, text: d.text, author: ev.actor, at: ev.at }; + act.entityId = d.expenseId; + act.after = { text: d.text }; + break; + } + case 'comment.deleted': { + const c = s.comments[ev.data?.id]; + if (!c) return ignore(); + act.entityId = c.expenseId; + act.before = { text: c.text }; + delete s.comments[c.id]; + break; + } + case 'recurring.created': + case 'recurring.updated': { + const r = ev.data; + const existing = s.recurring[r?.id]; + if ((ev.type === 'recurring.created') === !!existing) return ignore(); + if (!validRecurring(r, s)) return ignore(); + act.entityId = r.id; + act.before = existing ?? null; + s.recurring[r.id] = structuredClone(r); + act.after = s.recurring[r.id]; + break; + } + case 'recurring.deleted': { + const r = s.recurring[ev.data?.id]; + if (!r) return ignore(); + act.entityId = r.id; + act.before = r; + delete s.recurring[r.id]; + break; + } + case 'revert': { + const snap = snapshots.get(ev.data?.targetId); + if (!snap) return ignore(); + act.entityId = ev.data.targetId; + return { state: structuredClone(snap), activity: act }; + } + default: + return ignore(); + } + return { state: s, activity: act }; +} + +export interface ReplayResult { + state: GroupState; + /** oldest first, one entry per event */ + activity: Activity[]; +} + +/** Replay events (already in log order) into a state. */ +export function replay(events: GroupEvent[]): ReplayResult { + const targets = new Set(); + for (const ev of events) if (ev.type === 'revert' && typeof ev.data?.targetId === 'string') targets.add(ev.data.targetId); + + const snapshots = new Map(); + const activity: Activity[] = []; + let state = emptyState(); + for (const ev of events) { + const r = apply(state, ev, snapshots); + state = r.state; + activity.push(r.activity); + if (targets.has(ev.id) && !snapshots.has(ev.id)) snapshots.set(ev.id, structuredClone(state)); + } + return { state, activity }; +} + +/** Sort events into log order: synced by seq, then pending in outbox order. */ +export function logOrder(synced: GroupEvent[], pending: GroupEvent[]): GroupEvent[] { + const ids = new Set(synced.map((e) => e.id)); + return [...synced].sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0)).concat(pending.filter((e) => !ids.has(e.id))); +} diff --git a/packages/core/src/settle.ts b/packages/core/src/settle.ts new file mode 100644 index 0000000..a22fb68 --- /dev/null +++ b/packages/core/src/settle.ts @@ -0,0 +1,47 @@ +// Balances and settle-up suggestions (SPEC.md §5.3–5.4). +import { inBase } from './expense.ts'; +import type { GroupState } from './types.ts'; + +/** member id → balance in base minor units (positive = is owed money). */ +export function balances(s: GroupState): Record { + const out: Record = {}; + for (const m of s.members) out[m.id] = 0; + if (!s.group) return out; + for (const r of Object.values(s.expenses)) { + if (r.deleted) continue; + const b = inBase(r.expense, s.group.baseCurrency); + for (const [id, v] of Object.entries(b.paid)) out[id] = (out[id] ?? 0) + v; + for (const [id, v] of Object.entries(b.owed)) out[id] = (out[id] ?? 0) - v; + } + return out; +} + +export interface Transfer { + from: string; + to: string; + amount: number; +} + +/** + * Greedy settle-up: repeatedly pay the largest creditor from the largest + * debtor. At most n − 1 transfers. Ties go to the earlier member, so every + * client suggests the same transfers. + */ +export function settleUp(bal: Record, memberOrder: string[]): Transfer[] { + const idx = new Map(memberOrder.map((id, i) => [id, i])); + const rank = (id: string) => idx.get(id) ?? Number.MAX_SAFE_INTEGER; + const debtors = Object.entries(bal).filter(([, v]) => v < 0).map(([id, v]) => ({ id, v: -v })); + const creditors = Object.entries(bal).filter(([, v]) => v > 0).map(([id, v]) => ({ id, v })); + const pick = (xs: { id: string; v: number }[]) => + xs.reduce((best, x) => (x.v > best.v || (x.v === best.v && rank(x.id) < rank(best.id)) ? x : best)); + const out: Transfer[] = []; + while (debtors.some((d) => d.v > 0) && creditors.some((c) => c.v > 0)) { + const d = pick(debtors.filter((x) => x.v > 0)); + const c = pick(creditors.filter((x) => x.v > 0)); + const amount = Math.min(d.v, c.v); + out.push({ from: d.id, to: c.id, amount }); + d.v -= amount; + c.v -= amount; + } + return out; +} diff --git a/packages/core/src/stats.ts b/packages/core/src/stats.ts new file mode 100644 index 0000000..e9c8f1d --- /dev/null +++ b/packages/core/src/stats.ts @@ -0,0 +1,53 @@ +// Spending statistics (SPEC.md §7.5). Transfers are not spending, so they +// are left out of every figure here. +import { inBase } from './expense.ts'; +import type { GroupState } from './types.ts'; + +export interface Stats { + total: number; + byCategory: { category: string; amount: number }[]; + /** YYYY-MM → amount, ascending, months with no spending included */ + byMonth: { month: string; amount: number }[]; + /** paid = put money in; consumed = their share of the spending */ + perMember: { member: string; paid: number; consumed: number }[]; +} + +export function computeStats(s: GroupState, from: string | null, to: string | null): Stats { + const base = s.group?.baseCurrency ?? 'EUR'; + const cat = new Map(); + const month = new Map(); + const paid = new Map(); + const consumed = new Map(); + let total = 0; + for (const r of Object.values(s.expenses)) { + const e = r.expense; + if (r.deleted || e.kind === 'transfer') continue; + if ((from && e.date < from) || (to && e.date > to)) continue; + const b = inBase(e, base); + total += b.total; + cat.set(e.category, (cat.get(e.category) ?? 0) + b.total); + const mk = e.date.slice(0, 7); + month.set(mk, (month.get(mk) ?? 0) + b.total); + for (const [id, v] of Object.entries(b.paid)) paid.set(id, (paid.get(id) ?? 0) + v); + for (const [id, v] of Object.entries(b.owed)) consumed.set(id, (consumed.get(id) ?? 0) + v); + } + const months = [...month.keys()].sort(); + const byMonth: Stats['byMonth'] = []; + if (months.length) { + let [y, m] = months[0].split('-').map(Number); + const last = months[months.length - 1]; + for (;;) { + const k = `${y}-${String(m).padStart(2, '0')}`; + byMonth.push({ month: k, amount: month.get(k) ?? 0 }); + if (k >= last) break; + m += 1; + if (m > 12) (m = 1), (y += 1); + } + } + return { + total, + byCategory: [...cat].map(([category, amount]) => ({ category, amount })).sort((a, b) => b.amount - a.amount), + byMonth, + perMember: s.members.map((m) => ({ member: m.id, paid: paid.get(m.id) ?? 0, consumed: consumed.get(m.id) ?? 0 })), + }; +} diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts new file mode 100644 index 0000000..ae550d7 --- /dev/null +++ b/packages/core/src/types.ts @@ -0,0 +1,161 @@ +// Event schema (decrypted plaintext) and the state derived by replaying it. +// See SPEC.md §4. + +export const SCHEMA_VERSION = 1; + +export type SplitMode = 'equal' | 'shares' | 'exact' | 'percent'; +export type ExpenseKind = 'expense' | 'transfer'; + +export const CATEGORIES = [ + 'food', 'groceries', 'transport', 'accommodation', 'entertainment', + 'shopping', 'utilities', 'rent', 'travel', 'gifts', 'health', 'other', +] as const; +export type Category = (typeof CATEGORIES)[number] | 'transfer'; + +export interface Member { + id: string; + name: string; + color: string; + archived: boolean; +} + +export interface SplitEntry { + member: string; + /** equal: 1/0 · shares: weight · exact: minor units · percent: basis points */ + value: number; +} + +export interface Payer { + member: string; + amount: number; +} + +export interface Photo { + blobId: string; + thumbBlobId: string; + w: number; + h: number; +} + +export interface Expense { + id: string; + kind: ExpenseKind; + title: string; + category: Category; + /** YYYY-MM-DD */ + date: string; + currency: string; + /** minor units of `currency` */ + amount: number; + /** decimal string: 1 `currency` = rate × base currency */ + rate: string; + rateSource: string; + payers: Payer[]; + split: { mode: SplitMode; entries: SplitEntry[] }; + note: string; + photo: Photo | null; + /** set on occurrences generated from a recurring template */ + recurringId?: string; +} + +export type Freq = 'weekly' | 'monthly' | 'yearly'; + +export interface RecurringRule { + freq: Freq; + interval: number; + /** YYYY-MM-DD, first occurrence */ + start: string; + /** YYYY-MM-DD inclusive, or null */ + end: string | null; +} + +export type ExpenseTemplate = Omit; + +export interface Recurring { + id: string; + template: ExpenseTemplate; + rule: RecurringRule; +} + +export interface GroupInfo { + name: string; + baseCurrency: string; + icon: string; +} + +export type EventBody = + | { type: 'group.created'; data: GroupInfo } + | { type: 'group.updated'; data: Partial } + | { type: 'member.added'; data: { id: string; name: string; color: string } } + | { type: 'member.updated'; data: { id: string; name?: string; color?: string } } + | { type: 'member.archived'; data: { id: string } } + | { type: 'member.restored'; data: { id: string } } + | { type: 'expense.created'; data: Expense } + | { type: 'expense.updated'; data: Expense } + | { type: 'expense.deleted'; data: { id: string } } + | { type: 'expense.restored'; data: { id: string } } + | { type: 'comment.added'; data: { id: string; expenseId: string; text: string } } + | { type: 'comment.deleted'; data: { id: string } } + | { type: 'recurring.created'; data: Recurring } + | { type: 'recurring.updated'; data: Recurring } + | { type: 'recurring.deleted'; data: { id: string } } + | { type: 'revert'; data: { targetId: string } }; + +export type EventType = EventBody['type']; + +/** What gets encrypted into an event's ciphertext. */ +export type EventPlaintext = EventBody & { + v: number; + /** member id of whoever made the change, if they picked an identity */ + actor: string | null; + /** client clock, ISO 8601 */ + at: string; +}; + +/** A decrypted event as the client holds it. */ +export type GroupEvent = EventPlaintext & { + id: string; + /** server-assigned; null while still in the local outbox */ + seq: number | null; + deviceId: string; +}; + +export interface ExpenseRecord { + expense: Expense; + deleted: boolean; + createdBy: string | null; + createdAt: string; + updatedAt: string; +} + +export interface Comment { + id: string; + expenseId: string; + text: string; + author: string | null; + at: string; +} + +export interface GroupState { + group: GroupInfo | null; + /** in order of addition; order breaks rounding ties */ + members: Member[]; + expenses: Record; + comments: Record; + recurring: Record; +} + +/** One line of the group's activity feed. Not affected by rewinds. */ +export interface Activity { + eventId: string; + seq: number | null; + at: string; + actor: string | null; + type: EventType; + /** id of the entity concerned (expense, member, comment, …) */ + entityId: string | null; + before: unknown; + after: unknown; + /** set when the event was ignored as invalid or as a no-op */ + ignored?: boolean; +} diff --git a/packages/core/test/core.test.ts b/packages/core/test/core.test.ts new file mode 100644 index 0000000..dc56547 --- /dev/null +++ b/packages/core/test/core.test.ts @@ -0,0 +1,232 @@ +import { describe, expect, it } from 'vitest'; +import { + allocate, balances, convert, dueOccurrences, expensesCsv, inBase, logOrder, nthOccurrence, + occurrenceId, parseAmount, rateToString, replay, settleUp, toDecimalString, computeStats, + type EventBody, type Expense, type GroupEvent, +} from '../src/index.ts'; + +let seq = 0; +function ev(body: EventBody, actor: string | null = null, id?: string): GroupEvent { + seq += 1; + return { ...body, v: 1, actor, at: `2026-10-01T00:00:${String(seq % 60).padStart(2, '0')}Z`, id: id ?? `e${seq}`, seq, deviceId: 'd' } as GroupEvent; +} + +function expense(over: Partial = {}): Expense { + return { + id: 'x1', kind: 'expense', title: 'Dinner', category: 'food', date: '2026-10-01', + currency: 'CZK', amount: 10000, rate: '1', rateSource: 'manual', + payers: [{ member: 'a', amount: 10000 }], + split: { mode: 'equal', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 1 }, { member: 'c', value: 1 }] }, + note: '', photo: null, ...over, + }; +} + +function baseGroup(): GroupEvent[] { + return [ + ev({ type: 'group.created', data: { name: 'Trip', baseCurrency: 'CZK', icon: '🏔️' } }), + ev({ type: 'member.added', data: { id: 'a', name: 'Anna', color: '' } }), + ev({ type: 'member.added', data: { id: 'b', name: 'Petr', color: '' } }), + ev({ type: 'member.added', data: { id: 'c', name: 'Jana', color: '' } }), + ]; +} + +describe('allocate', () => { + it('splits 100.00 three ways as 33.34 / 33.33 / 33.33', () => { + expect(allocate(10000, [1, 1, 1])).toEqual([3334, 3333, 3333]); + }); + it('gives leftovers to the largest remainders, ties to the earlier index', () => { + expect(allocate(10, [1, 1, 1, 1])).toEqual([3, 3, 2, 2]); + expect(allocate(100, [1, 2])).toEqual([33, 67]); + }); + it('always sums to the total', () => { + for (let t = 1; t < 500; t += 7) { + const w = [3, 0, 7, 1, 13]; + expect(allocate(t, w).reduce((a, b) => a + b, 0)).toBe(t); + } + }); +}); + +describe('convert', () => { + it('converts EUR to CZK with the stored rate', () => { + expect(convert(12050, 'EUR', 'CZK', '25.214')).toBe(303829); // 120.50 × 25.214 = 3038.287 → 3038.29 + }); + it('handles differing exponents', () => { + expect(convert(1000, 'JPY', 'CZK', '0.1567')).toBe(15670); // ¥1000 → 156.70 Kč + expect(convert(100, 'CZK', 'JPY', '6.38')).toBe(6); // 1 Kč → ¥6.38 → ¥6 + }); + it('rounds half to even', () => { + expect(convert(1, 'EUR', 'CZK', '0.5')).toBe(0); // 0.005 → 0.00 + expect(convert(3, 'EUR', 'CZK', '0.5')).toBe(2); // 0.015 → 0.02 + }); +}); + +describe('parseAmount / toDecimalString', () => { + it('accepts comma or dot decimals and grouping', () => { + expect(parseAmount('12,5', 'CZK')).toBe(1250); + expect(parseAmount('1 234,50', 'CZK')).toBe(123450); + expect(parseAmount('1.234,5', 'EUR')).toBe(123450); + expect(parseAmount('1,234.56', 'USD')).toBe(123456); + expect(parseAmount('1.234', 'EUR')).toBe(123400); + expect(parseAmount('1.234', 'BHD')).toBe(1234); + expect(parseAmount('500', 'JPY')).toBe(500); + }); + it('rejects junk, zero and too many decimals', () => { + for (const s of ['', 'abc', '0', '1.234.5', '12.3456', '-5', '1e5']) expect(parseAmount(s, 'EUR')).toBeNull(); + expect(parseAmount('1.5', 'JPY')).toBeNull(); + }); + it('formats minor units', () => { + expect(toDecimalString(5, 'EUR')).toBe('0.05'); + expect(toDecimalString(-123450, 'CZK')).toBe('-1234.50'); + expect(toDecimalString(500, 'JPY')).toBe('500'); + }); + it('rateToString keeps 6 significant digits', () => { + expect(rateToString(25.21399999)).toBe('25.214'); + expect(rateToString(0.0412345678)).toBe('0.0412346'); + expect(rateToString(1)).toBe('1'); + }); +}); + +describe('inBase', () => { + it('paid and owed each sum to the converted total', () => { + const e = expense({ currency: 'EUR', amount: 1000, rate: '25.333', split: { mode: 'shares', entries: [{ member: 'a', value: 1 }, { member: 'b', value: 2 }, { member: 'c', value: 0 }] } }); + const b = inBase(e, 'CZK'); + expect(b.total).toBe(25333); + expect(Object.values(b.owed).reduce((x, y) => x + y)).toBe(b.total); + expect(Object.values(b.paid).reduce((x, y) => x + y)).toBe(b.total); + expect(b.owed.c).toBeUndefined(); + }); + it('supports exact and percent splits', () => { + expect(inBase(expense({ split: { mode: 'exact', entries: [{ member: 'a', value: 2500 }, { member: 'b', value: 7500 }] } }), 'CZK').owed).toEqual({ a: 2500, b: 7500 }); + expect(inBase(expense({ split: { mode: 'percent', entries: [{ member: 'a', value: 3333 }, { member: 'b', value: 6667 }] } }), 'CZK').owed).toEqual({ a: 3333, b: 6667 }); + }); +}); + +describe('replay', () => { + it('builds members and balances that sum to zero', () => { + const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() })]); + const bal = balances(state); + expect(bal).toEqual({ a: 6666, b: -3333, c: -3333 }); + expect(Object.values(bal).reduce((x, y) => x + y)).toBe(0); + }); + + it('ignores invalid expenses (bad sums, unknown members)', () => { + const bad1 = expense({ id: 'x2', payers: [{ member: 'a', amount: 1 }] }); + const bad2 = expense({ id: 'x3', split: { mode: 'equal', entries: [{ member: 'zzz', value: 1 }] } }); + const r = replay([...baseGroup(), ev({ type: 'expense.created', data: bad1 }), ev({ type: 'expense.created', data: bad2 })]); + expect(Object.keys(r.state.expenses)).toEqual([]); + expect(r.activity.filter((a) => a.ignored)).toHaveLength(2); + }); + + it('last writer wins, and delete/restore toggle', () => { + const evs = [ + ...baseGroup(), + ev({ type: 'expense.created', data: expense() }), + ev({ type: 'expense.updated', data: expense({ title: 'Lunch' }) }), + ev({ type: 'expense.deleted', data: { id: 'x1' } }), + ]; + let { state } = replay(evs); + expect(state.expenses.x1.expense.title).toBe('Lunch'); + expect(state.expenses.x1.deleted).toBe(true); + expect(balances(state)).toEqual({ a: 0, b: 0, c: 0 }); + ({ state } = replay([...evs, ev({ type: 'expense.restored', data: { id: 'x1' } })])); + expect(state.expenses.x1.deleted).toBe(false); + }); + + it('expense.created is first-wins (recurring dedupe)', () => { + const { state } = replay([ + ...baseGroup(), + ev({ type: 'expense.created', data: expense({ title: 'first' }) }), + ev({ type: 'expense.created', data: expense({ title: 'second' }) }), + ]); + expect(state.expenses.x1.expense.title).toBe('first'); + }); + + it('locks the base currency once there are expenses', () => { + const evs = [...baseGroup(), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })]; + expect(replay(evs).state.group!.baseCurrency).toBe('EUR'); + const locked = [...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'group.updated', data: { baseCurrency: 'EUR' } })]; + expect(replay(locked).state.group!.baseCurrency).toBe('CZK'); + }); + + it('revert restores an earlier state, and can itself be reverted', () => { + const evs = [...baseGroup(), ev({ type: 'expense.created', data: expense() }, 'a', 'keep')]; + evs.push(ev({ type: 'expense.updated', data: expense({ amount: 99900, payers: [{ member: 'a', amount: 99900 }] }) }, 'b', 'vandal')); + evs.push(ev({ type: 'member.added', data: { id: 'd', name: 'Dan', color: '' } })); + evs.push(ev({ type: 'revert', data: { targetId: 'keep' } }, 'a', 'rw')); + let r = replay(evs); + expect(r.state.expenses.x1.expense.amount).toBe(10000); + expect(r.state.members.map((m) => m.id)).toEqual(['a', 'b', 'c']); + expect(r.activity).toHaveLength(evs.length); // nothing erased from history + + // Undo the rewind: revert to the event just before it. + const before = evs[evs.length - 2].id; + evs.push(ev({ type: 'revert', data: { targetId: before } })); + r = replay(evs); + expect(r.state.expenses.x1.expense.amount).toBe(99900); + expect(r.state.members).toHaveLength(4); + }); + + it('logOrder puts synced events by seq, then pending ones', () => { + const a = ev({ type: 'member.added', data: { id: 'q', name: 'Q', color: '' } }); + const b = ev({ type: 'member.added', data: { id: 'r', name: 'R', color: '' } }); + const p = { ...b, id: 'p1', seq: null }; + expect(logOrder([b, a], [p, { ...a }]).map((e) => e.id)).toEqual([a.id, b.id, 'p1']); + }); +}); + +describe('settleUp', () => { + it('produces transfers that zero all balances', () => { + const bal = { a: 5000, b: -2000, c: -2000, d: -1000 }; + const t = settleUp(bal, ['a', 'b', 'c', 'd']); + expect(t).toEqual([ + { from: 'b', to: 'a', amount: 2000 }, + { from: 'c', to: 'a', amount: 2000 }, + { from: 'd', to: 'a', amount: 1000 }, + ]); + }); + it('uses at most n-1 transfers', () => { + const bal = { a: 700, b: 300, c: -400, d: -600 }; + const t = settleUp(bal, ['a', 'b', 'c', 'd']); + expect(t.length).toBeLessThanOrEqual(3); + const net: Record = { ...bal }; + for (const x of t) (net[x.from] += x.amount), (net[x.to] -= x.amount); + expect(Object.values(net).every((v) => v === 0)).toBe(true); + }); +}); + +describe('recurring', () => { + it('clamps monthly occurrences to the month end', () => { + const rule = { freq: 'monthly' as const, interval: 1, start: '2026-01-31', end: null }; + expect([0, 1, 2, 3].map((n) => nthOccurrence(rule, n))).toEqual(['2026-01-31', '2026-02-28', '2026-03-31', '2026-04-30']); + }); + it('creates missing occurrences once, and deleted ones stay deleted', () => { + const { template: _t, ...rest } = { template: null, ...expense() }; + const tpl = { ...rest } as Partial; + delete tpl.id; delete tpl.date; delete tpl.photo; + const rec = { id: 'r1', template: tpl as any, rule: { freq: 'weekly' as const, interval: 1, start: '2026-09-01', end: null } }; + const evs = [...baseGroup(), ev({ type: 'recurring.created', data: rec })]; + let { state } = replay(evs); + const due = dueOccurrences(state, '2026-09-20'); + expect(due.map((e) => e.date)).toEqual(['2026-09-01', '2026-09-08', '2026-09-15']); + for (const e of due) evs.push(ev({ type: 'expense.created', data: e })); + evs.push(ev({ type: 'expense.deleted', data: { id: occurrenceId('r1', '2026-09-08') } })); + ({ state } = replay(evs)); + expect(dueOccurrences(state, '2026-09-20')).toEqual([]); + expect(dueOccurrences(state, '2026-09-22').map((e) => e.date)).toEqual(['2026-09-22']); + }); +}); + +describe('stats and csv', () => { + it('excludes transfers from stats', () => { + const t = expense({ id: 't1', kind: 'transfer', category: 'transfer', amount: 500, payers: [{ member: 'b', amount: 500 }], split: { mode: 'equal', entries: [{ member: 'a', value: 1 }] } }); + const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense() }), ev({ type: 'expense.created', data: t })]); + const st = computeStats(state, null, null); + expect(st.total).toBe(10000); + expect(st.byCategory).toEqual([{ category: 'food', amount: 10000 }]); + expect(balances(state)).toEqual({ a: 6166, b: -2833, c: -3333 }); + }); + it('escapes CSV and neutralises formulas', () => { + const { state } = replay([...baseGroup(), ev({ type: 'expense.created', data: expense({ title: '=HYPERLINK("x")' }) })]); + expect(expensesCsv(state)).toContain(`"'=HYPERLINK(""x"")"`); + }); +}); diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json new file mode 100644 index 0000000..37c126d --- /dev/null +++ b/packages/core/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "test"] +} From 8dd25b93b0e540925bc1eabfe47345b6c8af08ef Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:33:28 +0000 Subject: [PATCH 02/18] Add server: encrypted event log API, blobs, SSE, ECB rates, Web Push Node 24 standard library only (node:http, node:sqlite, node:crypto). Push uses VAPID + RFC 8291 encryption with an allowlist of push services. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- apps/server/src/app.ts | 365 ++++++++++++++++++++++++++++++++ apps/server/src/config.ts | 47 ++++ apps/server/src/db.ts | 175 +++++++++++++++ apps/server/src/gen-vapid.ts | 28 +++ apps/server/src/main.ts | 30 +++ apps/server/src/push.ts | 105 +++++++++ apps/server/src/rates.ts | 52 +++++ apps/server/test/server.test.ts | 186 ++++++++++++++++ apps/server/tsconfig.json | 16 ++ package.json | 2 +- 10 files changed, 1005 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/app.ts create mode 100644 apps/server/src/config.ts create mode 100644 apps/server/src/db.ts create mode 100644 apps/server/src/gen-vapid.ts create mode 100644 apps/server/src/main.ts create mode 100644 apps/server/src/push.ts create mode 100644 apps/server/src/rates.ts create mode 100644 apps/server/test/server.test.ts create mode 100644 apps/server/tsconfig.json diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts new file mode 100644 index 0000000..d58137d --- /dev/null +++ b/apps/server/src/app.ts @@ -0,0 +1,365 @@ +// HTTP API and static file server (SPEC.md §8.1). Plain node:http with a +// small hand-written router; no dependencies. +import { createHash, timingSafeEqual } from 'node:crypto'; +import { createReadStream, existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { extname, join, normalize, sep } from 'node:path'; +import type { Config } from './config.ts'; +import type { Store } from './db.ts'; +import { isAllowedEndpoint, sendPush, type Vapid } from './push.ts'; + +const ID_RE = /^[A-Za-z0-9_-]{22}$/; // 16 random bytes, base64url +const EVENT_ID_RE = /^[A-Za-z0-9_-]{8,100}$/; +const BLOB_ID_RE = /^[A-Za-z0-9_-]{16,64}$/; +const DEVICE_RE = /^[A-Za-z0-9_-]{8,64}$/; +const B64U_RE = /^[A-Za-z0-9_-]+$/; +const HEX64_RE = /^[0-9a-f]{64}$/; + +class HttpError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +const SECURITY_HEADERS: Record = { + 'Content-Security-Policy': [ + "default-src 'self'", + "script-src 'self'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' blob: data:", + "connect-src 'self'", + "worker-src 'self'", + "manifest-src 'self'", + "object-src 'none'", + "base-uri 'none'", + "form-action 'self'", + "frame-ancestors 'none'", + ].join('; '), + 'Referrer-Policy': 'no-referrer', + 'X-Content-Type-Options': 'nosniff', + 'X-Frame-Options': 'DENY', + 'Permissions-Policy': 'camera=(self), geolocation=(), microphone=()', + 'Cross-Origin-Opener-Policy': 'same-origin', +}; + +const MIME: Record = { + '.html': 'text/html; charset=utf-8', + '.js': 'text/javascript; charset=utf-8', + '.css': 'text/css; charset=utf-8', + '.json': 'application/json', + '.webmanifest': 'application/manifest+json', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.woff2': 'font/woff2', + '.txt': 'text/plain; charset=utf-8', +}; + +function send(res: ServerResponse, status: number, body: unknown, headers: Record = {}): void { + const json = JSON.stringify(body); + res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...headers }); + res.end(json); +} + +async function readBody(req: IncomingMessage, limit: number): Promise { + const declared = Number(req.headers['content-length'] ?? 0); + if (declared > limit) throw new HttpError(413, 'too large'); + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + size += (chunk as Buffer).length; + if (size > limit) throw new HttpError(413, 'too large'); + chunks.push(chunk as Buffer); + } + return Buffer.concat(chunks); +} + +async function readJson(req: IncomingMessage, limit: number): Promise { + if (!String(req.headers['content-type'] ?? '').startsWith('application/json')) throw new HttpError(415, 'expected JSON'); + try { + return JSON.parse((await readBody(req, limit)).toString('utf8')); + } catch (e) { + if (e instanceof HttpError) throw e; + throw new HttpError(400, 'bad JSON'); + } +} + +const sha256hex = (s: string) => createHash('sha256').update(s).digest('hex'); + +/** Fixed-window rate limiter keyed by client IP. */ +class RateLimiter { + private hits = new Map(); + private readonly max: number; + private readonly windowMs: number; + constructor(max: number, windowMs: number) { + this.max = max; + this.windowMs = windowMs; + } + allow(key: string): boolean { + const now = Date.now(); + if (this.hits.size > 10_000) for (const [k, v] of this.hits) if (v.reset < now) this.hits.delete(k); + const h = this.hits.get(key); + if (!h || h.reset < now) { + this.hits.set(key, { n: 1, reset: now + this.windowMs }); + return true; + } + h.n += 1; + return h.n <= this.max; + } +} + +export function createApp(cfg: Config, store: Store) { + const streams = new Map>(); + const createLimiter = new RateLimiter(cfg.groupCreatePerHour, 3600_000); + const pushLimiter = new RateLimiter(60, 3600_000); + const vapid: Vapid | null = + cfg.vapidPublicKey && cfg.vapidPrivateKey && cfg.vapidSubject + ? { publicKey: cfg.vapidPublicKey, privateKey: cfg.vapidPrivateKey, subject: cfg.vapidSubject } + : null; + const blobDir = (g: string) => join(cfg.dataDir, 'blobs', g); + + function clientIp(req: IncomingMessage): string { + if (cfg.trustProxy) { + // Caddy appends the real client address as the last entry. + const xff = String(req.headers['x-forwarded-for'] ?? '').split(',').map((s) => s.trim()).filter(Boolean); + if (xff.length) return xff[xff.length - 1]; + } + return req.socket.remoteAddress ?? '?'; + } + + /** Check the bearer token for a group. Unknown group and wrong token both + * give 404, so the API doesn't reveal which group ids exist. */ + function authorize(req: IncomingMessage, groupId: string) { + if (!ID_RE.test(groupId)) throw new HttpError(404, 'not found'); + const g = store.getGroup(groupId); + const m = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(String(req.headers.authorization ?? '')); + const given = Buffer.from(sha256hex(m?.[1] ?? ''), 'hex'); + const expected = Buffer.from(g?.authHash ?? '0'.repeat(64), 'hex'); + if (!g || !m || !timingSafeEqual(given, expected)) throw new HttpError(404, 'not found'); + return g; + } + + function notify(groupId: string, seq: number, deviceId: string): void { + for (const res of streams.get(groupId) ?? []) res.write(`data: ${seq}\n\n`); + if (!vapid) return; + for (const sub of store.pushSubs(groupId)) { + if (sub.deviceId === deviceId) continue; + void sendPush(sub, { g: groupId }, vapid).then((r) => { + if (r === 'gone') store.deletePush(groupId, sub.endpoint); + }); + } + } + + // ---- route handlers -------------------------------------------------- + + async function createGroup(req: IncomingMessage, res: ServerResponse) { + if (!createLimiter.allow(clientIp(req))) throw new HttpError(429, 'too many groups created, try later'); + const body = await readJson(req, 1024); + if (!ID_RE.test(body?.id) || !HEX64_RE.test(body?.authHash)) throw new HttpError(400, 'bad group'); + if (!store.createGroup(body.id, body.authHash)) throw new HttpError(409, 'exists'); + send(res, 201, { id: body.id }); + } + + function getEvents(req: IncomingMessage, res: ServerResponse, groupId: string, url: URL) { + authorize(req, groupId); + const after = Math.max(0, Number(url.searchParams.get('after') ?? 0) || 0); + const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get('limit') ?? 500) || 500)); + send(res, 200, { events: store.eventsAfter(groupId, after, limit), latest: store.latestSeq(groupId) }); + } + + async function postEvents(req: IncomingMessage, res: ServerResponse, groupId: string) { + const g = authorize(req, groupId); + const body = await readJson(req, 200 * (cfg.maxEventBytes * 1.4 + 512)); + const events = body?.events; + if (!Array.isArray(events) || events.length === 0 || events.length > 200) throw new HttpError(400, 'events must be 1..200'); + let bytes = 0; + for (const e of events) { + if (!EVENT_ID_RE.test(e?.id) || !DEVICE_RE.test(e?.deviceId) || !B64U_RE.test(e?.iv) || !B64U_RE.test(e?.ct) || e.iv.length !== 16) + throw new HttpError(400, 'bad event'); + const size = Math.floor((e.ct.length * 3) / 4); + if (size > cfg.maxEventBytes) throw new HttpError(413, 'event too large'); + bytes += size; + } + if (g.bytes + bytes > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); + const seqs = store.tx(() => { + let next = store.latestSeq(groupId); + const out: number[] = []; + for (const e of events) { + const existing = store.seqOf(groupId, e.id); + if (existing !== undefined) { + out.push(existing); + continue; + } + next += 1; + store.insertEvent(groupId, next, { id: e.id, deviceId: e.deviceId, iv: e.iv, ct: e.ct }); + out.push(next); + } + store.addBytes(groupId, bytes); + return out; + }); + send(res, 200, { seqs }); + notify(groupId, Math.max(...seqs), events[0].deviceId); + } + + function stream(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-store', + Connection: 'keep-alive', + 'X-Accel-Buffering': 'no', + }); + res.write(`data: ${store.latestSeq(groupId)}\n\n`); + let set = streams.get(groupId); + if (!set) streams.set(groupId, (set = new Set())); + set.add(res); + const ping = setInterval(() => res.write(': ping\n\n'), 25_000); + req.on('close', () => { + clearInterval(ping); + set!.delete(res); + if (set!.size === 0) streams.delete(groupId); + }); + } + + async function putBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) { + const g = authorize(req, groupId); + if (!BLOB_ID_RE.test(blobId)) throw new HttpError(400, 'bad blob id'); + if (store.hasBlob(groupId, blobId)) return send(res, 200, { ok: true }); // immutable; retries are fine + const data = await readBody(req, cfg.maxPhotoBytes); + if (data.length === 0) throw new HttpError(400, 'empty'); + if (g.bytes + data.length > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); + mkdirSync(blobDir(groupId), { recursive: true }); + writeFileSync(join(blobDir(groupId), blobId), data, { flag: 'wx' }); + store.tx(() => { + store.insertBlob(groupId, blobId, data.length); + store.addBytes(groupId, data.length); + }); + send(res, 201, { ok: true }); + } + + function getBlob(req: IncomingMessage, res: ServerResponse, groupId: string, blobId: string) { + authorize(req, groupId); + if (!BLOB_ID_RE.test(blobId) || !store.hasBlob(groupId, blobId)) throw new HttpError(404, 'not found'); + const path = join(blobDir(groupId), blobId); + res.writeHead(200, { + 'Content-Type': 'application/octet-stream', + 'Content-Length': String(statSync(path).size), + 'Cache-Control': 'private, max-age=31536000, immutable', + }); + createReadStream(path).pipe(res); + } + + async function postPush(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + if (!vapid) throw new HttpError(501, 'push not configured'); + if (!pushLimiter.allow(clientIp(req))) throw new HttpError(429, 'slow down'); + const b = await readJson(req, 4096); + if (!isAllowedEndpoint(b?.endpoint) || b.endpoint.length > 1000) throw new HttpError(400, 'unsupported push service'); + if (!B64U_RE.test(b?.keys?.p256dh) || !B64U_RE.test(b?.keys?.auth) || !DEVICE_RE.test(b?.deviceId)) + throw new HttpError(400, 'bad subscription'); + store.upsertPush(groupId, { endpoint: b.endpoint, p256dh: b.keys.p256dh, auth: b.keys.auth, deviceId: b.deviceId }); + send(res, 200, { ok: true }); + } + + async function deletePush(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + const b = await readJson(req, 4096); + if (typeof b?.endpoint !== 'string') throw new HttpError(400, 'bad endpoint'); + store.deletePush(groupId, b.endpoint); + send(res, 200, { ok: true }); + } + + function deleteGroup(req: IncomingMessage, res: ServerResponse, groupId: string) { + authorize(req, groupId); + store.deleteGroup(groupId); + rmSync(blobDir(groupId), { recursive: true, force: true }); + for (const s of streams.get(groupId) ?? []) s.end(); + streams.delete(groupId); + send(res, 200, { ok: true }); + } + + function rates(res: ServerResponse, url: URL) { + const date = url.searchParams.get('date') ?? new Date().toISOString().slice(0, 10); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new HttpError(400, 'bad date'); + const r = store.ratesOn(date); + if (!r) throw new HttpError(404, 'no rates'); + // Past dates never change; today's may still be published later. + const final = r.date < date || date < new Date().toISOString().slice(0, 10); + send(res, 200, { base: 'EUR', ...r }, { 'Cache-Control': final ? 'public, max-age=86400' : 'public, max-age=900' }); + } + + function serveStatic(req: IncomingMessage, res: ServerResponse, url: URL) { + if (!cfg.staticDir) throw new HttpError(404, 'not found'); + let rel: string; + try { + rel = decodeURIComponent(url.pathname); + } catch { + throw new HttpError(400, 'bad path'); + } + let path = normalize(join(cfg.staticDir, rel)); + if (!path.startsWith(cfg.staticDir + sep) && path !== cfg.staticDir) throw new HttpError(404, 'not found'); + let isFile = existsSync(path) && statSync(path).isFile(); + if (!isFile) { + // SPA fallback for app routes; real missing assets stay 404. + if (extname(rel) !== '') throw new HttpError(404, 'not found'); + rel = '/index.html'; + path = join(cfg.staticDir, 'index.html'); + isFile = true; + } + const cache = rel.startsWith('/assets/') ? 'public, max-age=31536000, immutable' : 'no-cache'; + res.writeHead(200, { + 'Content-Type': MIME[extname(path)] ?? 'application/octet-stream', + 'Content-Length': String(statSync(path).size), + 'Cache-Control': cache, + ...(rel === '/sw.js' ? { 'Service-Worker-Allowed': '/' } : {}), + }); + if (req.method === 'HEAD') return res.end(); + createReadStream(path).pipe(res); + } + + // ---- router ---------------------------------------------------------- + + async function route(req: IncomingMessage, res: ServerResponse) { + const url = new URL(req.url ?? '/', 'http://x'); + const p = url.pathname; + const m = req.method ?? 'GET'; + if (!p.startsWith('/api/')) { + if (m !== 'GET' && m !== 'HEAD') throw new HttpError(405, 'method not allowed'); + return serveStatic(req, res, url); + } + if (p === '/api/health' && m === 'GET') return send(res, 200, { ok: true }); + if (p === '/api/config' && m === 'GET') + return send(res, 200, { vapidPublicKey: vapid?.publicKey ?? null, maxPhotoBytes: cfg.maxPhotoBytes, maxGroupBytes: cfg.maxGroupBytes }); + if (p === '/api/rates' && m === 'GET') return rates(res, url); + if (p === '/api/groups' && m === 'POST') return createGroup(req, res); + + const g = /^\/api\/groups\/([^/]+)(\/.*)?$/.exec(p); + if (g) { + const [, id, rest = ''] = g; + if (rest === '' && m === 'DELETE') return deleteGroup(req, res, id); + if (rest === '/events' && m === 'GET') return getEvents(req, res, id, url); + if (rest === '/events' && m === 'POST') return postEvents(req, res, id); + if (rest === '/stream' && m === 'GET') return stream(req, res, id); + if (rest === '/push' && m === 'POST') return postPush(req, res, id); + if (rest === '/push' && m === 'DELETE') return deletePush(req, res, id); + const b = /^\/blobs\/([^/]+)$/.exec(rest); + if (b && m === 'PUT') return putBlob(req, res, id, b[1]); + if (b && m === 'GET') return getBlob(req, res, id, b[1]); + } + throw new HttpError(404, 'not found'); + } + + return async function handler(req: IncomingMessage, res: ServerResponse) { + for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v); + try { + await route(req, res); + } catch (e) { + const status = e instanceof HttpError ? e.status : 500; + if (status === 500) console.error(`${req.method} ${new URL(req.url ?? '/', 'http://x').pathname}:`, e); + if (!res.headersSent) send(res, status, { error: e instanceof HttpError ? e.message : 'internal error' }); + else res.end(); + } + }; +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts new file mode 100644 index 0000000..c50144e --- /dev/null +++ b/apps/server/src/config.ts @@ -0,0 +1,47 @@ +// All configuration comes from environment variables (see deploy/.env.example). +import { resolve } from 'node:path'; + +function int(env: NodeJS.ProcessEnv, name: string, def: number): number { + const raw = env[name]; + if (raw === undefined || raw === '') return def; + const n = Number(raw); + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`${name} must be a non-negative integer, got "${raw}"`); + return n; +} + +export interface Config { + host: string; + port: number; + dataDir: string; + /** built web client; empty = API only (dev, where Vite serves the client) */ + staticDir: string; + trustProxy: boolean; + maxPhotoBytes: number; + maxEventBytes: number; + maxGroupBytes: number; + groupCreatePerHour: number; + vapidPublicKey: string; + vapidPrivateKey: string; + vapidSubject: string; + ratesEnabled: boolean; + ratesBaseUrl: string; +} + +export function loadConfig(env = process.env): Config { + return { + host: env.HOST || '127.0.0.1', + port: int(env, 'PORT', 8481), + dataDir: resolve(env.DATA_DIR || './data'), + staticDir: env.STATIC_DIR ? resolve(env.STATIC_DIR) : '', + trustProxy: env.TRUST_PROXY === '1', + maxPhotoBytes: int(env, 'MAX_PHOTO_BYTES', 2 * 1024 * 1024), + maxEventBytes: int(env, 'MAX_EVENT_BYTES', 64 * 1024), + maxGroupBytes: int(env, 'MAX_GROUP_BYTES', 200 * 1024 * 1024), + groupCreatePerHour: int(env, 'GROUP_CREATE_PER_HOUR', 10), + vapidPublicKey: env.VAPID_PUBLIC_KEY || '', + vapidPrivateKey: env.VAPID_PRIVATE_KEY || '', + vapidSubject: env.VAPID_SUBJECT || '', + ratesEnabled: env.RATES_DISABLED !== '1', + ratesBaseUrl: env.RATES_BASE_URL || 'https://www.ecb.europa.eu/stats/eurofxref', + }; +} diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts new file mode 100644 index 0000000..c550794 --- /dev/null +++ b/apps/server/src/db.ts @@ -0,0 +1,175 @@ +// SQLite storage. Everything group-related is ciphertext the server cannot +// read; the only plaintext is ids, sizes, timestamps and push endpoints. +import { DatabaseSync } from 'node:sqlite'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; + +export interface StoredEvent { + seq: number; + id: string; + deviceId: string; + iv: string; + ct: string; +} + +export interface PushSub { + endpoint: string; + p256dh: string; + auth: string; + deviceId: string; +} + +export class Store { + readonly db: DatabaseSync; + + constructor(dataDir: string) { + mkdirSync(dataDir, { recursive: true }); + this.db = new DatabaseSync(join(dataDir, 'oweme.sqlite')); + this.db.exec(` + PRAGMA journal_mode = WAL; + PRAGMA foreign_keys = ON; + CREATE TABLE IF NOT EXISTS groups ( + id TEXT PRIMARY KEY, + auth_hash TEXT NOT NULL, + bytes INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + CREATE TABLE IF NOT EXISTS events ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + id TEXT NOT NULL, + device_id TEXT NOT NULL, + iv TEXT NOT NULL, + ct TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, seq), + UNIQUE (group_id, id) + ); + CREATE TABLE IF NOT EXISTS blobs ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + id TEXT NOT NULL, + size INTEGER NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, id) + ); + CREATE TABLE IF NOT EXISTS push_subs ( + group_id TEXT NOT NULL REFERENCES groups(id) ON DELETE CASCADE, + endpoint TEXT NOT NULL, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + device_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (group_id, endpoint) + ); + CREATE TABLE IF NOT EXISTS rates ( + date TEXT PRIMARY KEY, + json TEXT NOT NULL + ); + `); + } + + tx(fn: () => T): T { + this.db.exec('BEGIN IMMEDIATE'); + try { + const r = fn(); + this.db.exec('COMMIT'); + return r; + } catch (e) { + this.db.exec('ROLLBACK'); + throw e; + } + } + + createGroup(id: string, authHash: string): boolean { + const r = this.db + .prepare('INSERT OR IGNORE INTO groups (id, auth_hash, created_at) VALUES (?, ?, ?)') + .run(id, authHash, Date.now()); + return r.changes === 1; + } + + getGroup(id: string): { authHash: string; bytes: number } | undefined { + const r = this.db.prepare('SELECT auth_hash, bytes FROM groups WHERE id = ?').get(id) as + | { auth_hash: string; bytes: number } + | undefined; + return r && { authHash: r.auth_hash, bytes: r.bytes }; + } + + deleteGroup(id: string): void { + this.db.prepare('DELETE FROM groups WHERE id = ?').run(id); + } + + addBytes(id: string, n: number): void { + this.db.prepare('UPDATE groups SET bytes = bytes + ? WHERE id = ?').run(n, id); + } + + latestSeq(groupId: string): number { + const r = this.db.prepare('SELECT MAX(seq) AS s FROM events WHERE group_id = ?').get(groupId) as { s: number | null }; + return r.s ?? 0; + } + + eventsAfter(groupId: string, after: number, limit: number): StoredEvent[] { + return this.db + .prepare('SELECT seq, id, device_id AS deviceId, iv, ct FROM events WHERE group_id = ? AND seq > ? ORDER BY seq LIMIT ?') + .all(groupId, after, limit) as unknown as StoredEvent[]; + } + + /** Existing seq for an event id (idempotent retries), if any. */ + seqOf(groupId: string, id: string): number | undefined { + const r = this.db.prepare('SELECT seq FROM events WHERE group_id = ? AND id = ?').get(groupId, id) as { seq: number } | undefined; + return r?.seq; + } + + insertEvent(groupId: string, seq: number, e: Omit): void { + this.db + .prepare('INSERT INTO events (group_id, seq, id, device_id, iv, ct, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)') + .run(groupId, seq, e.id, e.deviceId, e.iv, e.ct, Date.now()); + } + + hasBlob(groupId: string, id: string): boolean { + return !!this.db.prepare('SELECT 1 FROM blobs WHERE group_id = ? AND id = ?').get(groupId, id); + } + + insertBlob(groupId: string, id: string, size: number): void { + this.db.prepare('INSERT INTO blobs (group_id, id, size, created_at) VALUES (?, ?, ?, ?)').run(groupId, id, size, Date.now()); + } + + upsertPush(groupId: string, s: PushSub): void { + this.db + .prepare( + `INSERT INTO push_subs (group_id, endpoint, p256dh, auth, device_id, created_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (group_id, endpoint) DO UPDATE SET p256dh = excluded.p256dh, auth = excluded.auth, device_id = excluded.device_id`, + ) + .run(groupId, s.endpoint, s.p256dh, s.auth, s.deviceId, Date.now()); + } + + deletePush(groupId: string, endpoint: string): void { + this.db.prepare('DELETE FROM push_subs WHERE group_id = ? AND endpoint = ?').run(groupId, endpoint); + } + + deletePushEverywhere(endpoint: string): void { + this.db.prepare('DELETE FROM push_subs WHERE endpoint = ?').run(endpoint); + } + + pushSubs(groupId: string): PushSub[] { + return this.db + .prepare('SELECT endpoint, p256dh, auth, device_id AS deviceId FROM push_subs WHERE group_id = ?') + .all(groupId) as unknown as PushSub[]; + } + + saveRates(date: string, rates: Record): void { + this.db.prepare('INSERT OR REPLACE INTO rates (date, json) VALUES (?, ?)').run(date, JSON.stringify(rates)); + } + + /** Rates for the latest published date on or before `date`. */ + ratesOn(date: string): { date: string; rates: Record } | undefined { + const r = this.db.prepare('SELECT date, json FROM rates WHERE date <= ? ORDER BY date DESC LIMIT 1').get(date) as + | { date: string; json: string } + | undefined; + return r && { date: r.date, rates: JSON.parse(r.json) }; + } + + latestRatesDate(): string | undefined { + const r = this.db.prepare('SELECT MAX(date) AS d FROM rates').get() as { d: string | null }; + return r.d ?? undefined; + } +} diff --git a/apps/server/src/gen-vapid.ts b/apps/server/src/gen-vapid.ts new file mode 100644 index 0000000..091d1e7 --- /dev/null +++ b/apps/server/src/gen-vapid.ts @@ -0,0 +1,28 @@ +// Generate VAPID keys and write them into an env file without printing the +// private key: `node apps/server/src/gen-vapid.ts deploy/.env`. +// Existing VAPID_PUBLIC_KEY / VAPID_PRIVATE_KEY lines are kept unless +// --force is given (rotating keys invalidates every push subscription). +import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { generateVapidKeys } from './push.ts'; + +const file = process.argv[2]; +const force = process.argv.includes('--force'); +if (!file) { + console.error('usage: node gen-vapid.ts [--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 new file mode 100644 index 0000000..f06049e --- /dev/null +++ b/apps/server/src/main.ts @@ -0,0 +1,30 @@ +import { createServer } from 'node:http'; +import { createApp } from './app.ts'; +import { loadConfig } from './config.ts'; +import { Store } from './db.ts'; +import { RatesService } from './rates.ts'; + +const cfg = loadConfig(); +const store = new Store(cfg.dataDir); +const server = createServer(createApp(cfg, store)); +// SSE connections are long-lived; don't let the default timeouts cut them. +server.requestTimeout = 0; +server.headersTimeout = 30_000; + +const rates = new RatesService(store, cfg.ratesBaseUrl); +if (cfg.ratesEnabled) rates.start(); + +server.listen(cfg.port, cfg.host, () => { + console.log(`oweme server on http://${cfg.host}:${cfg.port}` + (cfg.staticDir ? ` serving ${cfg.staticDir}` : ' (API only)')); + if (!cfg.vapidPublicKey) console.log('push notifications disabled: VAPID_* not set'); +}); + +for (const sig of ['SIGINT', 'SIGTERM'] as const) { + process.on(sig, () => { + rates.stop(); + server.close(); + server.closeAllConnections(); + store.db.close(); + process.exit(0); + }); +} diff --git a/apps/server/src/push.ts b/apps/server/src/push.ts new file mode 100644 index 0000000..c37b77f --- /dev/null +++ b/apps/server/src/push.ts @@ -0,0 +1,105 @@ +// Web Push sender: VAPID (RFC 8292) + aes128gcm payload encryption +// (RFC 8291), using only node:crypto. The payload is just { g: groupId }; +// the service worker fetches and decrypts the actual events itself, so the +// push service never sees content (SPEC.md §7.7). +import { createCipheriv, createECDH, createPrivateKey, hkdfSync, randomBytes, sign } from 'node:crypto'; +import type { PushSub } from './db.ts'; + +const b64u = (b: Buffer | Uint8Array) => Buffer.from(b).toString('base64url'); +const fromB64u = (s: string) => Buffer.from(s, 'base64url'); + +/** Push services we deliver to. Anything else is refused, so a registered + * "endpoint" can't make the server send requests to arbitrary hosts. */ +const ALLOWED_PUSH_HOSTS = [ + 'fcm.googleapis.com', + 'updates.push.services.mozilla.com', + 'push.services.mozilla.com', + 'web.push.apple.com', + 'notify.windows.com', +]; + +export function isAllowedEndpoint(endpoint: string): boolean { + let u: URL; + try { + u = new URL(endpoint); + } catch { + return false; + } + if (u.protocol !== 'https:' || u.port !== '') return false; + return ALLOWED_PUSH_HOSTS.some((h) => u.hostname === h || u.hostname.endsWith(`.${h}`)); +} + +export function generateVapidKeys(): { publicKey: string; privateKey: string } { + const ecdh = createECDH('prime256v1'); + ecdh.generateKeys(); + return { publicKey: b64u(ecdh.getPublicKey()), privateKey: b64u(ecdh.getPrivateKey()) }; +} + +export interface Vapid { + publicKey: string; + privateKey: string; + subject: string; +} + +function vapidAuthHeader(endpoint: string, v: Vapid): string { + const pub = fromB64u(v.publicKey); + const key = createPrivateKey({ + key: { kty: 'EC', crv: 'P-256', d: v.privateKey, x: b64u(pub.subarray(1, 33)), y: b64u(pub.subarray(33, 65)) }, + format: 'jwk', + }); + const header = b64u(Buffer.from(JSON.stringify({ typ: 'JWT', alg: 'ES256' }))); + const claims = b64u( + Buffer.from(JSON.stringify({ aud: new URL(endpoint).origin, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: v.subject })), + ); + const sig = sign('sha256', Buffer.from(`${header}.${claims}`), { key, dsaEncoding: 'ieee-p1363' }); + return `vapid t=${header}.${claims}.${b64u(sig)}, k=${v.publicKey}`; +} + +/** RFC 8291 aes128gcm encryption of `plaintext` for one subscription. */ +export function encryptPayload(sub: Pick, plaintext: Buffer): Buffer { + const uaPublic = fromB64u(sub.p256dh); + const authSecret = fromB64u(sub.auth); + const ecdh = createECDH('prime256v1'); + const asPublic = ecdh.generateKeys(); + const shared = ecdh.computeSecret(uaPublic); + const keyInfo = Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]); + const ikm = Buffer.from(hkdfSync('sha256', shared, authSecret, keyInfo, 32)); + const salt = randomBytes(16); + const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16)); + const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12)); + const cipher = createCipheriv('aes-128-gcm', cek, nonce); + // 0x02 = padding delimiter for the last (only) record. + const body = Buffer.concat([cipher.update(Buffer.concat([plaintext, Buffer.from([2])])), cipher.final(), cipher.getAuthTag()]); + const rs = Buffer.alloc(4); + rs.writeUInt32BE(4096); + return Buffer.concat([salt, rs, Buffer.from([asPublic.length]), asPublic, body]); +} + +/** Send one push. Returns 'gone' if the subscription should be deleted. */ +export async function sendPush(sub: PushSub, payload: object, v: Vapid): Promise<'ok' | 'gone' | 'error'> { + if (!isAllowedEndpoint(sub.endpoint)) return 'gone'; + try { + const res = await fetch(sub.endpoint, { + method: 'POST', + headers: { + Authorization: vapidAuthHeader(sub.endpoint, v), + 'Content-Encoding': 'aes128gcm', + 'Content-Type': 'application/octet-stream', + TTL: String(24 * 3600), + Urgency: 'normal', + }, + body: encryptPayload(sub, Buffer.from(JSON.stringify(payload))), + redirect: 'error', + signal: AbortSignal.timeout(15_000), + }); + if (res.status === 404 || res.status === 410) return 'gone'; + if (!res.ok) { + console.error(`push: ${new URL(sub.endpoint).hostname} HTTP ${res.status}`); + return 'error'; + } + return 'ok'; + } catch (e) { + console.error(`push: ${(e as Error).message}`); + return 'error'; + } +} diff --git a/apps/server/src/rates.ts b/apps/server/src/rates.ts new file mode 100644 index 0000000..e0bc450 --- /dev/null +++ b/apps/server/src/rates.ts @@ -0,0 +1,52 @@ +// ECB daily reference rates (EUR-based). Fetched by the server so that +// clients never contact a third party (SPEC.md §8.2). +import type { Store } from './db.ts'; + +/** Parse the ECB eurofxref XML into date → { currency: rate }. EUR = "1". */ +export function parseEcbXml(xml: string): Map> { + const out = new Map>(); + const dayRe = /([\s\S]*?)<\/Cube>/g; + const rateRe = //g; + for (const day of xml.matchAll(dayRe)) { + const rates: Record = { EUR: '1' }; + for (const r of day[2].matchAll(rateRe)) rates[r[1]] = r[2]; + out.set(day[1], rates); + } + return out; +} + +export class RatesService { + private timer: NodeJS.Timeout | undefined; + private readonly store: Store; + private readonly baseUrl: string; + + constructor(store: Store, baseUrl: string) { + this.store = store; + this.baseUrl = baseUrl; + } + + async refresh(): Promise { + // Full history the first time (≈8 MB), the last 90 days afterwards. + const file = this.store.latestRatesDate() ? 'eurofxref-hist-90d.xml' : 'eurofxref-hist.xml'; + const res = await fetch(`${this.baseUrl}/${file}`, { signal: AbortSignal.timeout(60_000) }); + if (!res.ok) throw new Error(`ECB ${file}: HTTP ${res.status}`); + const days = parseEcbXml(await res.text()); + if (days.size === 0) throw new Error(`ECB ${file}: no rates parsed`); + this.store.tx(() => { + for (const [date, rates] of days) this.store.saveRates(date, rates); + }); + console.log(`rates: stored ${days.size} days from ${file}, latest ${this.store.latestRatesDate()}`); + } + + /** Refresh now and then every 6 hours (ECB publishes once a day ~16:00 CET). */ + start(): void { + const run = () => this.refresh().catch((e) => console.error(`rates: ${e.message}`)); + void run(); + this.timer = setInterval(run, 6 * 3600_000); + this.timer.unref(); + } + + stop(): void { + clearInterval(this.timer); + } +} diff --git a/apps/server/test/server.test.ts b/apps/server/test/server.test.ts new file mode 100644 index 0000000..e8bfe0c --- /dev/null +++ b/apps/server/test/server.test.ts @@ -0,0 +1,186 @@ +import assert from 'node:assert/strict'; +import { createDecipheriv, createECDH, createHash, hkdfSync, randomBytes } from 'node:crypto'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { createApp } from '../src/app.ts'; +import { loadConfig } from '../src/config.ts'; +import { Store } from '../src/db.ts'; +import { encryptPayload, isAllowedEndpoint } from '../src/push.ts'; +import { parseEcbXml } from '../src/rates.ts'; + +const b64u = (b: Buffer) => b.toString('base64url'); +const newGroup = () => { + const id = b64u(randomBytes(16)); + const token = b64u(randomBytes(32)); + return { id, token, authHash: createHash('sha256').update(token).digest('hex') }; +}; + +let server: Server; +let base: string; +let dir: string; +let store: Store; + +before(async () => { + dir = mkdtempSync(join(tmpdir(), 'oweme-test-')); + const web = join(dir, 'web'); + mkdirSync(join(web, 'assets'), { recursive: true }); + writeFileSync(join(web, 'index.html'), 'OweMe'); + writeFileSync(join(web, 'assets', 'app-abc.js'), 'console.log(1)'); + const cfg = loadConfig({ + DATA_DIR: join(dir, 'data'), STATIC_DIR: web, MAX_PHOTO_BYTES: '1000', MAX_EVENT_BYTES: '300', + MAX_GROUP_BYTES: '5000', GROUP_CREATE_PER_HOUR: '50', + }); + store = new Store(cfg.dataDir); + store.saveRates('2026-10-08', { EUR: '1', CZK: '24.4', USD: '1.12' }); + server = createServer(createApp(cfg, store)); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const addr = server.address() as { port: number }; + base = `http://127.0.0.1:${addr.port}`; +}); + +after(() => { + server.closeAllConnections(); + server.close(); + store.db.close(); + rmSync(dir, { recursive: true, force: true }); +}); + +async function api(method: string, path: string, opts: { token?: string; json?: unknown; body?: Buffer } = {}) { + const headers: Record = {}; + if (opts.token) headers.Authorization = `Bearer ${opts.token}`; + if (opts.json !== undefined) headers['Content-Type'] = 'application/json'; + const res = await fetch(base + path, { method, headers, body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body }); + const text = await res.text(); + let data: any = text; + try { data = JSON.parse(text); } catch { /* not JSON */ } + return { status: res.status, data, headers: res.headers }; +} + +const event = (id: string, size = 20) => ({ id, deviceId: 'device-123', iv: b64u(randomBytes(12)), ct: b64u(randomBytes(size)) }); + +describe('groups and events', () => { + it('creates a group, rejects duplicates and bad input', async () => { + const g = newGroup(); + assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 201); + assert.equal((await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } })).status, 409); + assert.equal((await api('POST', '/api/groups', { json: { id: 'short', authHash: g.authHash } })).status, 400); + }); + + it('requires the right token, answering 404 either way', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + assert.equal((await api('GET', `/api/groups/${g.id}/events`)).status, 404); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: newGroup().token })).status, 404); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 200); + }); + + it('appends idempotently and pages by seq', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const r1 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-aaaa'), event('evt-bbbb')] } }); + assert.deepEqual(r1.data.seqs, [1, 2]); + const r2 = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-bbbb'), event('evt-cccc')] } }); + assert.deepEqual(r2.data.seqs, [2, 3]); + const r3 = await api('GET', `/api/groups/${g.id}/events?after=1`, { token: g.token }); + assert.deepEqual(r3.data.events.map((e: any) => e.id), ['evt-bbbb', 'evt-cccc']); + assert.equal(r3.data.latest, 3); + }); + + it('enforces event and group size limits', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + assert.equal((await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-big1', 400)] } })).status, 413); + for (let i = 0; i < 17; i++) await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event(`evt-fill${i}`, 290)] } }); + const r = await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-over', 290)] } }); + assert.equal(r.status, 507); + }); + + it('streams new seqs over SSE', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const ac = new AbortController(); + const res = await fetch(`${base}/api/groups/${g.id}/stream`, { headers: { Authorization: `Bearer ${g.token}` }, signal: ac.signal }); + const reader = res.body!.getReader(); + const first = new TextDecoder().decode((await reader.read()).value); + assert.match(first, /data: 0/); + await api('POST', `/api/groups/${g.id}/events`, { token: g.token, json: { events: [event('evt-live')] } }); + const next = new TextDecoder().decode((await reader.read()).value); + assert.match(next, /data: 1/); + ac.abort(); + }); + + it('stores immutable blobs with a size cap, and deletes everything with the group', async () => { + const g = newGroup(); + await api('POST', '/api/groups', { json: { id: g.id, authHash: g.authHash } }); + const blob = randomBytes(500); + assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { token: g.token, body: blob })).status, 201); + assert.equal((await api('PUT', `/api/groups/${g.id}/blobs/blob-0123456789abcdee`, { token: g.token, body: randomBytes(1001) })).status, 413); + const res = await fetch(`${base}/api/groups/${g.id}/blobs/blob-0123456789abcdef`, { headers: { Authorization: `Bearer ${g.token}` } }); + assert.deepEqual(Buffer.from(await res.arrayBuffer()), blob); + assert.equal((await api('DELETE', `/api/groups/${g.id}`, { token: g.token })).status, 200); + assert.equal((await api('GET', `/api/groups/${g.id}/events`, { token: g.token })).status, 404); + }); + + it('refuses push endpoints outside known push services', async () => { + assert.equal(isAllowedEndpoint('https://fcm.googleapis.com/fcm/send/abc'), true); + assert.equal(isAllowedEndpoint('https://web.push.apple.com/xyz'), true); + assert.equal(isAllowedEndpoint('https://169.254.169.254/latest'), false); + assert.equal(isAllowedEndpoint('http://fcm.googleapis.com/x'), false); + assert.equal(isAllowedEndpoint('https://fcm.googleapis.com.evil.example/x'), false); + }); +}); + +describe('rates and static', () => { + it('returns the latest rates on or before a date', async () => { + const r = await api('GET', '/api/rates?date=2026-10-11'); + assert.equal(r.status, 200); + assert.equal(r.data.date, '2026-10-08'); + assert.equal(r.data.rates.CZK, '24.4'); + assert.equal((await api('GET', '/api/rates?date=2020-01-01')).status, 404); + }); + + it('parses ECB XML', () => { + const xml = ''; + assert.deepEqual(parseEcbXml(xml).get('2026-10-09'), { EUR: '1', USD: '1.1206', CZK: '24.369' }); + }); + + it('serves the SPA with security headers and blocks traversal', async () => { + const r = await api('GET', '/g/abc'); + assert.equal(r.status, 200); + assert.match(r.data, /OweMe/); + assert.match(r.headers.get('content-security-policy')!, /default-src 'self'/); + assert.equal(r.headers.get('referrer-policy'), 'no-referrer'); + assert.equal((await api('GET', '/assets/app-abc.js')).headers.get('cache-control'), 'public, max-age=31536000, immutable'); + assert.equal((await api('GET', '/assets/missing.js')).status, 404); + assert.equal((await api('GET', '/assets/..%2f..%2f..%2f..%2fetc%2fpasswd')).status, 404); + const dots = await api('GET', '/%2e%2e/%2e%2e/etc/passwd'); // URL parser collapses these → SPA fallback + assert.match(dots.data, /OweMe/); + }); +}); + +describe('web push encryption', () => { + it('produces an RFC 8291 payload the browser side can decrypt', () => { + // Play the browser: generate a subscription key pair and auth secret. + const ua = createECDH('prime256v1'); + const uaPublic = ua.generateKeys(); + const auth = randomBytes(16); + const body = encryptPayload({ p256dh: b64u(uaPublic), auth: b64u(auth) }, Buffer.from('{"g":"x"}')); + + const salt = body.subarray(0, 16); + const idlen = body[20]; + const asPublic = body.subarray(21, 21 + idlen); + const ct = body.subarray(21 + idlen); + const shared = ua.computeSecret(asPublic); + const ikm = Buffer.from(hkdfSync('sha256', shared, auth, Buffer.concat([Buffer.from('WebPush: info\0'), uaPublic, asPublic]), 32)); + const cek = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: aes128gcm\0'), 16)); + const nonce = Buffer.from(hkdfSync('sha256', ikm, salt, Buffer.from('Content-Encoding: nonce\0'), 12)); + const d = createDecipheriv('aes-128-gcm', cek, nonce); + d.setAuthTag(ct.subarray(ct.length - 16)); + const plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]); + assert.equal(plain.subarray(0, -1).toString(), '{"g":"x"}'); + assert.equal(plain[plain.length - 1], 2); + }); +}); diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json new file mode 100644 index 0000000..20153cf --- /dev/null +++ b/apps/server/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2023", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "lib": ["ES2023"], + "types": ["node"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + "skipLibCheck": true + }, + "include": ["src", "test"] +} diff --git a/package.json b/package.json index 0a43455..4975d5b 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "build": "npm run build -w apps/web", "test": "npm run test:core && npm run test:server", "test:core": "vitest run --root packages/core", - "test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/", + "test:server": "node --test --disable-warning=ExperimentalWarning apps/server/test/*.test.ts", "test:e2e": "playwright test", "check": "tsc -p packages/core && tsc -p apps/server && npm run check -w apps/web" }, From f67add3660256da74b66cbf18fec5eed6e6e8f50 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:59:16 +0000 Subject: [PATCH 03/18] Server: count only newly stored events toward the group quota Re-uploading existing events (retries, backup restore) is idempotent and must not eat into MAX_GROUP_BYTES. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- apps/server/src/app.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index d58137d..428be2c 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -174,17 +174,18 @@ export function createApp(cfg: Config, store: Store) { const body = await readJson(req, 200 * (cfg.maxEventBytes * 1.4 + 512)); const events = body?.events; if (!Array.isArray(events) || events.length === 0 || events.length > 200) throw new HttpError(400, 'events must be 1..200'); - let bytes = 0; + let incoming = 0; for (const e of events) { if (!EVENT_ID_RE.test(e?.id) || !DEVICE_RE.test(e?.deviceId) || !B64U_RE.test(e?.iv) || !B64U_RE.test(e?.ct) || e.iv.length !== 16) throw new HttpError(400, 'bad event'); const size = Math.floor((e.ct.length * 3) / 4); if (size > cfg.maxEventBytes) throw new HttpError(413, 'event too large'); - bytes += size; + incoming += size; } - if (g.bytes + bytes > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); + if (g.bytes + incoming > cfg.maxGroupBytes) throw new HttpError(507, 'group storage full'); const seqs = store.tx(() => { let next = store.latestSeq(groupId); + let bytes = 0; const out: number[] = []; for (const e of events) { const existing = store.seqOf(groupId, e.id); @@ -194,6 +195,7 @@ export function createApp(cfg: Config, store: Store) { } next += 1; store.insertEvent(groupId, next, { id: e.id, deviceId: e.deviceId, iv: e.iv, ct: e.ct }); + bytes += Math.floor((e.ct.length * 3) / 4); out.push(next); } store.addBytes(groupId, bytes); From 8fbbb4933eb0415df8c39cc2ff79ee58a3bd884d Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:59:16 +0000 Subject: [PATCH 04/18] Add Svelte web client and service worker Mobile-first PWA: groups via key-in-fragment links, encrypted outbox and sync over SSE, all split modes, currencies with ECB rate prefill, photos, comments, history and rewind, stats, recurring expenses, CSV and backup, EN/CS, dark/light theme, Web Push decrypted in the service worker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- apps/web/index.html | 18 + apps/web/package.json | 21 + apps/web/public/badge-96.png | Bin 0 -> 2493 bytes apps/web/public/icon-192.png | Bin 0 -> 8354 bytes apps/web/public/icon-512.png | Bin 0 -> 23806 bytes apps/web/public/icon-maskable-512.png | Bin 0 -> 16078 bytes apps/web/public/icon.svg | 5 + apps/web/public/manifest.webmanifest | 16 + apps/web/public/robots.txt | 2 + apps/web/src/App.svelte | 61 +++ apps/web/src/app.css | 241 ++++++++++ apps/web/src/components/Activity.svelte | 100 ++++ apps/web/src/components/AppSettings.svelte | 32 ++ apps/web/src/components/Avatar.svelte | 12 + apps/web/src/components/Balances.svelte | 92 ++++ apps/web/src/components/CurrencySelect.svelte | 37 ++ apps/web/src/components/ExpenseDetail.svelte | 161 +++++++ apps/web/src/components/ExpenseEditor.svelte | 422 +++++++++++++++++ apps/web/src/components/ExpenseList.svelte | 103 ++++ apps/web/src/components/GroupPage.svelte | 132 ++++++ apps/web/src/components/GroupSettings.svelte | 257 ++++++++++ apps/web/src/components/Home.svelte | 95 ++++ apps/web/src/components/Icon.svelte | 29 ++ apps/web/src/components/IdentityPicker.svelte | 50 ++ apps/web/src/components/NewGroup.svelte | 105 +++++ apps/web/src/components/PhotoView.svelte | 50 ++ apps/web/src/components/Restore.svelte | 40 ++ apps/web/src/components/Sheet.svelte | 32 ++ apps/web/src/components/Stats.svelte | 143 ++++++ apps/web/src/lib/api.ts | 90 ++++ apps/web/src/lib/backup.ts | 84 ++++ apps/web/src/lib/crypto.ts | 77 +++ apps/web/src/lib/events.ts | 17 + apps/web/src/lib/format.ts | 87 ++++ apps/web/src/lib/i18n.ts | 25 + apps/web/src/lib/idb.ts | 150 ++++++ apps/web/src/lib/locales/cs.ts | 253 ++++++++++ apps/web/src/lib/locales/en.ts | 270 +++++++++++ apps/web/src/lib/photo.ts | 49 ++ apps/web/src/lib/push.ts | 52 ++ apps/web/src/lib/rates.ts | 68 +++ apps/web/src/lib/router.svelte.ts | 66 +++ apps/web/src/lib/session.svelte.ts | 296 ++++++++++++ apps/web/src/lib/settings.svelte.ts | 58 +++ apps/web/src/lib/ui.svelte.ts | 14 + apps/web/src/main.ts | 25 + apps/web/src/sw.ts | 117 +++++ apps/web/svelte.config.js | 1 + apps/web/tsconfig.json | 16 + apps/web/vite.config.ts | 15 + apps/web/vite.sw.config.ts | 35 ++ package-lock.json | 445 ++++++++++++++++-- scripts/render-icons.mjs | 29 ++ 53 files changed, 4558 insertions(+), 37 deletions(-) create mode 100644 apps/web/index.html create mode 100644 apps/web/package.json create mode 100644 apps/web/public/badge-96.png create mode 100644 apps/web/public/icon-192.png create mode 100644 apps/web/public/icon-512.png create mode 100644 apps/web/public/icon-maskable-512.png create mode 100644 apps/web/public/icon.svg create mode 100644 apps/web/public/manifest.webmanifest create mode 100644 apps/web/public/robots.txt create mode 100644 apps/web/src/App.svelte create mode 100644 apps/web/src/app.css create mode 100644 apps/web/src/components/Activity.svelte create mode 100644 apps/web/src/components/AppSettings.svelte create mode 100644 apps/web/src/components/Avatar.svelte create mode 100644 apps/web/src/components/Balances.svelte create mode 100644 apps/web/src/components/CurrencySelect.svelte create mode 100644 apps/web/src/components/ExpenseDetail.svelte create mode 100644 apps/web/src/components/ExpenseEditor.svelte create mode 100644 apps/web/src/components/ExpenseList.svelte create mode 100644 apps/web/src/components/GroupPage.svelte create mode 100644 apps/web/src/components/GroupSettings.svelte create mode 100644 apps/web/src/components/Home.svelte create mode 100644 apps/web/src/components/Icon.svelte create mode 100644 apps/web/src/components/IdentityPicker.svelte create mode 100644 apps/web/src/components/NewGroup.svelte create mode 100644 apps/web/src/components/PhotoView.svelte create mode 100644 apps/web/src/components/Restore.svelte create mode 100644 apps/web/src/components/Sheet.svelte create mode 100644 apps/web/src/components/Stats.svelte create mode 100644 apps/web/src/lib/api.ts create mode 100644 apps/web/src/lib/backup.ts create mode 100644 apps/web/src/lib/crypto.ts create mode 100644 apps/web/src/lib/events.ts create mode 100644 apps/web/src/lib/format.ts create mode 100644 apps/web/src/lib/i18n.ts create mode 100644 apps/web/src/lib/idb.ts create mode 100644 apps/web/src/lib/locales/cs.ts create mode 100644 apps/web/src/lib/locales/en.ts create mode 100644 apps/web/src/lib/photo.ts create mode 100644 apps/web/src/lib/push.ts create mode 100644 apps/web/src/lib/rates.ts create mode 100644 apps/web/src/lib/router.svelte.ts create mode 100644 apps/web/src/lib/session.svelte.ts create mode 100644 apps/web/src/lib/settings.svelte.ts create mode 100644 apps/web/src/lib/ui.svelte.ts create mode 100644 apps/web/src/main.ts create mode 100644 apps/web/src/sw.ts create mode 100644 apps/web/svelte.config.js create mode 100644 apps/web/tsconfig.json create mode 100644 apps/web/vite.config.ts create mode 100644 apps/web/vite.sw.config.ts create mode 100644 scripts/render-icons.mjs diff --git a/apps/web/index.html b/apps/web/index.html new file mode 100644 index 0000000..79f2dd9 --- /dev/null +++ b/apps/web/index.html @@ -0,0 +1,18 @@ + + + + + + + + + OweMe + + + + + +
+ + + diff --git a/apps/web/package.json b/apps/web/package.json new file mode 100644 index 0000000..9a01338 --- /dev/null +++ b/apps/web/package.json @@ -0,0 +1,21 @@ +{ + "name": "@oweme/web", + "private": true, + "type": "module", + "scripts": { + "dev": "vite", + "build": "vite build && vite build -c vite.sw.config.ts", + "preview": "vite preview", + "check": "svelte-check --tsconfig ./tsconfig.json --fail-on-warnings" + }, + "dependencies": { + "@oweme/core": "*", + "uqr": "0.1.3" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "7.3.1", + "svelte": "5.57.1", + "svelte-check": "4.7.6", + "vite": "8.3.1" + } +} diff --git a/apps/web/public/badge-96.png b/apps/web/public/badge-96.png new file mode 100644 index 0000000000000000000000000000000000000000..47803b8a259295446c18a83caaea5f7f03a79b12 GIT binary patch literal 2493 zcmeAS@N?(olHy`uVBq!ia0y~yU`POA4mJh`hDS5XEf^R$i#%N%Ln`LHnZv$D)K#SI z{AQJD9irTVuCAS3u^U|krNu-xn1`5TDP^s>v8Z!za%aTigKS(JO)L|Y6qwAGcuY)i zUSiJ8;llE#{{5bg-{{}kYOGt+Xo*UQa3%WF?!GW3U(gLzq@NQYZBw6Un^d`f7lbC`um=`?we&C_lix|znr(%udUoqM; zC;w4kT`0ijaB#EcPWfFyoASlNo%BCf8XRHz*b~mY;DPz^hh;C)GKx=5UwUD(2+zmm z6^CXs2K-=u@PTnl_t9MM1vf9qEWY`yhI#Sao^2DJoN4fD7gXzF-y^}$TCc_zyUnBzn?O|Ku$#el30tWorsf7rjV2@_*kGpLc8y4{iFKk8@2gZI*Ly^bs&W zZ^O|Zy|7y==2ZGUJ3-dQ$)Bi_p_GvWF-))y0urt`L*bCRl? zE_322!-*f)EH(s4ACEEOe%0Z#U-{>f=Rz_O!jESyd%xiD#Ch?m$wuZ3MyKbv#oOZ^UPG@Rbk6s2%)zpC>m1BUo*g}M3uZ8y_| z3iEoHXLsD1{=+Ck`^e@?O0#asv)?y=ek|sb*`qx!Mk<#NTBJ!{ipgp zduMO04wyZ&IPAkspXMpElzYog9QK{0I8%~=GriG9O!y9`X8xjjDX1-S*Dms;H6&W(PyNi;zIh3FA`pEr-v zBY6^TO?hxM!1>5dADPLaygQt~9QrSol^y&;W5($PGk<)x)Qta;BK(3WL*v~`#u>jDvsll#to+dV-@ZzYGK=j6BkH*>0U#+ z*`Y+8Eu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o`2~vwzh|ACuxFdrgCiE3E&CyT|n4=b6{Nmzrz|Jm=fG z^=pp}*Ze2ja+jVI*q^j}+Rh$sV~ge1*WTnjVmacvxR~i_sb>6-KZo+>g+COImo_UD zRoc$I`U~@eb*hJZ+ZH7V`7+O1Us$FYEn&K@fP43>J8Pe2o|K#)J#B8&;p(LA;V~tr zjr6LQ3TAKDT77rhnY7bJ$4>rjZ0lgJ$-i~{&@Okc-KtS%=U6tJUjE`tsXW*HmC{Rj zU2kribZ+~1&yy>&oKK3GndduwU-TfoBfV=|q4w>pZ$U4j-dW|o2`$|8FYj@D6i3&t zQp3LmenyYNv!dRom1W=DR($s6f>}&CSEQCsVCzWwQxjqR%KI+wp3ZHR=I!dsybeaH z^K7u2e7iluL7iax1*2*6hna!l|Nqy8dM*qM3~Zp*7c;|4v1{2JdlJGK7#J8lUHx3v IIVCg!0G~^XdH?_b literal 0 HcmV?d00001 diff --git a/apps/web/public/icon-192.png b/apps/web/public/icon-192.png new file mode 100644 index 0000000000000000000000000000000000000000..8d9368b3dd08865c95dc5ca8b0404ba9ada1a793 GIT binary patch literal 8354 zcmeAS@N?(olHy`uVBq!ia0y~yU^oE69Bd2>3_*8t*cliE7(87ZLn`LHnaepNs%u{t(!NSR78X(cW?r_yKjvqbHrigD*GiRm*>w#+!=GwEWW zdiO~c#=>}Ea}ie&6PKlp%Q9co-oL);-MXh|ZTT;tFrbw|?KNr&G;B zzwfDj7y0iv8}oyRAgk+AJbEed&m1;A(K>JBXQORDxmeYsQ(y+0W8D`dYT)*B+>OPBU|y^vqeH{=_H2$U~Dky!t*rdUiFYqt1vu=Q)^@U$8P{kr{9JkQ)UNF}`kO8=zU58GES#mC zu=6U@&-XXx+A%X7{8Dnt@u#?)<_Gx|Id7WVGSV4-{#yH0-(PRGq=NWn5oS3&5FwEY)=m%Tb_WhH0T2=~h9BSF=zV?j7yN@B){?Dp??atD< zgwbQ&r%7kUxc^P9wG?M^JTkGLE%naBwQH*9>~m!4=wUo_+N;c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31vq%RbRM(%r@j^4bA9zi=ZUuW{$(Fo7?BWh<5tME6bg-@FxK z`$$bkS0UZ?rD+a#*utpt(RZB=5Ct+XEe|0(7-K0lXUtwPcBbM zFXduMcWk?JYSG;AYHjIzjuI{|yncbxH%G@MxNYEJYCN{#=zqJKgQrCUw;Kf3v&~?M z|9)VD{^tLQyH)qj{abl@hN6nILWhCQL09g7W&R7^iN#-aa9Jg+w4Qy|{P#sm)$g3y zl(v22`%Q`hE&k;O8u?$p{r;D}>k`}64E2uP2G%EYy?D^C(haVTs$C@xyVfTz|I9rJT`fTM=In` zh;-_eougc&AU=cn*{vTclKE^)9~5u$ud3RzY8_+X0SRYAJKo*Jdp0m^TKcQwyb%Kf zgFR?nzy+?A4%-$8YzjG07kpw;&YS0NsyQ_UX0S^(zcJ2EIk`&hTdcCmPEW2yh73DB z-47QaDi6TAA1G{hX4PIx3WHCU|?Va8O6-ta9Ln}$7z*)3=9kmp00i_>zopr E0Ig5^3jhEB literal 0 HcmV?d00001 diff --git a/apps/web/public/icon-512.png b/apps/web/public/icon-512.png new file mode 100644 index 0000000000000000000000000000000000000000..04e21fbe5e41c587d979193bdb53870192e75835 GIT binary patch literal 23806 zcmeAS@N?(olHy`uVBq!ia0y~yU}6Aa4mJh`hA$OYelaizFnGE+hE&XXbC`W%K{P-~J}b?AVFj#q%o9TfQ%B)H!IM?3H=v^}MAo zcU3HqkTPPlUEt__{iw6>`uo+>?D;Zg&Ew0ssi0&u_1^N=wVE?OR+%bJ>DCKc8K*s$|F4NUJ%Uk0{uA*PN92vM_U} zf|3{Ou6xRd8!9&XwX~P=>Bfn7XS_c2T58+L`K+1;876oHcXMCbv+wAv!-Ya7e?2}< zo%yKGj@QLy3wxlUMBBQnof9*6%Ju6P9@%ITas39H7YAFzNfq{*{qIA3%jamEich+5 zJ*}amL(T8{_3o^LLTpVZk24e)SUeCGTzS;NAX9?jSawzBzWdL2yYT#&{@SYVGK+xV z#G+ja>kjC@F8sUh!iyLCH*Q?YZI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se0&?%yRJpar)5B{IML1Hy4Lo)~CX%~(OpOv3? zC?ssvVigp;$k>_rR^rjEs|!te_qVb}8Zme%vFv%Qb>bd_uXVT!gE+_xr|X7FUALaM zUo+8q{nkEi+Wy_&&aSk%`Le`D1z3#qP zQL@k@IKR20C$K#Wo4+pmR=g|A3{WvP`K7~Vx&BzIJ!!93ZxB4~&-g}f z$Fhev1s1h;cpW&bprmAU-B!`PX5C%3`jgj|emU^xmH(?<-`oRvJ=g^WCn`NsEAi+* zzFscwb_IXVsc*$E@9hlEnmg-voFEe)D7c$Ww$>HemK9cf-BxuYVw29Y;-zQT|JvkS z{>R~ud}>oiN5-a?5*^Iu{Oi~KXZEoV?4h|# zE-ogLC60Gu?g?I!dF~c|{l9ySW}nK0Da|Rj?wm?CY5&assQ#USfS{o71c~3_uV(#= zKfGG%zQZKXXS-9{XNdjKTF%vvT(Ky)4|a_pNURr8zv=!XPO4*57FQ@9%0?-*wE*{JctE=>KK&uA~Es3Q9_s zzJ?aY{-6I)R{gtb>dyN7plvGe=Ev8rtN7K&_SQo{Fz}RM`JdBA?fg?>`e5;_WjEh#P*GC))u8eDwB=v+#TV)fcI~P& zeNoH9@H;5 zbiZ8svu^(TAVF1o#Z^r1%^e*&?swkq*JJx%&)eT~r@2=*cER5y1_|~1e@o&PXuuHIqp_9 zaPxg_a)t-KTWzi2UzEZ9tvAob+nXbW^S?X;!~g%Q3|FWyFfg!zx**I9?I%r}eu`$y RWME)m@O1TaS?83{1OR|5_@Dp) literal 0 HcmV?d00001 diff --git a/apps/web/public/icon-maskable-512.png b/apps/web/public/icon-maskable-512.png new file mode 100644 index 0000000000000000000000000000000000000000..1db0e73f4caa2e4d0aa726939a48ac0e199f5969 GIT binary patch literal 16078 zcmeAS@N?(olHy`uVBq!ia0y~yU}6Aa4iHr><-C@GL4d*2#WAE}&YQdJH8EG`n*S+Y zZl3A3_+CzFbP?&Lch{rTT(LLS&&$vMpYz$C z?e`%rCI*H_7X=v@1caCv7#spP7#J8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O9W-vNLS&E%GwLdHK*-gBzg@G*g8L(WD`d>?0feCw)fbF7)CKRu^l^^SjkX+^`EZ)LRS@rM5%;*3*4E@o+%cENOO&#s_Z zEbBx~qq1}aCBOCWxooiI@rf4)%WT%nYGeTI9`Ie{nV@~X{L0jx+N;x681lSW@ZSE4 zWnE{X`+}w6hnC5m1#O~WY2eUN&8v>pJP%`4cY=ZgjjKe_!s^gV(pJ z0%VvHo?WzO{v|7^z?U4iZ1Fmi#oLY;uD=pw@_BYgQ*86UUws#=el5E%_x7`pK(krZ zg^Y#L8fuJ(Cizqq?>jx?waN3;Sw%)Zm43l_%Pg;Fp4g=Q+v7sIj@c9b@BJ>n_6YvE zYb^Edv)gaCLwgSwnfN)_+>$60U|8V$Y>`fKS=+(HYqxbD$3M0&n8Ew)asAN;8zf@O zei<)5{BMT7$amJqjRj}q`+grPtk-xq|A$;xrSnBcd9#;?Jp~x{I503c%({4KGaH+1 z$!k`I8FrD}zjp~RFfcS-a$>mftA9A0&0v52BA%R%(+VB8H^Yh&Uvh8beh88pvb|n%wx_&rv;J+ zA{0FuLS-2|q-2#^svDKC`-F6IO=Az95~~2wq4N6;pFUy zR3}#sg}(ux16i0FI!)>_X7uD+x$!V8IrxP8`j5uio_{_8OhE@ec1>tmB;dg1Ym#Gc z_x0FvA5IR2qcZckJd9pVVmS5d#)bZ=aZeQ(M9e-;kh3>bcx=nsa55!PbaqV;BjW_2 zTwd`JTW0|SGn LtDnm{r-UW|M~ZcW literal 0 HcmV?d00001 diff --git a/apps/web/public/icon.svg b/apps/web/public/icon.svg new file mode 100644 index 0000000..71fa58b --- /dev/null +++ b/apps/web/public/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/apps/web/public/manifest.webmanifest b/apps/web/public/manifest.webmanifest new file mode 100644 index 0000000..4b616eb --- /dev/null +++ b/apps/web/public/manifest.webmanifest @@ -0,0 +1,16 @@ +{ + "name": "OweMe", + "short_name": "OweMe", + "description": "Split group expenses, end-to-end encrypted.", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#0B2E22", + "theme_color": "#0B2E22", + "icons": [ + { "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml" }, + { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }, + { "src": "/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" } + ] +} diff --git a/apps/web/public/robots.txt b/apps/web/public/robots.txt new file mode 100644 index 0000000..e71ea62 --- /dev/null +++ b/apps/web/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Disallow: /g/ diff --git a/apps/web/src/App.svelte b/apps/web/src/App.svelte new file mode 100644 index 0000000..1d63438 --- /dev/null +++ b/apps/web/src/App.svelte @@ -0,0 +1,61 @@ + + +{#if ready} + {#if router.route.name === 'home'} + + {:else if router.route.name === 'new'} + + {:else if router.route.name === 'settings'} + + {:else if router.route.name === 'restore'} + + {:else if groupId} + {#key groupId} + + {/key} + {:else} +
+ +
+ {/if} +{/if} + +{#if ui.toast} +
{ui.toast}
+{/if} + +{#if ui.updateReady} +
+ {t('update_available')} + +
+{/if} diff --git a/apps/web/src/app.css b/apps/web/src/app.css new file mode 100644 index 0000000..c13151f --- /dev/null +++ b/apps/web/src/app.css @@ -0,0 +1,241 @@ +/* OweMe theme: dark & light "money green" (SPEC.md §10.4). */ +:root { + --bg: #0b2e22; + --surface: #123d2e; + --surface-2: #1a4d3a; + --border: #255c46; + --text: #e8f3ec; + --muted: #9fbfae; + --accent: #3ddc97; + --accent-ink: #062016; + --owe: #f2a65a; + --danger: #f87171; + --gold: #d4af37; + /* chart series, validated for CVD separation on --surface */ + --chart-1: #22a66e; + --chart-2: #4a8fd0; + --shadow: 0 8px 30px rgb(0 0 0 / 0.35); + --radius: 14px; + --gutter: 16px; + color-scheme: dark; +} + +@media (prefers-color-scheme: light) { + :root:not([data-theme='dark']) { + --bg: #f2f7f4; + --surface: #ffffff; + --surface-2: #e4efe9; + --border: #cfe0d6; + --text: #0b2e22; + --muted: #4a6b5b; + --accent: #16865a; + --accent-ink: #ffffff; + --owe: #b5541c; + --danger: #c0392b; + --gold: #9a7b12; + --chart-1: #16865a; + --chart-2: #2f6fb0; + --shadow: 0 8px 30px rgb(11 46 34 / 0.12); + color-scheme: light; + } +} +:root[data-theme='light'] { + --bg: #f2f7f4; + --surface: #ffffff; + --surface-2: #e4efe9; + --border: #cfe0d6; + --text: #0b2e22; + --muted: #4a6b5b; + --accent: #16865a; + --accent-ink: #ffffff; + --owe: #b5541c; + --danger: #c0392b; + --gold: #9a7b12; + --chart-1: #16865a; + --chart-2: #2f6fb0; + --shadow: 0 8px 30px rgb(11 46 34 / 0.12); + color-scheme: light; +} + +* { box-sizing: border-box; } +html { -webkit-text-size-adjust: 100%; } +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 16px/1.45 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif; + -webkit-font-smoothing: antialiased; + min-height: 100dvh; +} +h1, h2, h3 { line-height: 1.2; margin: 0; } +h1 { font-size: 1.35rem; } +h2 { font-size: 1.05rem; } +h3 { font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); font-weight: 600; } +a { color: var(--accent); } +p { margin: 0; } +.muted { color: var(--muted); } +.small { font-size: 0.85rem; } +.pos { color: var(--accent); } +.neg { color: var(--owe); } +.num { font-variant-numeric: tabular-nums; } +.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; } + +/* layout */ +.page { max-width: 720px; margin: 0 auto; padding: 0 var(--gutter) calc(96px + env(safe-area-inset-bottom)); } +.page.wide { max-width: 1120px; } +.stack { display: flex; flex-direction: column; gap: 12px; } +.row { display: flex; align-items: center; gap: 10px; } +.row.wrap { flex-wrap: wrap; } +.spacer { flex: 1; } +.section { margin-top: 24px; display: flex; flex-direction: column; gap: 10px; } + +.topbar { + position: sticky; top: 0; z-index: 20; + display: flex; align-items: center; gap: 8px; + padding: calc(10px + env(safe-area-inset-top)) var(--gutter) 10px; + background: color-mix(in srgb, var(--bg) 88%, transparent); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} +.topbar h1 { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.card { + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + padding: 14px 16px; +} +.list { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; } +.list > * + * { border-top: 1px solid var(--border); } +.item { + display: flex; align-items: center; gap: 12px; padding: 12px 14px; width: 100%; + background: none; border: 0; color: inherit; font: inherit; text-align: left; text-decoration: none; +} +button.item, a.item { cursor: pointer; } +button.item:hover, a.item:hover { background: var(--surface-2); } +.item .grow { flex: 1; min-width: 0; } +.item .title { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.item .sub { font-size: 0.85rem; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.item .end { text-align: right; flex-shrink: 0; } + +/* controls */ +button, .btn { + font: inherit; color: inherit; cursor: pointer; +} +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: 8px; + min-height: 44px; padding: 0 16px; border-radius: 12px; + border: 1px solid var(--border); background: var(--surface); color: var(--text); + font-weight: 600; text-decoration: none; white-space: nowrap; +} +.btn:hover { background: var(--surface-2); } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); } +.btn.primary:hover { filter: brightness(1.08); } +.btn.danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 40%, var(--border)); } +.btn.ghost { background: transparent; border-color: transparent; } +.btn.small { min-height: 34px; padding: 0 12px; font-size: 0.9rem; border-radius: 10px; } +.btn.block { width: 100%; } +.btn:disabled { opacity: 0.5; cursor: not-allowed; } +.icon-btn { + display: inline-grid; place-items: center; width: 44px; height: 44px; flex-shrink: 0; + border-radius: 12px; border: 0; background: transparent; color: var(--text); +} +.icon-btn:hover { background: var(--surface-2); } + +label.field { display: flex; flex-direction: column; gap: 6px; font-size: 0.9rem; color: var(--muted); } +input, select, textarea { + font: inherit; color: var(--text); background: var(--surface); width: 100%; + border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; min-height: 44px; +} +textarea { min-height: 80px; resize: vertical; } +input:focus-visible, select:focus-visible, textarea:focus-visible, .btn:focus-visible, .icon-btn:focus-visible, .item:focus-visible, .chip:focus-visible { + outline: 2px solid var(--accent); outline-offset: 1px; +} +input[type='checkbox'] { width: 22px; height: 22px; min-height: 0; accent-color: var(--accent); flex-shrink: 0; } +input[type='date'] { min-width: 0; } + +.seg { display: flex; background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 3px; gap: 3px; } +.seg button { + flex: 1; min-height: 38px; border: 0; border-radius: 9px; background: transparent; color: var(--muted); font-weight: 600; font-size: 0.9rem; padding: 0 8px; +} +.seg button[aria-pressed='true'] { background: var(--surface-2); color: var(--text); } + +.chips { display: flex; flex-wrap: wrap; gap: 8px; } +.chip { + display: inline-flex; align-items: center; gap: 6px; min-height: 36px; padding: 0 12px; + border-radius: 999px; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-size: 0.9rem; +} +.chip[aria-pressed='true'] { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 16%, var(--surface)); } + +.avatar { + display: inline-grid; place-items: center; flex-shrink: 0; + width: 36px; height: 36px; border-radius: 50%; + font-weight: 700; font-size: 0.9rem; color: #062016; +} +.cat-icon { + display: inline-grid; place-items: center; flex-shrink: 0; + width: 40px; height: 40px; border-radius: 12px; background: var(--surface-2); font-size: 1.2rem; +} + +.banner { padding: 10px 14px; border-radius: 12px; font-size: 0.9rem; background: var(--surface-2); border: 1px solid var(--border); } +.banner.warn { border-color: color-mix(in srgb, var(--owe) 60%, var(--border)); } +.banner.danger { border-color: color-mix(in srgb, var(--danger) 60%, var(--border)); } + +.fab { + position: fixed; right: max(var(--gutter), calc(50% - 360px + var(--gutter))); bottom: calc(80px + env(safe-area-inset-bottom)); z-index: 30; + width: 60px; height: 60px; border-radius: 20px; border: 0; + background: var(--accent); color: var(--accent-ink); box-shadow: var(--shadow); + display: grid; place-items: center; +} + +.tabbar { + position: fixed; left: 0; right: 0; bottom: 0; z-index: 25; + display: flex; justify-content: center; + background: color-mix(in srgb, var(--surface) 94%, transparent); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border-top: 1px solid var(--border); + padding-bottom: env(safe-area-inset-bottom); +} +.tabbar a { + flex: 1; max-width: 180px; display: flex; flex-direction: column; align-items: center; gap: 2px; + padding: 8px 4px; color: var(--muted); text-decoration: none; font-size: 0.75rem; font-weight: 600; +} +.tabbar a[aria-current='page'] { color: var(--accent); } + +/* dialogs: full-screen sheet on phones, centered on desktop */ +dialog.sheet { + padding: 0; border: 0; color: var(--text); background: var(--bg); + width: 100%; max-width: 100%; height: 100%; max-height: 100%; margin: 0; +} +dialog.sheet::backdrop { background: rgb(0 0 0 / 0.5); } +@media (min-width: 760px) { + dialog.sheet { + width: min(640px, calc(100% - 48px)); height: auto; max-height: calc(100dvh - 64px); + margin: auto; border-radius: 20px; border: 1px solid var(--border); box-shadow: var(--shadow); + } +} +.sheet-body { padding: 0 var(--gutter) calc(24px + env(safe-area-inset-bottom)); } + +.toast { + position: fixed; left: 50%; transform: translateX(-50%); bottom: calc(150px + env(safe-area-inset-bottom)); z-index: 100; + background: var(--text); color: var(--bg); padding: 10px 16px; border-radius: 12px; font-weight: 600; box-shadow: var(--shadow); + max-width: calc(100% - 32px); +} + +.amount-input { + font-size: 2rem; font-weight: 700; text-align: center; border: 0; background: transparent; padding: 4px 0; min-height: 56px; +} +.amount-input:focus-visible { outline: none; border-bottom: 2px solid var(--accent); border-radius: 0; } + +.empty { text-align: center; color: var(--muted); padding: 40px 16px; } +.photo-thumb { width: 100%; max-height: 320px; object-fit: contain; border-radius: 12px; background: var(--surface-2); display: block; } + +/* desktop: group page with a side column */ +@media (min-width: 960px) { + .tabbar { position: static; justify-content: flex-start; gap: 4px; background: none; border: 0; backdrop-filter: none; padding: 0; } + .tabbar a { flex: 0 0 auto; flex-direction: row; gap: 8px; font-size: 0.95rem; padding: 10px 14px; border-radius: 10px; } + .tabbar a[aria-current='page'] { background: var(--surface); } + .fab { bottom: 32px; right: max(32px, calc(50% - 560px + 32px)); } + .page { padding-bottom: 48px; } +} diff --git a/apps/web/src/components/Activity.svelte b/apps/web/src/components/Activity.svelte new file mode 100644 index 0000000..44c015d --- /dev/null +++ b/apps/web/src/components/Activity.svelte @@ -0,0 +1,100 @@ + + +
+ {#if entries.length === 0} +

{t('no_activity')}

+ {:else} +
+ {#each entries.slice(0, limit) as a, i (a.eventId)} +
+ + {describe(a)} + {fmtDateTime(a.at)}{a.seq === null ? ' · ⏳' : ''} + + {#if a.type === 'revert'} + {@const prev = beforeOf(a.eventId)} + {#if prev} + + {/if} + {:else if i > 0} + + {/if} +
+ {/each} +
+ {#if entries.length > limit} + + {/if} + {/if} +
diff --git a/apps/web/src/components/AppSettings.svelte b/apps/web/src/components/AppSettings.svelte new file mode 100644 index 0000000..86643e1 --- /dev/null +++ b/apps/web/src/components/AppSettings.svelte @@ -0,0 +1,32 @@ + + +
+ +

{t('app_settings')}

+
+ +
+
+

{t('language')}

+
+ + + +
+
+
+

{t('theme')}

+
+ + + +
+
+

+ {t('e2e_note')} +

+
diff --git a/apps/web/src/components/Avatar.svelte b/apps/web/src/components/Avatar.svelte new file mode 100644 index 0000000..cb4d722 --- /dev/null +++ b/apps/web/src/components/Avatar.svelte @@ -0,0 +1,12 @@ + + + diff --git a/apps/web/src/components/Balances.svelte b/apps/web/src/components/Balances.svelte new file mode 100644 index 0000000..a07095b --- /dev/null +++ b/apps/web/src/components/Balances.svelte @@ -0,0 +1,92 @@ + + +
+ {#if !compact} +

{t('balances')}

+ {/if} +
+ {#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))} + +
+ {/each} +
+ +

{t('settle_up')}

+ {#if transfers.length === 0} +

{t('all_settled')}

+ {:else} +
+ {#each transfers as tr} +
+ + {session.memberName(tr.from)} → {session.memberName(tr.to)} + {conv(tr.amount)} + + +
+ {/each} +
+ {/if} + + {#if !compact} + + {/if} +
+ + diff --git a/apps/web/src/components/CurrencySelect.svelte b/apps/web/src/components/CurrencySelect.svelte new file mode 100644 index 0000000..e289571 --- /dev/null +++ b/apps/web/src/components/CurrencySelect.svelte @@ -0,0 +1,37 @@ + + + diff --git a/apps/web/src/components/ExpenseDetail.svelte b/apps/web/src/components/ExpenseDetail.svelte new file mode 100644 index 0000000..479ec76 --- /dev/null +++ b/apps/web/src/components/ExpenseDetail.svelte @@ -0,0 +1,161 @@ + + +{#if !e || !b} +

{t('loading')}

+{:else} + + {#snippet actions()} + {#if !rec.deleted} + + {/if} + {/snippet} +
+ {#if rec.deleted} + + {/if} + +
+ +
{money(e.amount, e.currency)}
+ {#if e.currency !== session.base} +
{t('converted', { amount: money(b.total, session.base), rate: e.rate })}
+ {/if} +
+ {fmtDate(e.date, 'long')} · {t(`cat_${e.category}` as MsgKey)} + {#if e.recurringId} · {t('recurring_badge')}{/if} +
+
+ + {#if e.photo}{/if} + {#if e.note}

{e.note}

{/if} + +

{t('split_details')}

+
+ {#each session.state.members.filter((m) => b.paid[m.id] || b.owed[m.id]) as m (m.id)} +
+ + + {m.name}{m.id === session.me ? ` (${t('you')})` : ''} + {#if b.paid[m.id]}{t('paid', { amount: money(e.payers.find((p) => p.member === m.id)!.amount, e.currency) })}{/if} + + {#if b.owed[m.id]} + + {t('owes_share', { amount: money(orig[m.id] ?? 0, e.currency) })} + {#if e.currency !== session.base}{money(b.owed[m.id], session.base)}{/if} + + {/if} +
+ {/each} +
+ +

{t('comments')}

+ {#if comments.length} +
+ {#each comments as c (c.id)} +
+ + + {session.memberName(c.author)} · {fmtDateTime(c.at)} + {c.text} + + +
+ {/each} +
+ {/if} +
+ + +
+ +

{t('history')}

+
+ {#each versions as v, i (v.eventId)} +
+ + {session.memberName(v.actor) === '?' ? t('someone') : session.memberName(v.actor)} · {fmtDateTime(v.at)} + {v.exp.title || t('kind_transfer')} · {money(v.exp.amount, v.exp.currency)} + {changed(versions[i + 1]?.exp, v.exp)} + + {#if !rec.deleted && JSON.stringify(v.exp) === JSON.stringify(e)} + {t('current_version')} + {:else} + + {/if} +
+ {/each} +
+ + {#if !rec.deleted} + + {/if} +
+
+{/if} diff --git a/apps/web/src/components/ExpenseEditor.svelte b/apps/web/src/components/ExpenseEditor.svelte new file mode 100644 index 0000000..e434d20 --- /dev/null +++ b/apps/web/src/components/ExpenseEditor.svelte @@ -0,0 +1,422 @@ + + + +
+ {#if !existing} +
+ + +
+ {/if} + +
+ + +
+ +
+
+ {#if currency !== base} +
+ + (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}{t('rate_source_manual')}{/if} + {#if amount && isValidRate(rateText.trim().replace(',', '.'))} · ≈ {money(Math.round(amount * Number(rateText.replace(',', '.')) * 10 ** (exponent(base) - exp)), base)}{/if} +

+ {/if} +
+ + {#if kind === 'expense'} + +
+ {t('category')} +
+ {#each CATEGORIES as c} + + {/each} +
+
+ {/if} + + + + + {#if kind === 'transfer'} +
+ + +
+ {:else} +
+ + {t('paid_by_label')} + + + {#if multiPayer} +
+ {#each members as m (m.id)} +
+ + {m.name} + +
+ {/each} +
+ {#if payersRemaining !== 0 && amount} + + {payersRemaining > 0 ? t('remaining', { amount: money(payersRemaining, currency) }) : t('over_by', { amount: money(-payersRemaining, currency) })} + + {/if} + {:else} + + {/if} +
+ + +
+ {t('split')} +
+ {#each [['equal', 'split_equal'], ['shares', 'split_shares'], ['exact', 'split_exact'], ['percent', 'split_percent']] as const as [m, label]} + + {/each} +
+
+ + +
+
+ {#each members as m (m.id)} +
+ + + + {m.name} + {#if preview[m.id]}{money(preview[m.id], currency)}{/if} + + {#if mode !== 'equal'} + + + {#if mode === 'percent'}%{/if} + + {/if} +
+ {/each} +
+ {#if (mode === 'exact' || mode === 'percent') && remaining !== 0} + + {#if mode === 'exact'} + {remaining > 0 ? t('remaining', { amount: money(remaining, currency) }) : t('over_by', { amount: money(-remaining, currency) })} + {:else} + {remaining > 0 ? t('remaining', { amount: `${remaining / 100} %` }) : t('over_by', { amount: `${-remaining / 100} %` })} + {/if} + + {/if} +
+ {/if} + + + {#if repeat === 'none'} +
+ {t('photo')} + {#if newPhotoUrl} + {t('photo')} + {:else if photo} + + {/if} +
+ + {#if photo || newPhoto}{/if} + {#if photoBusy}{t('processing_photo')}{/if} +
+
+ {/if} + + + + {#if !existing && kind === 'expense'} + + {/if} + + {#if error}{/if} +
+ + +
+
+
diff --git a/apps/web/src/components/ExpenseList.svelte b/apps/web/src/components/ExpenseList.svelte new file mode 100644 index 0000000..0f12c94 --- /dev/null +++ b/apps/web/src/components/ExpenseList.svelte @@ -0,0 +1,103 @@ + + +
+
+
+
{t('total_spent')}
+
{money(total, session.base)}
+
+
+ + {#if Object.keys(session.state.expenses).length > 6} + + {/if} + + {#if rows.length === 0} +

{session.status === 'loading' ? t('loading') : t('no_expenses')}

+ {/if} + + {#each rows as day (day.date)} +
+

{dayLabel(day.date)}

+ +
+ {/each} +
diff --git a/apps/web/src/components/GroupPage.svelte b/apps/web/src/components/GroupPage.svelte new file mode 100644 index 0000000..5ecd727 --- /dev/null +++ b/apps/web/src/components/GroupPage.svelte @@ -0,0 +1,132 @@ + + +{#if session === undefined} +

{t('loading')}

+{:else if session === null} +
+ +

{t('app_name')}

+
+

{t('group_not_on_device')}

+{:else if route.name === 'group-settings'} + +{:else} + {@const s = session} +
+ +

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

+ nav(e, `${base}/settings`)} aria-label={t('group_settings')}> +
+ +
+ {#if s.status === 'gone'} + + {:else if s.status === 'offline'} + + {/if} + {#if s.pending.length && s.status !== 'online'} +

{t('pending', { n: s.pending.length })}

+ {/if} + {#if s.rollback}{/if} + + + +
+
+ {#if tab === 'expenses'} + + {:else if tab === 'balances'} + + {:else if tab === 'stats'} + + {:else} + + {/if} +
+ {#if tab === 'expenses'} + + {/if} +
+
+ + {#if s.status !== 'gone' && (tab === 'expenses' || tab === 'balances')} + nav(e, `${base}/e/new`)} aria-label={t('add_expense')}> + {/if} + + {#if route.name === 'expense'} + + {:else if route.name === 'expense-edit'} + {#key route.eid} + + {/key} + {:else if needsIdentity} + (skippedIdentity = true)} /> + {/if} +{/if} + + diff --git a/apps/web/src/components/GroupSettings.svelte b/apps/web/src/components/GroupSettings.svelte new file mode 100644 index 0000000..ef800ff --- /dev/null +++ b/apps/web/src/components/GroupSettings.svelte @@ -0,0 +1,257 @@ + + +
+ +

{t('group_settings')}

+
+ +
+ +
+

{t('share_group')}

+
+ {#if justCreated}{/if} +

{t('share_intro')}

+
+ + {#if 'share' in navigator}{/if} + +
+ {#if showQr} +
{@html qr}
+ {/if} +
+
+ + +
+

{t('group_settings')}

+
+
+ + +
+ + +
+
+ + +
+

{t('identity')}

+ +
+ + +
+

{t('members')}

+
+ {#each s.state.members as m, i (m.id)} + {@const bal = s.balances[m.id] ?? 0} +
+ + + {m.name}{m.archived ? ` · ${t('archived')}` : ''} + {bal === 0 ? t('settled') : money(bal, s.base, { sign: true })} + + + {#if m.archived} + + {:else} + + {/if} +
+ {/each} +
+
+ + +
+
+ + +
+

{t('notifications')}

+
+ {#if push === 'ok' || s.local.push} + + {:else if push === 'needs-install'} +

{t('notifications_ios')}

+ {:else if push === 'denied'} +

{t('notifications_denied')}

+ {:else if push} +

{t('notifications_unavailable')}

+ {/if} +
+
+ + +
+

{t('recurring')}

+ {#if Object.keys(s.state.recurring).length === 0} +

{t('no_recurring')}

+ {:else} +
+ {#each Object.values(s.state.recurring) as r (r.id)} + {@const next = nextOccurrence(r.rule, today())} +
+ + + {r.template.title} · {money(r.template.amount, r.template.currency)} + {t(`repeat_${r.rule.freq}`)}{next ? ` · ${t('next_on', { date: fmtDate(next) })}` : ''} + + +
+ {/each} +
+ {/if} +
+ + +
+

{t('export')}

+
+ + + +
+

{t('backup_hint')}

+
+ + +
+

{t('danger_zone')}

+
+

{t('remove_from_device_hint')}

+ +
+
+

{t('delete_group_hint')}

+ + +
+
+
+ + diff --git a/apps/web/src/components/Home.svelte b/apps/web/src/components/Home.svelte new file mode 100644 index 0000000..1c85fd1 --- /dev/null +++ b/apps/web/src/components/Home.svelte @@ -0,0 +1,95 @@ + + +
+

{t('app_name')}

+ nav(e, '/settings')} aria-label={t('settings')}> +
+ +
+

{t('tagline')}

+ + + +
+ nav(e, '/new')}> {t('new_group')} + {#if showLink} +
+ + {#if linkError}{/if} + +
+ {:else} + + {/if} + nav(e, '/restore')}> {t('restore_backup')} +
+ +

+ {t('e2e_note')} +

+
diff --git a/apps/web/src/components/Icon.svelte b/apps/web/src/components/Icon.svelte new file mode 100644 index 0000000..f2352fe --- /dev/null +++ b/apps/web/src/components/Icon.svelte @@ -0,0 +1,29 @@ + + + diff --git a/apps/web/src/components/IdentityPicker.svelte b/apps/web/src/components/IdentityPicker.svelte new file mode 100644 index 0000000..d4e23e9 --- /dev/null +++ b/apps/web/src/components/IdentityPicker.svelte @@ -0,0 +1,50 @@ + + + +
+

{t('who_are_you_hint')}

+
+ {#each members as m, i (m.id)} + + {/each} +
+ {#if adding} +
+ + +
+ {:else} + + {/if} + +
+
diff --git a/apps/web/src/components/NewGroup.svelte b/apps/web/src/components/NewGroup.svelte new file mode 100644 index 0000000..7501f15 --- /dev/null +++ b/apps/web/src/components/NewGroup.svelte @@ -0,0 +1,105 @@ + + +
+ +

{t('new_group')}

+
+ +
+
+ + +
+ {t('icon')} +
+ {#each ICONS as i} + + {/each} +
+
+ + + + + +
+ {t('other_members')} + {#each others as _, i} +
+ + {#if others.length > 1} + + {/if} +
+ {/each} + +
+ + {#if error}{/if} + +
+
diff --git a/apps/web/src/components/PhotoView.svelte b/apps/web/src/components/PhotoView.svelte new file mode 100644 index 0000000..ecb2ab5 --- /dev/null +++ b/apps/web/src/components/PhotoView.svelte @@ -0,0 +1,50 @@ + + +{#if failed} +

📷 …

+{:else} + +{/if} + +{#if open} + (open = false)} onclick={() => dialog?.close()}> + {t('photo')} + +{/if} + + diff --git a/apps/web/src/components/Restore.svelte b/apps/web/src/components/Restore.svelte new file mode 100644 index 0000000..18f3060 --- /dev/null +++ b/apps/web/src/components/Restore.svelte @@ -0,0 +1,40 @@ + + +
+ +

{t('restore_title')}

+
+ +
+ + {#if busy}

{t('restoring')}

{/if} + {#if error}{/if} +
diff --git a/apps/web/src/components/Sheet.svelte b/apps/web/src/components/Sheet.svelte new file mode 100644 index 0000000..88522d5 --- /dev/null +++ b/apps/web/src/components/Sheet.svelte @@ -0,0 +1,32 @@ + + + { e.preventDefault(); onclose(); }} + onclick={(e) => { if (e.target === dialog) onclose(); }} +> +
+ +

{title}

+ {@render actions?.()} +
+
+ {@render children()} +
+
diff --git a/apps/web/src/components/Stats.svelte b/apps/web/src/components/Stats.svelte new file mode 100644 index 0000000..6137fb6 --- /dev/null +++ b/apps/web/src/components/Stats.svelte @@ -0,0 +1,143 @@ + + +
+
+ {#each [['all', 'range_all'], ['year', 'range_year'], ['month', 'range_month'], ['30', 'range_30']] as const as [r, label]} + + {/each} +
+ +
+
+
{t('total_spent')}
+
{money(st.total, base)}
+
+ {#if mine} +
+
{t('my_spending')}
+
{money(mine.consumed, base)}
+
+ {/if} +
+ + {#if st.total === 0} +

{t('no_data')}

+ {:else} +
+

{t('by_category')}

+
    + {#each st.byCategory as c (c.category)} +
  • + {t(`cat_${c.category}` as MsgKey)} + + {money(c.amount, base)} +
  • + {/each} +
+
+ + {#if st.byMonth.length > 1} +
+
+

{t('by_month')}

+ {#if shownMonth}{fmtMonth(shownMonth.month)}: {money(shownMonth.amount, base)}{/if} +
+
+ {#each st.byMonth as m, i (m.month)} + + {/each} +
+
+ {/if} + + {#if members.length} +
+

{t('per_member')}

+
+ {t('legend_paid')} + {t('legend_share')} +
+
    + {#each members as p (p.member)} +
  • + {session.memberName(p.member)} + + + + {money(p.paid, base)} + + + + {money(p.consumed, base)} + + +
  • + {/each} +
+
+ {/if} + {/if} +
+ + diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts new file mode 100644 index 0000000..1c4c8e3 --- /dev/null +++ b/apps/web/src/lib/api.ts @@ -0,0 +1,90 @@ +// Thin wrappers around the server API (SPEC.md §8.1). +import type { StoredEvent } from './idb.ts'; + +export class ApiError extends Error { + status: number; + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +/** True for errors that mean "try again later" rather than "this is wrong". */ +export const isOffline = (e: unknown) => !(e instanceof ApiError) || e.status >= 500 || e.status === 429; + +async function req(method: string, path: string, opts: { token?: string; json?: unknown; body?: BodyInit; signal?: AbortSignal } = {}): Promise { + const headers: Record = {}; + if (opts.token) headers.Authorization = `Bearer ${opts.token}`; + if (opts.json !== undefined) headers['Content-Type'] = 'application/json'; + const res = await fetch(path, { + method, + headers, + body: opts.json !== undefined ? JSON.stringify(opts.json) : opts.body, + signal: opts.signal, + cache: 'no-store', + }); + if (!res.ok) { + let msg = res.statusText; + try { + msg = (await res.json()).error ?? msg; + } catch { /* not JSON */ } + throw new ApiError(res.status, msg); + } + const type = res.headers.get('content-type') ?? ''; + return (type.includes('application/json') ? res.json() : res.arrayBuffer()) as Promise; +} + +export interface ServerConfig { + vapidPublicKey: string | null; + maxPhotoBytes: number; + maxGroupBytes: number; +} + +let configP: Promise | null = null; +export function serverConfig(): Promise { + configP ??= req('GET', '/api/config').catch((e) => { + configP = null; + throw e; + }); + return configP; +} + +export const api = { + createGroup: (id: string, authHash: string) => req('POST', '/api/groups', { json: { id, authHash } }), + deleteGroup: (id: string, token: string) => req('DELETE', `/api/groups/${id}`, { token }), + events: (id: string, token: string, after: number) => + req<{ events: Omit[]; latest: number }>('GET', `/api/groups/${id}/events?after=${after}&limit=500`, { token }), + append: (id: string, token: string, events: Omit[]) => + req<{ seqs: number[] }>('POST', `/api/groups/${id}/events`, { token, json: { events } }), + putBlob: (id: string, token: string, blobId: string, data: ArrayBuffer) => + req('PUT', `/api/groups/${id}/blobs/${blobId}`, { token, body: data }), + getBlob: (id: string, token: string, blobId: string) => req('GET', `/api/groups/${id}/blobs/${blobId}`, { token }), + pushSubscribe: (id: string, token: string, sub: PushSubscriptionJSON, deviceId: string) => + req('POST', `/api/groups/${id}/push`, { token, json: { ...sub, deviceId } }), + pushUnsubscribe: (id: string, token: string, endpoint: string) => req('DELETE', `/api/groups/${id}/push`, { token, json: { endpoint } }), + rates: (date: string) => req<{ base: string; date: string; rates: Record }>('GET', `/api/rates?date=${date}`), +}; + +/** + * Listen for "new seq" pings on the group's SSE stream. EventSource can't + * send an Authorization header, so this reads the stream with fetch. + * Resolves when the stream ends; throws on errors. + */ +export async function listen(id: string, token: string, signal: AbortSignal, onSeq: (seq: number) => void): Promise { + const res = await fetch(`/api/groups/${id}/stream`, { headers: { Authorization: `Bearer ${token}` }, signal, cache: 'no-store' }); + if (!res.ok || !res.body) throw new ApiError(res.status, 'stream failed'); + const reader = res.body.pipeThrough(new TextDecoderStream()).getReader(); + let buf = ''; + for (;;) { + const { value, done } = await reader.read(); + if (done) return; + buf += value; + let i: number; + while ((i = buf.indexOf('\n\n')) >= 0) { + const msg = buf.slice(0, i); + buf = buf.slice(i + 2); + const m = /^data: (\d+)$/m.exec(msg); + if (m) onSeq(Number(m[1])); + } + } +} diff --git a/apps/web/src/lib/backup.ts b/apps/web/src/lib/backup.ts new file mode 100644 index 0000000..9ee4aa0 --- /dev/null +++ b/apps/web/src/lib/backup.ts @@ -0,0 +1,84 @@ +// Backup file (SPEC.md §7.6): the encrypted event log and photos plus the +// group secret, so the group can be restored even if every link is lost. +// Events and photos stay encrypted inside; the secret makes the file as +// sensitive as the link. +import type { GroupEvent } from '@oweme/core'; +import { api, ApiError } from './api.ts'; +import { b64uDecode, b64uEncode, deriveKeys, isGroupId, isGroupSecret, sha256hex } from './crypto.ts'; +import { get, put, type StoredBlob } from './idb.ts'; +import { decryptEvent } from './events.ts'; +import { addGroup, type GroupSession } from './session.svelte.ts'; + +interface BackupFile { + format: 'oweme-backup'; + v: 1; + groupId: string; + secret: string; + createdAt: string; + events: { id: string; deviceId: string; iv: string; ct: string }[]; + blobs: { id: string; data: string }[]; +} + +function photoIds(events: GroupEvent[]): string[] { + const ids = new Set(); + for (const e of events) { + if ((e.type === 'expense.created' || e.type === 'expense.updated') && e.data?.photo) { + ids.add(e.data.photo.blobId); + ids.add(e.data.photo.thumbBlobId); + } + } + return [...ids]; +} + +export async function makeBackup(s: GroupSession): Promise { + await s.sync(); + const raw = await s.rawEvents(); + const blobs: BackupFile['blobs'] = []; + for (const id of photoIds(s.synced)) { + let rec = await get('blobs', [s.id, id]); + if (!rec) { + try { + rec = { g: s.id, id, data: await api.getBlob(s.id, s.keys.authToken, id), uploaded: true }; + await put('blobs', rec); + } catch { + continue; // missing photo shouldn't block the rest of the backup + } + } + blobs.push({ id, data: b64uEncode(new Uint8Array(rec.data)) }); + } + const file: BackupFile = { + format: 'oweme-backup', v: 1, groupId: s.id, secret: s.local.secret, createdAt: new Date().toISOString(), + events: raw.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct })), + blobs, + }; + return JSON.stringify(file); +} + +/** Restore a backup to this server. Returns the group id and whether it already existed. */ +export async function restoreBackup(text: string): Promise<{ id: string; existed: boolean }> { + let f: BackupFile; + try { + f = JSON.parse(text); + } catch { + throw new Error('bad file'); + } + if (f?.format !== 'oweme-backup' || !isGroupId(f.groupId) || !isGroupSecret(f.secret) || !Array.isArray(f.events) || !f.events.length) + throw new Error('bad file'); + const keys = await deriveKeys(f.secret); + // Make sure the key really opens this data before uploading anything. + if (!(await decryptEvent(keys, f.groupId, { ...f.events[0], seq: 0 }))) throw new Error('bad file'); + + let existed = false; + try { + await api.createGroup(f.groupId, await sha256hex(keys.authToken)); + } catch (e) { + if (e instanceof ApiError && e.status === 409) existed = true; + else throw e; + } + // Uploads are idempotent (by event and blob id), so this also completes + // an interrupted restore, and is harmless for a group that already exists. + for (const b of f.blobs ?? []) await api.putBlob(f.groupId, keys.authToken, b.id, b64uDecode(b.data).buffer); + for (let i = 0; i < f.events.length; i += 200) await api.append(f.groupId, keys.authToken, f.events.slice(i, i + 200)); + await addGroup(f.groupId, f.secret); + return { id: f.groupId, existed }; +} diff --git a/apps/web/src/lib/crypto.ts b/apps/web/src/lib/crypto.ts new file mode 100644 index 0000000..1aa1521 --- /dev/null +++ b/apps/web/src/lib/crypto.ts @@ -0,0 +1,77 @@ +// Client-side encryption (SPEC.md §3.1, §11). WebCrypto only: +// AES-256-GCM for data, HKDF-SHA-256 to derive keys from the group secret. + +const te = new TextEncoder(); +const td = new TextDecoder(); + +export function b64uEncode(bytes: Uint8Array): string { + let s = ''; + for (const b of bytes) s += String.fromCharCode(b); + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); +} + +export function b64uDecode(str: string): Uint8Array { + const s = atob(str.replace(/-/g, '+').replace(/_/g, '/')); + const out = new Uint8Array(s.length); + for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i); + return out; +} + +export function randomBytes(n: number): Uint8Array { + return crypto.getRandomValues(new Uint8Array(n)); +} + +/** Random base64url id; 16 bytes → 22 chars. */ +export function randomId(bytes = 16): string { + return b64uEncode(randomBytes(bytes)); +} + +export const isGroupId = (s: string) => /^[A-Za-z0-9_-]{22}$/.test(s); +export const isGroupSecret = (s: string) => /^[A-Za-z0-9_-]{43}$/.test(s); + +export interface GroupKeys { + encKey: CryptoKey; + /** bearer token for the API; the server only stores its SHA-256 */ + authToken: string; +} + +export async function deriveKeys(secret: string): Promise { + const ikm = await crypto.subtle.importKey('raw', b64uDecode(secret), 'HKDF', false, ['deriveKey', 'deriveBits']); + const params = (info: string) => ({ name: 'HKDF', hash: 'SHA-256', salt: new Uint8Array(0), info: te.encode(info) }); + const encKey = await crypto.subtle.deriveKey(params('oweme/enc/v1'), ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']); + const auth = new Uint8Array(await crypto.subtle.deriveBits(params('oweme/auth/v1'), ikm, 256)); + return { encKey, authToken: b64uEncode(auth) }; +} + +export async function sha256hex(s: string): Promise { + const d = new Uint8Array(await crypto.subtle.digest('SHA-256', te.encode(s))); + return [...d].map((b) => b.toString(16).padStart(2, '0')).join(''); +} + +/** Encrypt JSON for an event. `aad` binds the ciphertext to its group and id, + * so the server can't swap events between groups or ids. */ +export async function encryptJson(key: CryptoKey, value: unknown, aad: string): Promise<{ iv: string; ct: string }> { + const iv = randomBytes(12); + const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, te.encode(JSON.stringify(value))); + return { iv: b64uEncode(iv), ct: b64uEncode(new Uint8Array(ct)) }; +} + +export async function decryptJson(key: CryptoKey, iv: string, ct: string, aad: string): Promise { + const pt = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: b64uDecode(iv), additionalData: te.encode(aad) }, key, b64uDecode(ct)); + return JSON.parse(td.decode(pt)); +} + +/** Encrypt bytes for a blob: output is iv (12 bytes) || ciphertext. */ +export async function encryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise { + const iv = randomBytes(12); + const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: te.encode(aad) }, key, data)); + const out = new Uint8Array(12 + ct.length); + out.set(iv); + out.set(ct, 12); + return out.buffer; +} + +export async function decryptBytes(key: CryptoKey, data: ArrayBuffer, aad: string): Promise { + const bytes = new Uint8Array(data); + return crypto.subtle.decrypt({ name: 'AES-GCM', iv: bytes.subarray(0, 12), additionalData: te.encode(aad) }, key, bytes.subarray(12)); +} diff --git a/apps/web/src/lib/events.ts b/apps/web/src/lib/events.ts new file mode 100644 index 0000000..88ae490 --- /dev/null +++ b/apps/web/src/lib/events.ts @@ -0,0 +1,17 @@ +// Decrypting a stored event. Plain module (no runes) so the service worker +// can use it too. +import type { EventPlaintext, GroupEvent } from '@oweme/core'; +import { decryptJson, type GroupKeys } from './crypto.ts'; + +export async function decryptEvent( + keys: GroupKeys, + groupId: string, + e: { id: string; seq: number | null; deviceId: string; iv: string; ct: string }, +): Promise { + try { + const p = await decryptJson(keys.encKey, e.iv, e.ct, `${groupId}|${e.id}`); + return { ...p, id: e.id, seq: e.seq, deviceId: e.deviceId }; + } catch { + return null; // wrong key or tampered: skip it + } +} diff --git a/apps/web/src/lib/format.ts b/apps/web/src/lib/format.ts new file mode 100644 index 0000000..4738071 --- /dev/null +++ b/apps/web/src/lib/format.ts @@ -0,0 +1,87 @@ +import { exponent, toDecimalString } from '@oweme/core'; +import { settings } from './settings.svelte.ts'; + +const cache = new Map(); + +/** Format minor units as money in the current locale ("1 234,50 Kč"). */ +export function money(minor: number, currency: string, opts: { sign?: boolean } = {}): string { + const key = `${settings.locale}|${currency}|${opts.sign ? 1 : 0}`; + let f = cache.get(key); + if (!f) { + const e = exponent(currency); + try { + f = new Intl.NumberFormat(settings.locale, { + style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e, + signDisplay: opts.sign ? 'exceptZero' : 'auto', + }); + } catch { + f = new Intl.NumberFormat(settings.locale, { minimumFractionDigits: e, maximumFractionDigits: e }); + } + cache.set(key, f); + } + return f.format(minor / 10 ** exponent(currency)); +} + +/** Editable amount text for an input, in the user's decimal style. */ +export function amountInput(minor: number, currency: string): string { + const s = toDecimalString(minor, currency); + return settings.lang === 'cs' ? s.replace('.', ',') : s; +} + +export function fmtDate(d: string, style: 'short' | 'long' = 'short'): string { + const date = new Date(`${d}T12:00:00`); + return date.toLocaleDateString(settings.locale, style === 'long' + ? { weekday: 'short', day: 'numeric', month: 'long', year: 'numeric' } + : { day: 'numeric', month: 'short', year: date.getFullYear() === new Date().getFullYear() ? undefined : 'numeric' }); +} + +export function fmtDateTime(iso: string): string { + return new Date(iso).toLocaleString(settings.locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); +} + +export function fmtMonth(ym: string): string { + return new Date(`${ym}-15T12:00:00`).toLocaleDateString(settings.locale, { month: 'short', year: '2-digit' }); +} + +/** Today as YYYY-MM-DD in local time. */ +export function today(): string { + const d = new Date(); + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +export function addDays(d: string, n: number): string { + const x = new Date(`${d}T12:00:00`); + x.setDate(x.getDate() + n); + return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, '0')}-${String(x.getDate()).padStart(2, '0')}`; +} + +export function currencyName(code: string): string { + try { + return new Intl.DisplayNames(settings.locale, { type: 'currency' }).of(code) ?? code; + } catch { + return code; + } +} + +export const CATEGORY_ICONS: Record = { + food: '🍽️', groceries: '🛒', transport: '🚕', accommodation: '🏨', entertainment: '🎟️', + shopping: '🛍️', utilities: '💡', rent: '🏠', travel: '✈️', gifts: '🎁', health: '💊', + other: '🧾', transfer: '💸', +}; + +export const MEMBER_COLORS = ['#3DDC97', '#F2A65A', '#6CB4EE', '#E879A6', '#C9A227', '#9B8CF2', '#4FD1C5', '#F87171', '#A3E635', '#FB923C']; + +export function download(filename: string, content: BlobPart, type: string) { + const url = URL.createObjectURL(new Blob([content], { type })); + const a = document.createElement('a'); + a.href = url; + a.download = filename; + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 10_000); +} + +export function slug(s: string): string { + return s.normalize('NFKD').replace(/[̀-ͯ]/g, '').replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'group'; +} diff --git a/apps/web/src/lib/i18n.ts b/apps/web/src/lib/i18n.ts new file mode 100644 index 0000000..1f344d9 --- /dev/null +++ b/apps/web/src/lib/i18n.ts @@ -0,0 +1,25 @@ +// Tiny i18n. English is the default; Czech is used when the browser's +// preferred language is Czech, unless the user picks one in settings +// (SPEC.md §10.3). Plain module (no runes) so the service worker can use it. +import cs from './locales/cs.ts'; +import en, { type Messages, type Plural } from './locales/en.ts'; + +export type Lang = 'en' | 'cs'; +export type MsgKey = keyof Messages; +const dicts: Record = { en, cs }; + +export function detectLang(languages: readonly string[] = navigator.languages ?? [navigator.language]): Lang { + const first = (languages[0] ?? '').toLowerCase(); + return first === 'cs' || first.startsWith('cs-') ? 'cs' : 'en'; +} + +export const localeOf = (lang: Lang) => (lang === 'cs' ? 'cs-CZ' : 'en'); + +export function translate(lang: Lang, key: MsgKey, vars: Record = {}): string { + let msg: string | Plural = dicts[lang][key] ?? en[key]; + if (typeof msg !== 'string') { + const form = new Intl.PluralRules(localeOf(lang)).select(Number(vars.n ?? 0)); + msg = form === 'one' ? msg.one : form === 'few' ? msg.few : msg.other; + } + return msg.replace(/\{(\w+)\}/g, (_, k) => (k in vars ? String(vars[k]) : `{${k}}`)); +} diff --git a/apps/web/src/lib/idb.ts b/apps/web/src/lib/idb.ts new file mode 100644 index 0000000..a169c86 --- /dev/null +++ b/apps/web/src/lib/idb.ts @@ -0,0 +1,150 @@ +// IndexedDB storage, shared by the page and the service worker. +// Events are kept as the server's ciphertext and decrypted when loaded. + +export interface LocalGroup { + id: string; + /** the key from the link; anyone with this has full access */ + secret: string; + name: string; + icon: string; + baseCurrency: string; + /** "who am I" on this device */ + me: string | null; + /** my balance in base minor units, cached for the home screen */ + myBalance: number | null; + lastSeq: number; + lastOpened: number; + push: boolean; + /** highest seq the service worker has notified about */ + notifiedSeq: number; + /** set when the server says the group no longer exists */ + gone?: boolean; +} + +export interface StoredEvent { + g: string; + seq: number; + id: string; + deviceId: string; + iv: string; + ct: string; +} + +export interface OutboxItem { + n?: number; + g: string; + id: string; + deviceId: string; + iv: string; + ct: string; +} + +export interface StoredBlob { + g: string; + id: string; + /** encrypted bytes */ + data: ArrayBuffer; + uploaded: boolean; +} + +let dbp: Promise | null = null; + +export function openDb(): Promise { + if (dbp) return dbp; + dbp = new Promise((resolve, reject) => { + const req = indexedDB.open('oweme', 1); + req.onupgradeneeded = () => { + const db = req.result; + db.createObjectStore('groups', { keyPath: 'id' }); + db.createObjectStore('events', { keyPath: ['g', 'seq'] }); + db.createObjectStore('outbox', { keyPath: 'n', autoIncrement: true }).createIndex('g', 'g'); + db.createObjectStore('blobs', { keyPath: ['g', 'id'] }); + db.createObjectStore('kv'); + }; + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); + return dbp; +} + +type StoreName = 'groups' | 'events' | 'outbox' | 'blobs' | 'kv'; + +function wrap(req: IDBRequest): Promise { + return new Promise((resolve, reject) => { + req.onsuccess = () => resolve(req.result); + req.onerror = () => reject(req.error); + }); +} + +async function store(name: StoreName, mode: IDBTransactionMode = 'readonly'): Promise { + return (await openDb()).transaction(name, mode).objectStore(name); +} + +export async function get(name: StoreName, key: IDBValidKey): Promise { + return wrap((await store(name)).get(key)); +} +export async function put(name: StoreName, value: unknown, key?: IDBValidKey): Promise { + await wrap((await store(name, 'readwrite')).put(value, key)); +} +export async function del(name: StoreName, key: IDBValidKey | IDBKeyRange): Promise { + await wrap((await store(name, 'readwrite')).delete(key)); +} +export async function getAll(name: StoreName, query?: IDBKeyRange): Promise { + return wrap((await store(name)).getAll(query)) as Promise; +} + +export const groupRange = (g: string) => IDBKeyRange.bound([g, -Infinity], [g, Infinity]); +export const groupBlobRange = (g: string) => IDBKeyRange.bound([g, ''], [g, '￿']); + +export async function putEvents(events: StoredEvent[]): Promise { + if (!events.length) return; + const tx = (await openDb()).transaction('events', 'readwrite'); + for (const e of events) tx.objectStore('events').put(e); + await new Promise((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error)))); +} + +export async function outboxFor(g: string): Promise { + const s = await store('outbox'); + return wrap(s.index('g').getAll(g)) as Promise; +} + +export async function updateGroup(id: string, patch: Partial): Promise { + const tx = (await openDb()).transaction('groups', 'readwrite'); + const s = tx.objectStore('groups'); + const g = (await wrap(s.get(id))) as LocalGroup | undefined; + if (!g) return undefined; + const next = { ...g, ...patch }; + s.put(next); + await new Promise((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error)))); + return next; +} + +/** Remove a group and everything cached for it from this device. */ +export async function forgetGroup(id: string): Promise { + const db = await openDb(); + const tx = db.transaction(['groups', 'events', 'outbox', 'blobs'], 'readwrite'); + tx.objectStore('groups').delete(id); + tx.objectStore('events').delete(groupRange(id)); + tx.objectStore('blobs').delete(groupBlobRange(id)); + const ob = tx.objectStore('outbox'); + const keys = await wrap(ob.index('g').getAllKeys(id)); + for (const k of keys) ob.delete(k); + await new Promise((res, rej) => ((tx.oncomplete = () => res()), (tx.onerror = () => rej(tx.error)))); +} + +export async function kvGet(k: string): Promise { + return get('kv', k); +} +export async function kvSet(k: string, v: unknown): Promise { + await put('kv', v, k); +} + +/** Stable random id for this browser, so it can skip notifying itself. */ +export async function deviceId(): Promise { + let id = await kvGet('deviceId'); + if (!id) { + id = Array.from(crypto.getRandomValues(new Uint8Array(12)), (b) => b.toString(36).padStart(2, '0')).join(''); + await kvSet('deviceId', id); + } + return id; +} diff --git a/apps/web/src/lib/locales/cs.ts b/apps/web/src/lib/locales/cs.ts new file mode 100644 index 0000000..af00839 --- /dev/null +++ b/apps/web/src/lib/locales/cs.ts @@ -0,0 +1,253 @@ +import type { Messages } from './en.ts'; + +const cs: Messages = { + app_name: 'OweMe', + tagline: 'Dělte společné výdaje. Šifrováno end-to-end.', + + your_groups: 'Vaše skupiny', + no_groups: 'Na tomto zařízení zatím nejsou žádné skupiny. Vytvořte novou, nebo otevřete odkaz, který vám někdo poslal.', + new_group: 'Nová skupina', + open_link: 'Otevřít odkaz na skupinu', + restore_backup: 'Obnovit zálohu', + paste_link: 'Vložte odkaz na skupinu', + open: 'Otevřít', + invalid_link: 'Tohle nevypadá jako úplný odkaz na skupinu OweMe.', + you_are_owed: 'dluží vám {amount}', + you_owe: 'dlužíte {amount}', + settled: 'vyrovnáno', + pick_identity_hint: 'vyberte, kdo jste', + group_gone: 'smazáno', + e2e_note: 'Vše se šifruje přímo ve vašem zařízení. Server ukládá jen data, která nedokáže přečíst. Odkazy na skupiny si proto dobře uschovejte: ztracený odkaz nelze obnovit.', + + settings: 'Nastavení', + app_settings: 'Nastavení aplikace', + language: 'Jazyk', + lang_auto: 'Automaticky', + theme: 'Vzhled', + theme_system: 'Podle systému', + theme_dark: 'Tmavý', + theme_light: 'Světlý', + + create_group: 'Vytvořit skupinu', + group_name: 'Název skupiny', + group_name_ph: 'Výlet do Prahy', + base_currency: 'Hlavní měna', + base_currency_hint: 'V této měně se zobrazují zůstatky. Jakmile má skupina výdaje, nelze ji změnit.', + base_currency_locked: 'Uzamčeno, protože skupina už má výdaje.', + icon: 'Ikona', + your_name: 'Vaše jméno', + other_members: 'Další členové', + add_member: 'Přidat člena', + member_name: 'Jméno', + creating: 'Vytvářím…', + + share_group: 'Sdílet skupinu', + share_intro: 'Kdokoli s tímto odkazem může skupinu vidět i upravovat. Posílejte ho jen členům.', + save_link_warning: 'Uložte si tento odkaz na bezpečné místo. Pokud se ztratí všechny kopie, skupinu nepůjde obnovit.', + copy_link: 'Kopírovat odkaz', + copied: 'Zkopírováno', + share: 'Sdílet…', + done: 'Hotovo', + + who_are_you: 'Kdo jste?', + who_are_you_hint: 'Zapamatuje se na tomto zařízení, takže výdaje budou předvyplněné na vás.', + im_new: 'Nejsem v seznamu', + just_looking: 'Přeskočit', + change_identity: 'Nejsem {name}', + you: 'vy', + + expenses: 'Výdaje', + balances: 'Zůstatky', + stats: 'Statistiky', + activity: 'Aktivita', + add_expense: 'Přidat výdaj', + no_expenses: 'Zatím žádné výdaje. Klepněte na + a přidejte první.', + total_spent: 'Celkem utraceno', + paid_by: 'Platil(a) {name}', + paid_by_many: 'Platilo {n} lidí', + your_share: 'váš podíl {amount}', + you_lent: 'půjčili jste {amount}', + you_borrowed: 'dlužíte {amount}', + not_involved: 'netýká se vás', + transfer_line: '{from} → {to}', + offline: 'Jste offline. Změny se uloží v zařízení a synchronizují se později.', + pending: { one: '{n} změna čeká na synchronizaci', few: '{n} změny čekají na synchronizaci', other: '{n} změn čeká na synchronizaci' }, + rollback_warning: 'Server vrátil starší data, než toto zařízení už vidělo. Mohl s nimi někdo manipulovat, nebo byla obnovena ze zálohy.', + not_found_group: 'Tato skupina už na serveru neexistuje.', + remove_from_device: 'Odebrat z tohoto zařízení', + group_not_on_device: 'Tato skupina není uložená v tomto zařízení. Otevřete celý odkaz (včetně části za #).', + loading: 'Načítám…', + search: 'Hledat', + + settle_up: 'Vyrovnání', + all_settled: 'Všichni jsou vyrovnaní. 🎉', + mark_paid: 'Zaznamenat platbu', + show_in: 'Zobrazit v', + display_only_rate: 'Přepočteno dnešním kurzem, jen pro zobrazení.', + is_owed: 'má dostat {amount}', + owes: 'dluží {amount}', + + new_expense: 'Nový výdaj', + edit_expense: 'Upravit výdaj', + new_transfer: 'Zaznamenat platbu', + kind_expense: 'Výdaj', + kind_transfer: 'Platba', + amount: 'Částka', + title: 'Za co?', + title_ph: 'Večeře', + category: 'Kategorie', + date: 'Datum', + currency: 'Měna', + rate: 'Směnný kurz', + rate_source_ecb: 'Kurz ECB ze dne {date}', + rate_source_manual: 'Zadáno ručně', + rate_unavailable: 'Pro tuto měnu není kurz k dispozici, zadejte ho prosím.', + paid_by_label: 'Platil(a)', + multiple_payers: 'Platilo více lidí', + from_label: 'Od', + to_label: 'Komu', + split: 'Rozdělení', + split_equal: 'Rovným dílem', + split_shares: 'Podíly', + split_exact: 'Částky', + split_percent: 'Procenta', + remaining: 'Zbývá: {amount}', + over_by: 'Přebývá: {amount}', + select_all: 'Všichni', + select_none: 'Nikdo', + note: 'Poznámka', + photo: 'Fotka', + add_photo: 'Přidat fotku', + replace_photo: 'Vyměnit', + remove_photo: 'Odebrat', + processing_photo: 'Zpracovávám fotku…', + photo_too_large: 'Fotka je i po zmenšení příliš velká.', + repeat: 'Opakovat', + repeat_none: 'Nikdy', + repeat_weekly: 'Každý týden', + repeat_monthly: 'Každý měsíc', + repeat_yearly: 'Každý rok', + save: 'Uložit', + cancel: 'Zrušit', + invalid_amount: 'Zadejte platnou částku.', + invalid_split: 'Rozdělení nesedí.', + invalid_payers: 'Platby nedávají dohromady celou částku.', + need_title: 'Doplňte popis.', + need_members: 'Nejdřív do skupiny přidejte členy.', + + delete: 'Smazat', + restore: 'Obnovit', + edit: 'Upravit', + deleted_banner: 'Tento výdaj byl smazán.', + split_details: 'Rozdělení', + paid: 'zaplatil(a) {amount}', + owes_share: 'podíl {amount}', + converted: '{amount} při kurzu {rate}', + comments: 'Komentáře', + add_comment: 'Napište komentář…', + send: 'Odeslat', + history: 'Historie', + restore_version: 'Obnovit tuto verzi', + current_version: 'Aktuální verze', + recurring_badge: 'Opakuje se', + confirm_delete: 'Smazat tento výdaj? Později ho můžete obnovit z historie.', + + rewind_here: 'Vrátit skupinu sem', + undo_rewind: 'Zrušit toto vrácení', + confirm_rewind: 'Vrátit celou skupinu do stavu po této změně? Nic se neztratí: vrácení lze zase zrušit.', + act_group_created: '{actor} vytvořil(a) skupinu', + act_group_updated: '{actor} změnil(a) nastavení skupiny', + act_member_added: '{actor} přidal(a) člena {name}', + act_member_updated: '{actor} přejmenoval(a) {old} na {name}', + act_member_archived: '{actor} archivoval(a) člena {name}', + act_member_restored: '{actor} obnovil(a) člena {name}', + act_expense_created: '{actor} přidal(a) {title}', + act_expense_updated: '{actor} upravil(a) {title}', + act_expense_deleted: '{actor} smazal(a) {title}', + act_expense_restored: '{actor} obnovil(a) {title}', + act_comment_added: '{actor} okomentoval(a) {title}', + act_comment_deleted: '{actor} smazal(a) komentář u {title}', + act_recurring_created: '{actor} nastavil(a) opakování {title}', + act_recurring_updated: '{actor} změnil(a) opakování {title}', + act_recurring_deleted: '{actor} zrušil(a) opakování {title}', + act_revert: '{actor} vrátil(a) skupinu do stavu z {time}', + someone: 'Někdo', + changed_fields: 'Změněno: {fields}', + no_activity: 'Zatím žádná aktivita.', + + range_all: 'Celé období', + range_month: 'Tento měsíc', + range_30: 'Posledních 30 dní', + range_year: 'Tento rok', + by_category: 'Podle kategorie', + by_month: 'Podle měsíce', + per_member: 'Zaplaceno vs. podíl', + legend_paid: 'Zaplaceno', + legend_share: 'Podíl', + my_spending: 'Můj podíl na útratě', + no_data: 'Za toto období tu nic není.', + + group_settings: 'Nastavení skupiny', + members: 'Členové', + rename: 'Přejmenovat', + archive: 'Archivovat', + archived: 'archivován(a)', + unarchive: 'Obnovit', + archive_needs_zero: 'Archivovat lze jen členy s nulovým zůstatkem.', + identity: 'Jste', + not_set: 'Nenastaveno', + change: 'Změnit', + notifications: 'Oznámení', + notifications_hint: 'Dostanete oznámení, když skupinu změní někdo jiný.', + notifications_ios: 'Na iPhonu a iPadu nejdřív přidejte OweMe na plochu (Sdílet → Přidat na plochu).', + notifications_denied: 'Oznámení jsou pro tento web zablokovaná v nastavení prohlížeče.', + notifications_unavailable: 'Oznámení nejsou na tomto serveru nebo v tomto prohlížeči k dispozici.', + recurring: 'Opakované výdaje', + no_recurring: 'Žádné. Při přidání výdaje zvolte „Opakovat“.', + next_on: 'příště {date}', + stop: 'Zrušit', + export: 'Export', + export_expenses: 'Výdaje (CSV)', + export_balances: 'Zůstatky (CSV)', + backup: 'Soubor se zálohou', + backup_hint: 'Obsahuje klíč skupiny: kdokoli se souborem skupinu otevře. Uložte ho bezpečně.', + danger_zone: 'Nebezpečná zóna', + remove_from_device_hint: 'Skupina zůstane na serveru i v ostatních zařízeních.', + delete_group: 'Smazat skupinu pro všechny', + delete_group_hint: 'Smaže ze serveru všechny výdaje a fotky. Pro potvrzení napište název skupiny.', + confirm: 'Potvrdit', + saved: 'Uloženo', + + restore_title: 'Obnovit zálohu', + restore_pick: 'Vyberte soubor se zálohou OweMe (.json).', + restore_bad_file: 'Tohle není platná záloha OweMe.', + restore_exists: 'Tato skupina na serveru už existuje, takže byla jen přidána do tohoto zařízení.', + restoring: 'Obnovuji…', + + back: 'Zpět', + close: 'Zavřít', + error_generic: 'Něco se pokazilo: {msg}', + update_available: 'Je k dispozici nová verze.', + reload: 'Načíst znovu', + today: 'Dnes', + yesterday: 'Včera', + n_members: { one: '{n} člen', few: '{n} členové', other: '{n} členů' }, + + cat_food: 'Jídlo a pití', + cat_groceries: 'Potraviny', + cat_transport: 'Doprava', + cat_accommodation: 'Ubytování', + cat_entertainment: 'Zábava', + cat_shopping: 'Nákupy', + cat_utilities: 'Energie a služby', + cat_rent: 'Nájem', + cat_travel: 'Cestování', + cat_gifts: 'Dárky', + cat_health: 'Zdraví', + cat_other: 'Ostatní', + cat_transfer: 'Platba', + + notif_new_activity: { one: '{n} nová změna', few: '{n} nové změny', other: '{n} nových změn' }, +}; + +export default cs; diff --git a/apps/web/src/lib/locales/en.ts b/apps/web/src/lib/locales/en.ts new file mode 100644 index 0000000..c60c641 --- /dev/null +++ b/apps/web/src/lib/locales/en.ts @@ -0,0 +1,270 @@ +// English strings. `{name}` placeholders are filled by t(); entries with +// one/few/other are plural forms chosen by Intl.PluralRules on `{n}`. +const en = { + app_name: 'OweMe', + tagline: 'Split group expenses. End-to-end encrypted.', + + // home + your_groups: 'Your groups', + no_groups: 'No groups on this device yet. Create one, or open a group link someone sent you.', + new_group: 'New group', + open_link: 'Open a group link', + restore_backup: 'Restore a backup', + paste_link: 'Paste the group link', + open: 'Open', + invalid_link: "That doesn't look like a complete OweMe group link.", + you_are_owed: 'you are owed {amount}', + you_owe: 'you owe {amount}', + settled: 'settled up', + pick_identity_hint: 'choose who you are', + group_gone: 'deleted', + e2e_note: 'Everything is encrypted on your device. The server only stores data it cannot read, so keep your group links safe: lost links cannot be recovered.', + + // settings + settings: 'Settings', + app_settings: 'App settings', + language: 'Language', + lang_auto: 'Automatic', + theme: 'Theme', + theme_system: 'System', + theme_dark: 'Dark', + theme_light: 'Light', + + // new group + create_group: 'Create group', + group_name: 'Group name', + group_name_ph: 'Prague trip', + base_currency: 'Main currency', + base_currency_hint: 'Balances are shown in this currency. It can’t be changed once the group has expenses.', + base_currency_locked: 'Locked because the group has expenses.', + icon: 'Icon', + your_name: 'Your name', + other_members: 'Other members', + add_member: 'Add member', + member_name: 'Name', + creating: 'Creating…', + + // share + share_group: 'Share group', + share_intro: 'Anyone with this link can see and edit the group. Send it only to group members.', + save_link_warning: 'Save this link somewhere safe. If every copy is lost, the group can’t be recovered.', + copy_link: 'Copy link', + copied: 'Copied', + share: 'Share…', + done: 'Done', + + // identity + who_are_you: 'Who are you?', + who_are_you_hint: 'This is remembered on this device, so expenses default to you.', + im_new: 'I’m not on the list', + just_looking: 'Skip', + change_identity: 'I’m not {name}', + you: 'you', + + // group tabs + expenses: 'Expenses', + balances: 'Balances', + stats: 'Stats', + activity: 'Activity', + add_expense: 'Add expense', + no_expenses: 'No expenses yet. Tap + to add the first one.', + total_spent: 'Total spent', + paid_by: 'Paid by {name}', + paid_by_many: 'Paid by {n} people', + your_share: 'your share {amount}', + you_lent: 'you lent {amount}', + you_borrowed: 'you borrowed {amount}', + not_involved: 'not involved', + transfer_line: '{from} → {to}', + offline: 'Offline. Changes are saved on this device and will sync later.', + pending: { one: '{n} change waiting to sync', few: '{n} changes waiting to sync', other: '{n} changes waiting to sync' }, + rollback_warning: 'The server returned older data than this device has seen. Someone may have tampered with it, or it was restored from a backup.', + not_found_group: 'This group no longer exists on the server.', + remove_from_device: 'Remove from this device', + group_not_on_device: 'This group isn’t saved on this device. Open the full link (with the part after #) to add it.', + loading: 'Loading…', + search: 'Search', + + // balances + settle_up: 'Settle up', + all_settled: 'Everyone is settled up. 🎉', + mark_paid: 'Record payment', + show_in: 'Show in', + display_only_rate: 'Converted at today’s rate, for display only.', + is_owed: 'is owed {amount}', + owes: 'owes {amount}', + + // expense editor + new_expense: 'New expense', + edit_expense: 'Edit expense', + new_transfer: 'Record payment', + kind_expense: 'Expense', + kind_transfer: 'Payment', + amount: 'Amount', + title: 'What was it for?', + title_ph: 'Dinner', + category: 'Category', + date: 'Date', + currency: 'Currency', + rate: 'Exchange rate', + rate_source_ecb: 'ECB rate from {date}', + rate_source_manual: 'Entered manually', + rate_unavailable: 'No rate available for this currency, please enter it.', + paid_by_label: 'Paid by', + multiple_payers: 'Several people paid', + from_label: 'From', + to_label: 'To', + split: 'Split', + split_equal: 'Equally', + split_shares: 'Shares', + split_exact: 'Amounts', + split_percent: 'Percent', + remaining: 'Remaining: {amount}', + over_by: 'Over by: {amount}', + select_all: 'All', + select_none: 'None', + note: 'Note', + photo: 'Photo', + add_photo: 'Add photo', + replace_photo: 'Replace', + remove_photo: 'Remove', + processing_photo: 'Processing photo…', + photo_too_large: 'The photo is too large even after compressing.', + repeat: 'Repeat', + repeat_none: 'Never', + repeat_weekly: 'Every week', + repeat_monthly: 'Every month', + repeat_yearly: 'Every year', + save: 'Save', + cancel: 'Cancel', + invalid_amount: 'Enter a valid amount.', + invalid_split: 'The split doesn’t add up.', + invalid_payers: 'The payers don’t add up to the amount.', + need_title: 'Add a description.', + need_members: 'Add members to the group first.', + + // expense detail + delete: 'Delete', + restore: 'Restore', + edit: 'Edit', + deleted_banner: 'This expense was deleted.', + split_details: 'Split', + paid: 'paid {amount}', + owes_share: 'share {amount}', + converted: '{amount} at {rate}', + comments: 'Comments', + add_comment: 'Write a comment…', + send: 'Send', + history: 'History', + restore_version: 'Restore this version', + current_version: 'Current version', + recurring_badge: 'Repeats', + confirm_delete: 'Delete this expense? You can restore it later from its history.', + + // activity + rewind_here: 'Rewind group to here', + undo_rewind: 'Undo this rewind', + confirm_rewind: 'Restore the whole group to how it was after this change? Nothing is lost: the rewind itself can be undone.', + act_group_created: '{actor} created the group', + act_group_updated: '{actor} changed group settings', + act_member_added: '{actor} added {name}', + act_member_updated: '{actor} renamed {old} to {name}', + act_member_archived: '{actor} archived {name}', + act_member_restored: '{actor} restored {name}', + act_expense_created: '{actor} added {title}', + act_expense_updated: '{actor} edited {title}', + act_expense_deleted: '{actor} deleted {title}', + act_expense_restored: '{actor} restored {title}', + act_comment_added: '{actor} commented on {title}', + act_comment_deleted: '{actor} deleted a comment on {title}', + act_recurring_created: '{actor} set up repeating {title}', + act_recurring_updated: '{actor} changed repeating {title}', + act_recurring_deleted: '{actor} stopped repeating {title}', + act_revert: '{actor} rewound the group to {time}', + someone: 'Someone', + changed_fields: 'Changed: {fields}', + no_activity: 'No activity yet.', + + // stats + range_all: 'All time', + range_month: 'This month', + range_30: 'Last 30 days', + range_year: 'This year', + by_category: 'By category', + by_month: 'By month', + per_member: 'Paid vs. share', + legend_paid: 'Paid', + legend_share: 'Share', + my_spending: 'My share of spending', + no_data: 'Nothing to show for this period.', + + // group settings + group_settings: 'Group settings', + members: 'Members', + rename: 'Rename', + archive: 'Archive', + archived: 'archived', + unarchive: 'Restore', + archive_needs_zero: 'Only members with a zero balance can be archived.', + identity: 'You are', + not_set: 'Not set', + change: 'Change', + notifications: 'Notifications', + notifications_hint: 'Get a notification when someone else changes this group.', + notifications_ios: 'On iPhone and iPad, add OweMe to your home screen first (Share → Add to Home Screen).', + notifications_denied: 'Notifications are blocked for this site in your browser settings.', + notifications_unavailable: 'Notifications aren’t available on this server or in this browser.', + recurring: 'Repeating expenses', + no_recurring: 'None. Choose “Repeat” when adding an expense.', + next_on: 'next on {date}', + stop: 'Stop', + export: 'Export', + export_expenses: 'Expenses (CSV)', + export_balances: 'Balances (CSV)', + backup: 'Backup file', + backup_hint: 'Contains the group key: anyone with the file can open the group. Store it safely.', + danger_zone: 'Danger zone', + remove_from_device_hint: 'The group stays on the server and on other devices.', + delete_group: 'Delete group for everyone', + delete_group_hint: 'Deletes all expenses and photos from the server. Type the group name to confirm.', + confirm: 'Confirm', + saved: 'Saved', + + // backup restore + restore_title: 'Restore a backup', + restore_pick: 'Choose an OweMe backup file (.json).', + restore_bad_file: 'That isn’t a valid OweMe backup.', + restore_exists: 'This group already exists on the server, so it was added to this device.', + restoring: 'Restoring…', + + // misc + back: 'Back', + close: 'Close', + error_generic: 'Something went wrong: {msg}', + update_available: 'A new version is available.', + reload: 'Reload', + today: 'Today', + yesterday: 'Yesterday', + n_members: { one: '{n} member', few: '{n} members', other: '{n} members' }, + + cat_food: 'Food & drink', + cat_groceries: 'Groceries', + cat_transport: 'Transport', + cat_accommodation: 'Accommodation', + cat_entertainment: 'Entertainment', + cat_shopping: 'Shopping', + cat_utilities: 'Utilities', + cat_rent: 'Rent', + cat_travel: 'Travel', + cat_gifts: 'Gifts', + cat_health: 'Health', + cat_other: 'Other', + cat_transfer: 'Payment', + + // notifications (service worker) + notif_new_activity: { one: '{n} new change', few: '{n} new changes', other: '{n} new changes' }, +}; + +export type Plural = { one: string; few: string; other: string }; +export type Messages = { [K in keyof typeof en]: (typeof en)[K] extends string ? string : Plural }; +export default en satisfies Messages as Messages; diff --git a/apps/web/src/lib/photo.ts b/apps/web/src/lib/photo.ts new file mode 100644 index 0000000..09fb094 --- /dev/null +++ b/apps/web/src/lib/photo.ts @@ -0,0 +1,49 @@ +// Receipt photos (SPEC.md §9): shrink and re-encode on the device, which +// also strips EXIF metadata including GPS location, then encrypt. + +export interface ProcessedPhoto { + full: Blob; + thumb: Blob; + w: number; + h: number; +} + +async function encode(canvas: HTMLCanvasElement, quality: number): Promise { + const webp = await new Promise((r) => canvas.toBlob(r, 'image/webp', quality)); + // Browsers that can't encode WebP silently return PNG; use JPEG instead. + if (webp && webp.type === 'image/webp') return webp; + const jpeg = await new Promise((r) => canvas.toBlob(r, 'image/jpeg', quality)); + if (!jpeg) throw new Error('could not encode image'); + return jpeg; +} + +function draw(img: ImageBitmap, maxEdge: number): HTMLCanvasElement { + const scale = Math.min(1, maxEdge / Math.max(img.width, img.height)); + const c = document.createElement('canvas'); + c.width = Math.round(img.width * scale); + c.height = Math.round(img.height * scale); + c.getContext('2d')!.drawImage(img, 0, 0, c.width, c.height); + return c; +} + +/** + * Photo + thumbnail, together under `maxBytes` (minus encryption overhead). + * Tries lower quality, then smaller sizes, before giving up. + */ +export async function processPhoto(file: Blob, maxBytes: number): Promise { + const img = await createImageBitmap(file, { imageOrientation: 'from-image' }); + try { + const thumb = await encode(draw(img, 320), 0.7); + const budget = maxBytes - thumb.size - 1024; + for (const edge of [1600, 1280, 1024, 800]) { + const canvas = draw(img, edge); + for (const q of [0.82, 0.7, 0.55]) { + const full = await encode(canvas, q); + if (full.size <= budget) return { full, thumb, w: canvas.width, h: canvas.height }; + } + } + throw new Error('too large'); + } finally { + img.close(); + } +} diff --git a/apps/web/src/lib/push.ts b/apps/web/src/lib/push.ts new file mode 100644 index 0000000..fe7fd0a --- /dev/null +++ b/apps/web/src/lib/push.ts @@ -0,0 +1,52 @@ +// Web Push opt-in per group (SPEC.md §7.7). One browser subscription is +// shared by all groups; each group registers it with the server separately. +import { api, serverConfig } from './api.ts'; +import { b64uDecode } from './crypto.ts'; +import { deviceId, getAll, updateGroup, type LocalGroup } from './idb.ts'; +import type { GroupSession } from './session.svelte.ts'; + +export type PushSupport = 'ok' | 'unsupported' | 'needs-install' | 'denied' | 'no-server'; + +export async function pushSupport(): Promise { + const ios = /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1); + const standalone = matchMedia('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true; + if (!('serviceWorker' in navigator) || !('PushManager' in window) || !('Notification' in window)) { + return ios && !standalone ? 'needs-install' : 'unsupported'; + } + if (Notification.permission === 'denied') return 'denied'; + try { + if (!(await serverConfig()).vapidPublicKey) return 'no-server'; + } catch { + return 'no-server'; + } + return 'ok'; +} + +async function subscription(create: boolean): Promise { + const reg = await navigator.serviceWorker.ready; + const existing = await reg.pushManager.getSubscription(); + if (existing || !create) return existing; + const key = (await serverConfig()).vapidPublicKey; + if (!key) throw new Error('push not configured'); + return reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64uDecode(key) }); +} + +export async function enablePush(s: GroupSession): Promise { + if ((await Notification.requestPermission()) !== 'granted') return false; + const sub = await subscription(true); + if (!sub) return false; + await api.pushSubscribe(s.id, s.keys.authToken, sub.toJSON(), await deviceId()); + // Don't notify about everything that happened before opting in. + s.local = { ...s.local, push: true, notifiedSeq: s.local.lastSeq }; + await updateGroup(s.id, { push: true, notifiedSeq: s.local.lastSeq }); + return true; +} + +export async function disablePush(s: GroupSession): Promise { + const sub = await subscription(false); + if (sub) await api.pushUnsubscribe(s.id, s.keys.authToken, sub.endpoint).catch(() => {}); + s.local = { ...s.local, push: false }; + await updateGroup(s.id, { push: false }); + const others = (await getAll('groups')).filter((g) => g.push && g.id !== s.id); + if (sub && others.length === 0) await sub.unsubscribe(); +} diff --git a/apps/web/src/lib/rates.ts b/apps/web/src/lib/rates.ts new file mode 100644 index 0000000..7a7aed4 --- /dev/null +++ b/apps/web/src/lib/rates.ts @@ -0,0 +1,68 @@ +// Exchange rates from our own server (ECB daily, EUR-based). Cached in +// IndexedDB so prefilling still works offline (SPEC.md §5.2, §8.2). +import { rateToString } from '@oweme/core'; +import { api } from './api.ts'; +import { kvGet, kvSet } from './idb.ts'; +import { today } from './format.ts'; + +export interface RatesDay { + date: string; + rates: Record; +} + +const memory = new Map>(); + +/** Rates for a date (the latest published on or before it). */ +export function ratesOn(date: string): Promise { + let p = memory.get(date); + if (!p) { + p = (async () => { + const key = `rates:${date}`; + const cached = await kvGet(key); + // A past date's rates never change; today's might still be published. + if (cached && date < today()) return cached; + try { + const r = await api.rates(date); + const day = { date: r.date, rates: r.rates }; + await kvSet(key, day); + await kvSet('rates:latest', day); + return day; + } catch { + memory.delete(date); + return cached ?? (await kvGet('rates:latest')) ?? null; + } + })(); + memory.set(date, p); + } + return p; +} + +/** Suggested rate string for 1 `from` = x `to`, or null if unknown. */ +export async function suggestRate(from: string, to: string, date: string): Promise<{ rate: string; source: string } | null> { + if (from === to) return { rate: '1', source: 'same' }; + const day = await ratesOn(date); + const f = Number(day?.rates[from]); + const tt = Number(day?.rates[to]); + if (!day || !(f > 0) || !(tt > 0)) return null; + return { rate: rateToString(tt / f), source: `ecb:${day.date}` }; +} + +/** Float conversion for display only (never stored). */ +export async function displayRate(from: string, to: string): Promise { + if (from === to) return 1; + const day = await ratesOn(today()); + const f = Number(day?.rates[from]); + const tt = Number(day?.rates[to]); + return f > 0 && tt > 0 ? tt / f : null; +} + +/** Currencies with ECB rates first, then every other ISO currency. */ +export async function currencyList(): Promise<{ ecb: string[]; other: string[] }> { + const day = await ratesOn(today()); + const ecb = Object.keys(day?.rates ?? { EUR: '1', CZK: '1', USD: '1' }).sort(); + let all: string[] = []; + try { + all = Intl.supportedValuesOf('currency'); + } catch { /* old browser */ } + return { ecb, other: all.filter((c) => !ecb.includes(c)) }; +} diff --git a/apps/web/src/lib/router.svelte.ts b/apps/web/src/lib/router.svelte.ts new file mode 100644 index 0000000..875c9ac --- /dev/null +++ b/apps/web/src/lib/router.svelte.ts @@ -0,0 +1,66 @@ +// Minimal history-API router. The group secret lives only in the URL +// fragment and is stripped from the address bar as soon as it's saved. + +export type Route = + | { name: 'home' } + | { name: 'new' } + | { name: 'settings' } + | { name: 'restore' } + | { name: 'group'; id: string; tab: 'expenses' | 'balances' | 'stats' | 'activity' } + | { name: 'group-settings'; id: string } + | { name: 'expense'; id: string; eid: string } + | { name: 'expense-edit'; id: string; eid: string | null; params: URLSearchParams } + | { name: 'notfound' }; + +function parse(path: string, search: string): Route { + const parts = path.split('/').filter(Boolean); + if (parts.length === 0) return { name: 'home' }; + if (parts[0] === 'new' && parts.length === 1) return { name: 'new' }; + if (parts[0] === 'settings' && parts.length === 1) return { name: 'settings' }; + if (parts[0] === 'restore' && parts.length === 1) return { name: 'restore' }; + if (parts[0] === 'g' && parts[1]) { + const id = parts[1]; + const rest = parts.slice(2); + if (rest.length === 0) return { name: 'group', id, tab: 'expenses' }; + if (rest.length === 1 && ['balances', 'stats', 'activity'].includes(rest[0])) + return { name: 'group', id, tab: rest[0] as 'balances' | 'stats' | 'activity' }; + if (rest.length === 1 && rest[0] === 'settings') return { name: 'group-settings', id }; + if (rest[0] === 'e' && rest[1] === 'new' && rest.length === 2) + return { name: 'expense-edit', id, eid: null, params: new URLSearchParams(search) }; + if (rest[0] === 'e' && rest[1] && rest.length === 2) return { name: 'expense', id, eid: rest[1] }; + if (rest[0] === 'e' && rest[1] && rest[2] === 'edit') return { name: 'expense-edit', id, eid: rest[1], params: new URLSearchParams(search) }; + } + return { name: 'notfound' }; +} + +class Router { + route = $state(parse(location.pathname, location.search)); + /** how many entries we pushed, so "back" can stay inside the app */ + private depth = 0; + + constructor() { + addEventListener('popstate', () => { + this.depth = Math.max(0, this.depth - 1); + this.route = parse(location.pathname, location.search); + }); + } + + go(path: string, opts: { replace?: boolean } = {}) { + const url = new URL(path, location.origin); + if (opts.replace) history.replaceState(null, '', url.pathname + url.search); + else { + history.pushState(null, '', url.pathname + url.search); + this.depth += 1; + } + this.route = parse(url.pathname, url.search); + window.scrollTo(0, 0); + } + + /** Back within the app, or to `fallback` if this is the first page. */ + back(fallback: string) { + if (this.depth > 0) history.back(); + else this.go(fallback, { replace: true }); + } +} + +export const router = new Router(); diff --git a/apps/web/src/lib/session.svelte.ts b/apps/web/src/lib/session.svelte.ts new file mode 100644 index 0000000..b006bb2 --- /dev/null +++ b/apps/web/src/lib/session.svelte.ts @@ -0,0 +1,296 @@ +// One open group: its keys, decrypted log, derived state, and sync with the +// server. Changes are encrypted, written to the local outbox first, then +// uploaded, so the app works offline (SPEC.md §4.1, §10.1). +import { + balances, dueOccurrences, logOrder, replay, SCHEMA_VERSION, + type Activity, type EventBody, type GroupEvent, type GroupState, type EventPlaintext, +} from '@oweme/core'; +import { decryptEvent } from './events.ts'; +import { api, ApiError, isOffline, listen } from './api.ts'; +import { decryptBytes, deriveKeys, encryptBytes, encryptJson, randomId, type GroupKeys } from './crypto.ts'; +import { + del, deviceId, get, getAll, groupRange, outboxFor, put, putEvents, updateGroup, + type LocalGroup, type OutboxItem, type StoredBlob, type StoredEvent, +} from './idb.ts'; +import { today } from './format.ts'; + +export type Status = 'loading' | 'online' | 'offline' | 'gone' | 'error'; + +export class GroupSession { + readonly id: string; + local = $state() as LocalGroup; + status = $state('loading'); + /** seq rollback detected: server is behind what we've seen */ + rollback = $state(false); + synced = $state.raw([]); + pending = $state.raw([]); + state = $state.raw({ group: null, members: [], expenses: {}, comments: {}, recurring: {} }); + activity = $state.raw([]); + balances = $state.raw>({}); + + keys!: GroupKeys; + private device = ''; + private abort = new AbortController(); + private syncing: Promise | null = null; + private resync = false; + private generatedRecurring = false; + private retryTimer: ReturnType | undefined; + + constructor(local: LocalGroup) { + this.id = local.id; + this.local = local; + } + + /** Load from IndexedDB, then start syncing in the background. */ + async open(): Promise { + this.keys = await deriveKeys(this.local.secret); + this.device = await deviceId(); + const stored = await getAll('events', groupRange(this.id)); + const out = await outboxFor(this.id); + this.synced = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e); + this.pending = (await Promise.all(out.map((e) => decryptEvent(this.keys, this.id, { ...e, seq: null })))).filter((e): e is GroupEvent => !!e); + this.recompute(); + if (this.local.gone) { + this.status = 'gone'; + return; + } + addEventListener('online', this.onOnline); + void this.sync(); + void this.stream(); + } + + close() { + this.abort.abort(); + clearTimeout(this.retryTimer); + removeEventListener('online', this.onOnline); + } + + private onOnline = () => void this.sync(); + + get me(): string | null { + const me = this.local.me; + return me && this.state.members.some((m) => m.id === me) ? me : null; + } + + get base(): string { + return this.state.group?.baseCurrency ?? this.local.baseCurrency; + } + + memberName(id: string | null | undefined): string { + return this.state.members.find((m) => m.id === id)?.name ?? '?'; + } + + private recompute() { + const r = replay(logOrder(this.synced, this.pending)); + this.state = r.state; + this.activity = r.activity; + this.balances = balances(r.state); + const g = r.state.group; + if (g) { + const myBalance = this.local.me ? (this.balances[this.local.me] ?? null) : null; + const patch = { name: g.name, icon: g.icon, baseCurrency: g.baseCurrency, myBalance }; + if (Object.entries(patch).some(([k, v]) => this.local[k as keyof LocalGroup] !== v)) { + this.local = { ...this.local, ...patch }; + void updateGroup(this.id, patch); + } + } + } + + async setMe(memberId: string | null) { + this.local = { ...this.local, me: memberId }; + await updateGroup(this.id, { me: memberId }); + this.recompute(); + } + + /** Record a change: encrypt → outbox → apply locally → upload. */ + async emit(...bodies: EventBody[]): Promise { + const items: OutboxItem[] = []; + const evs: GroupEvent[] = []; + for (const body of bodies) { + const id = randomId(16); + const plain = { ...body, v: SCHEMA_VERSION, actor: this.me, at: new Date().toISOString() } as EventPlaintext; + const { iv, ct } = await encryptJson(this.keys.encKey, plain, `${this.id}|${id}`); + items.push({ g: this.id, id, deviceId: this.device, iv, ct }); + evs.push({ ...plain, id, seq: null, deviceId: this.device } as GroupEvent); + } + for (const it of items) await put('outbox', it); + this.pending = [...this.pending, ...evs]; + this.recompute(); + void this.sync(); + } + + /** Encrypt a photo blob and queue it for upload. Returns its id. */ + async addBlob(data: ArrayBuffer): Promise { + const id = randomId(18); + const enc = await encryptBytes(this.keys.encKey, data, `${this.id}|${id}`); + await put('blobs', { g: this.id, id, data: enc, uploaded: false } satisfies StoredBlob); + return id; + } + + private blobUrls = new Map>(); + + /** Object URL for a photo blob (from the local cache or the server). */ + blobUrl(blobId: string, type = 'image/webp'): Promise { + let p = this.blobUrls.get(blobId); + if (!p) { + p = (async () => { + let rec = await get('blobs', [this.id, blobId]); + if (!rec) { + const data = await api.getBlob(this.id, this.keys.authToken, blobId); + rec = { g: this.id, id: blobId, data, uploaded: true }; + await put('blobs', rec); + } + const plain = await decryptBytes(this.keys.encKey, rec.data, `${this.id}|${blobId}`); + return URL.createObjectURL(new Blob([plain], { type })); + })(); + p.catch(() => this.blobUrls.delete(blobId)); + this.blobUrls.set(blobId, p); + } + return p; + } + + /** Upload outbox, then pull new events. Coalesces concurrent calls. */ + sync(): Promise { + if (this.syncing) { + this.resync = true; + return this.syncing; + } + this.syncing = (async () => { + try { + do { + this.resync = false; + await this.flush(); + await this.pull(); + } while (this.resync); + this.status = 'online'; + await this.generateRecurring(); + } catch (e) { + this.handleError(e); + } finally { + this.syncing = null; + } + })(); + return this.syncing; + } + + private handleError(e: unknown) { + if (e instanceof ApiError && e.status === 404) { + this.status = 'gone'; + void updateGroup(this.id, { gone: true }); + this.close(); + return; + } + if (this.abort.signal.aborted) return; + this.status = isOffline(e) ? 'offline' : 'error'; + if (!(e instanceof ApiError)) console.warn('sync failed', e); + clearTimeout(this.retryTimer); + this.retryTimer = setTimeout(() => void this.sync(), 15_000); + } + + private async flush() { + // Photos first, so no event ever references a blob the server lacks. + const blobs = (await getAll('blobs')).filter((b) => b.g === this.id && !b.uploaded); + for (const b of blobs) { + await api.putBlob(this.id, this.keys.authToken, b.id, b.data); + await put('blobs', { ...b, uploaded: true }); + } + const out = await outboxFor(this.id); + for (let i = 0; i < out.length; i += 100) { + const chunk = out.slice(i, i + 100); + await api.append(this.id, this.keys.authToken, chunk.map(({ id, deviceId, iv, ct }) => ({ id, deviceId, iv, ct }))); + // The pull that follows stores them with their seqs. + for (const it of chunk) await del('outbox', it.n!); + } + } + + private async pull() { + for (;;) { + const { events, latest } = await api.events(this.id, this.keys.authToken, this.local.lastSeq); + if (latest < this.local.lastSeq) this.rollback = true; + if (events.length === 0) break; + const stored = events.map((e) => ({ ...e, g: this.id })); + await putEvents(stored); + const dec = (await Promise.all(stored.map((e) => decryptEvent(this.keys, this.id, e)))).filter((e): e is GroupEvent => !!e); + const lastSeq = stored[stored.length - 1].seq; + this.local = { ...this.local, lastSeq }; + await updateGroup(this.id, { lastSeq }); + const ids = new Set(dec.map((e) => e.id)); + this.synced = [...this.synced, ...dec]; + this.pending = this.pending.filter((e) => !ids.has(e.id)); + this.recompute(); + if (lastSeq >= latest) break; + } + } + + /** Create due recurring occurrences, once per open, after a full sync. */ + private async generateRecurring() { + if (this.generatedRecurring) return; + this.generatedRecurring = true; + await this.createDueOccurrences(); + } + + /** Emit any recurring occurrences that are due but missing. */ + async createDueOccurrences() { + const due = dueOccurrences(this.state, today()); + if (due.length) await this.emit(...due.map((e) => ({ type: 'expense.created' as const, data: e }))); + } + + /** Keep an SSE stream open; reconnect with backoff. */ + private async stream() { + let delay = 1000; + while (!this.abort.signal.aborted) { + try { + await listen(this.id, this.keys.authToken, this.abort.signal, (seq) => { + delay = 1000; + if (seq !== this.local.lastSeq) void this.sync(); + }); + } catch (e) { + if (this.abort.signal.aborted) return; + if (e instanceof ApiError && e.status === 404) return this.handleError(e); + } + await new Promise((r) => setTimeout(r, delay)); + delay = Math.min(delay * 2, 60_000); + } + } + + /** Every event in log order, as stored (for backups). */ + async rawEvents(): Promise { + return (await getAll('events', groupRange(this.id))).sort((a, b) => a.seq - b.seq); + } +} + +let current: GroupSession | null = null; + +/** The session for a group id, opening it (and closing any other). */ +export async function openSession(id: string): Promise { + if (current?.id === id) return current; + current?.close(); + current = null; + const local = await get('groups', id); + if (!local) return null; + await updateGroup(id, { lastOpened: Date.now() }); + const s = new GroupSession(local); + current = s; + await s.open(); + return s; +} + +export function closeSession(id: string) { + if (current?.id === id) { + current.close(); + current = null; + } +} + +/** Save a group (from a link) on this device. */ +export async function addGroup(id: string, secret: string, extra: Partial = {}): Promise { + const existing = await get('groups', id); + if (existing) { + if (existing.secret !== secret) await updateGroup(id, { secret, gone: false }); + return; + } + await put('groups', { + id, secret, name: '', icon: '', baseCurrency: 'EUR', me: null, myBalance: null, + lastSeq: 0, lastOpened: Date.now(), push: false, notifiedSeq: 0, ...extra, + } satisfies LocalGroup); +} diff --git a/apps/web/src/lib/settings.svelte.ts b/apps/web/src/lib/settings.svelte.ts new file mode 100644 index 0000000..c48eec9 --- /dev/null +++ b/apps/web/src/lib/settings.svelte.ts @@ -0,0 +1,58 @@ +// App-wide, per-device preferences: language and theme. Stored in +// localStorage (a per-device convenience; failures just mean defaults). +import { detectLang, localeOf, translate, type Lang, type MsgKey } from './i18n.ts'; +import { kvSet } from './idb.ts'; + +type LangPref = 'auto' | Lang; +type ThemePref = 'system' | 'dark' | 'light'; + +function load(key: string, allowed: readonly T[], def: T): T { + try { + const v = localStorage.getItem(key) as T | null; + return v && allowed.includes(v) ? v : def; + } catch { + return def; + } +} +function save(key: string, v: string) { + try { + localStorage.setItem(key, v); + } catch { /* private mode etc. */ } +} + +class Settings { + langPref = $state(load('oweme.lang', ['auto', 'en', 'cs'], 'auto')); + themePref = $state(load('oweme.theme', ['system', 'dark', 'light'], 'system')); + + lang = $derived(this.langPref === 'auto' ? detectLang() : this.langPref); + locale = $derived(localeOf(this.lang)); + + setLang(v: LangPref) { + this.langPref = v; + save('oweme.lang', v); + document.documentElement.lang = this.lang; + // the service worker reads this to localise notifications + void kvSet('lang', this.lang).catch(() => {}); + } + + setTheme(v: ThemePref) { + this.themePref = v; + save('oweme.theme', v); + this.applyTheme(); + } + + applyTheme() { + const root = document.documentElement; + if (this.themePref === 'system') delete root.dataset.theme; + else root.dataset.theme = this.themePref; + const dark = this.themePref === 'dark' || (this.themePref === 'system' && matchMedia('(prefers-color-scheme: dark)').matches); + document.querySelector('meta[name=theme-color]')?.setAttribute('content', dark ? '#0B2E22' : '#F2F7F4'); + } +} + +export const settings = new Settings(); + +/** Translate in the current language. Reactive inside components. */ +export function t(key: MsgKey, vars?: Record): string { + return translate(settings.lang, key, vars); +} diff --git a/apps/web/src/lib/ui.svelte.ts b/apps/web/src/lib/ui.svelte.ts new file mode 100644 index 0000000..f542619 --- /dev/null +++ b/apps/web/src/lib/ui.svelte.ts @@ -0,0 +1,14 @@ +// Small bits of global UI state: toasts and the "new version" prompt. +class Ui { + toast = $state(null); + updateReady = $state(false); + private timer: ReturnType | undefined; + + show(msg: string, ms = 2500) { + this.toast = msg; + clearTimeout(this.timer); + this.timer = setTimeout(() => (this.toast = null), ms); + } +} + +export const ui = new Ui(); diff --git a/apps/web/src/main.ts b/apps/web/src/main.ts new file mode 100644 index 0000000..51832e8 --- /dev/null +++ b/apps/web/src/main.ts @@ -0,0 +1,25 @@ +import { mount } from 'svelte'; +import App from './App.svelte'; +import './app.css'; +import { kvSet } from './lib/idb.ts'; +import { settings } from './lib/settings.svelte.ts'; +import { ui } from './lib/ui.svelte.ts'; + +settings.applyTheme(); +document.documentElement.lang = settings.lang; +void kvSet('lang', settings.lang).catch(() => {}); +matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => settings.applyTheme()); + +if ('serviceWorker' in navigator && import.meta.env.PROD) { + void navigator.serviceWorker.register('/sw.js').then((reg) => { + reg.addEventListener('updatefound', () => { + const sw = reg.installing; + sw?.addEventListener('statechange', () => { + // A new version installed while an old one controls the page. + if (sw.state === 'installed' && navigator.serviceWorker.controller) ui.updateReady = true; + }); + }); + }); +} + +mount(App, { target: document.getElementById('app')! }); diff --git a/apps/web/src/sw.ts b/apps/web/src/sw.ts new file mode 100644 index 0000000..f5c4b9b --- /dev/null +++ b/apps/web/src/sw.ts @@ -0,0 +1,117 @@ +/// +// Service worker: offline app shell + push notifications (SPEC.md §7.7, §10.1). +// A push only says "group X changed"; this worker fetches the new events, +// decrypts them on the device and writes the notification text itself. +import { exponent, logOrder, replay, type GroupEvent } from '@oweme/core'; +import { deriveKeys } from './lib/crypto.ts'; +import { translate, type Lang } from './lib/i18n.ts'; +import { deviceId, get, getAll, groupRange, kvGet, putEvents, updateGroup, type LocalGroup, type StoredEvent } from './lib/idb.ts'; +import { decryptEvent } from './lib/events.ts'; + +declare const __PRECACHE__: string[]; +declare const __VERSION__: string; +const sw = self as unknown as ServiceWorkerGlobalScope; +const CACHE = `oweme-${__VERSION__}`; + +sw.addEventListener('install', (e) => { + e.waitUntil(caches.open(CACHE).then((c) => c.addAll(__PRECACHE__)).then(() => sw.skipWaiting())); +}); + +sw.addEventListener('activate', (e) => { + e.waitUntil( + caches.keys() + .then((keys) => Promise.all(keys.filter((k) => k.startsWith('oweme-') && k !== CACHE).map((k) => caches.delete(k)))) + .then(() => sw.clients.claim()), + ); +}); + +sw.addEventListener('fetch', (e) => { + const url = new URL(e.request.url); + if (e.request.method !== 'GET' || url.origin !== location.origin || url.pathname.startsWith('/api/')) return; + if (e.request.mode === 'navigate') { + // Network first so deploys show up; the cached shell when offline. + e.respondWith(fetch(e.request).catch(async () => (await caches.match('/index.html')) ?? Response.error())); + return; + } + e.respondWith(caches.match(e.request).then((hit) => hit ?? fetch(e.request))); +}); + +function fmtMoney(minor: number, currency: string, locale: string): string { + const e = exponent(currency); + try { + return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: e, maximumFractionDigits: e }).format(minor / 10 ** e); + } catch { + return `${(minor / 10 ** e).toFixed(e)} ${currency}`; + } +} + +async function handlePush(groupId: string): Promise { + const lang: Lang = (await kvGet('lang')) ?? 'en'; + const locale = lang === 'cs' ? 'cs-CZ' : 'en'; + const tr = (k: Parameters[1], v?: Record) => translate(lang, k, v); + const group = await get('groups', groupId); + const fallback = () => sw.registration.showNotification('OweMe', { body: tr('notif_new_activity', { n: 1 }), tag: groupId, icon: '/icon-192.png' }); + if (!group) return fallback(); + + const keys = await deriveKeys(group.secret); + let lastSeq = group.lastSeq; + try { + for (;;) { + const res = await fetch(`/api/groups/${groupId}/events?after=${lastSeq}&limit=500`, { headers: { Authorization: `Bearer ${keys.authToken}` } }); + if (!res.ok) break; + const { events, latest } = (await res.json()) as { events: Omit[]; latest: number }; + if (!events.length) break; + await putEvents(events.map((e) => ({ ...e, g: groupId }))); + lastSeq = events[events.length - 1].seq; + if (lastSeq >= latest) break; + } + await updateGroup(groupId, { lastSeq }); + } catch { /* offline: notify with what we have */ } + + const stored = await getAll('events', groupRange(groupId)); + const all = (await Promise.all(stored.map((e) => decryptEvent(keys, groupId, e)))).filter((e): e is GroupEvent => !!e); + const { state, activity } = replay(logOrder(all, [])); + const me = await deviceId(); + const fresh = activity.filter((a) => !a.ignored && (a.seq ?? 0) > group.notifiedSeq && all.find((e) => e.id === a.eventId)?.deviceId !== me); + await updateGroup(groupId, { notifiedSeq: lastSeq }); + + // Skip if the user is looking at this group right now. + const windows = await sw.clients.matchAll({ type: 'window' }); + if (windows.some((w) => w.focused && w.visibilityState === 'visible' && new URL(w.url).pathname.startsWith(`/g/${groupId}`))) return; + if (!fresh.length && group.notifiedSeq >= lastSeq) return fallback(); + + const name = (id: string | null) => state.members.find((m) => m.id === id)?.name ?? tr('someone'); + const lines = fresh.slice(-4).map((a) => { + const ev = all.find((e) => e.id === a.eventId)!; + if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'expense') + return `${name(ev.actor)}: ${ev.data.title} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`; + if ((ev.type === 'expense.created' || ev.type === 'expense.updated') && ev.data.kind === 'transfer') + return `${name(ev.data.payers[0]?.member ?? null)} → ${name(ev.data.split.entries[0]?.member ?? null)} · ${fmtMoney(ev.data.amount, ev.data.currency, locale)}`; + if (ev.type === 'comment.added') return `${name(ev.actor)}: “${ev.data.text.slice(0, 80)}”`; + return `${name(ev.actor)}: ${tr('notif_new_activity', { n: 1 })}`; + }); + const body = fresh.length > 4 ? [tr('notif_new_activity', { n: fresh.length }), ...lines].join('\n') : lines.join('\n') || tr('notif_new_activity', { n: 1 }); + await sw.registration.showNotification(`${state.group?.icon ?? ''} ${state.group?.name ?? 'OweMe'}`.trim(), { + body, tag: groupId, icon: '/icon-192.png', badge: '/badge-96.png', data: { url: `/g/${groupId}` }, + }); +} + +sw.addEventListener('push', (e) => { + let groupId = ''; + try { + groupId = (e.data?.json() as { g?: string })?.g ?? ''; + } catch { /* empty payload */ } + e.waitUntil(handlePush(groupId).catch(() => sw.registration.showNotification('OweMe', { tag: groupId || 'oweme' }))); +}); + +sw.addEventListener('notificationclick', (e) => { + e.notification.close(); + const url = (e.notification.data as { url?: string } | null)?.url ?? '/'; + e.waitUntil( + sw.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((list) => { + const existing = list.find((c) => new URL(c.url).origin === location.origin); + if (existing) return existing.focus().then((c) => c.navigate(url)); + return sw.clients.openWindow(url); + }), + ); +}); diff --git a/apps/web/svelte.config.js b/apps/web/svelte.config.js new file mode 100644 index 0000000..ff8b4c5 --- /dev/null +++ b/apps/web/svelte.config.js @@ -0,0 +1 @@ +export default {}; diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json new file mode 100644 index 0000000..5b83bb5 --- /dev/null +++ b/apps/web/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"], + "types": ["svelte", "vite/client"], + "strict": true, + "noEmit": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "isolatedModules": true, + "skipLibCheck": true + }, + "include": ["src/**/*.ts", "src/**/*.svelte"] +} diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts new file mode 100644 index 0000000..23c78fa --- /dev/null +++ b/apps/web/vite.config.ts @@ -0,0 +1,15 @@ +import { svelte } from '@sveltejs/vite-plugin-svelte'; +import { defineConfig } from 'vite'; + +// Dev: the client on 127.0.0.1:8480, proxying /api to the server on 8481. +// Preview from your machine with: ssh -p 14922 -L 8480:localhost:8480 +export default defineConfig({ + plugins: [svelte()], + server: { + host: '127.0.0.1', + port: 8480, + strictPort: true, + proxy: { '/api': 'http://127.0.0.1:8481' }, + }, + build: { target: 'es2022', sourcemap: false }, +}); diff --git a/apps/web/vite.sw.config.ts b/apps/web/vite.sw.config.ts new file mode 100644 index 0000000..17bf91c --- /dev/null +++ b/apps/web/vite.sw.config.ts @@ -0,0 +1,35 @@ +// Second build step: the service worker, as one classic script at /sw.js +// (module service workers aren't supported everywhere yet). It precaches +// whatever the first step put in dist/, so this must run after it. +import { createHash } from 'node:crypto'; +import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, relative } from 'node:path'; +import { defineConfig } from 'vite'; + +const dist = join(import.meta.dirname, 'dist'); + +function listFiles(dir: string): string[] { + return readdirSync(dir).flatMap((f) => { + const p = join(dir, f); + return statSync(p).isDirectory() ? listFiles(p) : [p]; + }); +} + +const files = listFiles(dist) + .map((p) => '/' + relative(dist, p).split('\\').join('/')) + .filter((p) => p !== '/sw.js' && !p.endsWith('.map')); +const hash = createHash('sha256'); +for (const f of files.sort()) hash.update(f).update(readFileSync(join(dist, f))); + +export default defineConfig({ + define: { + __PRECACHE__: JSON.stringify(files), + __VERSION__: JSON.stringify(hash.digest('hex').slice(0, 12)), + }, + build: { + outDir: 'dist', + emptyOutDir: false, + target: 'es2022', + lib: { entry: 'src/sw.ts', formats: ['iife'], name: 'sw', fileName: () => 'sw.js' }, + }, +}); diff --git a/package-lock.json b/package-lock.json index a6ace43..c789849 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,119 @@ "node": ">=24" } }, + "apps/web": { + "name": "@oweme/web", + "dependencies": { + "@oweme/core": "*", + "uqr": "0.1.3" + }, + "devDependencies": { + "@sveltejs/vite-plugin-svelte": "7.3.1", + "svelte": "5.57.1", + "svelte-check": "4.7.6", + "vite": "8.3.1" + } + }, + "apps/web/node_modules/vite": { + "version": "8.3.1", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz", + "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.28", + "rolldown": "~1.2.9", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -51,13 +164,16 @@ "resolved": "packages/core", "link": true }, + "node_modules/@oweme/web": { + "resolved": "apps/web", + "link": true + }, "node_modules/@oxc-project/types": { "version": "0.153.0", "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/oxc-project" } @@ -91,7 +207,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -109,7 +224,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -127,7 +241,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -145,7 +258,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -163,7 +275,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -181,7 +292,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -202,7 +312,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -223,7 +332,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -244,7 +352,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -265,7 +372,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -286,7 +392,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -307,7 +412,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -325,7 +429,6 @@ "os": [ "openharmony" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -343,7 +446,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -361,7 +463,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -371,8 +472,47 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, + "license": "MIT" + }, + "node_modules/@sveltejs/acorn-typescript": { + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@sveltejs/acorn-typescript/-/acorn-typescript-1.0.13.tgz", + "integrity": "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ==", + "dev": true, "license": "MIT", - "peer": true + "peerDependencies": { + "acorn": "^8.9.0" + } + }, + "node_modules/@sveltejs/load-config": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@sveltejs/load-config/-/load-config-0.2.3.tgz", + "integrity": "sha512-VT3qmUb8pRV2QrZjd8iAmtg8lf4W0TIjZbvXtz5MKei/q96teWZgGJyyidJzOjzZzvdq616eSRVeMYIQChUTAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 18.0.0" + } + }, + "node_modules/@sveltejs/vite-plugin-svelte": { + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/@sveltejs/vite-plugin-svelte/-/vite-plugin-svelte-7.3.1.tgz", + "integrity": "sha512-ZPsLN8B1e/En+Ak5s4V7srFDT532oS0qieLsQwu63NGKsS+iAjoO2Js1BochlHlglcU+Pt7WAO3C5Ee+4f6gVA==", + "dev": true, + "license": "MIT", + "dependencies": { + "deepmerge": "^4.3.1", + "magic-string": "^1.0.0", + "obug": "^2.1.0", + "vitefu": "^1.1.2" + }, + "engines": { + "node": "^20.19 || ^22.12 || >=24" + }, + "peerDependencies": { + "svelte": "^5.46.4", + "vite": "^8.0.0-beta.7 || ^8.0.0" + } }, "node_modules/@types/chai": { "version": "5.2.3", @@ -447,6 +587,29 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/acorn": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.19.0.tgz", + "integrity": "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/aria-query": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.1.tgz", + "integrity": "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -457,6 +620,16 @@ "node": ">=12" } }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/chai": { "version": "6.3.0", "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", @@ -467,17 +640,59 @@ "node": ">=18" } }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz", + "integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, "license": "Apache-2.0", - "peer": true, "engines": { "node": ">=8" } }, + "node_modules/devalue": { + "version": "5.9.4", + "resolved": "https://registry.npmjs.org/devalue/-/devalue-5.9.4.tgz", + "integrity": "sha512-sPAT4pztbu6586/hrhOnMKS17IJrvg12mXiSPSS3W5qDeN2RGgvZ0diZCm31dBbnevfVmujNO3IM2wrS4Y2Rhg==", + "dev": true, + "license": "MIT" + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -485,6 +700,31 @@ "dev": true, "license": "MIT" }, + "node_modules/esm-env": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/esm-env/-/esm-env-1.2.2.tgz", + "integrity": "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/esrap": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/esrap/-/esrap-2.4.0.tgz", + "integrity": "sha512-CQPcneEHw/czj32uwQC52nYnax8H4SXt25FCM+LIwGZ49cMIxpOj3bP8wmzcI+Z0HIy5KkClaPhRLfCySzwHPA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.4.15" + }, + "peerDependencies": { + "@typescript-eslint/types": "^8.2.0" + }, + "peerDependenciesMeta": { + "@typescript-eslint/types": { + "optional": true + } + } + }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -534,18 +774,26 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/is-reference": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/is-reference/-/is-reference-3.0.3.tgz", + "integrity": "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.6" + } + }, "node_modules/lightningcss": { "version": "1.33.0", "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", - "peer": true, "dependencies": { "detect-libc": "^2.0.3" }, @@ -583,7 +831,6 @@ "os": [ "android" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -605,7 +852,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -627,7 +873,6 @@ "os": [ "darwin" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -649,7 +894,6 @@ "os": [ "freebsd" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -671,7 +915,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -696,7 +939,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -721,7 +963,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -746,7 +987,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -771,7 +1011,6 @@ "os": [ "linux" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -793,7 +1032,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -815,7 +1053,6 @@ "os": [ "win32" ], - "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -824,6 +1061,13 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/locate-character": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/locate-character/-/locate-character-3.0.0.tgz", + "integrity": "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA==", + "dev": true, + "license": "MIT" + }, "node_modules/magic-string": { "version": "1.4.3", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz", @@ -834,6 +1078,16 @@ "@jridgewell/sourcemap-codec": "^1.6.0" } }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, "node_modules/nanoid": { "version": "3.3.20", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", @@ -846,7 +1100,6 @@ } ], "license": "MIT", - "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -873,8 +1126,7 @@ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "dev": true, - "license": "ISC", - "peer": true + "license": "ISC" }, "node_modules/picomatch": { "version": "4.0.7", @@ -938,7 +1190,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.19", "picocolors": "^1.1.1", @@ -948,13 +1199,26 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/rolldown": { "version": "1.2.13", "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@oxc-project/types": "=0.153.0", "@rolldown/pluginutils": "^1.0.0" @@ -983,13 +1247,25 @@ "@rolldown/binding-win32-x64-msvc": "1.2.13" } }, + "node_modules/sade": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/sade/-/sade-1.8.1.tgz", + "integrity": "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "mri": "^1.1.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, "license": "BSD-3-Clause", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -1001,6 +1277,68 @@ "dev": true, "license": "MIT" }, + "node_modules/svelte": { + "version": "5.57.1", + "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.57.1.tgz", + "integrity": "sha512-Uqj49lWKB+iSSnneuwiYYJ7MZgkB+eXr0LXBhv4uDuAkXqnWmq65Sxflfvp0Lc6MdKjMUxGaeOKWJqz5SNiVIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "@jridgewell/sourcemap-codec": "^1.6.0", + "@sveltejs/acorn-typescript": "^1.0.13", + "@types/estree": "^1.0.9", + "acorn": "^8.18.0", + "aria-query": "5.3.1", + "axobject-query": "^4.1.0", + "clsx": "^2.1.1", + "devalue": "^5.9.2", + "esm-env": "^1.2.1", + "esrap": "^2.3.6", + "is-reference": "^3.0.3", + "locate-character": "^3.0.0", + "magic-string": "^0.30.11", + "zimmerframe": "^1.1.2" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/svelte-check": { + "version": "4.7.6", + "resolved": "https://registry.npmjs.org/svelte-check/-/svelte-check-4.7.6.tgz", + "integrity": "sha512-t2scM//ZuVbSY/T2w6FSBw1v9s2NEmh/g+sy1lqtosW5ylBV5AF4wFb1Ts9Kf3MbfPDUDJDZ9L436YT0SPTdvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.25", + "@sveltejs/load-config": "^0.2.3", + "chokidar": "^4.0.1", + "fdir": "^6.2.0", + "picocolors": "^1.0.0", + "sade": "^1.7.4" + }, + "bin": { + "svelte-check": "bin/svelte-check" + }, + "engines": { + "node": ">= 18.0.0" + }, + "peerDependencies": { + "svelte": "^4.0.0 || ^5.0.0-next.0", + "typescript": "^5.0.0 || ^6.0.0" + } + }, + "node_modules/svelte/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/tinybench": { "version": "6.2.1", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.1.tgz", @@ -1059,6 +1397,12 @@ "dev": true, "license": "MIT" }, + "node_modules/uqr": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz", + "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==", + "license": "MIT" + }, "node_modules/vite": { "version": "8.3.4", "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", @@ -1138,6 +1482,26 @@ } } }, + "node_modules/vitefu": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/vitefu/-/vitefu-1.1.3.tgz", + "integrity": "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg==", + "dev": true, + "license": "MIT", + "workspaces": [ + "tests/deps/*", + "tests/projects/*", + "tests/projects/workspace/packages/*" + ], + "peerDependencies": { + "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "vite": { + "optional": true + } + } + }, "node_modules/vitest": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.2.tgz", @@ -1234,6 +1598,13 @@ "node": ">=20.11" } }, + "node_modules/zimmerframe": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/zimmerframe/-/zimmerframe-1.1.5.tgz", + "integrity": "sha512-msJxIvYDYcoNL+PJsu+7qmpDWsYmAxTY+2TNYXXF0hzBzBk0BMecOqDOG/EckUoKCuKwObfbugIl8QpqHDXeFA==", + "dev": true, + "license": "MIT" + }, "packages/core": { "name": "@oweme/core" } diff --git a/scripts/render-icons.mjs b/scripts/render-icons.mjs new file mode 100644 index 0000000..eaebbb0 --- /dev/null +++ b/scripts/render-icons.mjs @@ -0,0 +1,29 @@ +// Render the PNG app icons from apps/web/public/icon.svg with headless +// Chromium (Playwright). Run after changing the SVG: node scripts/render-icons.mjs +import { chromium } from '@playwright/test'; +import { readFileSync } from 'node:fs'; + +const dir = new URL('../apps/web/public/', import.meta.url); +const svg = readFileSync(new URL('icon.svg', dir), 'utf8'); +const b64 = Buffer.from(svg).toString('base64'); +// Maskable: full-bleed background, artwork inside the 80% safe zone. +const maskable = ``; +// Badge: white glyph on transparent (Android tints it). +const badge = svg.replace(/]*\/>/, '').replaceAll('#3DDC97', '#FFFFFF'); + +const jobs = [ + ['icon-192.png', svg, 192], + ['icon-512.png', svg, 512], + ['icon-maskable-512.png', maskable, 512], + ['badge-96.png', badge, 96], +]; + +const browser = await chromium.launch(); +const page = await browser.newPage(); +for (const [name, src, size] of jobs) { + await page.setViewportSize({ width: size, height: size }); + await page.setContent(`${src}`); + await page.screenshot({ path: new URL(name, dir).pathname, omitBackground: true }); +} +await browser.close(); +console.log('icons written'); From a78d85588645b4cbc3df436959056ce8cfb64b05 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:59:16 +0000 Subject: [PATCH 05/18] Add Playwright end-to-end tests Two devices (EN + CS) sharing a group through sync, photos, rates, rewind, offline and settle-up; plus push delivery to the service worker via CDP. Can target a running deployment with E2E_BASE_URL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- e2e/app.spec.ts | 145 +++++++++++++++++++++++++++++++++++++++++++ e2e/push.spec.ts | 49 +++++++++++++++ playwright.config.ts | 27 ++++++++ 3 files changed, 221 insertions(+) create mode 100644 e2e/app.spec.ts create mode 100644 e2e/push.spec.ts create mode 100644 playwright.config.ts diff --git a/e2e/app.spec.ts b/e2e/app.spec.ts new file mode 100644 index 0000000..c4f5758 --- /dev/null +++ b/e2e/app.spec.ts @@ -0,0 +1,145 @@ +import { expect, test, type Browser, type Page } from '@playwright/test'; +import { deflateSync } from 'node:zlib'; + +/** A small valid PNG (solid colour), for the photo upload. */ +function png(w = 64, h = 48): Buffer { + const crcTable = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; + }); + const crc = (b: Buffer) => { let c = 0xffffffff; for (const x of b) c = crcTable[(c ^ x) & 0xff] ^ (c >>> 8); return (c ^ 0xffffffff) >>> 0; }; + const chunk = (type: string, data: Buffer) => { + const len = Buffer.alloc(4); len.writeUInt32BE(data.length); + const td = Buffer.concat([Buffer.from(type), data]); + const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); + return Buffer.concat([len, td, c]); + }; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2; + const raw = Buffer.alloc((w * 3 + 1) * h); + for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([61, 220, 151], y * (w * 3 + 1) + 1 + x * 3); + return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} + +async function device(browser: Browser, locale: string): Promise { + const ctx = await browser.newContext({ locale, viewport: { width: 412, height: 915 }, isMobile: true, hasTouch: true }); + await ctx.grantPermissions(['clipboard-read', 'clipboard-write']); + return ctx.newPage(); +} + +test('two devices share a group end to end', async ({ browser }) => { + // ---- Anna creates a group (English device) -------------------------- + const anna = await device(browser, 'en-US'); + await anna.goto('/'); + await expect(anna.getByText('No groups on this device yet')).toBeVisible(); + await anna.getByRole('link', { name: 'New group' }).click(); + await anna.getByLabel('Group name').fill('Prague trip'); + await anna.getByLabel('Main currency').selectOption('CZK'); + await anna.getByLabel('Your name').fill('Anna'); + await anna.getByPlaceholder('Name').fill('Petr'); + await anna.getByRole('button', { name: 'Add member' }).click(); + await anna.getByPlaceholder('Name').nth(1).fill('Jana'); + await anna.getByRole('button', { name: 'Create group' }).click(); + + // Lands on settings with the "save this link" warning; copy the link. + await expect(anna.getByText('Save this link somewhere safe')).toBeVisible(); + await anna.getByRole('button', { name: 'Copy link' }).click(); + const link = await anna.evaluate(() => navigator.clipboard.readText()); + expect(link).toMatch(/\/g\/[A-Za-z0-9_-]{22}#[A-Za-z0-9_-]{43}$/); + await anna.getByRole('button', { name: 'Back', exact: true }).click(); + + // ---- An equal split in the base currency ---------------------------- + await anna.getByRole('link', { name: 'Add expense' }).click(); + await anna.getByLabel('Amount').fill('300'); + await anna.getByLabel('What was it for?').fill('Dinner'); + await anna.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(anna.getByRole('link', { name: /Dinner/ })).toBeVisible(); + await expect(anna.getByText('you lent CZK 200.00')).toBeVisible(); + + // ---- Petr opens the link on a Czech device -------------------------- + const petr = await device(browser, 'cs-CZ'); + await petr.goto(link); + await expect(petr.getByRole('heading', { name: 'Kdo jste?' })).toBeVisible(); + // The secret is dropped from the address bar once saved. + expect(new URL(petr.url()).hash).toBe(''); + await petr.getByRole('button', { name: 'Petr' }).click(); + await expect(petr.getByRole('link', { name: /Dinner/ })).toBeVisible(); + await expect(petr.getByText(/dlužíte 100,00\sKč/)).toBeVisible(); + + // ---- Petr adds a EUR expense with exact amounts and a photo ---------- + await petr.getByRole('link', { name: 'Přidat výdaj' }).click(); + await petr.getByLabel('Částka').fill('30'); + await petr.getByLabel('Měna').selectOption('EUR'); + // The ECB rate is prefilled by our server. + await expect(petr.getByText(/Kurz ECB ze dne/)).toBeVisible({ timeout: 30_000 }); + const rate = Number((await petr.getByLabel('1 EUR =').inputValue()).replace(',', '.')); + expect(rate).toBeGreaterThan(15); + expect(rate).toBeLessThan(40); + await petr.getByLabel('Za co?').fill('Museum'); + await petr.getByRole('button', { name: 'Částky' }).click(); + await petr.getByLabel('Rozdělení: Anna').fill('10'); + await petr.getByLabel('Rozdělení: Petr').fill('20'); + await petr.getByLabel('Jana', { exact: true }).uncheck(); + await petr.locator('input[type=file]').setInputFiles({ name: 'receipt.png', mimeType: 'image/png', buffer: png() }); + await expect(petr.getByRole('img', { name: 'Fotka' })).toBeVisible(); + await petr.getByRole('button', { name: 'Uložit' }).click(); + await expect(petr.getByRole('link', { name: /Museum/ })).toBeVisible(); + + // ---- Anna sees it live (SSE), with the photo, without reloading ----- + await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible({ timeout: 15_000 }); + await anna.getByRole('link', { name: /Museum/ }).click(); + await expect(anna.getByText('€30.00').first()).toBeVisible(); + await expect(anna.getByRole('img', { name: 'Photo' })).toBeVisible({ timeout: 15_000 }); + await anna.getByRole('button', { name: 'Close', exact: true }).click(); + + // ---- Balances and settle-up ------------------------------------------ + await anna.getByRole('link', { name: 'Balances' }).click(); + const annaBal = 20000 - Math.round(rate * 1000); // +200 Kč − €10 + const fmt = (minor: number) => (minor / 100).toLocaleString('en-US', { minimumFractionDigits: 2 }); + const shown = `${annaBal > 0 ? '+' : '−'}CZK ${fmt(Math.abs(annaBal))}`; + await expect(anna.getByText(shown).first()).toBeVisible(); + await expect(anna.getByText('Settle up')).toBeVisible(); + const recordButtons = anna.getByRole('button', { name: 'Record payment' }); + const transfers = await recordButtons.count(); + expect(transfers).toBeGreaterThan(0); + expect(transfers).toBeLessThanOrEqual(2); + + // ---- Rewind and undo ------------------------------------------------ + await anna.getByRole('link', { name: 'Activity' }).click(); + await expect(anna.getByText(/Petr added Museum/)).toBeVisible(); + anna.once('dialog', (d) => d.accept()); + // Rewind to just after Dinner was added (the entry below "Museum"). + await anna.getByRole('button', { name: 'Rewind group to here' }).first().click(); + await expect(anna.getByText(/rewound the group/)).toBeVisible(); + await anna.getByRole('link', { name: 'Expenses' }).click(); + await expect(anna.getByRole('link', { name: /Museum/ })).toHaveCount(0); + await anna.getByRole('link', { name: 'Activity' }).click(); + anna.once('dialog', (d) => d.accept()); + await anna.getByRole('button', { name: 'Undo this rewind' }).click(); + await expect(anna.getByText(/rewound the group/)).toHaveCount(2); + await anna.getByRole('link', { name: 'Expenses' }).click(); + await expect(anna.getByRole('link', { name: /Museum/ })).toBeVisible(); + + // ---- Offline edits sync later --------------------------------------- + await anna.context().setOffline(true); + await anna.getByRole('link', { name: 'Add expense' }).click(); + await anna.getByLabel('Amount').fill('90'); + await anna.getByLabel('What was it for?').fill('Taxi'); + await anna.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(anna.getByRole('link', { name: /Taxi/ })).toBeVisible(); + await expect(anna.getByText(/Offline/)).toBeVisible({ timeout: 20_000 }); + await anna.context().setOffline(false); + await expect(petr.getByRole('link', { name: /Taxi/ })).toBeVisible({ timeout: 30_000 }); + + // ---- Home lists the group with my balance after reload -------------- + await anna.goto('/'); + await expect(anna.getByRole('link', { name: /Prague trip/ })).toBeVisible(); + await expect(anna.getByText(/you are owed/)).toBeVisible(); + + // ---- Stats render --------------------------------------------------- + await anna.getByRole('link', { name: /Prague trip/ }).click(); + await anna.getByRole('link', { name: 'Stats' }).click(); + await expect(anna.getByRole('heading', { name: 'By category' })).toBeVisible(); + await expect(anna.getByRole('heading', { name: 'Paid vs. share' })).toBeVisible(); +}); diff --git a/e2e/push.spec.ts b/e2e/push.spec.ts new file mode 100644 index 0000000..0c3c7d2 --- /dev/null +++ b/e2e/push.spec.ts @@ -0,0 +1,49 @@ +import { expect, test } from '@playwright/test'; + +// Delivers a push message straight to the service worker over CDP (no real +// push service involved) and checks that it decrypts the new events and +// shows a readable notification. +// The stripped-down headless shell always denies notifications; full +// Chromium in headless mode supports them. +test.use({ channel: 'chromium' }); + +test('service worker turns a push into a decrypted notification', async ({ browser, baseURL }) => { + const annaCtx = await browser.newContext({ locale: 'en-US' }); + await annaCtx.grantPermissions(['clipboard-read', 'clipboard-write', 'notifications']); + const anna = await annaCtx.newPage(); + await anna.goto('/new'); + await anna.getByLabel('Group name').fill('Flat'); + await anna.getByLabel('Your name').fill('Anna'); + await anna.getByPlaceholder('Name').fill('Petr'); + await anna.getByRole('button', { name: 'Create group' }).click(); + await anna.getByRole('button', { name: 'Copy link' }).click(); + const link = await anna.evaluate(() => navigator.clipboard.readText()); + const groupId = /\/g\/([^#]+)#/.exec(link)![1]; + await anna.evaluate(() => navigator.serviceWorker.ready); + + // Petr adds an expense from another device. + const petr = await (await browser.newContext({ locale: 'en-US' })).newPage(); + await petr.goto(link); + await petr.getByRole('button', { name: 'Petr' }).click(); + await petr.getByRole('link', { name: 'Add expense' }).click(); + await petr.getByLabel('Amount').fill('12.50'); + await petr.getByLabel('What was it for?').fill('Pizza'); + await petr.getByRole('button', { name: 'Save', exact: true }).click(); + await expect(petr.getByRole('link', { name: /Pizza/ })).toBeVisible(); + + // Anna is on the home screen (not looking at the group) when the push arrives. + await anna.goto('/'); + const cdp = await annaCtx.newCDPSession(anna); + const registrationId = await new Promise((resolve) => { + cdp.on('ServiceWorker.workerRegistrationUpdated', ({ registrations }) => { + const r = registrations.find((x: { scopeURL: string; isDeleted: boolean }) => x.scopeURL.startsWith(baseURL!) && !x.isDeleted); + if (r) resolve(r.registrationId); + }); + void cdp.send('ServiceWorker.enable'); + }); + await cdp.send('ServiceWorker.deliverPushMessage', { origin: new URL(baseURL!).origin, registrationId, data: JSON.stringify({ g: groupId }) }); + + await expect + .poll(async () => anna.evaluate(async () => (await (await navigator.serviceWorker.ready).getNotifications()).map((n) => `${n.title} | ${n.body}`)), { timeout: 15_000 }) + .toContainEqual(expect.stringMatching(/Flat \| Petr: Pizza · \S*12\.50/)); +}); diff --git a/playwright.config.ts b/playwright.config.ts new file mode 100644 index 0000000..b9f85e9 --- /dev/null +++ b/playwright.config.ts @@ -0,0 +1,27 @@ +import { defineConfig, devices } from '@playwright/test'; + +// E2E against the production build served by the real server. +// Run `npm run build` first. Uses a throwaway data dir per run. +// Set E2E_BASE_URL to test an already running deployment instead (e.g. the +// compose stack: E2E_BASE_URL=https://localhost:8483). +const external = process.env.E2E_BASE_URL; +const port = 8490; +const dataDir = `${process.env.TMPDIR ?? '/tmp'}/oweme-e2e-${Date.now()}`; + +export default defineConfig({ + testDir: 'e2e', + timeout: 90_000, + fullyParallel: false, + workers: 1, + reporter: [['list']], + use: { baseURL: external ?? `http://127.0.0.1:${port}`, ignoreHTTPSErrors: !!external, trace: 'retain-on-failure' }, + projects: [ + { name: 'mobile-chromium', use: { ...devices['Pixel 7'] } }, + ], + webServer: external ? undefined : { + command: 'node --disable-warning=ExperimentalWarning apps/server/src/main.ts', + url: `http://127.0.0.1:${port}/api/health`, + reuseExistingServer: false, + env: { PORT: String(port), DATA_DIR: dataDir, STATIC_DIR: 'apps/web/dist', GROUP_CREATE_PER_HOUR: '100' }, + }, +}); From 8c4e37ce4bfc59f641a3a79a71a9d8e3bdc51cf1 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 19:59:17 +0000 Subject: [PATCH 06/18] Add podman compose deployment, dev script and docs Containerfile + compose (app + Caddy with automatic HTTPS), env-driven domain/limits/ports, VAPID key generation that never prints the key. SPEC updated to match the implementation (Node stdlib server, Svelte SPA, revert by event id, backup contents, push options). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_013FYo6JSV1fDU1fm3LU77iF --- AGENTS.md | 59 ++++++++++++++++++++++++ README.md | 23 +++++++++- SPEC.md | 106 ++++++++++++++++++++++++++----------------- deploy/.env.example | 23 ++++++++++ deploy/Caddyfile | 10 ++++ deploy/Containerfile | 29 ++++++++++++ deploy/README.md | 92 +++++++++++++++++++++++++++++++++++++ deploy/compose.yaml | 49 ++++++++++++++++++++ scripts/dev.mjs | 16 +++++++ 9 files changed, 365 insertions(+), 42 deletions(-) create mode 100644 AGENTS.md create mode 100644 deploy/.env.example create mode 100644 deploy/Caddyfile create mode 100644 deploy/Containerfile create mode 100644 deploy/README.md create mode 100644 deploy/compose.yaml create mode 100644 scripts/dev.mjs diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..1ea0527 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,59 @@ +# AGENTS.md — OweMe + +End-to-end encrypted group expense splitter (a Settle Up clone). Read +`SPEC.md` first; it is the source of truth for behaviour and is kept current. + +## Layout +- `packages/core/` — pure TypeScript shared by client and service worker: + event schema, validation, money math, replay/rewind, settle-up, recurring, + stats, CSV. **No I/O, no floats for money.** +- `apps/server/` — Node 24, **standard library only** (`node:http`, + `node:sqlite`, `node:crypto`), run directly as TypeScript (type stripping: + erasable syntax only, `.ts` import extensions). No npm dependencies; keep it + that way unless there's a strong reason. +- `apps/web/` — Svelte 5 SPA + service worker (`src/sw.ts`, built separately + by `vite.sw.config.ts` as a classic script). +- `deploy/` — Containerfile, compose.yaml, Caddyfile, `.env.example`, deploy docs. +- `e2e/` — Playwright tests against the production build. + +## Run +Node lives at `~/.local/node/bin` on the dev box (not on PATH by default). + +```sh +npm ci +npm run dev # API 127.0.0.1:8481 + Vite 127.0.0.1:8480 +``` +Preview from your machine: `ssh -p 14922 -L 8480:localhost:8480 `, +then http://localhost:8480. + +## Test +```sh +npm test # core (vitest) + server (node:test) +npm run check # tsc + svelte-check (must be 0 errors, 0 warnings) +npm run build && npm run test:e2e +``` +E2E uses the Playwright browsers cached in `~/.cache/ms-playwright` +(`@playwright/test` is pinned to 1.63.0 to match them). `e2e/push.spec.ts` +needs full Chromium (`channel: 'chromium'`): the headless shell denies +notifications. + +## Invariants — do not break +1. **The server never sees plaintext or keys.** The group secret exists only + in the URL fragment, IndexedDB and backup files. Never send it in a path, + query string, header or log line. The server stores `SHA-256(authToken)`. +2. **Every client computes identical balances.** Money is integer minor units; + rates are decimal strings; rounding is largest-remainder with ties to + member order, conversion is round-half-even (BigInt). Any change to money + math needs a test in `packages/core/test/`. +3. **The event log is append-only.** Undo is a new event (`revert`, + `expense.restored`, …), never a deletion. Replay must ignore invalid + events (`validateExpense`), not crash. +4. **New event types** go in `types.ts` (`EventBody`), `replay.ts` (with + validation), the activity text in `Activity.svelte` and both locale files. +5. **i18n:** every string in `locales/en.ts` and `locales/cs.ts` (the type + enforces it). English is the default; Czech only if the browser prefers it. +6. **Push endpoints** are restricted to the allowlist in `push.ts` (no SSRF). + Push payloads carry only the group id. +7. Strict CSP: no inline scripts, no third-party origins. +8. Containers: rootless Podman; for local testing publish to `127.0.0.1` only + (`BIND_ADDR=127.0.0.1` in `deploy/.env`). diff --git a/README.md b/README.md index b27f8da..b0038dd 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,24 @@ # OweMe -End-to-end encrypted, mobile-first group expense splitter. See [SPEC.md](SPEC.md). +Split group expenses with friends: a mobile-first, **end-to-end encrypted** +Settle Up clone that runs in any browser and installs as an app. + +- Groups you open via a link; the key travels in the `#fragment` and never reaches the server +- Equal, shares, exact-amount and percent splits; several payers; any member can be left out +- Multiple currencies with ECB daily rates (stored per expense, editable) +- One receipt photo per expense (resized, location data stripped, encrypted) +- Who-pays-whom settle-up suggestions, with "record payment" +- Full history: restore any version, or rewind the whole group (and undo that) +- Comments, categories, statistics, recurring expenses, CSV export, backup files +- Push notifications that the server can't read +- Works offline; English and Czech; dark and light money-green theme + +See [SPEC.md](SPEC.md) for the design, [deploy/README.md](deploy/README.md) +to run it on a VPS with `podman compose`, and [AGENTS.md](AGENTS.md) for +development. + +```sh +npm ci +npm run dev # http://127.0.0.1:8480 +npm test +``` diff --git a/SPEC.md b/SPEC.md index 2130f2f..4ba86e8 100644 --- a/SPEC.md +++ b/SPEC.md @@ -3,7 +3,7 @@ A mobile-first, end-to-end encrypted group expense splitter (a Settle Up clone) that runs in any browser, on phones and desktops alike. -Status: **v1, agreed** · Last updated: 2026-10-09 +Status: **v1, implemented** · Last updated: 2026-10-09 --- @@ -138,7 +138,7 @@ Decrypted plaintext: | `expense.deleted` / `expense.restored` | expenseId | | `comment.added` / `comment.deleted` | commentId, expenseId, text | | `recurring.created` / `recurring.updated` / `recurring.deleted` | template (see 7.4) | -| `revert` | targetSeq — see 6.2 | +| `revert` | targetId (an event id) — see 6.2 | Updates carry the full new object (not a diff), so the latest event per entity fully defines it. Conflicts resolve **last-writer-wins by server @@ -244,10 +244,12 @@ the minimum in practice, and is easy to reason about. - **Restore an expense**: undelete, or roll it back to a chosen earlier version (emits `expense.updated` / `expense.restored` with the old content). -- **Rewind the whole group to a point in time**: emits a `revert { targetSeq }` - event. Replay treats the state as the state at `targetSeq`, and then applies - later events normally. Nothing is ever erased, so a rewind can itself be - undone (revert to the seq just before the revert). +- **Rewind the whole group to a point in time**: emits a `revert { targetId }` + event naming an earlier event. Replay replaces the state with a snapshot + taken right after that event, then applies later events normally. Nothing + is ever erased, so a rewind can itself be undone (revert to the event just + before the revert). Event ids rather than seqs are used so a restored + backup, which gets new seqs, keeps working. - The log is append-only on the server; there is no destructive delete API for events (only deleting the entire group, see 8.3). @@ -293,8 +295,9 @@ Transfers have their own implicit category. - There is no server-side worker (the server cannot read templates). When any member's client opens the group and a due occurrence is missing, it creates it. The occurrence's expense ID is derived deterministically - (`UUIDv5(templateId + occurrenceDate)`), so two clients doing it at once - produce the same ID and replay deduplicates it. + (`rec--`), so two clients doing it at once + produce the same ID; `expense.created` is first-wins on replay, so the + duplicate is ignored. Deleted occurrences are not recreated. - Occurrences are normal expenses (editable/deletable individually). ### 7.5 Statistics @@ -310,17 +313,27 @@ Client-side charts per group, filterable by date range: - **CSV export** of expenses (one row per expense, columns per member share) and of current balances. -- **Encrypted backup**: full event log + photos as one file, encrypted with - the group key. Restoring it recreates the group on the same or a new server. +- **Backup file** (JSON): the encrypted event log and photos exactly as the + server stores them, **plus the group secret**, so a group can be restored + even if every link is lost. The file is therefore as sensitive as the link, + and the UI says so. Restoring creates the group on the server (or finds it + already there) and re-uploads everything; uploads are idempotent by id, so + an interrupted restore can simply be run again. ### 7.7 Push notifications - Opt-in per group per device (Web Push, VAPID). - Because the server cannot read events, the push it sends **contains no - content**, just `{ groupId }`. The service worker wakes, fetches new events, - decrypts them locally and shows "Anna added Dinner · 120.50 EUR". + content**, just `{ g: groupId }` (itself encrypted to the browser per + RFC 8291). The service worker wakes, fetches new events, decrypts them + locally and shows "Anna: Dinner · 120.50 EUR". It stays quiet if that + group is open and focused. - The server skips the device that created the event (`deviceId`). -- Notification options: all activity / only expenses involving me. +- On/off per group only. An "only expenses involving me" option was dropped: + browsers require every push to show a notification, so the worker can't + silently discard irrelevant ones. +- The server only delivers to known push services (FCM, Mozilla, Apple, + Windows), so a registered endpoint can't make it call arbitrary hosts. - iOS: works only when the app is installed to the home screen (iOS 16.4+); the UI explains this. @@ -345,13 +358,18 @@ All group endpoints require `Authorization: Bearer `. | `POST/DELETE /api/groups/:id/push` | Register/unregister a Web Push subscription. | | `DELETE /api/groups/:id` | Delete group, events and blobs (requires typing the group name client-side as confirmation). | | `GET /api/rates?date=YYYY-MM-DD` | Daily reference rates (no auth). | +| `GET /api/config` | Public settings: VAPID public key, size limits (no auth). | | `GET /api/health` | Health check. | +Unknown groups and wrong tokens both answer `404`, so the API doesn't reveal +which group ids exist. + ### 8.2 Exchange rates -- The server fetches **ECB daily reference rates** (~30 currencies, via - Frankfurter or ECB XML directly) once a day and caches them in SQLite, - including history for back-dated expenses. +- The server fetches **ECB daily reference rates** (~30 currencies, from the + ECB's own XML feed) every 6 hours and caches them in SQLite. The first run + loads the full history (back to 1999) for back-dated expenses; later runs + fetch the last 90 days. - Clients fetch from our server only, so third parties don't learn users' IPs or currency usage. Clients cache rates offline. - Currencies outside the ECB set can be used with a manually entered rate. @@ -364,7 +382,8 @@ All group endpoints require `Authorization: Bearer `. - Limits (env variables, see 13): photo blob ≤ 2 MB (`MAX_PHOTO_BYTES`), event ≤ 64 KB (`MAX_EVENT_BYTES`), per-group storage ≤ 200 MB (`MAX_GROUP_BYTES`), group creation rate limit (`GROUP_CREATE_PER_HOUR`). - The thumbnail counts as part of its photo. + The server enforces the photo limit per uploaded blob; the client keeps a + photo and its thumbnail together under it. - Inactive-group retention: none by default (configurable). --- @@ -461,23 +480,24 @@ Hardening: | Layer | Choice | Why | |---|---|---| -| Frontend | **SvelteKit** (static adapter, SPA) + TypeScript | Small bundles (fast on phones), simple reactivity | -| PWA | Vite PWA plugin (Workbox) | Service worker, offline cache, push handling | -| Local storage | IndexedDB (via `idb`) | Groups, events, blobs cache | -| Charts | Lightweight library (e.g. Chart.js or LayerCake) | Stats tab | -| i18n | `svelte-i18n` or a small typed dictionary | EN/CS | -| Backend | **Bun + Hono** + TypeScript | Tiny, fast, shares types with the frontend | -| DB | SQLite (`bun:sqlite`) | Zero-ops, single file | +| Frontend | **Svelte 5 + Vite** SPA, TypeScript, a ~60-line history router | Small bundle (~65 KB gzipped), simple reactivity; SvelteKit wasn't needed for a static SPA | +| PWA | Hand-written service worker, built as a classic script by a second Vite step | Offline shell, push handling; no Workbox dependency | +| Local storage | IndexedDB (small hand-written wrapper) | Groups, events, outbox, blobs cache; shared with the service worker | +| Charts | Hand-built HTML/CSS bars | Stats tab; no chart library | +| i18n | Small typed dictionary (`locales/en.ts`, `cs.ts`) | EN/CS; the type makes missing translations a compile error | +| Backend | **Node 24, standard library only** (`node:http`, `node:sqlite`, `node:crypto`), run as TypeScript via type stripping | No npm dependencies on the server; Node was already on the dev box (Bun would have meant another runtime) | +| DB | SQLite (`node:sqlite`) | Zero-ops, single file | | Tests | Vitest (money math, replay, crypto), Playwright (E2E on mobile + desktop viewports) | Rounding and replay must be bulletproof | | Proxy/TLS | **Caddy** | Automatic HTTPS (required for WebCrypto, service workers and push) | Repo layout (monorepo): ``` -apps/web SvelteKit client -apps/server Bun + Hono API -packages/core shared: types, event schema, money math, replay, crypto -deploy/ compose.yaml, Caddyfile, .env.example +apps/web Svelte client + service worker +apps/server Node API (no dependencies) +packages/core shared: types, event schema, money math, replay, settle-up, recurring, stats, CSV +deploy/ Containerfile, compose.yaml, Caddyfile, .env.example, README +e2e/ Playwright tests ``` --- @@ -486,7 +506,7 @@ deploy/ compose.yaml, Caddyfile, .env.example `deploy/compose.yaml` runs two services: -- `app`: the Bun server, which also serves the built static client. Listens +- `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). @@ -497,15 +517,15 @@ Deploy steps (documented in `deploy/README.md`): 1. Point a DNS A/AAAA record at the VPS. 2. `cp deploy/.env.example deploy/.env && chmod 600 deploy/.env`, then set - `DOMAIN` (e.g. `oweme.example.com`). `compose.yaml` passes it to both - services as `${DOMAIN}`: Caddy uses it for the site address and - certificate, and the app uses it for share links and the CSP. Generate - VAPID keys with the provided script, which writes them into `.env` without - printing them. + `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`. Updates: `git pull && podman compose up -d --build`. +4. `cd deploy && podman compose up -d`. Updates: `git pull && podman compose up -d --build`. 5. Backups: copy the data volume. All contents are already encrypted, so backups can be stored anywhere. @@ -514,12 +534,14 @@ Environment variables (`deploy/.env`, read by `compose.yaml`): | Variable | Required | Default | Purpose | |---|---|---|---| | `DOMAIN` | yes | — | Public hostname; Caddy site + TLS, share links | -| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | yes | — | Web Push (generated by script) | -| `VAPID_SUBJECT` | yes | — | `mailto:` contact for push services | +| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Web Push (generated by script); empty = notifications off | +| `VAPID_SUBJECT` | for push | — | `mailto:` contact for push services | | `MAX_PHOTO_BYTES` | no | `2097152` | Per-photo upload cap | | `MAX_EVENT_BYTES` | no | `65536` | Per-event cap | | `MAX_GROUP_BYTES` | no | `209715200` | Per-group storage cap | | `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per IP per hour | +| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on | +| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy | Development (on the dev box): servers bind `127.0.0.1` only; preview over an SSH tunnel. Ports and commands go in `AGENTS.md`. @@ -528,12 +550,14 @@ SSH tunnel. Ports and commands go in `AGENTS.md`. ## 14. Milestones +All five milestones below shipped together in the first implementation +(2026-10-09): + 1. **Core**: crypto, event log, sync, groups (link + QR), members, identity, - expenses with all split modes in a single currency, balances, settle-up, - transfers, remembered groups, EN/CS, dark/light theme, PWA + offline, - podman compose deploy. + expenses with all split modes, balances, settle-up, transfers, remembered + groups, EN/CS, dark/light theme, PWA + offline, podman compose deploy. 2. **Money & media**: multiple currencies + rates service, photos. 3. **History**: activity feed, per-expense history, restore, group rewind. 4. **Extras**: comments, categories, statistics, recurring expenses, CSV - export, encrypted backup/restore. + export, backup/restore. 5. **Notifications**: Web Push. diff --git a/deploy/.env.example b/deploy/.env.example new file mode 100644 index 0000000..d40ace4 --- /dev/null +++ b/deploy/.env.example @@ -0,0 +1,23 @@ +# Copy to deploy/.env and `chmod 600 deploy/.env`. Never commit .env. + +# Required: public hostname, with a DNS A/AAAA record pointing at this server. +DOMAIN=oweme.example.com + +# Web Push. Generate the keys with: +# podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env +# (or, with Node 24 installed: node apps/server/src/gen-vapid.ts deploy/.env) +# Leave empty to disable notifications. +VAPID_SUBJECT=mailto:you@example.com +VAPID_PUBLIC_KEY= +VAPID_PRIVATE_KEY= + +# Limits (bytes). Defaults shown. +MAX_PHOTO_BYTES=2097152 +MAX_EVENT_BYTES=65536 +MAX_GROUP_BYTES=209715200 +GROUP_CREATE_PER_HOUR=10 + +# Where Caddy listens. Defaults: all interfaces, ports 80/443. +#BIND_ADDR=0.0.0.0 +#HTTP_PORT=80 +#HTTPS_PORT=443 diff --git a/deploy/Caddyfile b/deploy/Caddyfile new file mode 100644 index 0000000..171291f --- /dev/null +++ b/deploy/Caddyfile @@ -0,0 +1,10 @@ +# Automatic HTTPS for $DOMAIN (Let's Encrypt / ZeroSSL). HTTPS is required: +# WebCrypto, service workers and push only work in a secure context. +# Security headers (CSP etc.) are set by the app itself. +{$DOMAIN} { + encode zstd gzip + reverse_proxy app:8080 { + # Server-Sent Events: don't buffer + flush_interval -1 + } +} diff --git a/deploy/Containerfile b/deploy/Containerfile new file mode 100644 index 0000000..f5d4127 --- /dev/null +++ b/deploy/Containerfile @@ -0,0 +1,29 @@ +# OweMe: one image with the server (Node standard library only, no +# node_modules) and the built web client. Build context: the repo root. + +FROM docker.io/library/node:24.21.0-alpine AS build +WORKDIR /src +COPY package.json package-lock.json ./ +COPY packages/core/package.json packages/core/ +COPY apps/web/package.json apps/web/ +# --ignore-scripts: no install hooks from dependencies run during the build. +RUN npm ci --no-audit --no-fund --ignore-scripts +COPY packages/core packages/core +COPY apps/web apps/web +RUN npm run build -w apps/web + +FROM docker.io/library/node:24.21.0-alpine +WORKDIR /app +ENV NODE_ENV=production \ + HOST=0.0.0.0 \ + PORT=8080 \ + DATA_DIR=/data \ + STATIC_DIR=/app/web \ + TRUST_PROXY=1 +COPY apps/server/src ./server +COPY --from=build /src/apps/web/dist ./web +RUN mkdir -p /data && chown node:node /data +USER node +VOLUME /data +EXPOSE 8080 +CMD ["node", "--disable-warning=ExperimentalWarning", "server/main.ts"] diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..d07d670 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,92 @@ +# Deploying OweMe on a VPS + +Two containers via `podman compose`: **app** (the Node server plus the built +web client) and **caddy** (HTTPS and reverse proxy). Only Caddy publishes ports. + +## Requirements + +- Podman ≥ 4 with `podman compose` (podman-compose or docker-compose as the provider) +- A domain with an A/AAAA record pointing at the VPS +- Ports 80 and 443 (TCP, plus UDP 443 for HTTP/3) open in the firewall + +## First deploy + +```sh +git clone oweme && cd oweme/deploy + +cp .env.example .env +chmod 600 .env +$EDITOR .env # set DOMAIN and VAPID_SUBJECT (mailto:) + +podman compose build # builds localhost/oweme:latest +# Web Push keys: written into .env, private key never printed. +podman run --rm --user root -v ./:/out:Z localhost/oweme:latest node server/gen-vapid.ts /out/.env + +podman compose up -d +podman compose logs -f # Caddy obtains the certificate on first request +``` + +Open `https://$DOMAIN`. `curl https://$DOMAIN/api/health` should say `{"ok":true}`. + +## Updating + +```sh +cd oweme && git pull +cd deploy && podman compose up -d --build +``` + +Data lives in the `oweme-data` volume and survives rebuilds. + +## Configuration (`deploy/.env`) + +| Variable | Required | Default | Purpose | +|---|---|---|---| +| `DOMAIN` | yes | — | Public hostname; Caddy's site address and certificate | +| `VAPID_SUBJECT` | for push | — | `mailto:` contact sent to push services | +| `VAPID_PUBLIC_KEY` / `VAPID_PRIVATE_KEY` | for push | — | Generated by `gen-vapid.ts`; empty = notifications off | +| `MAX_PHOTO_BYTES` | no | `2097152` | Max size of one uploaded (encrypted) photo | +| `MAX_EVENT_BYTES` | no | `65536` | Max size of one encrypted event | +| `MAX_GROUP_BYTES` | no | `209715200` | Storage cap per group (events + photos) | +| `GROUP_CREATE_PER_HOUR` | no | `10` | Group creations per client IP per hour | +| `BIND_ADDR` | no | `0.0.0.0` | Address Caddy's ports are published on | +| `HTTP_PORT` / `HTTPS_PORT` | no | `80` / `443` | Host ports for Caddy | + +Rotating the VAPID keys (`gen-vapid.ts … --force`) silently invalidates every +push subscription; users have to toggle notifications off and on again. + +## Ports (rootless Podman) + +Rootless Podman can't bind ports below 1024 by default. Pick one: + +1. Allow it (simplest): + ```sh + echo 'net.ipv4.ip_unprivileged_port_start=80' | sudo tee /etc/sysctl.d/90-unprivileged-ports.conf + sudo sysctl --system + ``` +2. Or publish high ports (`HTTP_PORT=8080`, `HTTPS_PORT=8443`) and redirect + 80→8080 / 443→8443 in your firewall (e.g. nftables/UFW `nat` rules). + +With rootless Podman, published ports go through `rootlessport` and are +subject to the host firewall. Rootful container networking can add its own +firewall rules around UFW, so don't rely on UFW alone if you run rootful. + +## Backups + +Back up the `oweme-data` volume (SQLite database + encrypted photos): + +```sh +podman volume export oweme_oweme-data > oweme-data-$(date +%F).tar +``` + +Everything in it is already end-to-end encrypted, so the backup can be stored +anywhere. Users can also download per-group backup files in the app. + +## Testing a deployment + +From a machine with the repo and Node 24: + +```sh +npm ci && E2E_BASE_URL=https://$DOMAIN npx playwright test e2e/app.spec.ts +``` + +This creates a throwaway group on that server. diff --git a/deploy/compose.yaml b/deploy/compose.yaml new file mode 100644 index 0000000..c5ccc90 --- /dev/null +++ b/deploy/compose.yaml @@ -0,0 +1,49 @@ +# podman compose up -d --build (run from this directory; reads ./.env) +# See deploy/README.md for the full deploy steps. +name: oweme + +services: + app: + build: + context: .. + dockerfile: deploy/Containerfile + image: localhost/oweme:latest + restart: unless-stopped + env_file: .env + environment: + # fixed inside the container; everything else comes from .env + HOST: 0.0.0.0 + PORT: "8080" + DATA_DIR: /data + STATIC_DIR: /app/web + TRUST_PROXY: "1" + volumes: + - oweme-data:/data + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8080/api/health"] + interval: 30s + timeout: 5s + # no published ports: only Caddy can reach the app + + caddy: + image: docker.io/library/caddy:2.10.2-alpine + restart: unless-stopped + depends_on: + - app + environment: + DOMAIN: ${DOMAIN:?set DOMAIN in deploy/.env} + ports: + # BIND_ADDR defaults to all interfaces (a public VPS). Rootless Podman + # can't bind ports below 1024 by default; see README "Ports". + - "${BIND_ADDR:-0.0.0.0}:${HTTP_PORT:-80}:80" + - "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443" + - "${BIND_ADDR:-0.0.0.0}:${HTTPS_PORT:-443}:443/udp" + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro,Z + - caddy-data:/data + - caddy-config:/config + +volumes: + oweme-data: + caddy-data: + caddy-config: diff --git a/scripts/dev.mjs b/scripts/dev.mjs new file mode 100644 index 0000000..5ea283a --- /dev/null +++ b/scripts/dev.mjs @@ -0,0 +1,16 @@ +// `npm run dev`: API server on 127.0.0.1:8481 (restarts on change) and the +// Vite dev server on 127.0.0.1:8480 (proxies /api). Data goes to ./data. +import { spawn } from 'node:child_process'; + +const procs = [ + spawn(process.execPath, ['--watch', '--disable-warning=ExperimentalWarning', 'apps/server/src/main.ts'], { + stdio: 'inherit', + env: { ...process.env, PORT: '8481', DATA_DIR: process.env.DATA_DIR ?? 'data' }, + }), + spawn('npm', ['run', 'dev', '-w', 'apps/web'], { stdio: 'inherit' }), +]; + +const stop = () => procs.forEach((p) => p.kill('SIGTERM')); +process.on('SIGINT', stop); +process.on('SIGTERM', stop); +for (const p of procs) p.on('exit', (code) => { stop(); process.exitCode = code ?? 0; }); From 1382e533596e0c681751f397209b67113d3b0c25 Mon Sep 17 00:00:00 2001 From: agent Date: Fri, 9 Oct 2026 20:45:28 +0000 Subject: [PATCH 07/18] 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 08/18] 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 09/18] 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 10/18] 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 11/18] 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 12/18] 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 13/18] 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 14/18] 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} +