ADR-005: Family and delegated healthcare access (backend)


Sep 28, 2026

ACCEPTED

Md Khaled Bin Joha

Status

Proposed

Date

2026-09-28

Context

Problem

Children of roughly 0–6 years old and dependent elderly relatives cannot operate a smartphone, but they still need a healthcare identity: appointments booked for them, medications managed for them, reminders delivered through a caregiver, and records visible to authorised family members.

Today the only way a mother can manage her child's healthcare is to create an account in the child's name and sign in as the child. That is impersonation. Every action is recorded as performed by the patient, so the audit trail cannot say who actually did it, and a caregiver must sign out of their own account to act for someone else.

We need a model where an authenticated caregiver acts on another person's data without becoming that person.

Existing architecture, in brief

  • Shape. Express API over PostgreSQL, with Redis for ephemeral state and rate limiting, BullMQ background workers, and Cloudflare R2 for uploaded documents. Layers are route → service → SQL; there is no ORM.
  • Identity. A single users table with a role of either patient or doctor, plus one profile table per role. There is no separate patient entity — every patient reference in the schema is a user id.
  • Authorisation, mechanism one (self). A JSON Web Token identifies the caller. The route layer passes the caller's own id in as the patient id, and the service adds a SQL predicate scoping the query to that patient. Requests for another patient's row return 404.
  • Authorisation, mechanism two (doctor). A patient generates a short-lived numeric PIN. A doctor redeems it for a session token that grants 15 minutes of read access plus the ability to write a prescription. The session is bound to that one doctor and that one patient.
  • Medication reminders. Delivered entirely on the patient's own device by the operating system alarm scheduler. The server stores reminder times and an alarm policy but never sends a reminder.
  • Audit. A single audit table that already records the acting user separately from the patient whose data was touched.

Constraints

  1. The identity model cannot represent a person who does not log in. Email, phone and password are mandatory and unique, and account creation requires an email verification code. A five-year-old has none of these and must never hold credentials.
  2. Every clinical endpoint requires a verified email on the account being accessed. A managed dependent could never satisfy that check and would be locked out of its own data, including out of the doctor PIN flow.
  3. Caregiver reminders cannot be built on the current reminder system. A device-local alarm cannot notify a different person's phone. Multi-caregiver delivery and escalation require server-side scheduling, which does not exist.
  4. Access tokens live 15 minutes and cannot be revoked. Any permission cached in a token would keep a revoked caregiver working until the token expired.
  5. The API contract is frozen for the closed beta. Existing mobile clients must keep working without a version bump.
  6. The doctor PIN mechanism is in production and must be preserved.

Requirements

  1. Any adult can create a family; an adult may belong to several families; a dependent belongs to exactly one.
  2. Family members can declare relationships, with sibling order derived from date of birth.
  3. A family relationship must never, by itself, grant access to health data.
  4. A caregiver acts on a dependent's data without using the dependent's credentials and without signing out.
  5. An adult patient can explicitly grant, and later revoke, access to another adult.
  6. Permissions are granular: viewing records is not the same as booking appointments or editing medications.
  7. Medication reminders can reach several authorised caregivers, escalating from primary to secondary to backup when unacknowledged.
  8. Every access is attributable: who did what, to whose data, when, and under which authorisation.

Decision

