الصفحات · Health Debug
10 — Security, AI BYOK, IoT Integrations & Future B2B State
Purpose
This document plans the security-sensitive edges of Health Debug: how user-supplied AI keys (BYOK) are stored and used without ever touching a client, what the AI is and is not allowed to say (Core Opinion 2), how biometric data flows from IoT sources (Apple HealthKit, Google Health Connect) into the ToGO backend, and how the platform is shaped today so that the FUTURE STATE — doctor dashboards, Medical Restrictions, gamification badges, and B2B marketplace APIs — can be added later without re-architecting. This is a planning artifact only; no production code. The FUTURE STATE sections are explicitly out of initial scope: we design for them, we do not build them.
1. Security Principles (Recap of Non-Negotiables)
These constraints from the project charter govern everything in this document:
| # | Principle | Consequence in this document |
|---|---|---|
| 1 | The ToGO REST API is the Single Source of Truth (SSOT); clients never compute or hardcode protocol business logic | AI proxying, key handling, and (future) Medical Restrictions all live server-side only |
| 2 | Core Opinion 2 — the app NEVER invents medical certainty | Hard AI output boundaries (Section 3) |
| 3 | No AI API key ever reaches any client | BYOK design (Section 2) |
| 4 | Every DB column is NOT NULL with a defined default | All SQL sketches below follow this |
| 5 | Migrations follow strict expand-contract | Future-state tables are additive (expand) by design |
| 6 | Clients are presentation + sensor-collection layers | IoT pipeline (Section 4): clients read on-device, push to ToGO |
2. BYOK — Bring Your Own Key AI Management
2.1 Concept
Health Debug does not ship with a bundled AI subscription. The AI layer is BYOK: the user supplies their own API key for exactly one or more of the four supported providers:
- OpenAI
- Anthropic
- Apple Intelligence
The backend stores these keys encrypted at rest, and all AI calls are proxied server-side through the ToGO backend. No client — Web, Swift, Kotlin, Electron, or Chrome Extension — ever receives, caches, or transits a raw provider key.
2.2 Key Lifecycle
Lifecycle rules:
- Submission — the key travels once, over authenticated HTTPS, from client to backend. The client discards it from memory immediately after the request completes; it is never written to local storage, keychain, cookies, or logs on the client side.
- Encryption at rest — keys are encrypted before persistence in PostgreSQL. The specific encryption mechanism (e.g., application-level envelope encryption vs. an external key-management service, and the key-rotation policy for the encryption keys themselves) is undecided and must be settled in the Phase 1 backend design.
- Use — the ToGO backend decrypts the key only in memory, only at the moment of an outbound AI provider call, on the server.
- Read-back is prohibited — there is no endpoint that returns the key material. Clients can only learn that a key exists for a provider (status), never what it is. At most a masked hint may be shown; whether a masked hint is displayed at all is PENDING DESIGN.
- Deletion — the user can revoke a key at any time; revocation removes the ability to make AI calls with that provider.
2.3 The 'AI Settings' Screen Is a Passthrough Form
Every client's "AI settings" screen is purely a passthrough form to the backend. This is a hard architectural rule, consistent with the SSOT rule that clients never hold business logic:
- The form collects: provider selection (OpenAI / Anthropic / Google / Apple Intelligence) + the key string.
- The form submits directly to the ToGO API and renders whatever status the API returns.
- The client performs no key validation logic beyond trivial non-empty checks; the backend validates the key (e.g., by a server-side test call — exact validation behavior to be defined in Phase 1).
- The client stores nothing related to the key locally.
- The screen looks the same in function across Web (React + TanStack), iOS/macOS (Swift), Android (Kotlin), Electron, and the Chrome Extension — visual treatment for each platform is PENDING DESIGN (Figma work in progress), including how the dark-mode neon palette (#1A1A1A bg, #00CCFF active buttons, #FF3333 alerts) and light-mode flat palette (#FFFFFF bg, #20A060 teal, #0070A0 deep cyan blue) apply to this screen, and its full RTL/Arabic mirroring per the i18n rules (ICU Message Format, no string concatenation).
Special note on Apple Intelligence: it is listed as a BYOK provider alongside the three cloud providers. How an "Apple Intelligence key" is represented and whether its invocation path differs from the pure server-side proxy model (given Apple Intelligence's platform-bound nature) is undecided — this is an open question for Phase 1/Phase 4 planning and must be resolved without violating the "no key on client / all AI calls proxied server-side" rule or documenting an explicit, narrowly-scoped exception if the platform makes pure proxying impossible.
2.4 Planned API Surface (sketch)
Endpoint names are placeholders; final naming follows the Phase 1 ToGO API conventions document.
| Method | Path (sketch) | Purpose | Returns key material? |
|---|---|---|---|
| PUT | /v1/ai/keys/{provider} | Submit or replace the user's key for a provider | No |
| GET | /v1/ai/keys | List providers with key status (exists / not set) | Never |
| DELETE | /v1/ai/keys/{provider} | Revoke the key for a provider | No |
| POST | /v1/ai/analyze | Request a behavioral-pattern analysis; backend picks the user's configured provider and proxies the call | No (returns analysis text only) |
{provider} enum: openai, anthropic, google, apple_intelligence.
2.5 Storage Sketch (SQL, planning only)
Follows the strict schema rule: every column NOT NULL with a defined default. Table/column names are sketches, not final DDL; final schema goes through sqlc + Atlas with expand-contract migrations.
Notes:
- One row per (user, provider); a replacement key updates the row (rotation history retention is undecided).
- Whether an audit log of AI proxy calls is kept (and its retention) is undecided — flagged as an open question because it intersects with the privacy/regulatory questions in Section 6.
2.6 Proxy Flow
The client's role is strictly: send request, render response. No prompt construction, no provider selection logic, no post-processing of AI output happens on the client.
3. AI Behavioral-Analysis Boundaries (Core Opinion 2)
Core Opinion 2 is non-negotiable: the app NEVER invents medical certainty. The AI layer exists for one purpose only: behavioral pattern analysis over the user's logged protocol data.
3.1 Hard Prohibitions
The AI is strictly prohibited from:
- Diagnosing — it must never assert or imply that the user has, or does not have, any condition.
- Prescribing — it must never recommend starting, stopping, or changing any medication or treatment.
- Guessing drug categories — it must never infer what class or category a logged medication belongs to.
3.2 The Mandatory Deferral
Every AI output shown to the user must end by deferring to: "Consult your doctor." This is enforced server-side in the proxy layer, not left to prompt compliance alone — the proxy is the last gate before any AI text reaches a client, so the deferral is appended/verified there regardless of what the model produced.
3.3 Enforcement Layers (planned)
| Layer | Mechanism | Notes |
|---|---|---|
| Prompt | Guardrail system prompt constructed server-side, stating the prohibitions and the required deferral | Clients never see or modify the system prompt |
| Proxy post-processing | Backend verifies/attaches the "Consult your doctor." deferral before returning any AI text | Deterministic; does not rely on model obedience |
| Scope of input | AI receives behavioral/protocol log patterns, not free-form medical Q&A | Exact input schema to be defined with the Phase 1 API |
Whether additional server-side output filtering (e.g., rejecting responses that appear to diagnose despite the guardrail prompt) is implemented, and how a rejected response is surfaced to the user, is undecided and must be settled in Phase 1. The non-negotiable floor is: prohibitions in Section 3.1 + mandatory deferral in Section 3.2.
3.4 Interaction with the Categorical Protocol (Core Opinion 1)
Core Opinion 1 also constrains the AI: the protocol is categorical, not quantitative — food is strictly 'Safe' or 'Trigger-bearing'. Therefore the AI performs no complex quantitative deduction logic for food. Behavioral analysis operates over categorical events (e.g., trigger-family logs, protocol adherence patterns), never over invented quantitative food modeling.
4. IoT / Biometric Pipeline
4.1 Overview
IoT integration is via Apple HealthKit and Google Health Connect. The pipeline is deliberately simple and client-thin:
- The native client (Swift on Apple platforms; Kotlin on Android/WearOS) reads biometric/sensor data on-device from HealthKit or Health Connect, using the platform's own permission model.
- The client pushes that data securely to the ToGO backend over authenticated HTTPS.
- All interpretation — protocol-engine state transitions, alerts, pattern analysis — happens server-side in the ToGO SSOT. Clients never interpret biometric data locally.
4.2 Role of Wearable Data in the Protocol Engines
The one engine with an explicit wearable dependency in the charter is the Kinetic Pomodoro Engine: a desk timer whose break only registers if wearables detect physical movement away from the screen. The movement detection signal originates on the wearable (via HealthKit / Health Connect reads), is pushed to ToGO, and the decision that a break counts is made by the backend engine — never by the client or watch app locally.
Which specific HealthKit / Health Connect data types are read (and for which engines beyond Kinetic Pomodoro), the push cadence/batching strategy, and offline buffering behavior are not defined in the charter and belong to Phase 4 (Apple suite) and Phase 5 (Android suite) detailed planning. They are listed as open items there rather than invented here.
4.3 Transport Security
- All pushes are over authenticated HTTPS; identity comes from TOGO auth (the platform's identity layer, per the Phase 1 backend plan).
- The Chrome Extension (Manifest V3), Web, and Electron clients are not HealthKit/Health Connect sources — those APIs are native-platform only; the extension/web/desktop clients are presentation and (non-biometric) behavioral input surfaces.
5. FUTURE STATE — Design-For, Do-Not-Build
Everything in this section is explicitly OUT of initial scope. It is documented so that Phase 1 schema and engine design leave room for it. No future-state feature is implemented in Phases 1–6.
5.1 Doctor Dashboards & 'Medical Restrictions'
Future capability: doctors view patient data and prescribe 'Medical Restrictions' — examples from the charter:
- blocking certain foods
- enforcing fasting
- requiring tracked workouts
These restrictions dynamically alter the patient's Protocol Engines.
Design-for decision (binding on Phase 1): every Protocol Engine's parameters must be config-driven per user, not hardcoded. The 8 engines' charter constants (250ml hydration units / 5000ml max / 30-second cooldown, 90-minute caffeine block, 4-hour GERD window, 60-minute medication grace, 3-cycle fertility minimum, etc.) are the defaults in a per-user engine-parameter configuration, resolved by the backend at evaluation time. Today, every user simply runs on the defaults; in the future state, a doctor-prescribed Medical Restriction becomes an override layered onto that same configuration — no engine rewrite required.
Parameter-resolution sketch (server-side only, consistent with SSOT):
engine evaluation → load per-user engine config → (future: apply active Medical Restriction overrides) → run state machine
Storage direction (sketch — an additive/expand migration when the future state arrives, honoring the NOT NULL + default rule):
What Phase 1 must do now: implement engines so they read their parameters from a per-user config resolution step (even if that step only ever returns charter defaults initially). What Phase 1 must not do: build any doctor-facing surface, restriction authoring, or override UI.
Deliberately undecided (see Section 6): the doctor identity/authorization model, the consent model under which a doctor may view patient data or push restrictions, and the regulatory framing of a doctor "prescribing" behavioral restrictions through the app.
5.2 Gamification Badges
Future capability: badges for protocol compliance — the charter's example is a badge for a perfect GERD window. Design-for implication: protocol engines already produce compliance state as part of their server-side state machines; badges are a future read-model over that compliance history. No badge schema, badge list, or badge UI is defined now (badge visuals are additionally PENDING DESIGN whenever that phase arrives). The only Phase 1 obligation is that engine compliance outcomes are persisted server-side in a way that a future badge system can query — which the SSOT engine design already implies.
5.3 Marketplace APIs for B2B Partners
Future capability: APIs for B2B partners — pharmacies, insurance, wellness clinics — supporting the business model (free for end-users; ecosystem bridging patients, doctors, B2B corporate health insurance, and wellness marketplaces).
Design-for implications, nothing more:
- The ToGO API is already API-first; a future partner-facing API surface would be an additive namespace, not a rework.
- Partner authentication/authorization, data-sharing scope, commercial terms, and any partner-visible data model are entirely undefined and are not sketched here to avoid inventing requirements.
- Anything a partner could see about a user intersects with the same consent and regulatory open questions as the doctor dashboard (Section 6).
5.4 Future-State Boundary Summary
| Future feature | Built in Phases 1–6? | Phase 1 design-for obligation |
|---|---|---|
| Doctor dashboards | No | None beyond config-driven engines |
| Medical Restrictions altering engines | No | Engine parameters config-driven per user (defaults today) |
| Gamification badges | No | Engine compliance outcomes persisted server-side (already implied by SSOT) |
| Marketplace / B2B APIs | No | API-first backend (already the stack) |
6. Open Questions
Explicitly undecided items. These block the corresponding design work and must be resolved with the user (and, where noted, with professional legal/medical-compliance input) before the affected feature is planned in detail.
- Doctor identity & authorization model — how doctors are verified, credentialed, and authorized within TOGO auth; what role model separates doctor accounts from patient accounts. Undecided.
- Consent model for patient data sharing — how a patient grants, scopes, and revokes a doctor's (or future B2B partner's) access to their data; what the default is. Undecided.
- Regulatory considerations — the regulatory classification of the platform's future doctor-prescription-of-restrictions capability and B2B data sharing (jurisdictions, applicable health-data regulations) is entirely unresolved. Undecided; requires expert input.
- Key-encryption mechanism — application-level encryption vs. external KMS for BYOK keys, and rotation policy for the encryption keys themselves. Undecided (Phase 1).
- Apple Intelligence BYOK shape — how an Apple Intelligence "key" is represented and whether its platform-bound nature requires a documented, narrow exception to the pure server-side proxy model. Undecided (Phase 1 / Phase 4).
- AI proxy audit logging & retention — whether and how long proxied AI calls are logged. Undecided.
- Server-side AI output filtering beyond the mandatory deferral — whether responses that appear to diagnose are rejected outright, and what the user sees when that happens. Undecided (Phase 1).
- Masked key hint in AI settings — whether any masked representation of a stored key is shown. PENDING DESIGN.
- AI settings screen visuals per platform (incl. RTL mirroring and dark/light palette application) — PENDING DESIGN (Figma work in progress).
- HealthKit / Health Connect data types, push cadence, and offline buffering — deferred to Phase 4/5 detailed planning. Undecided.
Related plan documents: Phase 1 backend/auth plan, Protocol Engines plan, i18n & theming plan (numbering per the docs/plan series as it is created).