0. Current implementation (v0.2 commerce platform)
v0.2 replaces the v0.1 SQLite proof of concept with a PostgreSQL commerce platform. Sections 5, 6.1, 7, 9 and 10.1 below describe that historical v0.1 POC. Where they conflict with this section, this section is authoritative. Everything here is Implemented and verified by the API integration suite (PGlite) and Playwright end-to-end runs against the Docker stack, on desktop and iPhone 13.
0.1 Runtime
| Service | Technology | Notes |
|---|---|---|
db | PostgreSQL 16 (alpine) | Named volume breezrx_pg-data. Bound to 127.0.0.1:5544 for inspection. Health-checked with pg_isready. |
api | Node 22, Express 5, pg | Applies SQL migrations (apps/api/migrations) at boot, guarded by an advisory lock. Seeds the product catalog only. Runs an in-process renewal scheduler (SCHEDULER_INTERVAL_MS). Not published to the host. |
web | Next.js 16 / React 19 | App Router storefront. Same-origin /api/* rewrite to the API. Published on 127.0.0.1:3100. |
0.2 Data model
Money is integer cents and timestamps are timestamptz. Every externally originated record carries provider and livemode, so sandbox records remain identifiable after go-live. Nothing transactional is seeded: all rows come from API calls.
| Table | Purpose / key constraints |
|---|---|
users, sessions | scrypt password hashes. Sliding 30-day sessions stored as SHA-256 token hashes in an HttpOnly brx_session cookie. |
addresses | Soft-archived, so historical orders keep their references. At most one default per user. |
payment_customers, payment_methods | Provider customer and payment-method references plus display metadata (brand, last4, expiry, billing address). Never a card number or CVC. |
products, cart_items | Catalog with allowed autoship intervals and an autoship discount in basis points. One cart line per product (one-time or subscription). |
evaluations, prescriptions | Questionnaire answers and rule flags. Clinician decision. Prescriptions track fills authorized/remaining and expiry; status ∈ active/exhausted/expired/revoked. |
orders, order_items, order_events | Snapshotted prices, address and tax. A unique (user_id, idempotency_key) plus a request fingerprint. Source is checkout or subscription_renewal. Status ∈ awaiting_evaluation/confirmed/packed/shipped/delivered/cancelled. |
payments, payment_events | One payment per order: authorized → captured / voided / refunded / failed. Append-only provider ledger. |
shipments | Carrier and tracking from the fulfillment provider. |
subscriptions, subscription_events | Price locked at signup, interval, quantity, shipping method, address, card, linked prescription and next_order_at. Status ∈ pending_evaluation/active/paused/past_due/cancelled. A partial index on due rows. |
audit_log | Actor (customer/staff/system), action and entity for every state change. |
mock_gateway.* | The sandbox processor's own state (customers, single-use tokens, payment methods, intents) in a separate schema that can be dropped at go-live. |
0.3 Key flows
- Card capture: the browser posts card fields to
/api/mock-gateway/v1/tokens(standing in for processor hosted fields) and receives a single-use token.POST /payment-methodsexchanges it for a customer-attached payment method. - Checkout:
POST /checkoutrequires anidempotencyKey. The server re-prices the cart and creates a payment intent outside the database transaction, like a remote processor call. It captures immediately for non-Rx orders and authorizes only when any line awaits clinician review. A replay returns the original order withIdempotent-Replayed: true. A different payload under the same key returns 409. - Evaluation: Rx products need an evaluation before checkout. Approval issues a prescription, confirms the waiting order, captures the authorization and activates any pending subscription. Decline cancels the order and voids the authorization.
- Autoship renewals: the scheduler claims due subscriptions with
FOR UPDATE SKIP LOCKED. Each renewal re-checks prescription fills, charges the saved card with an idempotency key derived from the subscription and cycle, creates a renewal order and advancesnext_order_at. A declined card moves the subscription topast_due, and an exhausted prescription pauses it pending re-evaluation. - Security: non-GET requests need the
x-breezrx-clientheader (CSRF defense alongsideSameSite=Lax). Helmet, rate limiting, zod validation and structured errors{error:{code,message,param}}apply throughout./ops/*is open to any signed-in user in the demo Open decision; production requires staff authentication with RBAC (see §15).
0.4 REST surface (/api)
auth/signup|login|logout|session · me · account/summary · addresses[/:id] · payment-methods[/:id[/default]] · mock-gateway/v1/tokens · catalog[/:slug] · cart, cart/items[/:productId], cart/merge · checkout/quote, checkout · orders[/:id[/cancel]] · evaluations · prescriptions · questionnaires/:category · subscriptions[/:id[/pause|resume|skip|cancel|ship-now]] · ops/overview, ops/evaluations/:id/decision, ops/orders/:id/advance, ops/subscriptions/:id/make-due, ops/scheduler/run · graphql (read-only).
0.5 Provider seams
PaymentProvider (src/payments/provider.ts) and ClinicalProvider, FulfillmentProvider and TaxProvider (src/integrations.ts) are the only integration points, wired in src/services.ts. The production integration register maps each one to candidate vendors.
1. Status labels & honesty statement
Each capability in this document has one status label. The POC is an investor demonstration. It is not a pharmacy, not a medical service and not a production system.
This document was written while the POC was being built in parallel. Sections 6.1, 7, 8.1 and 10.1 were checked against the API source in apps/api/src (db.ts, store.ts, app.ts, schemas.ts, graphql.ts) at writing time and are labeled Implemented. The backend build session confirmed them: build and typecheck pass, 11 API tests pass, and the API container is healthy on internal port 4000. Verified facts include the 400/413/422/409/429 error codes, the replay behavior (201 + Idempotent-Replayed: true), the response shapes, and introspection being off in production. Full Docker and browser verification is the parent session's next step. Front-end behavior reported by the build session (the synthetic session user is “Avery Demo”): editorial and compact modes switched from a discreet profile menu and saved in the browser; no real profile or PII fields; a fixed synthetic shipping address. Docker Compose project breezrx publishes 127.0.0.1:3100 → web:3000 and keeps the API internal. Anything labeled Proposed is not built. Do not present it to investors as a feature.
| Capability | Local POC | Production |
|---|---|---|
| Catalog of products (GLP-1 flagship + wider Rx/wellness) | Implemented seeded synthetic SQLite rows, invented prices | Proposed drug compendium + formulary + pricing service |
| Customer identity | Implemented one shared synthetic demo identity. No authentication | Proposed OIDC (only once BAA and service eligibility are confirmed), MFA, WebAuthn |
| Medical intake | Implemented scenario selector (eligible/needs_review) and a consent flag. No real medical questions are stored | Proposed versioned clinical questionnaires reviewed by licensed clinicians |
| Prescription | Implemented a simulated review record, created with the intake, that a demo operator approves or declines | Proposed clinician-signed eRx through a vetted partner, plus pharmacist verification |
| Payments | Implemented none. Totals are display-only and no card data is requested | Proposed Stripe or another approved processor: authorize after eligibility, capture before lawful dispense |
| Fulfillment & tracking | Implemented manual "advance" through simulated statuses | Proposed pharmacy management system, lots, FEFO, cold chain, carrier webhooks |
| Documents / OCR / EHR / telehealth | Not in POC no uploads accepted | Proposed PHI vault with AV quarantine; OCR is assistive only; FHIR and telehealth through partners |
| Compliance | No claim | Open decision HIPAA program, SOC 2 audit, state licensure, GDPR applicability |
2. Scope, principles & non-goals
In scope (POC)
- Elegant storefront with editorial and compact modes
- Guided care flow → simulated intake → order
- Simulated pharmacist review queue and fulfillment advance
- Persistent local SQLite with seed data and a reset path
- Docker Compose project
breezrx: host127.0.0.1:3100→ web container :3000; API internal only on :4000
Explicit non-goals (POC)
- Real authentication, identity proofing or government ID checks
- Collecting real PHI, documents, insurance or payment data
- EHR, OCR, eRx, telehealth, carrier or payment integrations
- Any compliance, licensure or efficacy claim
Architectural principles
- A purchase is never a prescription. Clinical decisions are explicit and attributable
- Writes go through REST commands; reads can use GraphQL projections
- Every money or clinical mutation is idempotent and audited
- Minimize PHI and log no PHI
- Build a modular monolith first, then extract services in stages
Stack decisions (ADR summary)
| ADR | Decision | Rationale | Status |
|---|---|---|---|
| ADR-001 | TypeScript throughout; Next.js 16 / React 19 web app | One language, server components, standalone output for containers | POC contract |
| ADR-002 | Separate Express 5 API on Node 22 | Deploys independently from the web app; mirrors the production service seam; the web app proxies /api/* internally | Implemented |
| ADR-003 | GraphQL for reads, REST for writes | Commands get explicit idempotency, status codes and audit. Queries get flexible projections | Implemented |
| ADR-004 | Node built-in node:sqlite on a Docker volume | No native build step and zero ops. Persistent synthetic data. Not for production | Implemented |
| ADR-005 | AWS: EKS, Aurora PostgreSQL, ElastiCache Redis, S3 SSE-KMS, KMS | Managed, widely BAA-covered services. Eligibility is confirmed per service before use | Proposed |
| ADR-006 | Transactional outbox → SQS workers; Temporal for long-running sagas | Reliable side effects; compensation for clinical and payment flows | Proposed Open decision Temporal Cloud vs self-hosted vs Step Functions |
| ADR-007 | Vetted partners for eRx (Surescripts network), FHIR/EHR, telehealth, pharmacy | Certification, network access and licensure are not built in-house | Open decision |
3. System context
3.1 Local POC (Docker)
3.2 Proposed production (AWS)
Mermaid source: production context
flowchart LR
subgraph Clients
C[Customer browser / app]
O[Operations console]
end
C --> CF[CloudFront + WAF] --> ALB
O --> ZT[Zero-trust access] --> ALB
subgraph AWS_VPC[AWS VPC - private subnets]
ALB --> WEB[web: Next.js]
WEB --> BFF[api gateway / BFF]
BFF --> CAT[catalog] & ORD[orders] & CLIN[clinical] & PH[pharmacy] & PAY[payments] & ID[identity]
ORD --> OUT[(outbox)] --> SQS[[SQS / Temporal]] --> WRK[workers]
CAT & ORD & CLIN & PH & PAY --> PG[(Aurora PostgreSQL)]
BFF --> R[(ElastiCache Redis)]
CLIN --> S3[(S3 PHI vault SSE-KMS)]
AUD[audit] --> WORM[(S3 Object Lock)]
end
ID --- IDP{{OIDC provider*}}
CLIN --- ERX{{eRx / FHIR / telehealth partners*}}
PH --- PMS{{pharmacy system / carriers*}}
PAY --- PSP{{payment processor*}}
4. Domain boundaries & data ownership
Each bounded context owns its tables. Other contexts read through APIs, events or read models, and never through cross-schema joins. The POC keeps all tables in one SQLite file. Its modules should still follow these seams so they can be extracted later.
| Context | Owns (authoritative) | Publishes | PHI? | Production team owner |
|---|---|---|---|---|
| Identity & Consent | accounts, credentials refs, MFA/WebAuthn public keys, consents, legal acceptances | account.created, consent.granted/withdrawn | Identifiers (PII) | Platform/Identity |
| Catalog & Pricing | products, SKUs, NDC mapping, price books, state availability | product.changed | No | Commerce |
| Clinical Intake | questionnaire versions, intake responses, eligibility outcomes | intake.submitted, intake.flagged | Yes | Clinical Eng |
| Care & Prescribing | encounters, clinician decisions, prescriptions, refill authorizations | rx.signed, rx.declined, rx.cancelled | Yes | Clinical Eng + Medical Director |
| Pharmacy Fulfillment | verification, inventory lots, reservations, dispense, shipments, quarantine | dispense.completed, shipment.*, lot.recalled | Yes | Pharmacy Ops Eng + PIC |
| Orders | orders, order lines, subscriptions, status history | order.* | Limited (product implies condition) | Commerce |
| Payments | payment intents (token refs only), captures, refunds, ledger | payment.authorized/captured/voided/refunded | No (by design; no PHI metadata) | Payments |
| Documents | object refs, scan state, retention class | document.clean/quarantined | Yes | Platform Security |
| Audit | append-only audit events, WORM export | none | Refs only, no PHI payloads | Security |
| Notifications | templates, delivery log | none | Minimal: "you have a message" | Platform |
Under HIPAA, a GLP-1 product name tied to an identifiable person can be PHI. Treat order data as PHI for access control and logging, even though payment records deliberately exclude product names (see §14).
5. POC architecture Historical v0.1
apps/web: Next.js 16
/api/* → API_INTERNAL_URLapps/api: Express 5
DEMO_MODE=true guardSQLite: node:sqlite
/data/breezrx.sqliteRequest path
POC safeguards
- The UI shows a persistent "Demo, synthetic data" indicator. Checkout never renders card fields.
- The API refuses to start unless
DEMO_MODE=trueis set explicitly (config.ts). Implemented (verified) - Free-text input stays minimal and bounded. Intake uses a scenario enum, not medical questions.
- Rate limiting and body-size limits stop accidental abuse of a demo left running on a laptop.
- Security headers: the web app sets
X-Frame-Options: DENY,nosniff,Referrer-PolicyandPermissions-Policy(camera, mic and geolocation off). This is innext.config.tsat writing time, plus helmet on the API.
6. Data model & ERD
6.1 POC logical schema (SQLite)
Implemented (verified) This is schema version 1 in apps/api/src/db.ts. It is applied idempotently on startup with PRAGMA foreign_keys=ON, journal_mode=WAL and busy_timeout=5000. The database file is DATABASE_PATH, which is /data/breezrx.sqlite in the container, on a named volume. Money is integer cents. Timestamps are ISO-8601 UTC text. IDs are prefixed opaque strings (ord_…, rx_…, intake_…).
prescriptions) is created at intake time, and order_id is filled in once an order is placed.Mermaid source: POC ERD
erDiagram
USERS ||--o{ INTAKES : submits
USERS ||--o{ ORDERS : places
USERS ||--o{ PRESCRIPTIONS : "subject of"
PRODUCTS ||--o{ INTAKES : "for"
PRODUCTS ||--o{ ORDERS : "snapshot of"
PRODUCTS ||--o{ PRESCRIPTIONS : "for"
INTAKES ||--|| PRESCRIPTIONS : "creates review (UQ intake_id)"
INTAKES ||--o| ORDERS : "used once (UQ intake_id)"
ORDERS ||--o| PRESCRIPTIONS : "linked (UQ order_id)"
ORDERS ||--|{ ORDER_EVENTS : "tracking (UQ order_id,seq)"
PRODUCTS {
text id PK
text slug UK
text category "CHECK 4 values"
int price_cents "CHECK >= 0"
text interval "CHECK = month"
int prescription_required "0|1"
int sort_order
}
ORDERS {
text id PK
text user_id FK
text product_id FK
text product_name "snapshot"
int total_cents "CHECK >= 0"
text status "CHECK 6 values"
int subscription "0|1"
text shipping "CHECK = demo_home"
text intake_id FK "UNIQUE, nullable"
text idempotency_key UK
text request_fingerprint
}
PRESCRIPTIONS {
text id PK
text intake_id FK "UNIQUE"
text status "pending_review|approved|declined"
text order_id FK "UNIQUE, nullable"
text reviewed_at
}
AUDIT_LOG {
text id PK
int seq UK
text action
text entity_id
}
| Table | Key constraints | Owner module |
|---|---|---|
products | PK id; UNIQUE slug; CHECK category IN ('Weight care','Everyday health','Skin & hair','Wellness'); CHECK price_cents ≥ 0; CHECK interval = 'month'; CHECK prescription_required IN (0,1); sort_order | catalog (seeded) |
users | PK id; UNIQUE email. One seeded synthetic demo user. No credentials | identity (demo) |
intakes | FK user_id, product_id; CHECK scenario IN ('eligible','needs_review'); CHECK status = 'pending_review'; consented_at NOT NULL (consent must be literal true at the API) | intake |
prescriptions | Simulated review record. UNIQUE intake_id; UNIQUE order_id (nullable); CHECK status IN ('pending_review','approved','declined'); reviewed_at | clinical (simulated) |
orders | FK user_id, product_id; UNIQUE intake_id (an intake is used at most once); UNIQUE idempotency_key; request_fingerprint; CHECK status IN (awaiting_review, approved, ready_to_ship, shipped, delivered, declined); CHECK shipping = 'demo_home'; CHECK total_cents ≥ 0; INDEX (user_id, created_at) | orders |
order_events | FK order_id; UNIQUE (order_id, seq); status, label, at. Serves as trackingEvents | orders |
audit_log | UNIQUE seq; action, entity_id, created_at. No free text and no PHI. Append-only in code | audit |
6.2 Proposed production schema (Aurora PostgreSQL)
Each context gets one PostgreSQL schema and its own database role. Cross-schema foreign keys are not allowed, so references across contexts are ID values checked by the owning service. The tables below are the high-value invariants.
| Schema.table | Notable constraints / invariants |
|---|---|
identity.accounts | UUID PK; citext email UNIQUE where deleted_at IS NULL; state_of_residence CHECK in supported launch states |
identity.webauthn_credentials | credential_id bytea UNIQUE; public_key bytea; sign_count bigint; no biometric data |
identity.consents | (account_id, purpose, version) UNIQUE; granted_at, withdrawn_at; purposes: telehealth, HIPAA notice acknowledgement, marketing (separate, opt-in), research (separate) |
intake.responses | questionnaire_version FK; answers jsonb; encrypted columns for sensitive answers (app-level envelope) |
care.prescriptions | prescriber_npi NOT NULL; signed_at NOT NULL; signature_ref NOT NULL; refills_authorized ≥ 0; expires_at; status enum; one active Rx per (patient, drug, strength) via partial unique index |
care.refill_authorizations | CHECK refills_remaining ≥ 0; earliest_fill_at; decremented only inside the dispense transaction |
pharmacy.lots | (ndc, lot_number) UNIQUE; expiry_date NOT NULL; qty_on_hand ≥ 0; state enum (available, quarantined, recalled, expired, destroyed) |
pharmacy.reservations | FK lot; qty > 0; expires_at; EXCLUDE or SUM check enforced by SELECT … FOR UPDATE SKIP LOCKED allocation |
pharmacy.dispenses | rx_id, lot_id, verified_by_pharmacist NOT NULL, verified_at; immutable after insert |
pharmacy.shipments | cold_chain boolean; temp_excursion boolean; carrier_tracking_ref |
orders.orders | status enum with transition trigger; version int; idempotency_key UNIQUE per account |
payments.payment_intents | psp_ref UNIQUE; amount_cents; state enum; no product name, no diagnosis, no Rx data |
platform.outbox | id, aggregate, type, payload (no PHI beyond IDs), created_at, published_at NULL; dispatched by worker |
audit.events | Insert-only grant; hash chain (prev_hash) for tamper evidence; streamed to S3 Object Lock |
7. API contract (REST writes, GraphQL reads)
Base path: /api. The browser calls same-origin /api/* on the web container, which proxies to the API through a Next.js rewrite to API_INTERNAL_URL. Request bodies must be application/json, at most 16 KB, and pass strict zod schemas (unknown keys are rejected). Writes have a separate, stricter rate limit (default 60/min; reads 300/min). Every response carries an X-Request-Id header. Implemented (verified)
| Method & path | Request | Success | Notes |
|---|---|---|---|
GET /api/health | none | 200 {status:"ok", demo:true} | Used by the container HEALTHCHECK |
GET /api/catalog | none | 200 {products: Product[]} | 8 seeded synthetic products (GLP-1 flagship plus others such as omega-3 and calm-sleep), sorted by sort_order |
GET /api/session | none | 200 {user:{id,name,email}, demo:true}. The seeded user is the synthetic “Avery Demo” | Not authentication. Every visitor shares one synthetic identity |
POST /api/intakes | {productId, scenario:'eligible'|'needs_review', consent:true} | 201 {intake:{id, productId, status:'pending_review'}} | Creates the intake and a pending review record in one transaction. A non-Rx product returns 422 intake_not_applicable |
POST /api/orders | {productId, intakeId?, shipping:'demo_home', subscription:boolean, idempotencyKey} | 201 {order}; a replay returns the same order with the header Idempotent-Replayed: true | Rx: requires the intake for the same product, unused and not declined. Non-Rx: an intakeId is rejected |
GET /api/orders | none | 200 {orders: Order[]} | The demo user's orders |
GET /api/operations | none | 200 {prescriptions, orders, audit} | Simulated pharmacist workspace. Unauthenticated by design, demo only |
POST /api/prescriptions/:id/review | {decision:'approve'|'decline'} | 200 {prescription, order|null} | Only from pending_review. Can happen before the order exists |
POST /api/orders/:id/advance | none | 200 {order} | approved→ready_to_ship→shipped→delivered; anything else returns 409 |
POST /api/graphql | {query, variables?, operationName?} | 200 {data} | Read-only. Other methods return 405 method_not_allowed |
7.1 Resource shapes
type Product = {
id: string; slug: string; name: string;
category: "Weight care" | "Everyday health" | "Skin & hair" | "Wellness";
tagline: string; description: string;
priceCents: number; // synthetic demo price, integer cents
interval: "month";
prescriptionRequired: boolean;
form: string; // e.g. "Weekly pen" (synthetic)
accent: string; // UI color token
};
type Order = {
id: string; productId: string; productName: string;
totalCents: number;
status: "awaiting_review" | "approved" | "ready_to_ship" | "shipped" | "delivered" | "declined";
createdAt: string; // ISO-8601 UTC
trackingEvents: { status: string; label: string; at: string }[];
};
7.2 Error envelope
Implemented (verified) {"error":{"code","message"}}, where codes are snake_case and messages are safe to show to people. The request ID is in the X-Request-Id header. Stack traces and SQL are never returned.
HTTP/1.1 409 Conflict
Content-Type: application/json
X-Request-Id: 3f0c…
{ "error": { "code": "invalid_transition",
"message": "An order that is awaiting_review cannot be advanced." } }
| HTTP | code | When |
|---|---|---|
| 400 | validation_error | zod failure: unknown key, bad enum, consent not true, malformed idempotencyKey or ID |
| 404 | not_found | Unknown order or prescription in a path |
| 405 | method_not_allowed | Non-POST to /api/graphql |
| 409 | invalid_transition | Advancing awaiting_review, declined or delivered; reviewing a decided prescription; a lost compare-and-set race |
| 409 | idempotency_conflict | Same idempotencyKey with a different request fingerprint |
| 409 | intake_already_used / prescription_declined | Reusing an intake; ordering after a decline |
| 422 | unknown_product, intake_required, invalid_intake, intake_product_mismatch, intake_not_applicable | Business-rule failures |
| 413 | (payload too large) | JSON body over 16 KB |
| 429 | rate-limit code from the limiter handler | Read or write limit exceeded (draft-8 RateLimit headers) |
| 500 | internal_error | Unexpected error. The log has the request ID, not the body |
7.3 Idempotency
POC (source-observed)
- The client generates an
idempotencyKey(8–128 characters from[A-Za-z0-9_.:-]) once per checkout attempt and reuses it on retry. - Inside
BEGIN IMMEDIATE, the server looks uporders.idempotency_key(globally UNIQUE). - If a row exists and its
request_fingerprint(JSON of productId, intakeId, shipping and subscription) matches, the server returns the stored order with201andIdempotent-Replayed: true. If the fingerprint differs, it returns 409idempotency_conflict. - The order, the first tracking event, the prescription link and the audit row are written in that same transaction. A crash rolls everything back.
Proposed for production: an Idempotency-Key header scoped per account and route; a separate idempotency_keys table (stored status code + body, SHA-256 fingerprint, 24 h orders and 7 day payments TTL); a Redis in-flight lock (SET NX) returning 409 request_in_progress; and the same pattern on every payment and clinical command.
7.4 Concurrency
POC Writes are serialized by SQLite BEGIN IMMEDIATE transactions. State changes use a compare-and-set on the current status (UPDATE … WHERE id=? AND status=?). If zero rows change, the API returns 409 invalid_transition. Proposed Production adds an explicit version column for optimistic concurrency, and pessimistic row locks only for inventory allocation (§13).
8. State machines
8.1 Order lifecycle Implemented (verified)
| From | Trigger | To | Guard / side effects |
|---|---|---|---|
| (intake) | POST /intakes (Rx product) | review = pending_review | The review record is created with the intake; scenario is stored as a reviewer hint |
| (new) | POST /orders, Rx, review pending | awaiting_review | Intake for the same product and not yet used; links prescriptions.order_id |
| (new) | POST /orders, Rx, review already approved | approved | Review happened before checkout |
| (new) | POST /orders, Rx, review declined | — | 409 prescription_declined; no order created |
| (new) | POST /orders, non-Rx product | approved | An intakeId is rejected (422) |
| awaiting_review | review approve | approved | Review → approved; reviewed_at; order event; audit |
| awaiting_review | review decline | declined | Terminal. Production would void the payment authorization (§14) |
| approved | advance | ready_to_ship | Production guard: pharmacist verification, dispense recorded, payment captured |
| ready_to_ship | advance | shipped | Production: carrier label and shipment event |
| shipped | advance | delivered | Production: carrier delivery webhook only, not a manual action |
| awaiting_review / declined / delivered | advance | — | Rejected 409. Clinical review cannot be skipped |
8.2 Production prescription lifecycle Proposed
Side branches: declined, needs_info (back to the patient), cancelled (CancelRx), expired, exhausted, on_hold (safety or recall).
9. Sequence diagrams
9.1 POC: Rx checkout (needs review)
Mermaid source
sequenceDiagram
actor U as Demo customer
participant W as web (Next.js)
participant A as api (Express)
participant D as SQLite
U->>W: Choose GLP-1 product, scenario, consent
W->>A: POST /api/intakes {productId, scenario, consent:true}
A->>A: zod validate
A->>D: BEGIN IMMEDIATE; INSERT intake + prescription(pending_review) + audit; COMMIT
A-->>W: 201 {intake}
W->>A: POST /api/orders {productId, intakeId, subscription, idempotencyKey}
A->>D: BEGIN IMMEDIATE; lookup idempotency_key
A->>D: INSERT order(awaiting_review), order_event; link prescription; audit; COMMIT
A-->>W: 201 {order}
Note over W,A: Retry with same key returns same order
9.2 POC: simulated review and fulfillment
Mermaid source
sequenceDiagram
actor P as Demo operator
participant W as web workspace
participant A as api
participant D as SQLite
P->>W: Open operations
W->>A: GET /api/operations
A-->>W: queue
P->>W: Advance (too early)
W->>A: POST /api/orders/:id/advance
A-->>W: 409 INVALID_TRANSITION
P->>W: Approve
W->>A: POST /api/prescriptions/:id/review {approve}
A->>D: UPDATE prescription, order=approved (CAS), order_event, audit
A-->>W: 200
loop until delivered
W->>A: POST /api/orders/:id/advance
A-->>W: 200 next status
end
9.3 Production: order saga with payment and dispense Proposed
Mermaid source
sequenceDiagram
participant O as Orders
participant P as Payments
participant C as Clinical
participant R as Pharmacy
participant S as PSP
O->>C: intake eligible?
C-->>O: eligible (pre-screen)
O->>P: authorize(amount, idemKey)
P->>S: create+confirm (manual capture)
S-->>P: authorized
O->>C: request clinician review
C-->>O: rx.signed (clinician e-signature)
O->>R: verify + reserve lot (FEFO)
R-->>O: verified, reserved
O->>P: capture
P->>S: capture
S-->>P: captured (webhook, signed)
O->>R: dispense + ship
alt declined / out of stock / auth expired
O->>P: void or refund
O->>R: release reservation
end
10. GraphQL: POC read model & production proposal
10.1 POC schema Implemented (verified)
type Query {
catalog: Catalog!
products: [Product!]!
product(id: ID!): Product
orders: [Order!]! # demo user's orders
order(id: ID!): Order
}
type Catalog { products: [Product!]! }
type Product { id: ID! slug: String! name: String! category: String! tagline: String!
description: String! priceCents: Int! interval: String! prescriptionRequired: Boolean!
form: String! accent: String! }
type Order { id: ID! productId: String! productName: String! totalCents: Int! status: String!
createdAt: String! trackingEvents: [TrackingEvent!]! }
type TrackingEvent { status: String! label: String! at: String! }
# No Mutation type: writes are REST-only.
GraphQL errors use the standard GraphQL format {"errors":[{"message","extensions":{"code"}}]}, not the REST error envelope. Guards: POST only; query ≤ 4,000 characters; one operation; depth ≤ 6; ≤ 200 fields; introspection disabled when NODE_ENV=production; sanitized error messages with codes QUERY_TOO_LONG, QUERY_TOO_DEEP and QUERY_TOO_COMPLEX.
10.2 Production proposal Proposed
- Federated read graph through a gateway (Apollo Federation, GraphQL Mesh or a hand-rolled BFF). Each subgraph is owned by one context. There are no mutations; commands stay REST plus the outbox.
- Persisted queries only in production: an allow-list of hashed operations, with introspection off outside non-prod.
- Cost limits: max depth 8, cost budget per operation, pagination required (Relay connections,
first ≤ 50). - Field-level authorization with
@auth(policy:"…")directives. The resolver decides through the policy engine (§15). PHI fields resolve only for patient-self or an authorized clinician or pharmacist with a care relationship. - DataLoader batching per request, with no cross-request caching of PHI. Redis caches catalog data only.
- Enums replace strings for status. Money becomes
Money { amountCents: Int!, currency: Currency! }.
type Query {
catalog(state: USState!, first: Int = 20, after: String): ProductConnection!
me: Patient @auth(policy: "self")
order(id: ID!): Order @auth(policy: "order.read")
opsQueue(filter: QueueFilter!, first: Int!, after: String): WorkItemConnection!
@auth(policy: "ops.queue.read")
}
type Patient { id: ID! orders(first: Int!, after: String): OrderConnection!
prescriptions: [PrescriptionSummary!]! @auth(policy: "self|care-team") }
11. Identity, MFA, WebAuthn & biometrics
Everyone shares one synthetic demo identity. The operations workspace is also unauthenticated. This is acceptable only because all data is synthetic and the app is bound to loopback. It must never be exposed to a network or used with real people.
Production proposal Proposed
- Provider: Amazon Cognito or another OIDC provider. Choose one only after confirming it is covered by a signed BAA and listed as HIPAA-eligible for the intended use. Open decision (INT-ID-01 in the integrations report).
- Flows: Authorization Code + PKCE. Sessions are server-side (HttpOnly, Secure, SameSite=Lax cookie; Redis session store), with 15-minute idle and 12-hour absolute timeouts for patients and shorter ones for operations.
- MFA: required for all workforce users. Patients are offered MFA by default and must step up before viewing prescriptions, changing the address or payment method, or exporting data. Preferred factor order: WebAuthn passkey → TOTP → SMS (SMS only as a fallback because of SIM-swap risk).
- WebAuthn and biometrics: the device's authenticator does the biometric check (Face ID, fingerprint) locally. The server receives only a signed assertion and stores the credential ID, public key, sign count and AAGUID. We never receive, store or process biometric templates. In the UI, say "Sign in with your device's passkey", not "We verify your face".
- Identity proofing (government ID) goes through a vetted vendor if prescribing rules or fraud controls require it (INT-ID-03). We keep the result and a reference, not the document images, unless retention is legally required.
- Workforce: SSO from the corporate IdP, with phishing-resistant MFA (FIDO2) mandatory for clinicians, pharmacists and admins. Access reviews run quarterly.
12. Prescription verification, telehealth & refills
12.1 Verification is not OCR approval
OCR or ML may pre-fill or flag data from a user-uploaded prescription image. It must never approve, verify or dispense. Only a licensed pharmacist verifies a prescription, and only a licensed prescriber issues one. Electronic prescriptions arriving through a certified eRx network are preferred over images. An uploaded image can be treated as a transfer or lead that the pharmacy confirms with the prescriber, as state law allows.
- Pharmacist verification (PV) checklist, recorded per item: patient identity match, prescriber license/NPI/DEA as applicable and in-state validity, drug/strength/directions, DUR (interactions, duplicate therapy, contraindications from intake), quantity and days' supply, refills, and signature validity.
- Every PV action is attributed (who, when, what changed) and audited. Overriding a DUR alert requires a typed reason code.
12.2 Clinician-signed telehealth Proposed
- The patient completes a versioned intake. The system pre-screens against hard exclusions (for example contraindications defined by the medical director's protocol). The system cannot approve; it only routes the case.
- The case goes to a clinician licensed in the patient's state, using the telehealth partner's encounter (async or sync, as state rules require).
- The clinician documents the decision. Approval produces an eRx with the prescriber's credentials applied by the certified eRx system (electronic signature), sent to the dispensing pharmacy.
- Declines and requests for more information go back to the patient with a non-clinical-detail notification ("You have a new message").
12.3 Refill safeguards (GLP-1 focus)
- A refill requires an active Rx with refills_remaining > 0, not expired, and now ≥ earliest_fill_at (days' supply × the policy fraction, e.g. 75%, which is a medical director setting).
- Before each refill: a check-in questionnaire (side effects, new medications, pregnancy status where relevant, weight trend). Flagged answers send the case to a clinician before dispense.
- Dose escalation is a new clinical decision by a clinician, never an automatic subscription step.
- Subscription billing never triggers dispense on its own. The order saga (§14) still requires eligibility, PV and stock.
- Duplicate-therapy guard: a partial unique index stops two active GLP-1 prescriptions for one patient unless a clinician explicitly overrides.
- A pharmacy cooldown stops dispenses for the same patient and drug class that are less than N days apart.
13. Inventory, lots, FEFO, recalls & cold chain Proposed
13.1 Allocation (FEFO) and concurrency
-- Reserve qty for an order from the earliest-expiring sellable lot (first expired, first out) BEGIN; SELECT id, qty_on_hand - qty_reserved AS free FROM pharmacy.lots WHERE ndc = $ndc AND state = 'available' AND expiry_date > current_date + $min_remaining_shelf_days ORDER BY expiry_date, received_at FOR UPDATE SKIP LOCKED LIMIT 5; -- choose the first lot with free >= qty; INSERT reservation (expires_at = now()+30m); UPDATE lots SET qty_reserved = qty_reserved + $qty COMMIT;
SKIP LOCKEDlets parallel pick workers avoid deadlocks. CHECK constraints (qty_reserved ≤ qty_on_hand) are the last line of defense.- Expired reservations are released by a sweeper. Dispense turns a reservation into a decrement in the same transaction as the dispense record and the refill decrement.
- Minimum remaining shelf life at ship time is a configurable policy. A patient must not receive a pen that expires before the end of its supply period.
13.2 Recalls
- A recall notice (manufacturer or FDA) sets the matching lots to
recalled. Allocation stops at once because the predicate excludes them. - Open reservations on those lots are cancelled, and the affected orders are reallocated or put
on_hold. - A traceability query (lot → dispenses → patients) produces the outreach list for the pharmacist-in-charge. Messages stay PHI-minimal.
- The audit trail covers who triggered the recall, the counts affected and outreach completion.
13.3 Cold chain quarantine
- Many GLP-1 pens need refrigeration before first use. Receiving records the temperature log. Any excursion sets the lot to
quarantineduntil a pharmacist disposes of it (return to stock with a manufacturer stability justification, or destroy). - Outbound shipments use validated insulated packaging chosen by route and season. Carrier temperature indicators, or the patient reporting a compromised package, trigger a no-charge replacement workflow and quarantine of the returned item. Returned refrigerated medication is never restocked.
- Shipments are restricted to service levels and days that avoid weekend dwell (for example no Friday ship for 2-day service).
14. Payments saga Proposed
Authorize once the intake pre-screen passes. Capture only once a lawful dispense is assured (Rx signed, pharmacist-verified, stock reserved). If capture fails, the order does not ship. Payment metadata sent to the processor must not include product names, conditions or Rx data. Use opaque order IDs and a generic descriptor such as "BreezRx order".
| # | Step | Owner | Compensation on later failure |
|---|---|---|---|
| 1 | Create order (pending_payment_auth) | Orders | Cancel order |
| 2 | Authorize (manual capture, idempotency key) | Payments | Void authorization |
| 3 | Clinical review → rx.signed | Care | (decline) → void auth, notify |
| 4 | PV + FEFO reservation | Pharmacy | Release reservation |
| 5 | Capture | Payments | Refund (if a later step fails after capture) |
| 6 | Dispense (decrement stock, decrement refills) | Pharmacy | Not reversible. Handle with a pharmacist incident process, not automation |
| 7 | Ship / deliver (carrier webhooks) | Pharmacy | Replacement or refund policy |
- Authorizations expire (typically about 7 days for card networks; confirm with the processor). If clinical review may take longer, the saga re-authorizes or uses a setup-intent / saved-method pattern. Open decision
- Run the saga in Temporal (durable timers, retries) or a state table plus SQS workers fed by the transactional outbox. Every step is idempotent and keyed by
order_id + step. - Webhooks are verified with signatures and timestamp tolerance, de-duplicated by event ID, and processed asynchronously. See the webhook standard.
- Card data never touches BreezRx servers. The processor's hosted fields or elements keep PCI scope at SAQ A, or A-EP if needed. HSA/FSA eligibility is a separate open item.
15. Operations console: RBAC + ABAC Proposed
| Role (RBAC) | Can | ABAC conditions |
|---|---|---|
| Clinician | Review intakes, approve/decline, sign | Licensed in the patient's state; assigned case or care-team; active credential; MFA ≤ 12 h |
| Pharmacist | PV, DUR override with reason, dispense release, quarantine disposition | Licensed for the pharmacy location; on shift; cannot verify their own entry (separation of duties) |
| Pharmacy technician | Pick, pack, label, receive stock | Location-scoped. Cannot verify or override |
| Support agent | Order status, shipping, refunds up to $X | No clinical fields (masked). Break-glass needs a reason and creates an alert |
| Ops admin | Configuration, user provisioning | No PHI by default. Two-person rule for role grants |
| Auditor | Read audit trail | Time-boxed grant |
Enforce policy centrally (OPA/Cedar or an equivalent library) with policies-as-code, unit tests and decision logging. Default deny. Every PHI read is audited with its purpose of use.
16. Encryption: why this is not end-to-end encryption
True end-to-end encryption means only the patient's endpoints hold the decryption keys, so the server cannot read the content. BreezRx clinicians, pharmacists, DUR checks, optional assistive OCR, fraud controls and lawful record-keeping all need server-side access to plaintext. E2EE therefore conflicts with how the service must work. TLS protects data in transit, and KMS envelope encryption protects data at rest. Neither is E2EE, and marketing must not describe them that way.
In transit
TLS 1.2+ (prefer 1.3) at CloudFront/ALB, TLS between services (mesh mTLS or ALB→pod TLS) and TLS to Aurora/Redis. HSTS with preload once the domain is stable.
At rest
Aurora, EBS, S3, Redis and backups encrypted with KMS customer-managed keys, one key per data class. S3 PHI vault uses SSE-KMS with bucket keys, and policies deny non-TLS access and unencrypted PUT.
Application-level envelope
The highest-sensitivity fields (intake answers, ID references) are encrypted with data keys from KMS (GenerateDataKey) and an encryption context of {tenant, table, purpose}. Only trusted clinical services have kms:Decrypt under that context.
Scoped decryption
Decryption happens only in clinical and pharmacy services, for an authorized principal with a recorded purpose. Analytics, support and logging pipelines get tokenized or de-identified data.
Document vault with AV quarantine (future)
Infected or invalid files move to an isolated bucket with no read access for applications, and security is alerted. Pre-signed URLs are short-lived (≤ 5 minutes), and downloads go only to authorized clinicians. The POC accepts no uploads.
17. Audit (WORM) & logging without PHI
- Audit events record actor, actor role, action, resource type, resource ID, purpose of use, decision (allow/deny), request ID, IP hash and timestamp. They never contain field values from clinical records.
- Tamper evidence: an insert-only DB grant plus a hash chain. Events stream to S3 with Object Lock in compliance mode (WORM). The retention period comes from a legal decision; plan for at least 6 years for HIPAA documentation and confirm state pharmacy record rules.
- Application logs: structured JSON with allow-listed fields only. A redaction middleware drops request bodies by default, and CI has a lint rule against logging
req.body. A PHI canary test fails the build if synthetic PHI markers appear in captured logs. - Traces and metrics: no PHI in span attributes or metric labels. Use opaque IDs only.
- Third-party telemetry (analytics, session replay, error tracking): off on authenticated and clinical pages unless the vendor signs a BAA and the data is minimized. Session replay never runs on intake.
- POC: the
audit_logtable records demo actions (action, entity ID, time). Structured JSON request logs carry the request ID, method, route, status and duration, without bodies. Implemented (verified)
18. Regulatory posture (no certification claims)
This section frames engineering obligations. Counsel and qualified compliance staff must confirm every applicability decision.
| Topic | Correct framing | Engineering implication |
|---|---|---|
| HIPAA | There is no official HIPAA certification. Compliance is an ongoing program: risk analysis, safeguards, policies, training, BAAs and breach procedures. Third-party attestations exist but are not government certification. | Security risk analysis before PHI; access controls; audit; encryption; contingency plan; minimum-necessary |
| BAA | A BAA is necessary but not sufficient. It allocates responsibilities, and only some services or configurations are covered (for example AWS HIPAA-eligible services list). | Use only BAA-covered and eligible services for PHI; configure them correctly; check each vendor (see integrations report) |
| SOC 2 | An independent CPA firm's audit against the Trust Services Criteria. Type I covers a point in time, and Type II an observation period. We cannot "be SOC 2" without that audit. | Evidence automation, change management, access reviews and vendor management from MVP onward |
| State pharmacy & telehealth | Pharmacy licensure (resident and non-resident) and prescriber licensure per patient state. Telehealth prescribing and consent rules vary by state. | Launch-state gating in catalog and intake; license data model; state rules engine |
| FDA / compounding | Whether compounded GLP-1 products can lawfully be offered depends on current FDA policy and state law, which change. | Catalog flags and legal sign-off per SKU. No efficacy claims. Use FDA-approved labeling where applicable |
| Advertising / platforms | Payment processors, ad networks and app stores may require pharmacy or telehealth certification, for example via LegitScript-type programs. | Track as integration dependencies |
| GDPR (if ever in scope) | The US-first launch may still trigger GDPR through EU-targeted offerings or monitoring. If it applies: Article 6 legal basis and an Article 9 condition for health data, a DPIA, records of processing, data subject rights, residency choices, and transfer mechanisms (SCCs or adequacy, plus a transfer impact assessment). | Geo-scoped launch; region-aware data stores; DSR tooling; do not reuse US consent text |
| US state privacy | Consumer health data laws (for example Washington MHMDA) can apply to non-HIPAA data such as browsing or marketing data. | Separate consent for health-data collection outside HIPAA scope; no ad pixels on health pages |
19. SLOs, RTO/RPO & performance budgets
All figures are Target. None has been measured. The POC has no SLOs; it is a single-host demo.
Availability (storefront + checkout)
Monthly. Error budget ≈ 43 min/month.
Clinical + pharmacy console
During staffed hours. Degraded mode: read-only queue.
RPO / RTO (Tier 1 data)
Aurora PITR plus cross-region snapshot copy. Confirmed by a quarterly restore drill.
Audit store
Synchronous write to the DB plus a stream to S3 Object Lock within 5 minutes.
| Surface | Budget | Measured by |
|---|---|---|
| Storefront LCP (p75, mobile 4G) | ≤ 2.5 s | RUM (no PHI) + Lighthouse CI |
| INP (p75) | ≤ 200 ms | RUM |
| CLS | ≤ 0.1 | Lighthouse CI |
| Initial JS (storefront route) | ≤ 170 KB gzip | Bundle analyzer gate |
GET /catalog p95 (server) | ≤ 150 ms | k6 + APM |
POST /orders p95 (excluding PSP) | ≤ 400 ms | k6 |
| GraphQL operation p95 | ≤ 300 ms | APM |
| Ops queue load | ≤ 1 s for 500 items | Playwright trace |
| Throughput, launch | 50 orders/min sustained, 5× burst | k6 soak 2 h |
20. Test strategy
| Layer | POC | Production addition |
|---|---|---|
| Unit | node --test (via tsx) in apps/api/test for state transitions, validation and idempotency. The parent confirms coverage | Policy-as-code tests; refill/FEFO property tests |
| API contract | supertest-style HTTP tests per endpoint, including 409 on awaiting_review advance | OpenAPI and GraphQL schema diff gates; consumer-driven contracts with partners' sandboxes |
| E2E | Browser flow: catalog → intake → order → approve → deliver | Playwright across the editorial and compact modes; accessibility (axe) gate |
| Security | Header checks; no upload route; dependency audit | SAST, DAST, container scan, IaC scan, annual pentest, PHI-in-logs canary |
| Resilience | Restart the container; data persists on the volume | Chaos (pod or AZ loss), PSP or partner outage simulation, restore drills |
| Performance | none | k6 load and soak against §19 targets in a staging environment sized like production |
21. Phased roadmap & acceptance gates
| Phase | Outcome | Acceptance gate (all must pass) |
|---|---|---|
| 0. Investor POC POC contract | Local Docker demo with synthetic data | docker compose up --build works from a clean clone; web published only on 127.0.0.1:3100 (→ container 3000); API not host-published; data survives restart; API tests green; no real data inputs; demo disclaimers visible; both visual modes present |
| 1. MVP: one state, one pharmacy partner Proposed | Real patients for a narrow catalog | Signed BAAs for every PHI vendor; HIPAA risk analysis done; pharmacy and prescriber licensure confirmed for the launch state; pentest with no open critical or high findings; restore drill meets RPO/RTO targets; PSP approval for the category; clinical protocols signed by the medical director; WebAuthn/MFA live; audit WORM verified; incident runbooks rehearsed |
| 2. Automation | Temporal sagas, eRx/FHIR integration, refill automation, FEFO and lot tracking, cold-chain carriers | Saga chaos tests show no double capture and no dispense without capture; recall drill traces 100% of affected dispenses within 4 h; SOC 2 Type I report issued; refill safeguards verified with clinical QA |
| 3. Scale | Multi-state, multi-pharmacy, service extraction, multi-region DR | SOC 2 Type II; load test at 10× MVP peak within budgets; regional failover game day meets RTO; per-state rules engine audited; cost per order within the business target |
Service extraction order (staged, from a modular monolith): Payments → Pharmacy fulfillment → Clinical → Catalog. Extract a context only when team ownership, scaling or compliance isolation justifies the cost of running it separately.
22. Risks & open decisions
| ID | Risk / decision | Mitigation / next step | Status |
|---|---|---|---|
| R-01 | Investors read the POC as production-ready | Persistent demo banner; this document's honesty matrix; scripted demo narrative | POC contract |
| R-02 | Licensed pharmacy operator and launch states undecided | Choose the partner versus building our own pharmacy; legal analysis by state | Open decision |
| R-03 | Compounded GLP-1 regulatory volatility | SKU-level legal flags; fast catalog kill switch | Open decision |
| R-04 | Payment processor category restrictions | Early underwriting conversation; backup processor | Open decision |
| R-05 | EKS operational complexity for a small team | Managed add-ons, GitOps and a minimal node footprint; ECS Fargate kept as a fallback ADR | Proposed |
| R-06 | Auth expiry during long clinical review | Re-authorize or setup-intent pattern; SLA on review time | Open decision |
| R-07 | node:sqlite is experimental in Node 22 | POC only; pin the Node version; production uses PostgreSQL | POC contract |
Inline concierge and product packs — implemented runtime extension
The current PostgreSQL runtime adds product_packs and product_pack_items in migration 006_product_packs.sql. Curated packs are seeded after products; custom packs belong to the authenticated customer. Pack items are unique products with bounded quantities. Cart, order-item and subscription records retain pack IDs, with pack-name snapshots in orders and subscriptions.
Guest pack drafts remain in the browser bag until sign-in saves the pack and merges its items. Adding a pack is transactional, preserves unrelated bag items, and replaces existing lines for the same product. A shared customer lock serializes cart writes. Checkout uses the existing idempotency, pricing, payment and clinical rules; packs do not create another billing engine. Each recurring item keeps its own status, cadence, renewal lease, prescription checks and pause/skip/cancel controls.
POST /api/assistant/turn accepts bounded shopping preferences and an optional message. A private configurable OpenAI-compatible adapter extracts validated preferences and topics. Catalog facts, prices, budget/cadence filtering, question progression and clinical disclosures are server-controlled. Raw model prose and reasoning are never shown. Prescription selection requires an explicitly named product; clinician review remains mandatory.
Inference is bounded by total deadline, per-replica admission and response size, with explicit fallback reasons and a circuit breaker. Button answers and built-in FAQs need no inference. Chat transcripts are ephemeral and excluded from logs. API/network outages surface as errors rather than pretending guided inference succeeded. See the README for API/environment contracts and the deployment report for remaining VPC, privacy, licensing and global-capacity work.