Core decisions

  1. Relationship and authorisation are separate. Families and relationships are for discovery and presentation only. Every access to another person's data requires an explicit delegation record naming the subject, the grantee and the permission. Family isolation then follows by construction — one family cannot reach another because families authorise nothing at all.

  2. Dependents are ordinary user records marked as managed. A new account type distinguishes self from managed. Managed records have no credentials and cannot sign in. This keeps every existing reference to a patient valid and requires no migration of existing health data.

  3. Email verification is a property of the actor, not the subject. The existing check applies unchanged to self accounts. A managed account inherits trust from the guardian who created it.

  4. One authorisation decision point, three bases. A single function answers "may this actor perform this action on this subject?" and returns which basis allowed it: self, delegated, or doctor_session. Role checks stay at the route, the relationship check happens here, and the existing SQL scoping stays at the data layer — three independent layers.

  5. Authorisation is resolved from the database on every request, never from a token. Given constraint 4, this is the only way revocation can take effect immediately. No permission caching in the first version.

  6. The subject is explicit in the URL. A new route namespace carries the patient id in the path. Existing endpoints remain as self-only aliases calling the same services. No version bump, and the security boundary is visible in the request rather than hidden in a header.

  7. A small, closed permission set. Nine permissions covering profile view and edit, appointment view and manage, medication view and manage, record view, reminder receipt, and generating a PIN on the subject's behalf. Writing a prescription, deleting a record, changing account credentials, and re-delegating are not delegable — these are boundaries, not settings.

  8. The doctor PIN mechanism is preserved as-is. Same storage, same 15-minute lifetime, same request header, same error codes. The two mechanisms share only the decision function and the audit format. The term "grant" continues to mean the doctor session; the family mechanism is called a delegation everywhere, so the two are never confused in code or in review.

  9. Caregiver reminders are server-scheduled. Each due dose becomes a row, uniquely keyed by medication and due time so duplicate processing cannot produce duplicate alerts. A periodic worker fires due doses and escalates tiers, and recipients are resolved from live delegations at send time — a subscription alone never authorises delivery. Reminder notifications name the person and the action but never the drug.

  10. Audit records the authorisation basis and the outcome, including denials, so an incident can be reconstructed.

  11. Data lifetime is bounded by authorisation lifetime. Time-limited download links are capped to the remaining authorisation window, so a revoked caregiver or an expired doctor session cannot keep reading files.

System design

Authorisation pipeline. The new decision point sits between the route and the service. The service and data layers are unchanged, which is why this is a refactor rather than a rewrite.

                     HTTP request
                          |
        route layer: authenticate, verify email, check role
                          |
             { actor, subject, permission }
                          |
              +-----------v-----------+
              |  authorise()   NEW    |
              |  self? doctor? delegated? |
              +-----------+-----------+
                  allow   |   deny -> 404 / 403 + audit
                          |
        service layer (already takes a subject id)
                          |
        data layer: query scoped to that subject
                          |
              PostgreSQL   Redis   R2 (links time-capped)

Identity.

                  users
     +-----------------------------+
     | role:         patient | doctor
     | account_type: self | managed     <- new
     | date_of_birth, timezone          <- new
     | email, phone, password           (empty when managed)
     +-----------------------------+

  self     -> signs in, verifies own email
  managed  -> no credentials, cannot sign in,
              trust inherited from the guardian

Domain model. Conceptual; column-level design follows acceptance of this record.

families ----< family_memberships >---- users
                  member_kind: adult | dependent
                  (a dependent may appear in only one family)

family_relationships   from-user, to-user, type      (presentation only)
family_invitations     hashed token, expiry, status

delegations            subject, grantee, status, expiry, revoked   <- ONLY
  \__ delegation_permissions   one row per permission                 source of
                                                                      authority
managed_account_links  managed user, creator, primary caregiver

caregiver_reminder_subscriptions   subject, caregiver, escalation tier
medication_reminder_occurrences    medication, due time, status,
                                   acknowledged by, tier reached
                                   (unique per medication and due time)

audit_logs   + authorisation basis, delegation id, resource, outcome

Delegations are deliberately independent of families, so a grandfather can grant access to a granddaughter whether or not they share a family record. The one-family rule for dependents is enforced by a database constraint rather than application code.

Actor, subject, action.

Family delegation     actor mother    subject child     long-lived, revocable
Doctor session        actor doctor    subject patient   15 minutes, PIN-initiated

Composed case: a guardian generates a PIN for the dependent; the doctor
redeems it. The doctor session's subject is the dependent, never the
guardian. Both steps are audited.

API shape.

NEW, subject-explicit    /v1/patients/:patientId/{home,profile,medications,
                                                  records,appointments,share/pin}
NEW, management          /v1/families..., /v1/delegations..., /v1/invitations...
UNCHANGED                all existing patient, doctor and share endpoints

Delegated booking.

mother -> POST /v1/patients/<child>/appointments   with her own token
       -> authorise(mother, child, appointment.manage) -> allowed (delegated)
       -> appointment created against the child
       -> audit: actor=mother, subject=child, basis=delegated, result=allowed
       -> mother stays signed in as herself throughout

