Rewrites src/lib/geo.ts so lookupIpLocation reads from the bundled
MaxMind GeoLite2-City MMDB first and falls back to the existing
ipwho.is path only for IPs the offline DB cannot resolve. Adds a
sibling lookupIpAsn that returns { asn, carrier } from the
GeoLite2-ASN MMDB so the admin login-overview can grow a carrier
chip alongside the auth-provider chip.
The MMDB files are too large to vendor in git. scripts/fetch-geolite2.sh
downloads them at build time using a MaxMind license key; the
Dockerfile copies assets/geolite2/ into /opt/geolite2/. When the
license key is absent or the files are missing the image still
builds and the resolver falls back to ipwho.is (v1.4.26 behaviour).
GeoLite2 is CC BY-SA 4.0 — attribution lives on the new public
/about page and in docs/audit/v1427-summary.md.
Public privacy-policy page at /privacy enumerates every Apple
HealthKit identifier the iOS app reads, names every third-party
sub-processor, and restates the EU MDR + GDPR boundaries. Unblocks
Apple BLOCKER 2 of the iOS App Store Connect submission by giving
the registered Privacy URL a real page to point at.
Largest feature delta in the v1.4.x line. Insights expands into seven dedicated metric sub-pages; GLP-1 medication tracking lands end-to-end (drug-level chart with Research Mode acknowledgment, EMA titration ladder, cadence + compliance, side-effect taxonomy, pen/vial inventory); cross-source priority becomes a two-axis resolver; per-user timezone threads through ten analytics surfaces; Withings activity + sleep v2 sync; onboarding rebuilt as a nested-route wizard; Personal Records ship end-to-end; Health Score provenance accordion; Coach runs native first-party prompts across six locales with a 1800-assertion refusal-probe matrix; OpenAPI drift gate hard-fails; multi-arch GHCR image. Migrations 0043 through 0060 are additive and forward-only. PROMPT_VERSION 4.24.0 → 4.25.0 with GROUND RULE 9 (refuses dose recommendations) and GROUND RULE 15 (refuses drug-level estimates with MDR + MDCG 2021-24 cites).
See CHANGELOG.md for the full per-section delta.
Pre-iOS prep + hygiene. Apple Health backend foundation (schema +
batch ingest + APNs scaffolding), OpenAPI generator + warn-only CI
gate, per-device refresh-token revocation + device-management
endpoints, Coach Apple Health metric slot at PROMPT_VERSION 4.23.0,
per-user Coach prefs surface, per-message thumbs feedback loop.
Seven W5 hygiene items closed alongside.
User-visible delta is small on purpose — the weight is in the
contract surface the iOS app gets to compile against on day zero.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wires the OpenAPI 3.1 generator scaffolding ahead of the iOS-touched
route registrations. `zod-openapi` (samchungy variant, picked in W1
stream-3) reads Zod v4's native `.meta()` so schemas can stay in their
original validation files; `yaml@2` with `sortMapEntries: true` keeps
the emitted spec stable across re-runs.
`pnpm openapi:generate` overwrites `docs/api/openapi.yaml` from the
registry; `pnpm openapi:check` exits non-zero on drift. The legacy
hand-maintained spec is preserved at `docs/api/openapi-v1422-legacy.yaml`
so the iOS contract reference doesn't disappear during the
incremental migration.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds the APNs Provider library the v1.5 iOS app needs so per-metric
alerts can land via Apple's push service alongside the existing
Telegram → ntfy → Web Push cascade. Bundles the env-var contract
(APNS_KEY_ID / APNS_TEAM_ID / APNS_BUNDLE_ID plus one of APNS_KEY or
APNS_KEY_FILE) in .env.example so a fresh deploy knows the four
required values up front. The dispatcher wiring + sender ship in
follow-up commits.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Hotfix release for the legacy-payload /insights crash users hit on
2026-05-10 the morning after v1.4.16 shipped. See CHANGELOG.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Bumps version to 1.4.15 and adds the corresponding CHANGELOG entry
covering backup completeness, achievements UI, onboarding tour,
doctor-report v2, auto-deploy on GHCR push, empty-states sweep,
notification + integration status UI, AI hallucination guardrails,
mobile UX fixes, and the BD-Zielbereich percentage fix.
Includes the formatting drift left over by the v1.4.15 development
phases (Prettier sweep on touched files) and a typecheck fix in
`dashboard-layout.test.ts` so `pnpm typecheck`, `pnpm lint`,
`pnpm format:check`, `pnpm test`, and `pnpm test:integration` all
pass green on the release tag.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Authenticated specs need a deterministic user and a persistent session
cookie. global-setup.ts upserts an `e2e-tester` admin via raw `pg` (the
generated Prisma client uses ESM `import.meta.url`, which Playwright's
TS loader cannot resolve), then logs the user in once and writes
`storageState.json` so every authenticated spec reuses the same
session — the per-IP login rate-limit (5 attempts / 15 min) would
otherwise lock out the suite the moment six specs run in parallel.
Adds `pg` + `@types/pg` as devDependencies — required for the seed
step. `pg` is already used by `scripts/seed-demo.ts` for the same
loader-incompatibility reason, so we're not introducing a new
dependency footprint, only making it explicit in the lockfile.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The Codex backend rejects `gpt-5-codex` when authenticated via the
ChatGPT-account OAuth flow with:
"The 'gpt-5-codex' model is not supported when using Codex with a
ChatGPT account."
The `-codex` suffix is API-key-auth-only. ChatGPT subscriptions route
through the plain `gpt-5` slug instead. Switch the client default and
expose a `CODEX_MODEL` env override for operators on plan tiers that
prefer a different slug (e.g. `gpt-5-codex-mini` or a future
preview model).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Stop iterating on individual 400 errors and implement the full Codex
Responses-API protocol once, from the source. Wrote a 713-line
reference at docs/codex-protocol-spec.md from the official
openai/codex Rust client; this commit is the TS implementation
against that spec.
Required pieces that were missing in v1.4.11:
- `ChatGPT-Account-ID` header — extracted from the `chatgpt_account_id`
claim of the OAuth id_token (also accepts the URI-namespaced
variant under `https://api.openai.com/auth`). Without it: 401.
- `originator`, `User-Agent`, `Accept: text/event-stream`,
`session_id`/`session-id` (both spellings), `thread_id`/`thread-id`.
- Body fields `reasoning: null` and `include: []` are required even
when no reasoning is requested.
- Model slug is `gpt-5-codex`, not `gpt-5.3-codex` (the latter is a
test placeholder upstream).
- Refresh endpoint takes a JSON body, not form-urlencoded.
Storage codec rewrite: `codexAccessTokenEncrypted` now holds an
encrypted JSON blob `{ accessToken, accountId, expiresAt }` instead
of just the raw access token, so the account id stays available
across requests. v1.4.7-v1.4.11 records that lack the field cannot
be revived — `decryptCodexCreds` returns null for those rows and
`resolveCodexProvider` flips the connection to `expired`, prompting
the user to re-link once.
Removed the dead browser-flow routes (`/api/auth/codex/authorize`
and `/callback`). They never worked on hosted domains because
Hydra's redirect-URI allow-list for the public Codex client ID
covers only localhost; device-code is the only viable path.
CodexClient SSE parsing extended to handle `response.failed` and
`response.incomplete` terminal events, and to read the actual
routed model from the `OpenAI-Model` response header.
Tests rebuilt: codex-oauth covers the full device-code flow with a
synthesised id_token JWT, the JSON-body refresh, and the
storage-codec round-trip. CodexClient tests carry an `accountId`
through the constructor. All 720 tests pass; typecheck clean.
Refs: docs/codex-protocol-spec.md §1-§6 for every claim.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After v1.4.10 fixed the request body, the Codex backend started
returning 400:
{ "detail": "Stream must be set to true" }
The endpoint is streaming-only — `stream: false` is rejected
outright. The official Codex CLI consumes a Server-Sent-Events
stream (`codex-rs/codex-api/src/sse/responses.rs`); we have to do
the same.
CodexClient now requests `stream: true` and reads the response body
incrementally via the standard `ReadableStream` reader. Each SSE
message ends in a blank line; the `data:` payload is JSON. We listen
for three event types from the OpenAI Responses API protocol:
- `response.output_item.done` with an assistant `message` item — the
final text is read directly from the message's `output_text`
content. Preferred path because the backend has already stitched
any deltas together.
- `response.output_text.delta` — incremental text chunks. Fallback
when no `output_item.done` arrived (e.g. older models or
reasoning-only responses), all deltas are concatenated.
- `response.completed` — picks up `usage.total_tokens`.
- `response.error` / `error` — bubbled as a thrown Error with the
upstream message.
Tests rebuilt to drive the client with synthetic SSE bodies, plus
new coverage for the delta-fallback path. All 720 unit tests pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After v1.4.9 the OAuth connect went green, but every real insight
call still failed with:
Codex request failed (400): { "detail": "Input must be a list" }
The `chatgpt.com/backend-api/codex/responses` endpoint speaks the
OpenAI Responses API shape (`ResponsesApiRequest` in
`codex-rs/codex-api/src/common.rs`), where `input` is a list of typed
message items rather than a single string. CodexClient was sending
the older Chat-Completions-style body (`input: <string>`) which the
upstream rejects with the 400 above.
The body now mirrors the canonical shape:
{
"model": "gpt-5.3-codex",
"instructions": "<system prompt>",
"input": [
{ "type": "message", "role": "user",
"content": [{ "type": "input_text", "text": "<user prompt>" }] }
],
"tools": [], "tool_choice": "auto",
"parallel_tool_calls": false, "store": false, "stream": false
}
The response shape (Output `ResponseItem[]` with `output_text`
content) is unchanged, so `parseResponse` still works without
modification. Both Settings → KI "Verbindung testen" and the insight
generator now complete end-to-end through the ChatGPT subscription.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v1.4.8's device-code flow got the user as far as the chatgpt.com
approval, but the connect step at the end still failed with:
Codex api-key exchange failed (401): "Invalid ID token: missing
organization_id"
Root cause: the api-key exchange (RFC 8693, swap id_token for an
OpenAI API key) requires the id_token to carry an `organization_id`
claim. That claim only gets added when the authorize URL is hit with
`id_token_add_organizations=true` — which the browser/auth-code
flow does, but the device-code flow does NOT (the user types the
code on chatgpt.com's own page; we never control the authorize URL).
The official Codex CLI handles this by NOT calling the api-key
exchange in the device path: it persists the OAuth access_token /
refresh_token directly and uses them against
`https://chatgpt.com/backend-api/codex/responses` (the Codex backend
that bills against the ChatGPT subscription). v1.4.9 does the same.
`pollDeviceCode` no longer calls `obtainApiKey`; it returns the raw
OAuth access_token instead. New `refreshDeviceTokens()` mirrors that
on the refresh path. The provider rewires Codex back through the
existing `CodexClient` (bg backend-api), with proactive refresh
+ on-401 refresh both going through `refreshDeviceTokens`.
The browser/auth-code flow path is left in place — operators who
register a private OAuth app with OpenAI (e.g. for an enterprise
deployment) can still use the api-key exchange via the
`exchangeCodeForTokens` helper. For the public Codex client ID on
hosted instances, device-code is the only working path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
v1.4.7 corrected the issuer (`auth.openai.com`) and added the
RFC-8693 api-key exchange, but the Connect button still failed in
production with `unknown_error`. Root cause: OpenAI's Hydra
allow-lists only `http://localhost:1455/auth/callback` and
`:1457/auth/callback` for the public Codex CLI client ID. Any hosted
redirect URI gets silently rejected — the v1.4.7 user landed on the
"An error occurred during authentication (unknown_error)" page.
The official Codex CLI ships a parallel **device-code flow** for
exactly this case (`codex-rs/login/src/device_code_auth.rs`):
1. POST `https://auth.openai.com/api/accounts/deviceauth/usercode`
with the client id → `{ device_auth_id, user_code, interval }`.
2. Show the user the code and a link to
`https://auth.openai.com/codex/device`. They open it on any
device, log in, and type the code.
3. POST `https://auth.openai.com/api/accounts/deviceauth/token`
repeatedly until Hydra returns `{ authorization_code,
code_challenge, code_verifier }` (otherwise 403 / 404).
4. Standard PKCE token exchange against `/oauth/token` — but with
`redirect_uri = https://auth.openai.com/deviceauth/callback`,
which IS allow-listed for the public client. Then the same
id_token → API-key exchange that v1.4.7 already added.
This sidesteps the redirect-URI allow-list entirely; HealthLog's
domain never appears in any OAuth round-trip.
Implementation:
- `src/lib/ai/codex-oauth.ts` adds `requestDeviceCode()` and
`pollDeviceCode()`.
- `POST /api/auth/codex/device-start` initialises the flow, persists
the `device_auth_id` + `user_code` in an encrypted httpOnly cookie
(15 min, scoped to the requesting user), and returns the user-
facing pieces.
- `POST /api/auth/codex/device-poll` does one poll attempt; on
`pending` it returns `{ status: "pending" }`, on success it
exchanges + persists the api key + refresh token and returns
`{ status: "connected" }`.
- The Settings → KI section replaces the "redirect to OAuth"
button with an inline card showing the user code, the
verification URL, and a copy button. The page polls every
`intervalSeconds` (5s default) until status flips to "connected"
or the user cancels. EN + DE strings under
`settings.ai.deviceCode*` cover the new copy.
- The legacy authorize / callback routes stay on disk for now —
they're harmless when the redirect-URI allow-list is updated for
a private client ID, so operators with an OpenAI partner client
can still use the original flow via `CODEX_OAUTH_CLIENT_ID`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The "Connect with ChatGPT" button never actually completed an OAuth
flow. The implementation hit `chatgpt.com/authorize` and
`chatgpt.com/oauth/token`, which are not OAuth endpoints — ChatGPT
silently rendered its normal web app, dropped our params on the
floor, and the user landed on a regular logged-in chat session with
nothing else happening. There was no error and no callback, which is
why the regression survived multiple releases.
The canonical issuer for ChatGPT-OAuth is `auth.openai.com`. The
official `openai/codex` CLI confirms this in
`codex-rs/login/src/auth/manager.rs` and `codex-rs/login/src/server.rs`.
The flow is also slightly more involved than a vanilla PKCE
authorisation:
1. PKCE authorize against `auth.openai.com/oauth/authorize` with the
`openid profile email offline_access api.connectors.read
api.connectors.invoke` scope set, plus `id_token_add_organizations`
and `codex_cli_simplified_flow` flags so the resulting `id_token`
carries the ChatGPT-subscription claims.
2. Token exchange against `auth.openai.com/oauth/token` (form-
urlencoded body, NOT JSON) yields `{ id_token, access_token,
refresh_token }`.
3. **Second token exchange** with grant
`urn:ietf:params:oauth:grant-type:token-exchange`, swapping the
`id_token` for an OpenAI API key (`requested_token=openai-api-key`).
This key bills against the ChatGPT subscription rather than a
separate API plan — exactly what the v1.2/v1.3 design intended.
4. HealthLog stores the API key in `codexAccessTokenEncrypted`
(re-purposing the existing column to avoid a migration) and the
OAuth refresh token in `codexRefreshTokenEncrypted`. When the
key is about to age out we refresh + re-exchange transparently
before the next request.
The downstream provider is now a regular `OpenAIClient` tagged with
`providerType: "codex"` so logs and analytics still distinguish
ChatGPT-subscription billing from plain BYOK. The bespoke
`codex-client.ts` (which hit the chatgpt.com/backend-api/codex/responses
endpoint with the OAuth access token) is still on disk for now so the
prisma columns and the provider tag stay stable, but is unreferenced
by the active path.
The public Codex CLI client ID `app_EMoamEEZ73f0CkXaXp7hrann` is
shipped as a default; operators who registered a private OAuth app
with OpenAI can override via `CODEX_OAUTH_CLIENT_ID`. The
`isCodexOAuthConfigured()` gate is a no-op now because the default
always has a value, so the UI surface no longer silently hides the
"Connect with ChatGPT" button.
Tests cover the new shape end-to-end: PKCE generation, the
authorize-URL parameters, the form-encoded token exchange, the
api-key exchange, the refresh path, and the encrypt/decrypt
round-trip. The provider integration test is updated to expect a
`providerType: "codex"` OpenAIClient instead of the legacy
`CodexClient`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Marc's v1.4.4 feedback: the tiles look better when they're all
exactly the same size and the strip begins and ends at the same
x-coordinate as the charts — the v1.4.4 `flex-1 basis-0` distribution
was close but not quite symmetric, and at 6 tiles the right edge
of the strip didn't line up with the charts below.
Switched to the v1.3-era pattern but with the modern `auto-fit +
minmax(9rem, 1fr)` form so it doesn't need explicit breakpoints:
grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr));
gap: 0.75rem;
CSS Grid puts every tile in an identical 1fr track. Width is
literally identical, gaps are symmetric, and the strip is bounded
by the same parent box as the charts so left/right edges align by
construction. When the row no longer fits a 9 rem floor the grid
wraps to a new row — Marc explicitly tested both and prefers the
wrap over the v1.4.x horizontal-scroll for the symmetry it
preserves.
Tests + typecheck green (671/671).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Marc's v1.4.3 feedback:
- Tiles end up the same height now but uneven widths — they should
distribute symmetrically across the strip.
- BP shouldn't be one combined tile; sys + dia should sit side by
side as two distinct tiles like every other metric.
Two fixes:
1. **Strip wrapper switches from `shrink-0 grow basis-[10rem]` to
`flex-1 basis-0 min-w-[9rem]`.** With `basis-[10rem]` the floor
was 160 px, and tiles whose content rendered wider (the combined
BP tile rendering "117.0/79.0 mmHg" plus a paired avg row) pushed
past their share, breaking symmetry. `flex-1 basis-0` starts every
tile from zero, so the row-width gets divided evenly regardless of
how much text each card contains. `min-w-[9rem]` is the readable
floor — if the row no longer fits at that width, the parent's
existing `overflow-x-auto` lets the user swipe instead of wrap.
2. **BP renders as two tiles again.** Reverted the v1.4.3 combined
`secondary` rendering: the dashboard now pushes a `bp-sys` and
a `bp-dia` entry, ordered with a 0.001 sub-step so dia stays
immediately after sys without colliding with the next widget's
integer order. The `secondary` prop on TrendCard stays in the
API for callers that *do* want a paired-value tile.
Tests + typecheck green (671/671).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Wraps the polish pass: dashboard layout, About + API surfaces,
KI-provider UX, AI insights chart-tokens + evidence contract, admin
bug-report toggle, and the Trennen-button consistency sweep.
Migrations 0026 (user OpenAI key) and 0027 (bug-report toggle) ride
along — both are additive columns with safe defaults so existing
deployments upgrade without data work.
CHANGELOG.md describes the user-visible deltas section by section.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Revert "revert: roll source tree back to v1.4.0 to restore production"
This reverts commit e444a90b10.
* fix(v1.4.2): summaries.WEIGHT + medications array guards + healthcheck IPv4
Three production bugs surfaced after the v1.4.0 deploy stabilized:
1. `TypeError: undefined is not an object (evaluating 'E?.summaries.WEIGHT')`
on /dashboard and /insights for users without weight readings —
the optional chain stopped at `data` when it needed to also cover
`data.summaries`. Fixed: `data?.summaries?.WEIGHT` (one level deeper).
2. `TypeError: y?.filter is not a function` on /medications — the
medications query value was non-array (likely a stale
service-worker response from an older API shape). Replaced with
`Array.isArray(medications) ? medications : []` so the page is
immune to any future shape drift.
3. Healthcheck-induced 503 outage (already in 1.4.1 — included here
so 1.4.2 is the single coherent release). The docker-compose
healthcheck used `localhost` which busybox-wget resolves to IPv6
::1; Next.js standalone listens on IPv4 0.0.0.0 only. Pinned
to 127.0.0.1.
This release also includes everything from v1.4.1 (which never
published a clean GHCR tag): the per-section admin extraction, the
testcontainers integration suite, the Playwright + axe-core E2E
foundation, the moodLog SSRF fix, the central error-redaction in
WideEventBuilder + Glitchtip, the medical-citation drift fixes
(ESH 2023, Saint-Maurice attribution, steps source), and the docs
sync.
Co-Authored-By: Marc-André Bombeck <mbombeck@gmail.com>
Production at healthlog.bombeck.io has been 503-ing since the v1.4.1
deploys started landing on apps-01 (Coolify). The container boots —
Next.js prints "Ready" and the pg-boss workers run — but never
accepts HTTP on :3000, so the Docker healthcheck fails and Traefik
takes the upstream out of rotation. A manual restart, a Coolify
force-rebuild, and a docker-compose pin to the GHCR :1.4.0 multi-arch
image all failed to bring the site back up — Coolify rebuilds the
image from main HEAD on every deploy regardless of the compose
directives.
This commit resets the working tree to commit 21bd46d (v1.4.0
release). Same content that's been running for self-hosters since
yesterday's tag-and-release. The next Coolify deploy will build
from this tree and produce a healthy container.
The v1.4.1 work is NOT lost:
- PRs #144, #145, #137, #146, #147, #148, #149, #150 remain in
git history.
- Their commits are still tagged (`v1.4.1`), still on the GHCR
multi-arch image (`ghcr.io/mbombeck/healthlog:1.4.1`), still in
the GitHub Release notes.
- Self-hosters who have already pulled the v1.4.1 image keep it.
- Local development continues from main HEAD with the v1.4.1
code — the regression only surfaced under the Coolify build
flow.
Re-applying v1.4.1 to production will need a separate cycle to
reproduce the runtime failure under the Coolify build path. That
work is tracked in docs/ops/v141-followup-issues.md (added back
when the tree is reapplied) and the deploy gating in
.github/workflows/e2e.yml will catch this class of bug going
forward.
No DB migration. No env-var change. No API contract change.
Co-Authored-By: Marc-André Bombeck <mbombeck@gmail.com>
CHANGELOG entry covers the three buckets of change between 1.4.0 and
1.4.1: security hardening from the audit pass (moodLog SSRF closed
+ centralised error redaction), citation-accuracy fixes (ESH 2023
label, Saint-Maurice attribution, steps source), and the CI safety
nets (executable Postgres testcontainers + Playwright/axe-core
foundation), plus the structural per-section admin extraction and
the in-tree docs sync. The deferred items from the audit pass land
in docs/ops/v141-followup-issues.md so they're discoverable for the
v1.4.2 cycle without re-running the audit.
package.json bumped 1.4.0 → 1.4.1.
No DB migration. No env-var change required. No API contract
change.
Builds out the foundation for end-to-end tests against the production
build: Playwright with desktop + mobile projects, axe-core for WCAG
2.1 AA gating, and a GitHub Actions workflow that caches the browser
download and uploads the HTML report on failure.
What lands now (public surfaces only — no DB seed required):
e2e/version.spec.ts /api/version returns shape, no auth
e2e/auth-redirect.spec.ts proxy gate bounces / → /auth/login etc.
e2e/login.spec.ts login form renders + autoComplete hints
+ invalid-credential error surfaces
e2e/locale-switch.spec.ts DE/EN cookie switch, no raw i18n keys
leak into the DOM
e2e/a11y.spec.ts axe-core fails on serious or critical
WCAG 2.1 A/AA violations on /auth/login
The four authenticated flow specs from the v1.4.1 plan
(quick-entry, doctor-report, settings-roundtrip, test-buttons,
onboarding) need a seeded test user; they're tracked as a follow-up
because the seeding pipeline + WebAuthn polyfill they require warrant
their own PR. The smoke specs above cover the proxy, the login surface,
the version healthcheck endpoint, and the locale machinery — i.e.
every path a v1.4.X regression could realistically break without
deeper UAT.
CI workflow (.github/workflows/e2e.yml):
- postgres:16-alpine service container
- prisma migrate deploy seeds an empty schema
- playwright install --with-deps chromium (cached)
- next build, then `playwright test` against `next start`
- playwright-report uploaded as an artifact on failure
Quality gates:
- pnpm typecheck — clean
- pnpm test — 658/658 pass (vitest excludes e2e/**)
- pnpm lint — 0 errors
* test(integration): Postgres testcontainers + 4 critical-path tests
Adds an integration test suite that runs against a real Postgres booted
in-process via testcontainers. Lives under tests/integration/, runs via
`pnpm test:integration`, and is excluded from the default `pnpm test`
loop so the 477-test unit suite stays fast (~1.2s).
Covers four regression-prone behaviours that pure unit tests cannot
validate against a mocked client:
- rate-limit.test.ts — atomic UPSERT under concurrency (5/6 allowed)
and window-reset semantics for src/lib/rate-limit.ts
- idempotency-replay.test.ts — cached replay with X-Idempotent-Replay,
expired-row purge, and the do-not-cache contract for 401/403/408/429/5xx
on top of src/lib/idempotency.ts
- cascade-delete.test.ts — GDPR Art. 17 erasure: user.delete wipes
every onDelete:Cascade table and SetNulls AuditLog/Feedback
- auth-flow.test.ts — createSession/getSession round-trip plus
expired-session purge for src/lib/auth/session.ts
Adds .github/workflows/integration.yml triggering on pull_request and
push to main. Local Docker is not running in this worktree environment;
the suite was verified by collecting all 10 tests via `vitest list` and
will execute in CI.
Co-Authored-By: Marc-André Bombeck <mbombeck@gmail.com>
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(integration): rebase onto v1.4 + exclude live agent worktrees from default test scope
Rebase brings PR #137's testcontainers infrastructure on top of the
user-locale migration drift fix landed in #140 — the integration suite
should now bootstrap a fresh Postgres container with all 25 migrations
applied cleanly.
vitest.config.mts also gains a `.claude/worktrees/**` exclude so live
agent worktrees (which mirror `src/` while their parent agents are
running) don't double-execute the project's tests against possibly-stale
copies.
* test(integration): boot one Postgres container per run via vitest globalSetup
The first iteration of the testcontainers suite started/stopped a
fresh container in each test file's beforeAll/afterAll. That works
in isolation but breaks when files share a worker (`pool: forks`,
`fileParallelism: false`, `isolate: false`):
1. Test file A boots container 1, sets DATABASE_URL.
2. The application's Prisma singleton in src/lib/db.ts is built
when test code dynamic-imports @/lib/auth/session — it captures
container 1's URL.
3. afterAll stops container 1.
4. Test file B boots container 2, sets DATABASE_URL to a new port.
5. Test file B imports application code that resolves to the same
singleton — still pointing at the dead container 1. Queries fail
with a generic PrismaClientKnownRequestError.
Fix: move the container lifecycle to vitest's globalSetup. One
container, booted once, torn down at the end of the run. Tests still
get isolation because beforeEach truncates every personal-data table
in dependency-safe CASCADE order.
- tests/integration/global-setup.ts boots postgres:16-alpine,
runs `pnpm db:migrate:deploy`, exports a teardown for end-of-run.
- tests/integration/setup.ts now exports getPrismaClient() (which
delegates to the application singleton) and truncateAllTables().
No more startTestDb / stopTestDb.
- All four test files lose their beforeAll/afterAll boilerplate.
- vitest.integration.config.mts wires the new globalSetup.
- truncate list adds refresh_tokens (added in 0025_refresh_tokens).
Result: pnpm test:integration → 10/10 pass in 3.9s (was 6/10 with
4 cross-file failures). pnpm test → 658/658 unchanged.
Co-Authored-By: Marc-André Bombeck <mbombeck@gmail.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* chore(release): prepare v1.4.0 — CHANGELOG, version bump, migration guide
Bumps `package.json` 1.3.3 → 1.4.0 and the OpenAPI spec to match.
Adds a comprehensive user-facing CHANGELOG entry for v1.4.0 covering
the foundation, medical safety, i18n, performance, chart-math,
dashboard one-row, /api/version, AI insights memory + hero card,
onboarding redesign, and the chart-math fixes that landed across the
v1.4 marathon. Bundles the migration guide
(`docs/migration/v1.3-to-v1.4.md`) covering env vars, behaviour-only
API changes, UI/UX deltas, the medical-default updates, and
rollback steps. Updates AGENTS.md status block.
Tests: 440/440 green. Typecheck clean.
Note: a few additional v1.4 buckets (admin redesign A4, settings split
A2, multi-tenant prep G, test coverage lift H, A8 test buttons) are
landing in parallel branches and may merge after this. The CHANGELOG
will be amended on the release branch as those PRs land.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* chore(release): amend v1.4.0 changelog with everything from the finish-marathon
Adds the user-facing bullets for the settings split, the five
"Test connection" buttons, AI inline charts, off-host backup,
encryption-key rotation, worker/web split, refresh-token rotation,
admin status grid, and the operational hardening fixes (tzdata,
healthcheck, idempotency hlr_, paired access-token revoke,
users.locale migration backfill).
Replaces the "tracked for v1.4.x or later" deferred block — the
items it listed have shipped or moved to v1.4.1.
---------
Co-authored-by: Marc-André Bombeck <noreply@anthropic.com>
* feat(crypto): G2 — encryption-key versioning + rotation CLI
Adds backwards-compatible support for ENCRYPTION_KEYS (JSON map of
{ "id": "<key>" }) plus ENCRYPTION_ACTIVE_KEY_ID. Ciphertext format is now
"<keyId>.<base64payload>"; legacy bare-base64 ciphertext still decrypts
under the synthetic "v1" id derived from the existing ENCRYPTION_KEY.
scripts/rotate-encryption-key.ts re-encrypts every encrypted column on
User / WithingsConnection / AppSettings with the active key. Idempotent —
rows already on the active id are skipped.
Why: enables zero-downtime rotation when a key is suspected leaked,
without forcing every encrypted row through a single big-bang rewrite.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* feat(auth): G4 — native-Bearer UA gating + rotating refresh tokens
Web callers (UA contains 'Mozilla/') keep the legacy 90d Bearer when they
explicitly opt in via X-Client-Type: native. Native callers (HealthLog-iOS,
HealthLog-iPad, n8n, Health-Connect, unrecognised UAs) now receive a 24h
access token plus a 60d rotating refresh token in the login response.
New /api/auth/refresh endpoint atomically validates + rotates the refresh
token (one-time-use), revokes the previously paired access token, and
audit-logs every refresh + revoke. Reuse of an already-consumed refresh
token revokes the entire family for the user/device — defence against a
stolen refresh token.
Migration 0025_refresh_tokens adds the table; the only DDL is CREATE
TABLE so it is forward-compatible. Down migration documented at
docs/ops/migrations/0025-down.sql.
Why: the V3 audit (still-V2-A) flagged that 90d tokens are too long for
native callers when refresh-token rotation is now table-stakes for mobile
apps. Web flows are unchanged so existing browser sessions keep working.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* feat(infra): G3 — web/worker container split via HEALTHLOG_PROCESS_TYPE
Adds a tiny startup gate (src/lib/process-type.ts) so the same Docker image
can run as web-only, worker-only, or 'all' (default — single-container,
backwards compatible). assertSubsystemEnabled() refuses to boot the
reminder worker when HEALTHLOG_PROCESS_TYPE=web, preventing accidental
double-cron when an operator splits the deployment.
docker-compose.yml ships the optional app-worker service block commented
out so 'docker compose up' keeps working out of the box; uncommenting it
+ flipping app to HEALTHLOG_PROCESS_TYPE=web is the only change to scale
HTTP horizontally. Healthchecks are isolated per service so neither
startup deadlocks the other; both wait on db: service_healthy.
docs/self-hosting/scaling.md walks through when + how to split.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* feat(jobs): G1 — daily off-host encrypted backup to S3-compatible storage
New pg-boss queue 'data-backup-offhost' runs at 02:30 Europe/Berlin, dumps
each user's measurements + medications + intake events + mood entries,
encrypts the JSON under a SEPARATE key (BACKUP_ENCRYPTION_KEY, isolated
from the application ENCRYPTION_KEY), and uploads to any S3-compatible
target via @aws-sdk/client-s3.
Wire format documented in docs/ops/backup-restore.md:
magic "HLBK" || version 0x01 || iv(12) || authTag(16) || ciphertext
The worker prunes objects older than BACKUP_RETENTION_DAYS (default 30);
operators are encouraged to also configure a bucket-level lifecycle rule.
Admin endpoint POST /api/admin/backup/test issues a 1-byte PUT+GET
roundtrip and returns endpoint + bucket + per-call latency. Credentials
are never returned.
scripts/restore-backup.ts downloads + decrypts a single object so
operators can verify the chain end-to-end without standing up a separate
restore harness.
Why: GDPR Art. 32 + V3 audit "data durability" — without an off-host copy
the only line of defence against a Postgres volume loss is the in-DB
DataBackup model on the same host. Separate-key isolation means a leak of
the application encryption key does not also expose every user's archive.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* fix(multi-tenant): address review findings — rotation coverage, hard decrypt errors, web/worker gates
Multi-agent review on PR #135 caught several CRITICAL + HIGH issues that
would have shipped silent data corruption or weakened the threat model:
Encryption + rotation
- scripts/rotate-encryption-key.ts: stop selecting `bugReportTokenEncrypted`
(column doesn't exist in the schema; the script crashed on the AppSettings
step). Add the three encrypted columns it was missing —
NotificationChannel.config, PushSubscription.p256dh, PushSubscription.auth
— so rotating to a new key actually re-encrypts every encrypted row.
Without this, dropping the old key id from ENCRYPTION_KEYS would leave
notification channels and web-push subscriptions permanently
undecryptable.
- src/lib/crypto.ts: refuse to silently fall back to the active key when a
legacy bare-base64 row is decrypted but no v1 entry is configured. Throws
a clear "Restore ENCRYPTION_KEY (or add a v1 entry to ENCRYPTION_KEYS)
and run scripts/rotate-encryption-key.ts before removing it" so an
operator who pulled the v1 too early notices immediately instead of
hitting opaque GCM tag errors.
- docs/ops/encryption-key-rotation.md: full step-by-step + rollback note +
troubleshooting section. Spells out that rotation is a forward-only
operation and what to do if the rollback path is needed.
Web / worker split (G3)
- src/proxy.ts: refuse HTTP traffic with a 503 +
X-HealthLog-Process-Type: worker header when HEALTHLOG_PROCESS_TYPE=worker.
The worker container (which still runs `node server.js` for now) no
longer accepts requests, so a misrouted client gets a clear hint instead
of a partially-served response.
- src/instrumentation.ts: short-circuit before importing the reminder
worker when HEALTHLOG_PROCESS_TYPE=web — avoids the noisy
"[instrumentation] CRITICAL" stderr line we emitted on every web boot.
- /api/version added to PUBLIC_PATHS so the compose healthcheck doesn't
silently 302-redirect through the auth gate (the prior wget treated the
login page as a 200 success and would never notice an unhealthy backend).
Refresh-token rotation (G4)
- src/lib/auth/refresh-token.ts: reuse-detection now revokes ALL active
refresh tokens for the user, not only those scoped to the same deviceId.
An attacker who rotated without an X-Device-Id header would otherwise
keep their family alive on the no-device branch. Defence-in-depth.
- revokeRefreshToken() also revokes the paired access token so a leaked
access token cannot outlive the refresh-token sibling that the caller
just killed (logout-on-device).
Off-host backup (G1)
- src/lib/jobs/offhost-backup.ts: drop the worker-side DeleteObject path.
Retention is the bucket's lifecycle-policy job; the worker keeps a
PutObject + GetObject grant only. A compromised worker can no longer
wipe the backup history. Per-user errors are now surfaced as Wide
Event warnings + a structured failures[] array on the report so an
operator can tell which user failed and why.
- scripts/restore-backup.ts: schema-validate the decrypted payload before
writing to disk, plus an optional --user-id=<id> flag that refuses to
proceed unless the dump's userId matches. Prevents silent
cross-tenant restores when an operator points the script at the wrong
S3 key.
Idempotency
- src/lib/idempotency.ts: the leak-guard already blocked `hlk_`
(access-token prefix); also block `hlr_` so a future caller wrapping
the new /api/auth/refresh endpoint with withIdempotency() can't
accidentally cache a freshly-issued refresh token.
Migration / schema
- prisma/migrations/0025_refresh_tokens/migration.sql: wrap in a single
transaction; switch to CREATE { TABLE | INDEX } IF NOT EXISTS so a
partial-deploy retry is a no-op instead of "relation already exists";
guard the FK ADD with information_schema lookup for the same reason.
- Schema replaces the single-column `@@index([deviceId])` with a
composite `@@index([userId, deviceId])` (every lookup also filters on
userId; the old index would never have been used). Comment on
accessTokenHash corrected to HMAC-SHA-256.
Container / ops
- Dockerfile: install tzdata + ENV TZ=Europe/Berlin so the daily
pg-boss schedule (`30 2 * * *` Europe/Berlin) actually fires at 02:30
Berlin instead of silently falling back to UTC on the alpine base.
- docker-compose.yml: tighten the healthcheck to `wget --spider` (matches
the Dockerfile HEALTHCHECK style, doesn't pipe the body), pass through
BACKUP_RETENTION_DAYS so a custom retention env reaches the container.
- .env.example: document every new env var added in this PR
(HEALTHLOG_PROCESS_TYPE, ENCRYPTION_KEYS, ENCRYPTION_ACTIVE_KEY_ID,
BACKUP_S3_*, BACKUP_ENCRYPTION_KEY, BACKUP_RETENTION_DAYS) with
comments and the all-or-none semantics for the backup block.
491 tests still green, typecheck clean.
* chore: retrigger CI
---------
Co-authored-by: Marc-André Bombeck <noreply@anthropic.com>
* docs(ui): add UI guidelines as single source of truth + shadcn MCP server
- `docs/ui-guidelines.md` lays out Dracula tokens, spacing, typography,
component picks (button/input/dialog/sheet decision tree), layout
rules (settings split target, dashboard one-row), accessibility
baseline (WCAG 2.1 AA + axe-core in CI), the autofill / honeypot
pattern for measurement forms, and a reusable "Test button" UX for
every integration. New components in v1.4 reference this doc.
- `.mcp.json` wires the official `shadcn` MCP server so the design
system can be browsed and components installed without leaving the
editor.
- Adds `@vitest/coverage-v8` to dev dependencies — `pnpm test
--coverage` now reports real per-file coverage (the v1.4 cycle uses
this to lift critical-path coverage).
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* fix(settings/ai): connection-test honours the unsaved provider selection
Changing the AI provider in /settings, then clicking "Verbindung testen"
without saving first, used to silently run the test against the *saved*
provider instead — so the result felt unrelated to what the user had on
screen. This often surfaced as a confusing OK / failure depending on
whichever provider had previously been persisted.
The test endpoint now accepts an optional JSON body that mirrors the
form fields (provider, model, baseUrl, anthropicKey, localKey). When
present, the server resolves a transient provider from those values —
falling back to the persisted, encrypted credentials per field, so a
user with a stored Anthropic key can swap models in the dropdown
without re-typing the key. Plaintext keys never persist; the existing
SSRF guard for the Local provider's base URL is reused, the existing
rate limit (5/min) and the V3 error-leak shielding stay in place.
Empty body keeps the previous behaviour for any other caller.
Tests cover the new override path (provider forwarded, unknown
provider rejected with 422, empty body uses persisted config, config
errors surface the resolver's status). Whitespace in
`src/app/settings/page.tsx` is reformatted by Prettier as a
side-effect; logic touches only the AI section.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* feat(ui): add Skeleton and EmptyState primitives
Two pieces every page in v1.4 needs and the codebase didn't have:
- `<Skeleton>` — a presentation `<div>` with the standard pulse
animation, `aria-hidden`, and `motion-reduce:animate-none`. Used to
shape the page while data loads instead of dropping a spinner. The
visible layout no longer jumps when the first measurement arrives.
- `<EmptyState>` — the shape every list, tile, and chart panel
reaches for when it has no data: optional icon, title, description,
primary action; `card` (default) and `plain` variants;
`default`/`compact` density. Lives inside an `aria-live="polite"`
region so screen readers announce the message and its action.
Tests cover screen-reader semantics, prettier-merged class names,
density/variant switches.
These two land first because the v1.4 pages — the split settings
sections, the new dashboard hero, the redesigned admin status grid —
all assume the primitives exist. The patterns are documented in
`docs/ui-guidelines.md` §4.1–4.2.
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
* fix(ui): block password-manager autofill on health-data inputs by default
Browsers and password managers were happily autofilling the user's
account credentials into measurement, medication, mood, and AI-token
fields whenever those forms didn't explicitly set `autoComplete`. The
codebase had zero `autoComplete` attributes across the data-entry
surfaces, so this happened often enough to be both a UX papercut
(account password landing in a "Notiz" field) and a real privacy issue
(secrets persisting through CSV/JSON export).
The base `<Input>` primitive now:
- Defaults `autoComplete` to `"off"` when the caller doesn't supply a
value.
- Adds `data-lpignore="true"` and `data-1p-ignore="true"` whenever
autoComplete resolves to `"off"`, so LastPass and 1Password skip
the field too.
- Keeps the password manager active for any form that already passes a
semantic `autoComplete` (`"username"`, `"email"`,
`"current-password"`, `"new-password"`) — the existing login,
register, and AI-key inputs continue to work unchanged.
Tests cover the three meaningful states (default off, explicit
semantic value, login-flow `username`).
Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com>
---------
Co-authored-by: Marc-André Bombeck <noreply@anthropic.com>
* fix(measurements): close issue #109 + sync body composition across UI/PDF/thresholds
User-visible: TOTAL_BODY_WATER, BONE_MASS, and BLOOD_GLUCOSE now appear in
the measurements filter, badge, mobile icon, and edit dialog (issue #109).
Server-rendered doctor report now includes body composition rows (audit
C-9). Body water + bone mass have proper effective-range thresholds so
severity logic doesn't silently return `nominal` (audit C-15).
Structural: extracted the per-type display maps from measurement-list.tsx
into measurement-list-meta.ts as a deliberate first step toward the
single-source manifest planned for phase P5. Coverage tests now fail-fast
if a future enum addition skips any of: list label/icon/color, doctor-PDF
label/unit/vital-types, chart label, threshold metric order/label/bounds.
Audit-2026-05-07 / phase P0:
- closes#109 (filter UI gap, root cause for the German raw-enum display)
- closes audit C-9 (server PDF used a stale type map)
- closes audit C-15 (no warn/critical bands for body composition)
Tests: 282 → 296 (14 new). Typecheck clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: align OpenAPI spec + migration comment with body-composition reality
- OpenAPI MeasurementType enum: add TOTAL_BODY_WATER + BONE_MASS (was at
v1.3.0 baseline; spec drifted past the v1.3 server release)
- Bump openapi version 1.3.0 → 1.3.2 to match package.json
- Migration 0022 comment: TOTAL_BODY_WATER stores kg (water content),
not percent of body weight. Validators (VALUE_RANGES) and the Withings
client (type 77 → kg) treat it as kg already; the comment was the lone
outlier and would mislead the next reviewer.
Audit-2026-05-07 / phase P1a — closes audit M-B1 (partial; OpenAPI enum)
and M-B2 (migration unit comment).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(security): close 3 audit CRITICALs (Withings header / idempotency Bearer / GlitchTip URL strip)
C-3 (Withings webhook secret in URL):
Now reads X-Withings-Webhook-Secret header in preference; URL ?secret=…
fallback retained for legacy Withings configurations and emits a Wide
Event warning so operators can spot still-using-the-old-flow integrators.
The query-string secret was leaking into Coolify access logs and any
GlitchTip event whose request.url got captured.
C-4 (idempotency dead for Bearer-token clients):
The default userIdResolver only consulted getSession(). Bearer-authed
clients (the iOS / n8n / headless-API fleet that PR #117 was built for)
fell through, so every retry created duplicate measurements. The default
now tries cookie session first, then Bearer token via
hashToken+apiToken.findUnique with revoked/expiry checks. All three
existing call sites (measurements, mood-entries, medications/intake) get
the fix automatically.
H-B7 (request.url with secrets shipped to GlitchTip):
reportToGlitchtip now strips the query string before forwarding the URL,
so Withings legacy ?secret=… and any OAuth ?code=… that errors during
the callback don't end up in someone else's incident UI.
Audit-2026-05-07 / phase P2.
Tests: 296 → 301 (5 new in idempotency.test for the Bearer fallback +
revoked/expired/null cases).
Deferred to a follow-up (needs DB migration / lock primitive):
C-2 moodLog webhook → AES-GCM at rest + HMAC-over-body
C-5 idempotency TOCTOU advisory_lock or in-flight sentinel row
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat(measurements): add OXYGEN_SATURATION (SpO2) as first-class measurement type — v1.3.3
Closes the OxygenSaturation feature request from #109.
- Migration 0024 extends MeasurementType enum (additive, IF NOT EXISTS)
- Zod validators: plausibility 50–100% (below 50 is incompatible with
sustained life; above 100 is physically impossible)
- effective-range thresholds: green 95–100, orange 92–94, red <92.
Sources: BTS Guideline 2017 (target 94–98%), ATS clinical practice
(≥95% at rest is healthy), AHA/clinical literature (<92% = call
provider, <88% = ER). Lower-only concern — upper orange wing
collapses to greenMax since saturation cannot exceed 100%.
- Personalisation: existing thresholds-override UI lets COPD /
chronic-respiratory users with a doctor-set 88–92 baseline tune the
bands. METRIC_ORDER + METRIC_LABEL_KEYS extended in
thresholds-section.tsx; the exhaustive `Record<ThresholdMetric>`
forces TS to catch any missed surface.
- Withings ScanWatch type 54 mapping (best-effort — only fires for
pulse-ox-capable devices).
- Wired through measurement-form, measurement-list-meta (icon: Wind),
health-chart, both doctor-report-pdf renderers (core + browser-side
near-duplicate), OpenAPI spec (version 1.3.0 → 1.3.3), and i18n in
4 sections × 2 locales.
- iOS DTO already declared `OXYGEN_SATURATION` — server enum addition
closes the long-standing drift flagged in audit V2.
- 4 new tests: numeric green band, upper-wing collapse,
user-override (COPD baseline), METRIC_BOUNDS shape.
Tests: 301 → 305. Typecheck: clean.
Audit-2026-05-07 / v1.3.3 / closes#109 SpO2 feature request.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(analytics): truthfulness pass on medical citations + clamp override orangeMax
Doctor-agent + hallucination-hunter audit V3 found six medical citations
in effective-range.ts that the code did not actually implement. Plus a
latent bug in the user-override path that produced physically-impossible
orangeMax values (>100% saturation, <0% body-fat).
Citation rewrites (no numeric changes):
- ACTIVITY_STEPS: "WHO ≥8000 steps/day" → Saint-Maurice JAMA 2020.
WHO publishes activity in min/week, not steps. Step-count was a
misattribution that also leaked into AI prompts.
- TOTAL_BODY_WATER: "ESPEN Body Composition Guidance 2017" → Watson
formula / ICRP Reference Man. ESPEN 2017 is BIA practice guidance,
it does not publish kg cut-offs.
- BONE_MASS: "DEXA-equivalent bone mineral content" → "Bioimpedance-
estimated; not DEXA-comparable". Withings BIA values typically run
5–7% below DEXA — calling them DEXA-equivalent in a doctor-report
PDF was a real legal-exposure misattribution.
- OXYGEN_SATURATION: "BTS Guideline 2017 (target 94–98%) + ATS
clinical practice (≥95% at rest is healthy)" → "consumer pulse-
oximeter consensus (≥95% normal at rest); slightly tighter than
BTS 2017 (94–98%); NICE NG115 ≤92% escalation, BMJ panel / FDA
pulse-oximeter labelling ≤88% ER threshold". Code uses 95-100/92-100
band — that's an ATS/consumer-consensus number, not BTS's literal
94-98 target. Soften the citation to match the code, not vice versa.
Bug fix (1 latent, 1 real-today):
- effective-range override path now clamps orangeMin/orangeMax to
METRIC_BOUNDS.{min,max}. Without the clamp, a COPD user setting
SpO2 override to {95,100} emitted orangeMax = 100.75 (impossible
saturation), and a BODY_FAT override of {2,80} emitted orangeMin
= -9.7 (negative percent). Default-range case 210 already
hard-coded orangeMax: 100 for the same reason — the override path
was the only branch missing the invariant.
Tests: 305 → 306 (1 new: clamps override orangeMax to physiological 100%).
Typecheck: clean.
Audit-2026-05-07-V3 / closes Doctor + Senior-Dev medical-citation findings.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(security): Bearer-scope wildcard handling + GDPR Art.17 account-delete erasure
Two CRITICAL fixes from audit V3.
NEW-V3-1: Bearer-scope bypass.
apiToken.permissions ["*"] is meant to be the wildcard "session-equivalent"
scope (the iOS app receives this on login). The previous check
permissions.includes(requiredPermission)
treated "*" as a literal string — never matched. Today many sensitive
routes call requireAuth() *without* a requiredPermission, so a leaked iOS
token can act as a full-scope token (account delete, settings wipe). Once
those routes adopt requireAuth("scope:name"), this wildcard handling keeps
the iOS app working while narrower-scoped tokens (e.g. user-issued
["medication:ingest"]) get correctly 403'd.
Same wildcard handling added to the standalone permission checks in
src/app/api/ingest/medication/route.ts:65, 119.
NEW-V3-2: GDPR Art. 17 account-delete erasure completeness.
Feedback + AuditLog rows had `onDelete: SetNull` in the schema, which
preserved PII (free-text symptom descriptions, IP addresses, login-city
geolocation) after the user was deleted. We now explicitly
prisma.feedback.deleteMany + prisma.auditLog.deleteMany before the
cascade-delete, making account deletion genuinely complete erasure.
Tests 306/306 still pass; typecheck clean. Audit V3.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* test(pdf): real text-content assertions for body composition + SpO2 rows
Replaces bytes-only "renders body composition rows" theatre test with
pdf-parse-driven text extraction that asserts the actual rendered labels
+ values for TOTAL_BODY_WATER, BONE_MASS, OXYGEN_SATURATION (DE + EN).
Closes V3 audit finding STILL-V2-NEW-3: the previous test only verified
"%PDF-" header + byte-count, so a regression that drops a row would
still pass. Now a missing label fails the test.
- adds dev dep: pdf-parse@^2.4.5
- 308/308 tests pass (was 306, +2 SpO2 + EN-locale coverage)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(measurements): close enum drift cousins — derive 5 type-arrays from canonical enum + extend 2 contract enums
V3 audit finding "enum drift cousins": 7 hardcoded module-level type arrays
silently dropped SpO2/TBW/BoneMass/BloodGlucose from their respective
domains. Adding a new measurement type required hunting these down.
Now all aggregation paths derive from `measurementTypeEnum.options`:
- /api/insights/comprehensive (AI insights)
- /api/dashboard/summary (iOS dashboard adapter)
- /api/analytics (analytics aggregator)
- /lib/insights/general-status (AI general-status fetch)
- /api/import (Zod schema — round-trip now covers all 11 types)
External-contract enums extended additively (no breakage for old clients):
- /api/measurements/series kindEnum: + oxygen, totalBodyWater, boneMass
- /api/dashboard/widgets widgetIdEnum: + oxygenSaturation
- DashboardWidgetId + DEFAULT_DASHBOARD_LAYOUT: + oxygenSaturation row
- formatMeasurementsForExport: glucoseContext now round-trips
Coverage test (`measurement-type-enum-coverage.test.ts`) asserts the
canonical enum stays the source of truth and documents PDF exclusions
(BLOOD_GLUCOSE renders via context section, SLEEP/STEPS lifestyle-only).
313/313 tests pass (was 308, +5 new).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(security): close 6 V3-audit HIGH findings (CSP, web-push SSRF, IP geo, AI provider leak, import rate-limit)
- CSP: chatgpt.com + api.openai.com only on /settings/ai/** routes (was
blanket connect-src on every page including /auth/login → DOM-XSS exfil
channel)
- web-push: webPushSubscriptionSchema.endpoint requires HTTPS + isPublicUrl
refinement; was z.url() only → blind SSRF probe via Push subscription
- isPublicUrl: also fixes a regression where DNS labels starting with
"fc"/"fd" (fcm.googleapis.com etc.) were falsely classified as IPv6
unique-local. Check is now gated on a colon being present in the host.
- /api/ai/test: stop returning provider err.message + bodyExcerpt to the
client (leaked provider URLs / partial keys / internal headers). Now
returns categorised generic message; full details land in the wide-event
via annotate() for the operator.
- /lib/geo (auditLog IP geo lookup): switch default provider to
ipwho.is over HTTPS, accept ipwho.is + ip-api pro response shapes,
add IP_GEO_LOOKUP_DISABLED env, refuse non-HTTPS configured URLs.
Previously leaked IP+timestamp over plaintext HTTP every auth event
(GDPR Art. 32 + Art. 44).
- /api/import: add 5/hour rate-limit (was unlimited; bulk-injection vector)
Tests: 325/325 pass (was 313, +12 new — webPushSubscriptionSchema SSRF
guards, fc/fd-prefix domain regression, geo HTTPS-only, geo provider
shapes, geo opt-out env).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(security,gdpr): trusted-proxy IP, audit-log retention, idempotency cachable filter, Bearer mock tightening
V3 audit follow-on bundle covering 4 HIGH findings.
(I) getClientIp — TRUST_PROXY_HOPS env (default 1) replaces blind XFF
trust. Reads chain right-to-left so client-supplied leftmost entries
cannot rotate the per-IP rate-limit bucket. Default 1 matches typical
single-proxy self-host (Coolify/Caddy/Cloudflare-Tunnel); 0 forces
x-real-ip / null. New 7-test suite covers the rotation attack +
malformed entries + zero-hop fallback.
(F) Audit-log retention job — daily 03:15 cleanup of audit_logs older
than AUDIT_LOG_RETENTION_DAYS (default 365). Closes GDPR Art. 5(1)(e)
"storage limitation" gap; previously IPs + city + login events
accumulated forever. 6-test suite covers default + override +
misconfig guard (rejects <7 days).
(G) isCachableStatus — extracted the inline 4xx/5xx filter into a
named, exported, tested function. 7 cases cover the full do-not-cache
contract (401 / 403 / 408 / 429 / any 5xx) and confirm 2xx + 4xx
validation are still cached.
(H) Bearer-mock tightening — apiToken.findUnique mocks in
require-auth-bearer.test + idempotency.test now assert the
where.tokenHash shape uses the hashed value (not the raw bearer).
A regression that switched back to raw-token comparison would have
been silent without this assertion.
Tests: 345/345 pass (was 332, +13 new).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(security): encrypt moodLog webhook secret at rest with AES-256-GCM (V3 audit STILL-V2-C-2)
The mood_log_webhook_secret column previously stored a plaintext secret
that the webhook handler compared timing-safe against every enabled
user. A DB dump or backup snapshot leaked active webhook credentials.
New contract — no schema migration required:
- Writes go through encryptMoodLogSecret() (AES-256-GCM via existing
crypto helper, ENCRYPTION_KEY).
- Reads go through readMoodLogSecret() which transparently decrypts
envelopes and tolerates legacy plaintext rows during the transition
(graceful upgrade path — no breaking change for self-hosted users).
- Webhook lookup decrypts each candidate before timing-safe compare.
- Status endpoint decrypts for the user's settings page.
One-shot startup migration in reminder-worker rotates any leftover
plaintext rows on next worker boot. Idempotent; encrypted rows are
skipped.
Tests: 350/350 pass (was 345, +5 new — round-trip, legacy passthrough,
isLegacyPlaintext semantics, rotateLegacy idempotence).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* docs: sync README + AGENTS + CLAUDE + CHANGELOG + OpenAPI for v1.3.3 (V3 audit doc-drift)
V3 audit Doku Specialist findings — drift between code and meta-docs.
- README §Key Features now mentions pulse oximetry (SpO₂) + Withings
ScanWatch sync; Tech Stack model count corrected 23 → 25.
- AGENTS.md status promoted v1.3.2 → v1.3.3; vitest config corrected
`vitest.config.ts` → `vitest.config.mts`; migration range corrected
`0001–0022` → `0001–0024`; model count + list updated to 25 (adds
Device, IdempotencyKey).
- CLAUDE.md model count updated (2 occurrences).
- CHANGELOG.md v1.3.3 expanded with Security + Internal sections that
were missing the audit-fix-marathon work (Bearer-scope, account-delete
cascade, moodLog encryption, CSP tightening, Web-Push SSRF, IP-geo
HTTPS, AI-test leak fix, import rate-limit, trusted-proxy XFF,
audit-log retention, idempotency cachable filter, Bearer mock
tightening, enum-drift cousins, PDF text-content tests).
- OpenAPI Bearer description corrected `SHA-256 hashes` →
`HMAC-SHA-256 hashes (keyed with API_TOKEN_HMAC_KEY)` so the docs
match the actual server-side implementation. Wildcard scope contract
documented.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(audit-review): close 4 HIGH + 2 MEDIUM findings from multi-agent review pass
Multi-agent review of the audit-fix branch surfaced four HIGH issues
and a couple of MEDIUM hardenings. All addressed before merge.
HIGH-1 — OpenAPI MetricKind enum drift (iOS strict-decode crash risk).
The dashboard-summary route now emits totalBodyWater/boneMass/
oxygenSaturation MetricCards, but the spec still listed only the
original 7 kinds. Generated iOS Codable would have crashed the dash
the moment a user logged SpO2. MetricKind extended with the 3 new
kinds + comment documenting unknown-value defensive decoding.
HIGH-2 — kindEnum naming consistency on /api/measurements/series.
The series adapter shipped "oxygen" while the dashboard summary used
"oxygenSaturation"; both routes now use "oxygenSaturation" so iOS
decoders can share a single MetricKind type across endpoints.
HIGH-3 — /api/ai/test no-leak guard had no test. Added 4 tests that
mock provider errors with sk-leaked-key + provider URLs in the err
fields and assert the response body never echoes them, plus the
3-status-categorised generic messages (401/429/5xx/other).
HIGH-4 — /api/import 5/hour rate-limit had no test. Added 2 tests that
mock checkRateLimit allowed/disallowed and assert the 429 path uses
the right key shape (`import:<userId>`, 5, 1h) and that the within-
quota path proceeds.
MEDIUM-3 — getClientIp under-length XFF chain regression. With
TRUST_PROXY_HOPS=2 and a chain of length 1, the previous clamp
returned the leftmost (attacker-controlled) entry, silently
re-introducing the rotation attack the helper was meant to close.
Now: when chain is shorter than configured hops, refuse XFF entirely
(fall back to x-real-ip / null). Added regression test.
LOW-1 — TRUST_PROXY_HOPS=garbage now throws at boot instead of
silently degrading to hops=0. Added regression test.
Tests: 358/358 pass (was 350, +8 new). Typecheck clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>