* fix(medical): protect against silent DBP hypotension and align BP citations Three correctness issues that the v1.3.3 ecosystem audit surfaced and that we deferred until the v1.4 cycle: 1. **Diastolic blood-pressure orange band reached 60 mmHg.** With the default age-based targets (DBP 70-79), the lower orange wing was computed as `diaLow - 10 = 60`, putting a sustained reading of 60 mmHg into "mildly low" territory — visually a yellow tile, not a red one. 60 mmHg is widely treated as a hypotension / perfusion-risk threshold (general-adult <90/60 from AHA/NIH; J-curve evidence in ONTARGET / TRANSCEND for treated hypertensives; ESH 2023's explicit caution against treating below 70 in the elderly). The orange floor is now clamped at 65 mmHg, so a reading of 60 lands in red. The user-override path stays untouched and is already audit-logged. 2. **"ESC/ESH 2023" doesn't exist as a joint guideline.** ESC withdrew from the 2023 authoring; the 2023 hypertension document is ESH-only. The codebase had a mix of "ESC/ESH 2018" (analytics) and "ESC/ESH 2023" (AI prompts). Both are wrong in different directions. Every site (`bp-targets.ts`, `targets/route.ts`, `ai/prompts/blood-pressure.ts`, `ai/prompts/base-system.ts`) now cites "ESH 2023" with the published source URL. Target bands are unchanged 2018 → 2023 — only the citation moves. 3. **"WHO ≥ 8 000 steps/day" was a recurring hallucination.** WHO's 2020 Physical Activity guidelines publish minutes per week, not a step quota. The cohort study HealthLog actually relies on is Saint-Maurice et al., JAMA 2020 (mortality plateau 8 000–12 000 steps). The v1.3.3 fix landed in `effective-range.ts` but four AI prompt strings (`base-system.ts` DE+EN, `general-status.ts` DE+EN) carried the old wording forward. Same fix shape: cite Saint-Maurice for the step number and add an explicit "WHO does not publish a step quota" note so the model doesn't regress. Sleep target moves from "ESC" to AASM 2015 in the same surfaces — ESC publishes no adult sleep duration guideline. Adds `src/lib/medical-citations.ts` as the new single source of truth for cited guidelines (id, name, year, url, caveat). v1.4 surfaces will import these constants instead of duplicating strings, and the new `medical-citations.test.ts` drift-test asserts that every entry has a non-empty url + caveat, that ids are unique, and that the WHO-as-step- source hallucination cannot reappear as a constant. Tests: 358 → 363 (5 new for the master citations list). Typecheck and existing analytics tests pass. No clinical numbers changed beyond the DBP orange-floor clamp. Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com> * fix(medical): consolidate body-fat ACE bands and document bedtime-glucose source Two related medical-truthfulness issues from the v1.3.3 ecosystem audit. **Body-fat classification: ACE bands corrected.** v1.3.3's classifier used `essential = 6 (M) / 14 (F)` as the *floor* of the "Essential" category, which is actually ACE's *Athletes* lower bound. Anything below was lumped under "Essential" — including readings (e.g. 1% male) that are clinically concerning, not just "athletically extreme". The classifier now mirrors the ACE table precisely: - Below essential (M <2 / F <10): danger. - Essential (M 2–5 / F 10–13): warning. - Athletic (M 6–13 / F 14–20): normal. - Fitness (M 14–17 / F 21–24): normal. - Acceptable (M 18–24 / F 25–31): warning. - Obese (M ≥25 / F ≥32): danger. **Three-way drift in body-fat target ranges consolidated.** v1.3.3 had three sites with three different green-band numbers: - `value-bands.ts:118-120` returned M{10,20} / F{18,28}. - `app/api/insights/targets/route.ts:336-338` hardcoded M{14,24} / F{21,31} with `source: "ACE"`. - `classifications.ts:155-205` used a third overlapping set of thresholds for the band labels. ACE fitness + acceptable (M 14–24 / F 21–31) is the realistic healthy band for a non-athlete adult and is now the single source in `getBodyFatTargetRange`. Targets route and chart value-bands import the helper instead of duplicating the numbers. **Bedtime glucose citation softened.** ADA Standards of Care 2024 §6 publishes pre-prandial 80–130 and post-prandial <180; the document does NOT publish an adult bedtime target. The 90–150 mg/dL band HealthLog ships is reasonable advice (within the daytime pre-prandial range, slightly raised floor to avoid nocturnal hypoglycaemia) but it's not ADA-published. The inline comment in `effective-range.ts` now states the absence of an adult guideline explicitly and cites ISPAD 2022 (pediatric T1D, 80–140) as the closest comparator. Numbers unchanged. Tests: 363 → 369 (6 new for the ACE bands). Existing assertions unchanged. Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com> * fix(medical): align step-range target with the effective-range source `getStepsRange()` in classifications.ts returned `{7 000, 10 000}` while `effective-range.ts` (the canonical resolver behind `getEffectiveRange`) returned `{8 000, 15 000}`. The two surfaces showed different "green" bands to the same user — `/api/insights/ targets` used the lower pair, the dashboard chart-bands used the upper pair. Aligns both on the upper pair, anchored on Saint-Maurice et al. JAMA 2020 (mortality plateau 8 000–12 000 steps/day). Adds the citation header to the steps section so the next audit pass can verify in place. WHO is explicitly called out as NOT a source for a step quota (only an activity-time guideline). The classifier function `classifySteps` is unchanged — its 3 / 5 / 7.5 / 10 k bands match Tudor-Locke 2004 pedometer indices and are kept distinct from the two-number "target range" helper. Tests stay at 369/369. Co-Authored-By: Marc-André Bombeck <noreply@anthropic.com> --------- Co-authored-by: Marc-André Bombeck <noreply@anthropic.com>
HealthLog
Your health data belongs to you. Track it on your own terms.
A self-hosted, privacy-first health tracking PWA.
Weight, blood pressure, mood, medications, AI insights -- all under your control.
Website · Live Demo · Documentation
Why HealthLog?
Most health apps lock your data behind proprietary clouds, push subscriptions, and sell your metrics to advertisers. HealthLog takes a different approach: your data stays on your server, encrypted at rest, accessible only to you.
Key Features
Health Metrics -- Track weight, blood pressure, pulse, body fat, sleep, steps, blood glucose (fasting/postprandial/random/bedtime, mg/dL ↔ mmol/L), total body water, bone mass, and pulse oximetry (SpO₂) with interactive trend charts, moving averages, and traffic-light ranges based on ESC/ESH 2018, ADA 2024, and consensus pulse-oximeter guidance (NICE NG115). Body-composition + SpO₂ metrics sync automatically from Withings Body+ scales and ScanWatch devices.
Custom Thresholds -- Override the computed default ranges per metric with the targets your clinician set. Audit-logged. Doctor Report PDF prints both your target and the standard reference.
Customizable Dashboard -- Show, hide, and drag-to-reorder every widget. Per-user layout with reset-to-defaults.
Mood Logging -- 5-point scale with tags, notes, and trend analytics. Syncs automatically from moodLog.app via webhook.
Medication Compliance -- Flexible scheduling with time windows, recurrence patterns, intake logging (take/skip/snooze), and compliance heatmaps. External API for iOS Shortcuts integration.
Withings Integration -- OAuth2 device sync for scales, blood pressure monitors, and activity trackers with automatic deduplication.
Multi-Provider AI Insights -- Pick OpenAI, Anthropic Claude, or any local OpenAI-compatible endpoint (Ollama, LM Studio, vLLM). BYOK or admin-shared key. Cached daily. Local endpoints keep all data on your network.
Doctor Report PDF Export -- Generate professional medical reports client-side. Locale-aware (English/German), with vital sign summaries, BP/BMI/glucose classification, compliance rates, custom-threshold badges, and optional AI analysis.
Built-in Feedback -- Send bug reports and feature requests from inside the app. Stored in your HealthLog database — no GitHub config required. Optional GitHub escalation for admins.
PWA with Offline Support -- Installable on iOS and Android. Service worker with intelligent caching strategies for reliable offline access.
Multi-Channel Notifications -- Telegram (with inline action buttons), ntfy (self-hostable), and Web Push. Medication reminders with late/missed escalation.
Gamification -- 38+ persistent achievements across intake streaks, compliance milestones, and healthy metric streaks.
Internationalization -- English (default) and German UI with 1500+ translation keys, guarded by a CI integrity test that fails the build on duplicate keys or drift between locales. Numbers, dates, units, and AI prompts all locale-aware via useFormatters(). Browser-based detection with per-user override.
Quick Start
Plan ~5 minutes for a working install. The bundled docker-compose.yml pulls a pre-built multi-arch image (linux/amd64 + linux/arm64) from GitHub Container Registry; no build step required for self-hosters. Contributors who want to test local changes can docker compose up --build.
git clone https://github.com/MBombeck/HealthLog.git
cd HealthLog
cp .env.example .env
Generate the four required secrets and paste them into .env:
echo "POSTGRES_PASSWORD=$(openssl rand -base64 24)" >> .env
echo "SESSION_SECRET=$(openssl rand -hex 32)" >> .env
echo "ENCRYPTION_KEY=$(openssl rand -hex 32)" >> .env
echo "API_TOKEN_HMAC_KEY=$(openssl rand -hex 32)" >> .env
Then bring the stack up:
docker compose up -d
Open http://localhost:3000. The first registered user becomes admin.
Behind a reverse proxy (Caddy / Traefik / Nginx) for TLS, set
NEXT_PUBLIC_APP_URLandAPP_URLto your public URL in.envbefore starting. See Self-Hosting → Reverse Proxy for examples.
Tech Stack
| Layer | Technology |
|---|---|
| Framework | Next.js 16 (App Router, React Server Components) |
| Language | TypeScript (strict mode) |
| Database | PostgreSQL 16 + Prisma 7 (25 models) |
| Job Queue | pg-boss 12 (reminders, insights, backups) |
| UI | shadcn/ui, Tailwind CSS 4, Radix UI, Lucide Icons |
| Charts | Recharts 3 |
| Data Fetching | TanStack Query 5 |
| Forms | React Hook Form 7 + Zod 4 |
| Auth | SimpleWebAuthn 13, Argon2id |
| Notifications | Telegram Bot API, ntfy, Web Push (VAPID) |
| jsPDF (client-side generation) | |
| Testing | Vitest 4 |
| Deployment | Docker (multi-stage Alpine) |
Security and Privacy
HealthLog is designed for people who take data ownership seriously.
- Self-hosted -- Your data never leaves your server. No telemetry, no third-party tracking.
- AES-256-GCM encryption -- All stored secrets (OAuth tokens, API keys, VAPID keys) are encrypted at rest.
- Passkey authentication -- WebAuthn as primary auth with password fallback (Argon2id + zxcvbn strength validation).
- Server-side sessions -- PostgreSQL-backed with 30-day sliding expiry, HttpOnly/SameSite=Strict cookies.
- Security headers -- CSP with nonces, HSTS, X-Frame-Options DENY, Permissions-Policy, Referrer-Policy.
- Rate limiting -- Sliding window on auth and API endpoints.
- HMAC-SHA256 API tokens -- Bearer tokens are hashed before storage.
- Audit logging -- All sensitive operations tracked with IP addresses.
Environment Variables
Required
| Variable | Description |
|---|---|
POSTGRES_PASSWORD |
Password for the bundled Postgres service (Docker Compose) |
DATABASE_URL |
PostgreSQL connection string (uses POSTGRES_PASSWORD above) |
SESSION_SECRET |
64-char hex string for session signing |
ENCRYPTION_KEY |
64-char hex string for AES-256-GCM |
API_TOKEN_HMAC_KEY |
64-char hex string for API token hashing |
Optional
| Variable | Description |
|---|---|
NEXT_PUBLIC_APP_URL |
Public-facing URL (default: http://localhost:3000) |
WITHINGS_CLIENT_ID |
Withings OAuth2 client ID |
WITHINGS_CLIENT_SECRET |
Withings OAuth2 client secret |
WITHINGS_REDIRECT_URI |
OAuth callback URL |
WITHINGS_WEBHOOK_SECRET |
Webhook URL hardening secret |
TELEGRAM_WEBHOOK_SECRET |
Telegram bot webhook secret |
Telegram bot token, ntfy settings, Web Push VAPID keys, Umami, and GlitchTip URLs are configured in the Admin Panel and stored encrypted in the database.
Architecture
src/
├── app/ # Next.js App Router pages & API routes
│ ├── api/ # REST API endpoints (100+ route files)
│ ├── admin/ # Admin panel
│ ├── auth/ # Login, register, passkey enrolment
│ ├── medications/ # Medication management
│ ├── measurements/ # Health metric entry
│ ├── mood/ # Mood log
│ ├── insights/ # AI-powered analytics
│ ├── charts/ # Long-form charts
│ ├── achievements/ # Gamification page
│ ├── targets/ # Custom thresholds dashboard
│ ├── notifications/ # Notification preferences matrix
│ ├── bugreport/ # Built-in feedback / bug report
│ ├── onboarding/ # 4-step guided setup
│ └── settings/ # User preferences (8 top-level sections)
├── components/
│ ├── ui/ # shadcn/ui primitives
│ ├── layout/ # Shell (sidebar, topbar, bottom nav)
│ ├── medications/ # Medication cards, forms, timeline
│ ├── measurements/ # Measurement form, list
│ ├── mood/ # Mood form, mood list
│ ├── charts/ # Recharts wrappers
│ ├── insights/ # AI insight status / advisor cards
│ ├── gamification/ # Achievement cards, progress
│ ├── monitoring/ # Umami / GlitchTip bootstrap
│ └── settings/ # Settings-page section components
├── lib/
│ ├── auth/ # Session, audit, passkey logic
│ ├── notifications/ # Dispatcher + channel senders
│ ├── jobs/ # pg-boss worker (reminders, insights, backups)
│ ├── analytics/ # Trend calculations, compliance, correlations
│ ├── ai/ # Multi-provider client (OpenAI, Anthropic, local)
│ ├── insights/ # Insight pipeline + medical prompts
│ ├── gamification/ # Achievement definitions
│ ├── feedback/ # Built-in feedback + GitHub escalation
│ ├── moodlog/ # moodLog.app webhook + sync
│ ├── monitoring/ # Umami / GlitchTip server-side hooks
│ ├── withings/ # OAuth client, sync service
│ ├── logging/ # Wide Events: builder, context, transports
│ ├── i18n/ # Translations context & config
│ ├── validations/ # Shared Zod schemas
│ ├── api-handler.ts # apiHandler wrapper, requireAuth/requireAdmin
│ ├── api-response.ts # { data, error } envelope helpers
│ ├── crypto.ts # AES-256-GCM encrypt/decrypt
│ ├── rate-limit.ts # Sliding-window rate limiter
│ ├── db.ts # Prisma singleton
│ └── doctor-report-pdf.ts # Client-side PDF generation
├── hooks/ # React hooks
└── generated/prisma/ # Generated Prisma client
Key Patterns
- RSC by default --
"use client"only for interactive components - API envelope -- All responses follow
{ data, error }shape viaapiSuccess()/apiError()insrc/lib/api-response.ts - apiHandler wrapper -- Every API route wraps its handler in
apiHandler()(src/lib/api-handler.ts) for consistent error handling, Wide-Event structured logging, andx-request-idpropagation - Encrypted secrets -- Withings tokens, API keys, VAPID keys, notification credentials
- Timezone-aware --
Europe/Berlinfor display, UTC in database - Route protection --
proxy.ts(Next.js 16's renamed middleware) checks session cookie, redirects unauthenticated requests - Client-side PDF -- Doctor reports generated in browser via jsPDF
API Reference
All mutations require authentication via session cookie. External ingest uses Bearer tokens.
Health Data
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/measurements |
List measurements (paginated, filterable) |
POST |
/api/measurements |
Create measurement |
DELETE |
/api/measurements/:id |
Delete measurement |
GET |
/api/analytics |
Trend summaries (7d/30d) |
GET |
/api/export |
Export as CSV or JSON |
POST |
/api/import |
Import from JSON |
POST |
/api/doctor-report |
Aggregated data for PDF |
Mood
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/mood-entries |
List mood entries |
POST |
/api/mood-entries |
Create mood entry |
DELETE |
/api/mood-entries/:id |
Delete mood entry |
GET |
/api/mood/analytics |
Mood trend analytics |
POST |
/api/integrations/moodlog/webhook |
moodLog.app webhook |
Medications
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/medications |
List all medications |
POST |
/api/medications |
Create medication |
PUT |
/api/medications/:id |
Update medication |
DELETE |
/api/medications/:id |
Delete medication |
POST |
/api/medications/:id/intake |
Log intake event |
GET |
/api/medications/:id/compliance |
Compliance stats |
POST |
/api/ingest/medication |
External intake (Bearer) |
Auth and Integrations
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/auth/register |
Create account |
POST |
/api/auth/login |
Password login |
POST |
/api/auth/logout |
Destroy session |
GET |
/api/auth/me |
Current user profile + Gravatar URL |
POST |
/api/auth/password |
Change password |
PATCH |
/api/auth/profile |
Update profile fields |
POST |
/api/auth/passkey/* |
WebAuthn flows (4 sub-routes) |
GET |
/api/auth/passkeys |
List enrolled passkeys |
GET |
/api/auth/codex/authorize |
ChatGPT (codex) OAuth start |
GET |
/api/withings/connect |
Initiate Withings OAuth |
POST |
/api/withings/sync |
Trigger manual Withings sync |
POST |
/api/withings/webhook |
Withings notification webhook |
POST |
/api/insights/generate |
Regenerate AI insights |
GET |
/api/insights/comprehensive |
Aggregated insight payload |
GET |
/api/gamification/achievements |
Achievement progress |
GET |
/api/health |
Docker health check |
Personalization (Thresholds + Dashboard)
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/user/thresholds |
Read per-user threshold overrides |
PUT |
/api/user/thresholds |
Upsert thresholds (rate-limited, audit-logged) |
GET |
/api/insights/targets |
Effective ranges (defaults + overrides merged) |
GET |
/api/dashboard/widgets |
Read dashboard layout |
PUT |
/api/dashboard/widgets |
Persist dashboard layout (show/hide/reorder) |
POST |
/api/onboarding/complete |
Mark onboarding finished |
Feedback + API Tokens
| Method | Endpoint | Description |
|---|---|---|
POST |
/api/feedback |
Submit in-app feedback |
GET |
/api/bugreport/status |
Check published GitHub issue state |
GET |
/api/tokens |
List own API tokens |
POST |
/api/tokens |
Mint new API token (Bearer, hashed) |
DELETE |
/api/tokens/:id |
Revoke API token |
Notifications
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/notifications/preferences |
Read per-channel × per-event matrix |
PUT |
/api/notifications/preferences |
Update preferences |
GET |
/api/notifications/vapid |
VAPID public key for Web Push |
POST |
/api/notifications/web-push |
Register Web Push subscription |
POST |
/api/telegram/webhook |
Telegram bot inline-button callback |
Admin (admin role required)
| Method | Endpoint | Description |
|---|---|---|
GET |
/api/admin/status |
System + integration status |
GET |
/api/admin/users |
List users |
POST |
/api/admin/users/:id/reset-password |
Force password reset |
GET |
/api/admin/feedback |
All feedback / bug reports |
POST |
/api/admin/feedback/:id/github |
Escalate feedback to GitHub issue |
GET |
/api/admin/audit-log |
Audit-log viewer |
GET |
/api/admin/ai-settings |
Read shared AI provider config |
PUT |
/api/admin/ai-settings |
Update shared AI provider config |
GET |
/api/admin/tokens |
All issued API tokens |
POST |
/api/admin/notifications/test |
Send test notification |
GET |
/api/admin/data |
Data backups + counts |
Integrations
| Integration | Setup | Purpose |
|---|---|---|
| Withings | Env vars | Auto-sync weight, BP, and activity |
| Telegram | Admin Panel | Medication reminders with inline buttons |
| ntfy | User Settings | Self-hosted push notifications |
| Web Push | Admin Panel | Browser-native VAPID notifications |
| OpenAI | User Settings | AI health insights (BYOK) |
| moodLog.app | User Settings | Mood tracking sync |
| Umami | Admin Panel | Privacy-friendly analytics |
| GlitchTip | Admin Panel | Sentry-compatible error tracking |
Local Development
# Prerequisites: Node.js 20+, pnpm, PostgreSQL
cp .env.example .env
pnpm install
pnpm db:generate
pnpm db:migrate
pnpm dev
Scripts
pnpm dev # Development server
pnpm build # Production build
pnpm lint # ESLint
pnpm typecheck # TypeScript strict check
pnpm test # Vitest
pnpm format # Prettier
pnpm db:generate # Generate Prisma client
pnpm db:migrate # Create & apply migration
pnpm db:migrate:deploy # Apply migrations (production)
pnpm db:studio # Prisma Studio GUI
Deployment
The included docker-compose.yml runs the app and PostgreSQL. The entrypoint automatically waits for the database, runs pending migrations, and starts the server.
The app listens on port 3000. Place it behind Nginx, Caddy, or Traefik for TLS termination. Works out of the box with Coolify.
Contributing
Contributions are welcome. See CONTRIBUTING.md for guidelines.
- Code style:
pnpm format && pnpm lint - Type safety:
pnpm typecheckmust pass - Tests:
pnpm test - UI language: English by default, German selectable per user. Code, comments, and commits: English.
License
HealthLog is licensed under the GNU Affero General Public License v3.0.