Reminder escalation.

dose due -> tier 1 primary caregiver
   no acknowledgement -> tier 2 secondary
   no acknowledgement -> tier 3 backup
   acknowledged, or caregiver revoked -> escalation stops at the next tick

Alternatives

Family membership implies access. Simplest to build and familiar from consumer family-sharing products. Rejected: an estranged or malicious relative would gain health data merely by being added to a family, there is no per-permission control, and revoking access would mean expelling someone from the family. Directly contrary to requirement 3.

A separate patient table, distinct from accounts. Conceptually cleaner. Rejected: it would require migrating every patient reference in the schema and rewriting every patient-scoped query, against a production database holding real health data, for no new capability.

Separate systems for child care and elderly care. Each could be tuned independently. Rejected: the actor/subject/action shape is identical in both cases, so it would double the authorisation code, the audit shapes and the test surface.

Permissions carried inside the access token. Removes the per-request authorisation query. Rejected: tokens live 15 minutes and cannot be revoked, so a revoked caregiver would keep working until expiry.

The subject passed in a request header instead of the URL. Smaller change to existing endpoints. Rejected: an invisible subject is easy to omit when adding an endpoint, and it makes logs and error reports ambiguous about whose data was touched.

One unified mechanism for doctor sessions and family delegations. One code path instead of two. Rejected: it couples a 15-minute clinical consent ceremony to long-lived family sharing and forces two very different lifetimes and actor types into one policy. They share the decision function and the audit format; nothing more.

A dedicated policy engine. Declarative and externally auditable. Rejected for the first version: a new runtime dependency and policy language for a nine-permission relational model is more machinery than one database query. Worth revisiting if the permission model grows substantially.

Extending device-local alarms to caregivers. Reuses a working subsystem. Rejected: a device alarm cannot reach another person's phone, and the alarm namespace has no notion of whose medication it is.

Consequences

Positive

  • The service and data layers need no change; the decision point generalises a resolver the ingest path already uses.
  • No migration of existing health data. Existing users receive no delegations, so "membership grants nothing" holds from day one by default.
  • The doctor PIN contract is untouched, so mobile clients need no change there.
  • The audit table already separates actor from subject, so the extension is purely additive.
  • Attribution improves for everyone, not only caregivers, because the authorisation basis is now recorded.

Negative

  • Every route that currently treats the caller as the patient must be converted. A missed route is a potential bypass, so an automated check asserting that every subject-scoped route passes through the decision point is a hard requirement, not a nice-to-have.
  • One extra database query per delegated request.
  • Making credentials optional on the users table touches authentication and is the riskiest single migration in this work; it should ship on its own.
  • Server-side reminders are a genuinely new subsystem and the largest piece of new work here. A defect in it is a patient-safety issue rather than a usability one.
  • Caregiver reminders require connectivity, unlike the patient's own device alarms.
  • The stored timezone becomes load-bearing once the server fires reminders; today the device owns the clock.

Operational

  • Introduced behind a feature flag, following the existing pattern, and disabled by default.
  • Sequencing: audit extension first, then the decision point in self-only mode (which must leave the existing test suite passing unchanged — this is the gate that proves the refactor is safe), then the subject-explicit endpoints, then adult-to-adult delegation, then families, then managed dependents, then reminders, then escalation. The first three steps deliver no visible feature and carry most of the safety value.
  • Rollback is the feature flag. The schema is additive and harmless when unused. Only the managed-dependent step needs an agreed plan for orphaned records before it ships.

Follow-up records

Three decisions are deliberately out of scope here and should be recorded separately rather than expanding this one: hardening of the doctor PIN session (rate limiting on redemption, session revocation, scope enforcement, audit coverage), the design of the server-side reminder and escalation subsystem, and the unresolved product questions on delegation lifecycle (what happens to delegations when someone leaves a family, who may authorise access over a managed account, and whether a managed account can later become a full account).

  • ADR-006 — the mobile client. The subject-explicit endpoints are the contract boundary between the two records.
  • ADR-001 — soft-delete and retention, which is why record deletion is not delegable.
  • ADR-002 — the worker process the reminder scheduler joins.