Files
token-circles/worker
KomediruzeckiandGitHub b58c662a84 fix(retirement): saving a default was indistinguishable from not saving (#411)
* fix(retirement): saving a default was indistinguishable from not saving

Derivation decided "the user has not set this" by comparing the stored value to
the default. Every default is also a perfectly ordinary answer, so anyone who
saved one had it quietly overwritten on the next load. Reported as a monthly
contribution of exactly 500 reverting to a derived 7.29 after a profile switch;
the same hole swallowed a net worth of 0, an income or spending of 0, and a
retirement spend of 2000.

The fix is to stop inferring it. deriveSettings now takes the stored row rather
than a normalised object and asks which keys are present, because normalising
invents a default for every absent key and destroys exactly the distinction the
function turns on. Both loaders return raw rows to match. A key counts as set
when it is present and not null: null is how the client says "no value" for an
optional field such as birthMonth, so it keeps meaning that, while 0 and 500 are
now treated as the answers they are.

Both PUT handlers re-derive and return the provenance with the settings. Saving
is precisely what stops a field being derived, so a client that only took
`settings` back went on crediting "filled in from your data" for figures the
user had just typed.

Field hints move into info tips
------------------------------
The explanations under the controls were block text, so a field that had one was
taller than the field beside it and its control sat out of line — visible as the
date-of-birth picker floating above the net worth box. They are now revealed
from a circled-i beside the label, painted over the page and costing no layout.

The old InfoTip leaned on the native `title` attribute, which is hover-only: on
a phone every explanation in the app was unreachable. The rewrite opens on
hover, on focus, and on tap, pins on click, closes on Escape, outside press or
blur, and follows its icon when the page scrolls. Writing the tests turned up
that Escape closed the panel and the focus it returned reopened it, so Escape
appeared to do nothing.

Withdrawal rate
---------------
The most misread control on the page: a higher rate reads as "more money", when
the spending never changes and only the pot you call sufficient does. It is now
a slider — the number is a trade-off, and dragging it moves the chart and the
runway together — with the number box kept for exact entry, and a tip that says
what the percentage is a percentage of.

A chip under the lifestyle cards turns the rate into the answer people actually
want: retired for as long as you like, or for about eleven years, to around age
46. The cards say when you can stop; nothing said how long stopping then lasts.

Chart markers
-------------
A dashed line at the month each lifestyle becomes affordable, labelled with a
pill in that lifestyle's own colour, on by default. The crossing was in the
cards and the target was on the chart, but nothing showed where the two met.
Drawn as a Chart.js plugin so it redraws with the chart and clips to the plot
area; pills stack when they would overlap and long names are cut with an
ellipsis.

Tests
-----
Every derivable field from both sides, a saved plan stable across reloads, the
save response clearing the provenance, and the round trip at the route level in
the Worker. Mutation-checked: restoring the old sentinel for netWorth, income,
spending, contribution or lifestyles fails a test each. birthMonth is the one
where the two rules genuinely coincide, since null is both its sentinel and its
unset marker.

The layout defect gets a measured guard rather than an eyeball: no field may
carry text below its control, checked across every field in the form, so the
next hint someone adds inline is caught wherever it lands.

InfoTip, RangeField and the marker plugin are at 100% of lines and functions.

* fix(retirement): every profile in browser mode shared one saved plan

Reviewing the branch turned up the third runtime. The settings store in
IndexedDB is keyed by `key` alone — it has no profile column — and the
assumptions were saved under a bare 'retirement_settings'. So one plan served
every profile in the browser: opening a second profile showed the first one's
figures, and saving there overwrote them. Both server runtimes have always
separated profiles through the settings table's (key, profile_id) primary key,
so this was browser mode alone, which is where the demo account runs.

The profile now goes in the key, since the store has nowhere else to put it. A
plan saved under the old bare key is adopted by whichever profile opens the page
first and the old row is removed — leaving it would hand the same plan to every
profile that has not saved one yet, which is the behaviour being fixed.

Eight tests, driven through the local API router against real idb: two profiles
never see each other's plan, a row per profile rather than one overwritten, the
legacy row adopted exactly once, a saved default surviving the round trip, JSON
text as a server backup restores it, an unparseable blob falling back to
defaults, and the projection endpoint scoped too. Reverting the key to its bare
form fails six of them.

Chart options wear the app's switch
-----------------------------------
Three native checkboxes above the chart, in a page that has a branded switch
everywhere else. Toggle grows a compact size for rows of switches that annotate
something rather than being the subject, and an optional label rendered inside
the button — so clicking the words flips it and the text names the control for a
screen reader, which a <label> wrapped round a <button> would not do. The pill
moved into its own span; with no label the wrapper shrinks to the pill and the
control is the same 44x26 box it has always been, which the tests hold.

The info tip's accent hairline spans a panel with rounded corners, so it ran
straight past where the corner curves away and overhung the edge. The panel
clips it.

Also from the review
--------------------
- The legacy backend keys these per profile while the Worker keys on the plain
  name; that reads as an accident but is not. Its settings repository looks rows
  up by key alone with no profile filter, so a shared key there would hand back
  whichever profile's row came first. Said so, at the key.
- Both PUT handlers re-derive and hand back `filled` and `missing`. What is
  stored is the normalised object, so `filled` is empty by construction — but
  `missing` reports what the data cannot answer at all, which a save does not
  change, so the extra read earns its place. The comments now say which is which
  rather than implying both are computed.
- `.field-warn` lost its last user when the withdrawal-rate hint became a chip.
  Deleted.
- Said which lifestyle the runway chip counts from. It is the first, the one the
  cards mark primary, and a single chip has to pick one.

Two more e2e guards on what was reported: the tip panel clips its accent and
stays on screen, and the chart options are switches with markers on by default
whose label text flips them.
2026-08-23 13:33:39 +02:00
..

Finance Manager — Cloudflare Worker + D1

A self-contained Worker (Hono + D1) reimplementing the API off the Apache + SQLite (better-sqlite3) host. Not live yet and intentionally not part of the pnpm workspace, so it doesn't touch the existing backend, lockfile, or CI. Install and run it on its own when you're ready.

The frontend already deploys to Cloudflare ("Workers Builds"), so the API becomes a sibling Worker (e.g. api.<your-domain>) and the whole stack lives on one platform.

Why D1

The app is already SQLite, and D1 is SQLite — so the schema transfers almost verbatim (migrations/0001_init.sql, with the users table adapted for the Worker's auth). The real work was swapping the runtime: better-sqlite3 (sync, native) → D1's async prepare().bind().all()/first()/run(), and Express → Hono.

Layout

worker/
  wrangler.jsonc            Worker config: top-level bindings = local dev; env.dev / env.prod deploys
  package.json              hono + wrangler deps and the d1:* / dev / deploy:{dev,prod} scripts
  migrations/0001_init.sql  D1 schema
  src/index.ts              Hono entry: CORS, /api/health, mounts every route module, error handler
  src/http.ts               HttpError (mapped to JSON by app.onError)
  src/db.ts                 async D1 helpers (all/first/run/insert/update/del) — analog of baseRepo
  src/profile.ts            X-Profile-Id scoping, verified against the JWT user
  src/auth.ts               JWT (HS256) + Google Sign-In + httpOnly cookie session
  src/routes/*.ts           one module per resource (auth, transactions, accounts, …)
  .dev.vars.example         local secrets template

Ported routes (status)

Every module in src/routes/ follows one pattern (requireAuth → getProfileId/ getProfileIds → async D1) and is mounted in index.ts. Data is scoped by the X-Profile-Id header, verified to belong to the authenticated user.

  • Ported (≈all of the app): auth (Google), profiles, transactions (list/filter/ summary/CRUD + bulk + reconcile), accounts (+ balance history), categories (+ mappings, auto-map, apply-mappings), tags (+ transaction tagging), budgets (+ summary/history/ alerts/forecast/zero-based/allocate/…), bills (+ upcoming/summary/calendar/mark-paid), recurring (+ upcoming/populate), savings-goals, loans (+ rates/prepayments/amortization), portfolio (+ live Yahoo prices), housing, retirement-goals (+ projection), counterparties, settings, dashboard, analytics, calculators, and the report DATA/JSON endpoints.
  • PDF reports via pdf-lib (pure JS): monthly, tax-summary, pl-summary, annual.
  • Receipt files in R2 ([[r2_buckets]]): upload is a premium feature (gated by users.plan; free accounts get 402) with type/size + per-profile count limits; serving is owner-scoped. Spreadsheet import via SheetJS (xlsx + csv).
  • Remaining gaps are edge-only: the Google-Sheets xlsx fallback (CSV export covers the common case) and the old stateful /import/file-sheet (replaced by re-uploading with a sheetName field).
  • Status: typechecks, bundles, and boots locally — pnpm run dev serves the full Hono app off a local D1 + R2 (/api/health → {"ok":true}, protected routes 401 without a session). Not yet run against a remote D1/R2 — smoke-test after the first deploy.

Local dev (worker + frontend interplay)

Two processes, both same-origin via the vite proxy — so the SameSite=Lax session cookie works with no CORS and no domain:

cd worker
pnpm install --ignore-workspace    # worker is NOT in the pnpm workspace
cp .dev.vars.example .dev.vars     # fill JWT_SECRET + Google client id/secret (for sign-in)
pnpm run d1:migrate:local          # create + migrate the LOCAL D1 (.wrangler/state)
pnpm run dev                       # worker on http://127.0.0.1:8787 (local D1 + R2)

In a second terminal:

pnpm -C frontend run dev           # vite on http://127.0.0.1:3800, proxies /api -> :8787

Open http://127.0.0.1:3800 and switch Settings → storage to "self-hosted" (or put VITE_DEFAULT_STORAGE=sqlite in frontend/.env.local) to drive the app off the worker instead of client-only IndexedDB. Google sign-in works locally once the OAuth client lists http://localhost:8787/api/auth/google/callback as an authorized redirect URI (see Auth).

Deploy (dev → prod)

wrangler.jsonc defines two environments — env.dev (finance-manager-api-dev, api.dev.<domain>) and env.prod (finance-manager-api, api.<domain>) — each with its own D1 database, R2 bucket, vars and route. Run once per environment (shown for dev; repeat the :prod variants for production):

cd worker
npx wrangler login
pnpm run d1:create:dev     # prints a database_id -> paste into env.dev.d1_databases.database_id
pnpm run r2:create:dev     # premium receipt storage bucket
pnpm run d1:migrate:dev    # apply the schema to the remote dev D1
pnpm run secret:dev        # JWT_SECRET + GOOGLE_CLIENT_SECRET for the dev worker
# set env.dev.vars.GOOGLE_CLIENT_ID; once you own a domain also set CORS_ORIGIN / APP_ORIGINS /
# COOKIE_DOMAIN and uncomment the api.dev.<domain> route, then:
pnpm run deploy:dev

The frontend deploys the same way (pnpm -C frontend run deploy:dev / deploy:prod); the dev build (--mode dev → frontend/.env.dev) points VITE_API_URL at api.dev.<domain>, sharing the session cookie cross-subdomain via COOKIE_DOMAIN. Full account/domain/D1 runbook: ~/.dotfiles/personal/finance/cloudflare-d1-setup.md.

CI deploys (GitHub Actions)

.github/workflows/deploy-worker.yml (this worker) and deploy-frontend.yml (the app) mirror the mercurypitch/chaos-master setup: push to main → dev, tag v* → prod, plus manual workflow_dispatch (pick dev/prod). The worker job runs d1 migrations apply before deploying. Prerequisites:

  • Repo secrets CLOUDFLARE_API_TOKEN + CLOUDFLARE_ACCOUNT_ID (deploy steps skip if the token is absent). The token needs Workers Scripts / D1 / R2 / Workers Routes / SSL edit (the "Edit Cloudflare Workers" template + SSL); add Zone DNS:Edit if custom-domain attach fails.
  • The one-time d1:create / r2:create / secret: setup above must be done per env, and the printed database_id pasted into wrangler.jsonc, before the first CI deploy.
  • Disable Cloudflare "Workers Builds" for the frontend — its auto-deploy targets the same finance-manager worker as the prod job and would race on a tag.

Auth

Implemented (adapted from mercurypitch's zero-dependency WebCrypto module): stateless JWT (HS256) in an httpOnly, Secure, SameSite=Lax cookie + Google Sign-In (server-side code flow with a signed-state CSRF guard and a returnTo allowlist), in src/auth.ts + src/routes/auth.ts. Routes: /api/auth/google/start, /callback, /me, /logout. Logout bumps users.token_version to revoke all issued tokens. Setup steps: ~/.dotfiles/personal/finance/google-oauth-setup.md. Password login uses PBKDF2; existing bcrypt hashes need a re-hash-on-next-login migration.

src/auth.ts depends only on WebCrypto + a D1Database handle (the Hono-specific part is just the requireAuth wrapper), so it's designed to lift into a shared cross-app auth lib later, alongside the wrangler/D1 setup.

Open items

  • Domain — tokencircles.com. Dev is wired and being brought up first: app at dev.tokencircles.com, API at api.dev.tokencircles.com (cookie shared via COOKIE_DOMAIN=.dev.tokencircles.com). Prod (app./api.tokencircles.com) is filled but its route stays commented until you deploy it. The zone must be active in Cloudflare so the custom_domain routes can provision DNS on deploy. Remaining placeholders: D1 database_ids (from d1:create:dev/:prod), GOOGLE_CLIENT_ID, optional account_id, and the secrets.
  • Premium billing — receipt upload is gated to users.plan = 'premium', but there's no billing/upgrade flow yet; set a user premium manually for now (UPDATE users SET plan='premium' WHERE id=?). PDF reports + spreadsheet import are free.
  • R2 bucket — create the per-env buckets (pnpm run r2:create:dev / :prod) and keep their names in wrangler.jsonc; receipt endpoints return 501 until the bucket is bound.
  • Data migration — to move existing rows into D1: sqlite3 finance.db .dump > dump.sql, strip pragmas/transactions, then npx wrangler d1 execute finance-manager --remote --file dump.sql.