Lean EHR architecture

FHIR-inspired resident records, KMS-backed envelope encryption, cryptographic access control, and financial analytics.

On this page

Status: Lean EHR is still heavily under development. APIs, schema, and UI may change.

Overview

Lean EHR is a monorepo for a modern electronic health record system. Its assisted-living module handles resident management, clinical data, financial tracking, and analytics; a separate Snowstorm-Lite service provides SNOMED CT terminology lookups.

The design prioritizes confidentiality: sensitive records are encrypted before they reach Firestore, and access to each key class is enforced through Google Cloud KMS rather than application checks alone.

System context

LayerChoice
FrontendNext.js 15 App Router, React, Shadcn UI
BackendNext.js Server Actions, Firebase Admin SDK
Primary storeFirestore, multi-database per environment
Key managementGoogle Cloud KMS, four KEK classes
Session/cacheGoogle Cloud Memorystore (Redis)
AnalyticsBigQuery for financial aggregation
Cold archiveGoogle Cloud Storage ciphertext archive (planned)
DeployCloud Run, Cloud Functions, GitHub Actions
mermaid
Next.js App RouterServer ActionsFirebase AdminFirestoreCloud KMSMemorystoreBigQuery
View source
flowchart LR
  UI[Next.js App Router] --> SA[Server Actions]
  SA --> FA[Firebase Admin]
  FA --> FS[Firestore]
  SA --> KMS[Cloud KMS]
  SA --> REDIS[Memorystore]
  FS --> BQ[BigQuery]

Firestore stores resident data under:

text
1providers/{providerId}/residents/{residentId}/{subcollection}/{docId}

Monorepo layout

  • packages/assisted-living — the core EHR module, including resident management, clinical records, financial workflows, analytics, and deployment configuration.
  • packages/deploy-snowstorm-lite — builds a pre-indexed Snowstorm-Lite image from the UK SNOMED CT RF2 release and deploys it to Cloud Run. It backs terminology lookups in the assisted-living module.

Data model

  • Resident is the aggregate root. Clinical, contact, and financial records live in subcollections.
  • FHIR-inspired, not FHIR-conformant. Domain objects use FHIR-shaped fields and a Reference for the patient (subject, patient, beneficiary, or for). There is no FHIR REST server, search, bundle, or terminology server.
  • Storage linkage is a plaintext resident_id. Firestore .where() queries and archive object paths need a raw field; converters bridge resident_id ↔ patient: { reference: "Patient/<id>" }.
  • CarePlan.activity[] is nested, matching the FHIR BackboneElement shape. It archives and truncates with its parent instead of becoming a separate subcollection.
  • FHIR names use the codebase's snake_case convention (scheduledTiming → scheduled_timing, doNotPerform → do_not_perform).

Encryption & access control

Envelope mode

Envelope mode is the default production mode.

  • A random DEK per document encrypts the payload with AES-256-GCM.
  • The DEK is wrapped by a KEK held in Cloud KMS.
  • Four key classes separate general, contact, clinical, and financial data.
  • lib/access-control.ts owns the role-to-key-class matrix.
  • Resident reads and subcollection reads are both role-gated.
  • Firestore sees ciphertext. Only non-sensitive linkage such as resident_id, facility_id, and timestamps is plaintext.

This is cryptographic RBAC: a role without unwrap permission cannot decrypt a key class even if it has the ciphertext and wrapped DEK.

Plaintext mode

A plaintext mode is in progress for deployments where field-level encryption adds too much friction.

  • lib/crypto defines a CryptoProvider interface implemented by KmsEnvelopeProvider and PlaintextProvider.
  • CRYPTO_MODE selects the provider and fails closed on unknown values.
  • Storage formats are distinct. Documents carry crypto_scheme: 'kms-envelope:v1' | 'none:v1'; plaintext documents have no encrypted fields and no wrapped DEK.
  • Reads verify the document's scheme against the active mode and fail closed on mismatch.
  • Migrated collections include allergies, observations, diagnostic history, prescriptions, charges, payments, and adjustments.
  • The resident document, remaining subcollections, and tenant-scoped mode configuration are still pending. In plaintext mode, role gating becomes application-level authorization.

Threat model

  • Envelope mode: the store and cloud provider see ciphertext. Only authorized roles with KMS access can decrypt.
  • Plaintext mode: the store is trusted; protection depends on IAM, network controls, and audit logging.
  • Not defended: an attacker who already holds the application's service-account identity and KMS permissions.

Retention & encrypted archive

This is designed but not implemented.

  • Hot tier: Firestore keeps recent data, with a cutoff from RETENTION_DAYS (default 90).
  • Cold tier: encrypted documents move to a GCS ciphertext archive keyed by provider, resident, collection, retention timestamp, and document id.
  • Rehydrate: list and download archived blobs, decrypt with the same converters, then merge with the Firestore slice.
  • Truncation: a scheduled Cloud Function deletes Firestore documents only after the archive write is confirmed.
  • BigQuery is analytics-only and never a PHI archive.
  • A plaintext retention_ts still needs to be added; event dates are encrypted, so Firestore cannot filter on them today.

Analytics

Firestore triggers stream the financial collections (charges, claims, payments, and adjustments) into BigQuery *_raw tables, and dashboards aggregate there. Clinical and contact data are deliberately not streamed.

Multi-tenancy

Firebase Auth custom claims (provider_id, roles) combine with Firestore pathing to scope tenants. Native Firebase Auth multi-tenancy is a proposed improvement.

Testing & tooling

  • Jest unit tests cover the access-control matrix, FHIR references, nested CarePlan.activity[], encrypted write shapes, storage codecs, and the provider factory.
  • pnpm test runs without an emulator; pnpm typecheck checks types.
  • Gap: there are no integration or end-to-end tests against Firestore and KMS, and no CI gate. Write paths are only schema-tested.

Key decisions

  • Envelope encryption over at-rest-only encryption. Stronger confidentiality; the trade-off is query limits, handled with plaintext linkage and, if needed, blind indexes.
  • No ORE or FHE. Order/range search over ciphertext leaks order and can enable reconstruction attacks; equality on a small set of linkage fields is sufficient.
  • GCS ciphertext archive over BigQuery. BigQuery is for plaintext analytics; a PHI archive must remain ciphertext and be decrypted at read time.
  • FHIR-inspired, not conformant. Borrow useful interoperability shapes without the cost of running a full FHIR server.
  • Nested CarePlan.activity[]. Matches FHIR, uses fewer documents, and archives with the parent.
  • Distinct storage formats with fail-closed reads. Prevents a silent plaintext downgrade of a privacy-focused tenant.
  • One provider abstraction. Supports both a premium privacy tier and a regular EHR tier from one codebase.

Future directions

  1. Finish two-mode encryption for the resident document, then add tenant-scoped mode configuration.
  2. Migrate the remaining subcollections and backfill resident_id and crypto_scheme onto legacy documents.
  3. Implement retention and archive: retention_ts, GCS writer/backfill, rehydrate path, and scheduled truncation.
  4. Add break-glass emergency access with short-lived STS credentials and IAM on the real KEKs.
  5. Add integration tests and a CI gate for tests and typechecking.
  6. Evaluate FHIR interoperability through HAPI or the GCP Healthcare API if a real requirement appears, along with native multi-tenancy.

Known gaps

  • No runtime or integration tests; the unit suite is schema-level only.
  • The resident document is still envelope-only.
  • CRYPTO_MODE is process-global, not per tenant.
  • Retention and archive are not implemented.
  • Legacy documents still need a resident_id and crypto_scheme backfill.