From 122f6b692782d80d017855ef69f6b3a39774f4f5 Mon Sep 17 00:00:00 2001 From: Birger Date: Sat, 19 Sep 2026 08:32:06 +0200 Subject: [PATCH 1/2] Add persistent PostgreSQL clinic backend and recovery Introduce async plugin API v2, role-bound PostgreSQL isolation, guarded migrations, encrypted backup and restore, and persistent synthetic staging. Add concurrency, startup-security, recovery and browser regression coverage, plus Swedish integration and project documentation. --- .github/workflows/ci.yml | 15 + README.md | 6 + apps/app.ts | 147 ++--- apps/public-demo.ts | 24 +- apps/seed.ts | 49 +- apps/server.ts | 9 +- apps/staging-server.ts | 30 + apps/staging.ts | 31 + compose.staging.yml | 19 + docs/ARCHITECTURE.md | 2 +- docs/IDENTITY-AND-ACCESS.md | 4 +- docs/OPERATIONS.md | 26 +- docs/PERSISTENCE.md | 86 +++ docs/PLAN.md | 4 +- docs/PLUGINS.md | 6 +- docs/PROJECT-STATUS.md | 63 ++ docs/RECOVERY.md | 239 ++++++++ docs/SWEDISH-INTEGRATIONS.md | 34 ++ eir.staging.config.json | 28 + package-lock.json | 155 ++++- package.json | 10 +- packages/backup.ts | 533 +++++++++++++++++ packages/contracts.ts | 253 +++++--- packages/openapi.ts | 2 +- packages/postgres-migrations.ts | 382 +++++++++++++ packages/runtime.ts | 10 +- packages/staff-sessions.ts | 102 ++-- plugins/access-clinic.ts | 181 +++--- plugins/access-review.ts | 99 ++-- plugins/access.ts | 61 +- plugins/ai-extractive.ts | 2 +- plugins/ai-ollama.ts | 2 +- plugins/ai-review.ts | 95 +-- plugins/care-team.ts | 214 +++---- plugins/clinical.ts | 154 +++-- plugins/country-eu-local.ts | 2 +- plugins/country-se.ts | 2 +- plugins/fhir-r4.ts | 41 +- plugins/identity-local.ts | 16 +- plugins/identity-oidc.ts | 27 +- plugins/identity-staff-local.ts | 29 +- plugins/laboratories.ts | 84 +-- plugins/medications.ts | 113 ++-- plugins/storage-postgres.ts | 700 +++++++++++++++++++++++ plugins/storage-sqlite.ts | 109 +++- plugins/terminology-icd-se.ts | 2 +- plugins/workforce.ts | 120 ++-- scripts/migrate-postgres.ts | 43 ++ scripts/plugins.ts | 2 +- scripts/postgres-backup-loop.ts | 61 ++ scripts/postgres-backup.ts | 32 ++ scripts/postgres-restore.ts | 40 ++ scripts/prepare-postgres-test-clients.ts | 41 ++ scripts/smoke-model.ts | 2 +- scripts/test-postgres.ts | 21 + tests/backup.test.ts | 421 ++++++++++++++ tests/care-team.e2e.ts | 42 +- tests/care-team.test.ts | 249 +++++--- tests/clinical.test.ts | 162 ++++-- tests/helpers.ts | 6 +- tests/integration.test.ts | 98 +++- tests/medication-results.e2e.ts | 14 +- tests/medication-results.test.ts | 399 ++++++++----- tests/oidc.e2e.ts | 12 +- tests/oidc.test.ts | 44 +- tests/plugins-ai.test.ts | 66 ++- tests/postgres-clinical-helpers.ts | 156 +++++ tests/postgres-clinical.test.ts | 497 ++++++++++++++++ tests/postgres-helpers.ts | 155 +++++ tests/postgres-http.test.ts | 82 +++ tests/postgres-lifecycle.test.ts | 134 +++++ tests/postgres-recovery.test.ts | 172 ++++++ tests/postgres-security.test.ts | 303 ++++++++++ tests/postgres-startup.test.ts | 247 ++++++++ tests/postgres-workflow.e2e.ts | 89 +++ tests/postgres.test.ts | 324 +++++++++++ tests/public.e2e.ts | 17 +- tests/security.test.ts | 45 +- tests/storage-async.test.ts | 133 +++++ tests/terminology.test.ts | 27 +- tests/workflow.e2e.ts | 9 +- tests/workforce-helpers.ts | 20 +- tests/workforce.e2e.ts | 8 +- tests/workforce.test.ts | 313 +++++++--- 84 files changed, 7486 insertions(+), 1322 deletions(-) create mode 100644 apps/staging-server.ts create mode 100644 apps/staging.ts create mode 100644 compose.staging.yml create mode 100644 docs/PERSISTENCE.md create mode 100644 docs/PROJECT-STATUS.md create mode 100644 docs/RECOVERY.md create mode 100644 docs/SWEDISH-INTEGRATIONS.md create mode 100644 eir.staging.config.json create mode 100644 packages/backup.ts create mode 100644 packages/postgres-migrations.ts create mode 100644 plugins/storage-postgres.ts create mode 100644 scripts/migrate-postgres.ts create mode 100644 scripts/postgres-backup-loop.ts create mode 100644 scripts/postgres-backup.ts create mode 100644 scripts/postgres-restore.ts create mode 100644 scripts/prepare-postgres-test-clients.ts create mode 100644 scripts/test-postgres.ts create mode 100644 tests/backup.test.ts create mode 100644 tests/postgres-clinical-helpers.ts create mode 100644 tests/postgres-clinical.test.ts create mode 100644 tests/postgres-helpers.ts create mode 100644 tests/postgres-http.test.ts create mode 100644 tests/postgres-lifecycle.test.ts create mode 100644 tests/postgres-recovery.test.ts create mode 100644 tests/postgres-security.test.ts create mode 100644 tests/postgres-startup.test.ts create mode 100644 tests/postgres-workflow.e2e.ts create mode 100644 tests/postgres.test.ts create mode 100644 tests/storage-async.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7363e6c..f7a1a3f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,20 @@ jobs: verify: runs-on: ubuntu-latest timeout-minutes: 10 + services: + postgres: + image: postgres:18 + env: + POSTGRES_DB: eir_test + POSTGRES_PASSWORD: eir_disposable_ci_only + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U postgres -d eir_test" + --health-interval 5s --health-timeout 3s --health-retries 10 + env: + EIR_TEST_POSTGRES_URL: postgresql://postgres:eir_disposable_ci_only@127.0.0.1:5432/eir_test + PG_BIN: ${{ runner.temp }}/eir-pg-bin steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -13,6 +27,7 @@ jobs: node-version: '22' cache: npm - run: npm ci + - run: node --import tsx scripts/prepare-postgres-test-clients.ts --container '${{ job.services.postgres.id }}' --output "$PG_BIN" - run: npm run terminology:import - run: npm run check - run: npm run format:check diff --git a/README.md b/README.md index 6d33f8b..171a48f 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Without `EIR_DEMO=1`, startup does not seed patient records. Data persists in `. ## Working Modules +The [persistent backend release](docs/PERSISTENCE.md) adds an asynchronous transaction contract, a replaceable PostgreSQL provider, database role-bound provider isolation, guarded migrations, encrypted logical backup/recovery tooling and a separate persistent synthetic staging profile. SQLite and the disposable public demo remain supported. See the [project overview and LinkedIn draft](docs/PROJECT-STATUS.md) for a shareable account of what works and what remains. + The [staff identity and access release](docs/IDENTITY-AND-ACCESS.md) adds OIDC login, unit/assignment/action-level authorization, staff revocation, protected-record exclusion, audit review and temporary read access. The demo uses local identities; real SITHS/HSA connectivity still needs onboarding. The legacy `eir.config.json` remains development-only; consult the clinic profile and migration notes before changing a persistent installation. The [care-team release](docs/CARE-TEAM.md) adds daily booking/check-in, a shared assigned inbox with explicit handover, encounter-linked appointment completion and server-autosaved drafts with conflict recovery. It keeps the public workspace disposable; persistent draft recovery is available in the local persistent installation. @@ -63,6 +65,10 @@ npm run backup -- .data/ehr.sqlite /secure/path/ehr-backup.sqlite - [Diagnosis catalogue, import and data rights](docs/TERMINOLOGY.md) - [Sweden, Estonia, Denmark and EU evidence](docs/SOURCES.md) - [Operations and security boundaries](docs/OPERATIONS.md) +- [Persistent storage and staging](docs/PERSISTENCE.md) +- [Encrypted backup and recovery](docs/RECOVERY.md) +- [Project overview and contribution invitation](docs/PROJECT-STATUS.md) +- [Swedish integration stakeholders and onboarding](docs/SWEDISH-INTEGRATIONS.md) - [Public demo hosting, cost controls and DNS](docs/HOSTING.md) - [Social preview and regeneration](docs/SHARING.md) diff --git a/apps/app.ts b/apps/app.ts index 16a8996..7e989be 100644 --- a/apps/app.ts +++ b/apps/app.ts @@ -7,7 +7,6 @@ import { openApi } from '../packages/openapi.ts'; import { baseApp, webFiles } from './http.ts'; import { visibleRecord } from '../packages/visibility.ts'; import cookie from '@fastify/cookie'; - const uuid = z.uuid(); const version = z.number().int().positive(); export async function createApp( @@ -21,6 +20,14 @@ export async function createApp( store = runtime.get('store'); const app = await baseApp(240, 128 * 1024, identity.browser ? [identity.browser.origin] : []); await app.register(cookie); + app.get('/ready', async (_req, reply) => { + try { + await store.health(); + return { status: 'ready' }; + } catch { + return reply.code(503).send({ status: 'unavailable' }); + } + }); const actors = new WeakMap(); const actor = (request: FastifyRequest) => { const a = actors.get(request); @@ -62,7 +69,7 @@ export async function createApp( req.cookies[flowCookie] ?? '', ); const previous = req.cookies[sessionCookie]; - if (previous) identity.revoke?.(previous); + if (previous) await identity.revoke?.(previous); return reply.setCookie(sessionCookie, token, cookieOptions).redirect('/'); }); } @@ -80,7 +87,7 @@ export async function createApp( api.addHook('onError', async (req, _reply, error) => { const a = actors.get(req); if (a && error instanceof Fault && error.status === 403) - store.audit(a, 'request.denied', undefined, undefined, 'denied'); + await store.audit(a, 'request.denied', undefined, undefined, 'denied'); }); api.get('/session', async (req) => ({ actor: actor(req), @@ -89,37 +96,36 @@ export async function createApp( vitals, renderers: rendererIds, defaultRenderer, - authorization: runtime.get('access').context?.(actor(req)) ?? null, + authorization: (await runtime.get('access').context?.(actor(req))) ?? null, assignments: runtime.has('workforce') - ? runtime - .get('workforce') - .assignments(actor(req)) - .map((row) => ({ - id: row.id, - unitId: row.data.unitId, - role: row.data.role, - name: - runtime.get('workforce').units.find((u) => u.id === row.data.unitId)?.name ?? - row.data.unitId, - })) + ? (await runtime.get('workforce').assignments(actor(req))).map((row) => ({ + id: row.id, + unitId: row.data.unitId, + role: row.data.role, + name: + runtime.get('workforce').units.find((u) => u.id === row.data.unitId)?.name ?? + row.data.unitId, + })) : [], careTeam: actor(req).role === 'clinician' ? { - members: runtime.get('careTeam').members(actor(req)), + members: await runtime.get('careTeam').members(actor(req)), timeZone: runtime.get('careTeam').timeZone, } : null, })); api.get('/care-team', async (req) => { const query = z.object({ day: z.iso.date() }).strict().parse(req.query); - return runtime.get('careTeam').workspace(actor(req), query.day); + return await runtime.get('careTeam').workspace(actor(req), query.day); }); api.post('/patients/:id/appointments', async (req, reply) => reply .code(201) .send( - runtime.get('careTeam').book(actor(req), uuid.parse((req.params as any).id), req.body), + await runtime + .get('careTeam') + .book(actor(req), uuid.parse((req.params as any).id), req.body), ), ); api.post('/appointments/:id/:action', async (req) => { @@ -127,7 +133,7 @@ export async function createApp( .object({ version, data: z.unknown().default({}) }) .strict() .parse(req.body); - return runtime + return await runtime .get('careTeam') .appointment( actor(req), @@ -138,7 +144,7 @@ export async function createApp( ); }); api.post('/logout', async (req, reply) => { - identity.revoke?.(tokenFor(req)); + await identity.revoke?.(tokenFor(req)); if (browser) reply.clearCookie(sessionCookie, cookieOptions); return { ok: true }; }); @@ -146,38 +152,39 @@ export async function createApp( api.post('/session/assignment', async (req) => { const { assignmentId } = z.object({ assignmentId: uuid }).strict().parse(req.body); assert(identity.select, 409, 'Assignment selection unavailable'); - return identity.select(tokenFor(req), assignmentId); + return await identity.select(tokenFor(req), assignmentId); }); - api.get('/workforce', async (req) => runtime.get('workforce').staff(actor(req))); + api.get('/workforce', async (req) => await runtime.get('workforce').staff(actor(req))); api.post('/workforce', async (req, reply) => - reply.code(201).send(runtime.get('workforce').create(actor(req), req.body)), + reply.code(201).send(await runtime.get('workforce').create(actor(req), req.body)), ); api.post('/workforce/:id', async (req) => { const body = z.object({ version, data: z.unknown() }).strict().parse(req.body); - return runtime + return await runtime .get('workforce') .update(actor(req), uuid.parse((req.params as any).id), body.version, body.data); }); } if (runtime.has('accessReview')) { - api.get('/access-review', async (req) => - runtime.get('accessReview').list(actor(req), req.query), + api.get( + '/access-review', + async (req) => await runtime.get('accessReview').list(actor(req), req.query), ); api.post('/access-review', async (req, reply) => - reply.code(201).send(runtime.get('accessReview').review(actor(req), req.body)), + reply.code(201).send(await runtime.get('accessReview').review(actor(req), req.body)), ); api.post('/patients/:id/emergency-access', async (req, reply) => reply .code(201) .send( - runtime + await runtime .get('accessReview') .emergency(actor(req), uuid.parse((req.params as any).id), req.body), ), ); api.post('/patients/:id/protection', async (req) => { const body = z.object({ version, data: z.unknown() }).strict().parse(req.body); - return runtime + return await runtime .get('accessReview') .protect(actor(req), uuid.parse((req.params as any).id), body.version, body.data); }); @@ -195,28 +202,31 @@ export async function createApp( const terminology = runtime.get('terminology'); return { ...terminology.search(query.q, query.limit), source: terminology.source }; }); - api.get('/patients', async (req) => clinical.patients(actor(req))); + api.get('/patients', async (req) => await clinical.patients(actor(req))); api.post('/patients', async (req, reply) => - reply.code(201).send(clinical.register(actor(req), req.body)), + reply.code(201).send(await clinical.register(actor(req), req.body)), ); - api.get('/patients/:id/chart', async (req) => - clinical.chart(actor(req), uuid.parse((req.params as any).id)), + api.get( + '/patients/:id/chart', + async (req) => await clinical.chart(actor(req), uuid.parse((req.params as any).id)), ); api.get('/patients/:id/permissions', async (req) => { const patientId = uuid.parse((req.params as any).id), a = actor(req), access = runtime.get('access'); - access.check(a, patientId); + await access.check(a, patientId); return access.context?.(a, patientId) ?? null; }); - api.get('/patients/:id/medications', async (req) => - runtime.get('medications').list(actor(req), uuid.parse((req.params as any).id)), + api.get( + '/patients/:id/medications', + async (req) => + await runtime.get('medications').list(actor(req), uuid.parse((req.params as any).id)), ); api.post('/patients/:id/medications', async (req, reply) => reply .code(201) .send( - runtime + await runtime .get('medications') .add(actor(req), uuid.parse((req.params as any).id), req.body), ), @@ -225,14 +235,14 @@ export async function createApp( reply .code(201) .send( - runtime + await runtime .get('medications') .reconcile(actor(req), uuid.parse((req.params as any).id), req.body), ), ); api.post('/medications/:id', async (req) => { const body = z.object({ version, data: z.unknown() }).strict().parse(req.body); - return runtime + return await runtime .get('medications') .update(actor(req), uuid.parse((req.params as any).id), body.version, body.data); }); @@ -240,7 +250,7 @@ export async function createApp( reply .code(201) .send( - runtime + await runtime .get('laboratories') .order(actor(req), uuid.parse((req.params as any).id), req.body), ), @@ -248,7 +258,7 @@ export async function createApp( for (const action of ['receive', 'review', 'cancel'] as const) { api.post(`/lab-orders/:id/${action}`, async (req) => { const body = z.object({ version, data: z.unknown() }).strict().parse(req.body); - return runtime + return await runtime .get('laboratories') [action](actor(req), uuid.parse((req.params as any).id), body.version, body.data); }); @@ -257,7 +267,7 @@ export async function createApp( reply .code(201) .send( - clinical.create( + await clinical.create( actor(req), uuid.parse((req.params as any).id), (req.params as any).kind, @@ -270,7 +280,7 @@ export async function createApp( .object({ version, data: z.unknown().default({}) }) .strict() .parse(req.body); - return clinical.transition( + return await clinical.transition( actor(req), uuid.parse((req.params as any).id), (req.params as any).action, @@ -278,30 +288,33 @@ export async function createApp( body.data, ); }); - api.get('/records/:id/history', async (req) => - clinical.history(actor(req), uuid.parse((req.params as any).id)), + api.get( + '/records/:id/history', + async (req) => await clinical.history(actor(req), uuid.parse((req.params as any).id)), + ); + api.get('/patients/:id/changes', async (req) => + store.transaction(async () => { + const a = actor(req), + patientId = uuid.parse((req.params as any).id); + await runtime.get('access').check(a, patientId); + const after = z.coerce + .number() + .int() + .nonnegative() + .max(Number.MAX_SAFE_INTEGER) + .parse((req.query as any).after ?? 0); + const rows = await store.changes(a.tenant, patientId, after); + const entries = rows.filter(({ record }) => visibleRecord(a, record)); + return { entries, nextCursor: rows.length ? Number(rows.at(-1)!.cursor) : after }; + }), ); - api.get('/patients/:id/changes', async (req) => { - const a = actor(req), - patientId = uuid.parse((req.params as any).id); - runtime.get('access').check(a, patientId); - const after = z.coerce - .number() - .int() - .nonnegative() - .max(Number.MAX_SAFE_INTEGER) - .parse((req.query as any).after ?? 0); - const rows = store.changes(a.tenant, patientId, after); - const entries = rows.filter(({ record }) => visibleRecord(a, record)); - return { entries, nextCursor: rows.length ? Number(rows.at(-1)!.cursor) : after }; - }); api.get('/patients/:id/export/fhir', async (req, reply) => { reply.type('application/fhir+json'); - return runtime.get('fhir').bundle(actor(req), uuid.parse((req.params as any).id)); + return await runtime.get('fhir').bundle(actor(req), uuid.parse((req.params as any).id)); }); api.post('/patients/:id/ai', async (req) => { const body = z.object({ encounterId: uuid }).strict().parse(req.body); - return runtime + return await runtime .get('aiReview') .propose(actor(req), uuid.parse((req.params as any).id), body.encounterId); }); @@ -314,7 +327,7 @@ export async function createApp( }) .strict() .parse(req.body); - return runtime + return await runtime .get('aiReview') .review( actor(req), @@ -334,7 +347,7 @@ export async function createApp( }) .strict() .parse(req.body); - runtime + await runtime .get('access') .grant( actor(req), @@ -348,7 +361,7 @@ export async function createApp( }); api.post('/patients/:id/restriction', async (req) => { const { blocked } = z.object({ blocked: z.boolean() }).strict().parse(req.body); - runtime.get('access').block(actor(req), uuid.parse((req.params as any).id), blocked); + await runtime.get('access').block(actor(req), uuid.parse((req.params as any).id), blocked); return { ok: true }; }); api.get('/audit', async (req) => { @@ -359,10 +372,10 @@ export async function createApp( 403, 'Auditor or patient role required', ); - store.audit(a, 'audit.read', a.patientId); + await store.audit(a, 'audit.read', a.patientId); return { - verification: store.verifyAudit(), - entries: store.auditEntries( + verification: await store.verifyAudit(), + entries: await store.auditEntries( a.tenant, a.role === 'patient' ? (a.patientId ?? '') : undefined, ), diff --git a/apps/public-demo.ts b/apps/public-demo.ts index f96cab6..feaa29d 100644 --- a/apps/public-demo.ts +++ b/apps/public-demo.ts @@ -8,7 +8,6 @@ import { createApp } from './app.ts'; import { baseApp, webFiles } from './http.ts'; import { seedDemo } from './seed.ts'; import { demoWorkforce } from './demo-workforce.ts'; - type Workspace = { app: FastifyInstance; runtime: Runtime; @@ -27,7 +26,6 @@ export type DemoLimits = { allowedOrigins?: string[]; }; const digest = (token: string) => createHash('sha256').update(token).digest('hex'); - export async function createPublicDemo(root: string, limits: DemoLimits = {}) { const now = limits.now ?? Date.now; const ttl = limits.ttl ?? 30 * 60000; @@ -38,7 +36,7 @@ export async function createPublicDemo(root: string, limits: DemoLimits = {}) { const retire = async (key: string, workspace: Workspace) => { workspaces.delete(key); await workspace.app.close(); - workspace.runtime.stop(); + await workspace.runtime.stop(); }; const prune = async () => { for (const [key, workspace] of workspaces) { @@ -101,12 +99,12 @@ export async function createPublicDemo(root: string, limits: DemoLimits = {}) { runtime = loaded.runtime; const workforce = runtime.get('workforce'); actor = workforce.actor( - workforce - .forIdentity('https://local.eir.invalid', 'emma') - .find((a) => a.data.role === 'clinician')!, + (await workforce.forIdentity('https://local.eir.invalid', 'emma')).find( + (a) => a.data.role === 'clinician', + )!, ); - seedDemo(runtime, actor); - const token = runtime.get('identity').issue!(actor); + await seedDemo(runtime, actor); + const token = await runtime.get('identity').issue!(actor); inner = await createApp( runtime, root, @@ -126,7 +124,7 @@ export async function createPublicDemo(root: string, limits: DemoLimits = {}) { return reply.code(201).send({ token, expiresAt: new Date(expires).toISOString() }); } catch (error) { await inner?.close(); - runtime?.stop(); + await runtime?.stop(); throw error; } finally { pending--; @@ -162,7 +160,13 @@ export async function createPublicDemo(root: string, limits: DemoLimits = {}) { ); if (req.method === 'POST' && req.url.split('?')[0] === '/api/patients') { assert( - (req.body as { identifier?: { type?: string } })?.identifier?.type === 'local', + ( + req.body as { + identifier?: { + type?: string; + }; + } + )?.identifier?.type === 'local', 422, 'Use a made-up local ID in the public demo, never a real national identifier.', ); diff --git a/apps/seed.ts b/apps/seed.ts index f32aa2c..f0e02e0 100644 --- a/apps/seed.ts +++ b/apps/seed.ts @@ -3,7 +3,6 @@ import type { Runtime } from '../packages/runtime.ts'; import { vitals } from '../plugins/clinical.ts'; import { Temporal } from '@js-temporal/polyfill'; import { randomUUID } from 'node:crypto'; - // Fictional clinical scenarios. Local identifiers never resemble national identity numbers. const patients = [ { @@ -61,25 +60,27 @@ const patients = [ tasks: ['Boka fysioterapeut', 'Telefonuppföljning av funktion och smärta'], }, ]; - -export function seedDemo(runtime: Runtime, actor: Actor) { +export async function seedDemo(runtime: Runtime, actor: Actor) { + return runtime.get('store').transaction(() => seedRecords(runtime, actor)); +} +async function seedRecords(runtime: Runtime, actor: Actor) { const clinical = runtime.get('clinical'); const terminology = runtime.get('terminology'); const now = Date.now(); const team = runtime.get('careTeam'); - const staff = team.members(actor); + const staff = await team.members(actor); const today = Temporal.Now.plainDateISO(team.timeZone).toString(); const days = (offset: number) => new Date(now + offset * 86400000).toISOString(); // Insert in reverse so the newest-first directory opens Anna's follow-up. for (const [index, scenario] of [...patients.entries()].reverse()) { - const patient = clinical.register(actor, { + const patient = await clinical.register(actor, { name: scenario.name, birthDate: scenario.birthDate, identifier: { type: 'local', value: `DEMO-00${index + 1}` }, }); for (const member of staff) if (member.id !== actor.id) - runtime + await runtime .get('access') .grant( actor, @@ -89,17 +90,18 @@ export function seedDemo(runtime: Runtime, actor: Actor) { days(30), 'Scheduled care in the synthetic clinic', ); - const appointment = team.book(actor, patient.id, { + const appointment = await team.book(actor, patient.id, { practitionerId: actor.id, localStart: `${today}T${String(9 + index).padStart(2, '0')}:00`, durationMinutes: 30, reason: scenario.reason, type: index === 3 ? 'phone' : 'visit', }); - if (index === 0) team.appointment(actor, appointment.id, 'arrive', appointment.version, {}); + if (index === 0) + await team.appointment(actor, appointment.id, 'arrive', appointment.version, {}); for (const code of scenario.codes) { const term = terminology.lookup(code)!; - clinical.create(actor, patient.id, 'condition', { + await clinical.create(actor, patient.id, 'condition', { code: { system: term.system, version: term.version, @@ -108,24 +110,26 @@ export function seedDemo(runtime: Runtime, actor: Actor) { }, }); } - if (scenario.allergy) clinical.create(actor, patient.id, 'allergy', scenario.allergy); - const intake = clinical.create(actor, patient.id, 'encounter', { + if (scenario.allergy) await clinical.create(actor, patient.id, 'allergy', scenario.allergy); + const intake = await clinical.create(actor, patient.id, 'encounter', { reason: 'Genomgång av bakgrund', }); - const history = clinical.create(actor, patient.id, 'note', { + const history = await clinical.create(actor, patient.id, 'note', { encounterId: intake.id, text: scenario.background, }); - clinical.transition(actor, history.id, 'sign', history.version, {}); - clinical.transition(actor, intake.id, 'close', intake.version, {}); - const encounter = clinical.create(actor, patient.id, 'encounter', { reason: scenario.reason }); + await clinical.transition(actor, history.id, 'sign', history.version, {}); + await clinical.transition(actor, intake.id, 'close', intake.version, {}); + const encounter = await clinical.create(actor, patient.id, 'encounter', { + reason: scenario.reason, + }); const medicine = [ ['Enalapril 5 mg, tablett', 'Hypertoni'], ['Metformin 500 mg, tablett', 'Typ 2-diabetes'], ['Pulmicort Turbuhaler 200 mikrogram/dos', 'Astma'], ][index]; if (medicine) - runtime.get('medications').add(actor, patient.id, { + await runtime.get('medications').add(actor, patient.id, { clientId: randomUUID(), name: medicine[0], indication: medicine[1], @@ -137,7 +141,7 @@ export function seedDemo(runtime: Runtime, actor: Actor) { }); if (index < 2) { const labs = runtime.get('laboratories'); - const order = labs.order(actor, patient.id, { + const order = await labs.order(actor, patient.id, { clientId: randomUUID(), encounterId: encounter.id, test: index === 0 ? 'Kreatinin och kalium' : 'HbA1c', @@ -149,7 +153,7 @@ export function seedDemo(runtime: Runtime, actor: Actor) { priority: 'routine', }); if (index === 0) - labs.receive(actor, order.id, order.version, { + await labs.receive(actor, order.id, order.version, { source: 'Exempellaboratoriet', messageId: 'LAB-2026-001', collectedAt: days(-1), @@ -166,7 +170,7 @@ export function seedDemo(runtime: Runtime, actor: Actor) { [scenario.previous[i], -28], [scenario.current[i], 0], ]) { - clinical.create(actor, patient.id, 'observation', { + await clinical.create(actor, patient.id, 'observation', { encounterId: encounter.id, code, value, @@ -175,9 +179,12 @@ export function seedDemo(runtime: Runtime, actor: Actor) { }); } } - clinical.create(actor, patient.id, 'note', { encounterId: encounter.id, text: scenario.note }); + await clinical.create(actor, patient.id, 'note', { + encounterId: encounter.id, + text: scenario.note, + }); for (const [i, title] of scenario.tasks.entries()) { - clinical.create(actor, patient.id, 'task', { + await clinical.create(actor, patient.id, 'task', { title, due: days(index === 1 && i === 0 ? -1 : 3 + i * 11).slice(0, 10), assigneeId: i === 1 ? (staff[1]?.id ?? actor.id) : actor.id, diff --git a/apps/server.ts b/apps/server.ts index 309c99e..e8ca3cd 100644 --- a/apps/server.ts +++ b/apps/server.ts @@ -4,25 +4,24 @@ import { fromConfig } from '../packages/runtime.ts'; import { createApp } from './app.ts'; import type { Actor } from '../packages/contracts.ts'; import { seedDemo } from './seed.ts'; - const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); process.chdir(root); const { runtime, config } = await fromConfig(resolve(process.env.EIR_CONFIG ?? 'eir.config.json')); const actor: Actor = { id: 'demo-clinician', tenant: 'demo-vardcentral', role: 'clinician' }; if ( process.env.EIR_DEMO === '1' && - !runtime.get('store').list(actor.tenant, undefined, 'patient').length + !(await runtime.get('store').list(actor.tenant, undefined, 'patient')).length ) { - seedDemo(runtime, actor); + await seedDemo(runtime, actor); } const app = await createApp(runtime, root, config.chartRenderers, config.defaultRenderer); const address = await app.listen({ port: Number(process.env.PORT ?? 4180), host: '127.0.0.1' }); console.log(`Eir EHR: ${address}`); -const token = runtime.get('identity').issue?.(actor); +const token = await runtime.get('identity').issue?.(actor); if (token) console.log(`Local clinician session (8 hours): ${token}`); const shutdown = async () => { await app.close(); - runtime.stop(); + await runtime.stop(); process.exit(0); }; process.on('SIGINT', shutdown); diff --git a/apps/staging-server.ts b/apps/staging-server.ts new file mode 100644 index 0000000..2a45298 --- /dev/null +++ b/apps/staging-server.ts @@ -0,0 +1,30 @@ +import { fileURLToPath } from 'node:url'; +import { createStaging } from './staging.ts'; + +if (process.env.EIR_SYNTHETIC_STAGING !== '1') + throw new Error('Set EIR_SYNTHETIC_STAGING=1 for this persistent synthetic-only environment'); +const root = fileURLToPath(new URL('../', import.meta.url)); +const { runtime, app, actor } = await createStaging(root); +try { + const address = await app.listen({ port: Number(process.env.PORT ?? 4194), host: '127.0.0.1' }); + console.log(`Persistent synthetic staging: ${address}`); + const token = await runtime.get('identity').issue!(actor); + console.log(`Local synthetic clinician session: ${token}`); +} catch (error) { + await app.close(); + await runtime.stop(); + throw error; +} +let stopping = false; +const shutdown = async () => { + if (stopping) return; + stopping = true; + await app.close(); + await runtime.stop(); +}; +process.on('SIGINT', () => { + void shutdown(); +}); +process.on('SIGTERM', () => { + void shutdown(); +}); diff --git a/apps/staging.ts b/apps/staging.ts new file mode 100644 index 0000000..e3576ee --- /dev/null +++ b/apps/staging.ts @@ -0,0 +1,31 @@ +import { resolve } from 'node:path'; +import { fromConfig } from '../packages/runtime.ts'; +import { demoWorkforce } from './demo-workforce.ts'; +import { seedDemo } from './seed.ts'; +import { createApp } from './app.ts'; + +export const stagingTenant = 'eir-synthetic-staging'; + +// This profile is deliberately separate from both public visitor workspaces and clinic OIDC. +export async function createStaging(root: string) { + const { runtime, config } = await fromConfig(resolve(root, 'eir.staging.config.json'), { + 'eir.workforce': demoWorkforce(stagingTenant), + }); + try { + const workforce = runtime.get('workforce'); + const assignments = await workforce.forIdentity('https://local.eir.invalid', 'emma'); + const assignment = assignments.find((row) => row.data.role === 'clinician'); + if (!assignment) throw new Error('Synthetic staging clinician assignment is unavailable'); + const actor = workforce.actor(assignment); + const store = runtime.get('store'); + await store.transaction(async () => { + if (!(await store.list(stagingTenant, undefined, 'patient')).length) + await seedDemo(runtime, actor); + }); + const app = await createApp(runtime, root, config.chartRenderers, config.defaultRenderer); + return { app, runtime, actor }; + } catch (error) { + await runtime.stop(); + throw error; + } +} diff --git a/compose.staging.yml b/compose.staging.yml new file mode 100644 index 0000000..e53c897 --- /dev/null +++ b/compose.staging.yml @@ -0,0 +1,19 @@ +name: eir-ehr-synthetic-staging +services: + postgres: + image: postgres:18 + environment: + POSTGRES_DB: eir_staging + POSTGRES_PASSWORD: ${EIR_STAGING_ADMIN_PASSWORD:?Set a unique staging database administrator password} + ports: + - '127.0.0.1:55433:5432' + volumes: + - staging-postgres:/var/lib/postgresql + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U postgres -d eir_staging'] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped +volumes: + staging-postgres: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2138465..f0af256 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -43,7 +43,7 @@ Draft notes can be revised with an expected version. Signing persists actor and No deletion endpoint exists. Erasure, identity merge/unmerge, legal retention, legal hold and migration require designed workflows rather than bypassing the audit trail. The version log also supplies a cursor-based change feed. Consumers must deduplicate by entity ID plus version, store cursors, and re-authorize each poll. -The v1 storage contract uses synchronous transactions suited to SQLite and single-process deployments. It is not a PostgreSQL abstraction already implemented. Before a multi-process service, introduce an async unit-of-work API and its compatibility adapter, then run the same contract tests against PostgreSQL with row-level security. This is a planned versioned contract change, not a silent drop-in promise. +Runtime API v2 uses asynchronous unit-of-work contracts across storage and stateful services. SQLite serializes awaited work on its local connection; PostgreSQL uses independent clients, serializable transactions, role-bound RLS and a separately operated migration ledger. Both providers preserve version and audit atomicity. This is an explicit breaking plugin contract change, not a silent drop-in adapter. See [PERSISTENCE.md](PERSISTENCE.md) for boundaries, staging and recovery. ## AI Native Workflow diff --git a/docs/IDENTITY-AND-ACCESS.md b/docs/IDENTITY-AND-ACCESS.md index 85db409..d27b05c 100644 --- a/docs/IDENTITY-AND-ACCESS.md +++ b/docs/IDENTITY-AND-ACCESS.md @@ -6,7 +6,7 @@ Release: 2026-09-19. Working identity/authorization modules, not a completed SIT - `eir.config.json`: legacy development policy, retained for existing integrations/tests. Never use as a clinic deployment. - `eir.demo.config.json`: strict workforce policy; public launcher provisions fictional local identities into disposable stores. Run `PORT=4193 npm run demo:public` to try clinical, reviewer and administrator assignments. Demo permissions are not recommended clinic role templates. -- `eir.clinic.config.example.json`: OIDC + strict authorization + workforce administration + audit review. Replace placeholders and provision staff before first startup. Storage remains SQLite, not the future PostgreSQL pilot architecture. +- `eir.clinic.config.example.json`: OIDC + strict authorization + workforce administration + audit review. Replace placeholders and provision staff before first startup. The example retains SQLite; select the PostgreSQL provider using [PERSISTENCE.md](PERSISTENCE.md) for a separately provisioned database. Register a confidential OIDC client supporting Authorization Code flow, S256 PKCE, RS256 ID tokens and `client_secret_basic`. Register the exact callback `https://your-host/auth/callback`. Configure exact issuer, client ID, origin and approved `acr` assurance allowlist. Set the secret through the environment variable named by `clientSecretEnv`; never commit it. Start with `EIR_CONFIG=/absolute/path/to/profile.json npm start` behind a reviewed TLS reverse proxy. The server binds loopback. The `localTestOnly` HTTP exception is false by default and accepts only loopback endpoints; never use it in a real deployment. @@ -59,7 +59,7 @@ SQLite v2 adds session inactivity and durable login transactions. Upgrade invali Tests cover permissions, provider/unit boundaries, protected disclosure routes, exceptional access, review pagination/self-review, session switching/expiry/revocation, restart/bootstrap, schema migration, post-inference revocation, signed OIDC failure paths, browser CSRF/HttpOnly, authenticated signing and UI clearing. The loopback IdP signs real protocol messages but does not establish national integration or independent security review. -Before real data: a clinical design partner, approved access matrix/threat model, verified professional IdP and assignment source, privacy/safety/regulatory reviews, durable deployment with tested restore, external audit anchoring, incident/recovery exercises and independent testing. Next infrastructure milestone: asynchronous transaction-safe PostgreSQL and a separate supervised pilot environment. +Before real data: a clinical design partner, approved access matrix/threat model, verified professional IdP and assignment source, privacy/safety/regulatory reviews, durable deployment with tested restore, external audit anchoring, incident/recovery exercises and independent testing. The asynchronous PostgreSQL provider and separate persistent synthetic staging are now described in [PERSISTENCE.md](PERSISTENCE.md); they are infrastructure groundwork, not a supervised clinical pilot approval. ## Primary References diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index 6dbb097..78233e7 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -2,14 +2,16 @@ ## Current Deployment -This release is for synthetic development data. The server binds to `127.0.0.1`, uses a local bearer identity plugin and stores data in SQLite. It does not provide encrypted database storage, production identity assurance, national service access, full Swedish legal policy, high availability or external immutable log storage. The HTTP app and browser can be replaced; deploying behind a public proxy is not by itself a production conversion. +This release is for synthetic development data. The local server binds to `127.0.0.1`. Profiles select SQLite or PostgreSQL storage and local or OIDC identity. The public demo uses independent disposable SQLite workspaces; persistent PostgreSQL staging is separate. See [PERSISTENCE.md](PERSISTENCE.md) and [IDENTITY-AND-ACCESS.md](IDENTITY-AND-ACCESS.md). Encrypted logical backup/recovery is implemented, but managed encryption at rest, real professional identity onboarding, national connections, the full Swedish rights model, high availability and external immutable audit storage remain deployment work. A public proxy does not make this a clinical deployment. SQLite transactions use WAL, full synchronous writes, foreign-key checks, a busy timeout, parameterized queries, append-only version/audit guards and an immutable signed-note trigger. Clinical creation/revision and successful write audit commit atomically. Authorization decisions are appended before data is returned. The audit chain is checked on startup. A privileged database operator can still replace/truncate/recompute the file and chain; external signed checkpoints and WORM archives remain necessary for stronger tamper evidence. -Session secrets are random, eight-hour bearer tokens. Only SHA-256 token hashes are stored. Session state is held in browser memory, not localStorage. Revocation is implemented. The server does not log request bodies, authorization headers, identifiers or records. Failed authentication has no principal-linked clinical audit entry; infrastructure authentication monitoring is a future operational layer. +Session secrets are random and only token hashes are stored. Local development bearer tokens stay in browser memory; the OIDC profile uses HttpOnly cookies, inactivity expiry and bounded absolute lifetimes. Revocation is implemented, and restored sessions/login transactions are purged before the recovery fence can be released. The server does not log request bodies, authorization headers, identifiers or records. Infrastructure authentication monitoring remains an operational layer to deploy. ## Backup And Restore Drill +PostgreSQL has separate encrypted backup, non-overlapping scheduling and guarded fresh-database restore commands. The real-EHR drill verifies preserved records, signed-note immutability, assignments, orders, audit chains and invalidated authentication state. See [RECOVERY.md](RECOVERY.md). Logical backups are not PITR; remote retention, key custody, monitoring and agreed recovery targets remain explicit operator responsibilities. + Public mode is a separate entry point and plugin profile, described in [HOSTING.md](HOSTING.md). It creates one in-memory runtime/database per visitor and never loads the local persistent database. Limits, origin checks, an explicit demo-mode start payload and expiry are enforced server-side. The public start page carries a concise demo notice, not a legal consent workflow. Expiry is checked on every API access; memory cleanup runs when CPU is available or on the next workspace creation. Request-based Cloud Run may suspend idle timers. Expired records remain inaccessible even before memory cleanup. This mode is for temporary synthetic demonstrations only. Run `npm run backup -- .data/ehr.sqlite /secure/path/backup.sqlite`. This uses SQLite's online backup API, not an unsafe copy of the main file while WAL writes are in flight. The destination must not exist. Protect backup permissions and encrypt at the storage boundary; the script does not implement encryption. @@ -18,16 +20,16 @@ For a local restore drill: stop the application, preserve the current database a ## Threats And Enforced Controls -| Threat | Current control | Remaining work | -| -------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------------------------------------------- | -| Forged role/tenant headers | Authentication resolves server-side actor; client role headers ignored | Strong eID and verified professional attributes | -| Wrong-patient or wrong-tenant writes | Tenant query scoping, encounter ownership and active-care checks | Database RLS and protected-identity policy | -| Lost update or altered signed note | Expected version, immutable note trigger, amendments | Multi-client load/failover tests in PostgreSQL | -| Missing access audit | Audit before disclosure; write audit in same transaction | External anchoring, review queue and archival retention | -| Model fabricated source | Exact record/version quotes checked; proposals reviewed | Clinical correctness evaluation; quotations alone cannot prove correctness | -| Changed permissions/context during inference | Recheck access after inference; compare evidence again on acceptance | Cancellable jobs and cross-process inference orchestration | -| Dependency/plugin compromise | Operator-selected source, lockfile, dependency audit | Signed distribution, SBOM, isolated untrusted extension runtime | -| Browser data disclosure | Escaping, CSP, no-store, no embedded bearer, no third-party assets | Dedicated security review, CSP regression and assistive-technology tests | +| Threat | Current control | Remaining work | +| -------------------------------------------- | ------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| Forged role/tenant headers | Authentication resolves server-side actor; client role headers ignored | Strong eID and verified professional attributes | +| Wrong-patient or wrong-tenant writes | Tenant query scoping, PostgreSQL role-bound RLS, encounter ownership and active-care checks | Complete protected-identity lifecycle and country-specific rights policy | +| Lost update or altered signed note | Expected versions, immutable note triggers, amendments, real PostgreSQL concurrency tests | Production-scale load/soak tests and deployed failover exercises | +| Missing access audit | Audit before disclosure; write audit in same transaction | External anchoring, review queue and archival retention | +| Model fabricated source | Exact record/version quotes checked; proposals reviewed | Clinical correctness evaluation; quotations alone cannot prove correctness | +| Changed permissions/context during inference | Recheck access after inference; compare evidence again on acceptance | Cancellable jobs and cross-process inference orchestration | +| Dependency/plugin compromise | Operator-selected source, lockfile, dependency audit | Signed distribution, SBOM, isolated untrusted extension runtime | +| Browser data disclosure | Escaping, CSP, no-store, no embedded bearer, no third-party assets | Dedicated security review, CSP regression and assistive-technology tests | The current patient restriction is intentionally coarse: it blocks assigned clinician/proxy access while preserving self-access. It is not an implementation of Sweden's unit/provider-specific record blocks, emergency overrides, age-dependent proxy rights or all patient rights. No emergency override is silently granted. diff --git a/docs/PERSISTENCE.md b/docs/PERSISTENCE.md new file mode 100644 index 0000000..37c9a67 --- /dev/null +++ b/docs/PERSISTENCE.md @@ -0,0 +1,86 @@ +# Persistent Clinic Backend + +This milestone supplies a real PostgreSQL provider and a persistent synthetic staging profile. It does not authorize a live patient deployment, replace national-service onboarding, or provide a managed hosting SLA. + +## Storage Contract v2 + +All storage and stateful clinical/identity/access service methods return promises. `Store.transaction(async () => ...)` is an awaited unit of work. A domain mutation, version snapshot and success audit commit together; a failed operation cannot leave a successful partial record behind. Nested transactions join the same unit and a nested failure makes the entire unit rollback-only. + +PostgreSQL uses one checked-out client per unit of work and serializable isolation. Expected record versions still control updates; stale edits never silently overwrite newer content. Transaction callbacks must be replayable and database-only: no network calls, notifications, model inference, file writes or external side effects. Model generation happens outside the transaction, with authorization and evidence rechecked before storage. Exhausted database contention is an explicit conflict, not an automatic last-write-wins update. + +SQLite remains available for local single-process installations and public visitor workspaces. Its asynchronous adapter serializes callers around the synchronous connection, including across awaits. Signed-note, append-only version and audit guards remain in place. This is not a multi-process SQLite deployment recommendation. + +Runtime API version 2 intentionally rejects version 1 plugins. Third-party replacements must update their method signatures, await operations and asynchronous cleanup, and rerun the contract suite. The HTTP payloads and renderer contract are unchanged. SQLite's on-disk schema remains version 2; runtime API versions and database migration versions are separate. + +## Provider Isolation + +The PostgreSQL plugin is bound to one healthcare provider and one database login. The operator provisions a database-side role-to-provider mapping. RLS uses the authenticated role, not a request header or a caller-set tenant variable. Every provider-data table has forced RLS, including sessions, login transactions, versions and audit metadata. Within-provider care-unit, patient and action authorization still belongs to the access modules. + +The application refuses privileged runtime accounts: no superuser, BYPASSRLS, ownership, role membership or database/schema creation rights. The runtime cannot edit tenant mappings, migration metadata, audit heads or existing audit/version rows. A fixed-search-path database trigger appends the audit chain. Database operators and trusted in-process plugins remain inside the trust boundary; this is not protection against a compromised host or a malicious database administrator. + +Use distinct runtime credentials per provider. Do not configure multiple providers in one runtime's workforce units. Certificate-verified TLS is required outside explicit loopback-only local development. Keep migration/backup credentials out of the application environment. + +## Migrations + +Migrations run as a separate operator command, never automatically with application credentials. DDL and the version/checksum ledger commit together under a migration lock. Startup rejects pending, newer or modified migration history, unsafe runtime permissions, disabled RLS and an invalid audit chain. + +Create a restricted login using your database administrator, then set the migration URL through your secret management system: + +```sh +npm run db:migrate -- --tenant YOUR_PROVIDER_ID --runtime-role YOUR_EXISTING_RUNTIME_ROLE +``` + +The default operator variable is `EIR_POSTGRES_MIGRATION_URL`. The runtime profile uses a different variable, such as `EIR_DATABASE_URL`. Never place credentials in JSON profiles or commit them. For local loopback staging only, add `--local-development-only` to the migration command. + +Replace the storage entry in a reviewed clinic profile with: + +```json +{ + "module": "./plugins/storage-postgres.ts", + "config": { + "tenant": "YOUR_PROVIDER_ID", + "connectionStringEnv": "EIR_DATABASE_URL" + } +} +``` + +There is no implicit SQLite-to-PostgreSQL transfer. Changing providers points at a different database. Existing clinical data needs an explicitly reviewed migration with patient/reference reconciliation, preserved versions/audit evidence and cutover validation. Do not repoint an installation and assume the records moved. + +## Persistent Synthetic Staging + +`eir.staging.config.json` and `apps/staging-server.ts` are separate from `eir.demo.config.json` and the public website. The staging tenant is fixed to `eir-synthetic-staging`; it uses local synthetic identities and binds only to loopback. Four fictional patients are seeded atomically on first empty startup. Restart does not reset the clinic, restore revoked assignments or reseed existing records. + +`compose.staging.yml` provides a PostgreSQL 18 service on `127.0.0.1:55433`, backed by a named Docker volume. Supply a unique `EIR_STAGING_ADMIN_PASSWORD` outside the repository: + +```sh +docker compose -f compose.staging.yml up -d +``` + +In that database, create the restricted `eir_staging` login and set its password using your administrator's secure provisioning tool. Set `EIR_POSTGRES_MIGRATION_URL` to the administrator URL for database `eir_staging`, and `EIR_STAGING_DATABASE_URL` to the restricted login URL for the same database. Then: + +```sh +npm run db:migrate -- --tenant eir-synthetic-staging --runtime-role eir_staging --local-development-only +EIR_SYNTHETIC_STAGING=1 npm run staging +``` + +Open `http://127.0.0.1:4194` and use the local synthetic session printed by the server. Another `PORT` selects a different loopback port. Keep this profile off public hosting: it has intentionally local identity assurance and persistent shared synthetic records. The public demo remains disposable, and no paid cloud database is provisioned by these commands. + +`docker compose -f compose.staging.yml down` stops the database without deleting the named volume. Do not add `--volumes` unless intentionally destroying the staging data. A retained volume is not a backup. + +## Recovery And Acceptance + +See [RECOVERY.md](RECOVERY.md) for authenticated encrypted logical backups, fresh-target restoration, session invalidation and scheduling. Point-in-time recovery, off-host immutable storage, key custody/rotation, monitoring and clinic-agreed RPO/RTO remain deployment work. A local successful restore drill does not establish production recovery capacity. + +`/health` is liveness; `/ready` checks the database and returns 503 without driver details when unavailable. Shut down by draining HTTP work and awaiting storage disposal. Startup verifies the audit chain; it is not externally anchored evidence against a privileged database operator. + +The database test suite uses real PostgreSQL connections, not an in-memory SQL emulator. Set `EIR_TEST_POSTGRES_URL` to a disposable administrator database and run `npm run test:postgres`. Tests create their own synthetic databases/roles; never use a clinical database or production credentials. CI runs PostgreSQL 18 alongside the backend and browser suites. + +Acceptance evidence should cover concurrent editors and bookings, rollback when audit writes fail, provider isolation through direct SQL, signed-note immutability, session/login boundaries, restart persistence, migration failure and a verified backup restored into an isolated database. Preserve the test and restore output with each release. + +The current automated PostgreSQL tests use a loopback development connection. TLS configuration is validated, but a certificate-backed remote handshake, certificate rotation and failure recovery still need environment-specific acceptance tests. + +## Technical References + +- [PostgreSQL row security and role bypass rules](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) +- [node-postgres transaction client requirements](https://node-postgres.com/features/transactions) +- [PostgreSQL continuous archiving and point-in-time recovery](https://www.postgresql.org/docs/current/continuous-archiving.html) diff --git a/docs/PLAN.md b/docs/PLAN.md index c1cf41d..082c624 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -28,11 +28,13 @@ Plan for a multidisciplinary team: 3–4 product/backend engineers, 1 integratio ## Next Concrete Backlog +Persistence v2 is implemented in the 2026-09-19 development milestone: asynchronous stateful services, SQLite compatibility, a real PostgreSQL provider with role-bound RLS, guarded migrations, encrypted logical recovery and a separate persistent synthetic staging profile. The P0 persistence foundation now has executable tests; deployed key management, off-host retention, load/soak testing, PITR/failover and clinic-agreed recovery objectives remain operational pilot gates. See [PERSISTENCE.md](PERSISTENCE.md) and [RECOVERY.md](RECOVERY.md). Next connected workflow: one laboratory partner's real order/result transport with reliable delivery and critical-result escalation. + | Priority | Work package | Acceptance criterion | | -------- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | P0 | Strong identity adapter | Validate issuer, audience, nonce/PKCE where applicable, assurance and actor attributes; no browser-supplied role/tenant; test logout/revocation with the selected IdP | | P0 | Swedish authorization model | Map HSA unit/assignment, patient relationship, within-provider vs cross-provider use, consent, protected identity, restrictions, proxy validity and emergency access; exercise every deny branch | -| P0 | Persistence v2 | Async unit-of-work contracts; PostgreSQL integration tests with two concurrent clients and RLS; migration rollback/recovery path | +| P0 | Persistent pilot operations | Build on implemented async/PostgreSQL/RLS/recovery foundation; establish external key custody, off-host backups, monitored restore drills and clinic-agreed availability/RPO/RTO | | P0 | Audit export and review | Externally anchor log digests, archive immutably, assign a log-review queue, test tamper/deletion detection and patient-specific access reports | | P1 | Patient identity lifecycle | Local reserve ID, corrected birth dates, deceased/unknown patients, protected identity masking, merge/unmerge with evidence and no silent reattachment | | P1 | Complete note workflow | Autosave/recovery, co-sign rules, template plugins, dictated text, patient-release policy, corrected authorship and cross-cover handover | diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md index 968e996..d0a7fe6 100644 --- a/docs/PLUGINS.md +++ b/docs/PLUGINS.md @@ -23,7 +23,7 @@ Replace `./plugins/country-se.ts` with `./plugins/country-eu-local.ts`, with `co `eir.terminology.icd-se` provides release metadata, diagnosis search and canonical code validation through `Terminology`. It is independently replaceable, including alongside another country pack. See [terminology setup and source rights](TERMINOLOGY.md). The clinical plugin requires a terminology provider and never trusts a browser-supplied diagnosis label. -A module exports a default `Plugin`. It declares version 1 of the runtime API and its required/provided services. Its `setup` obtains dependencies through `ctx.get`, installs implementations with `ctx.provide`, and registers immediate cleanup with `ctx.onDispose`. Every acquired connection, timer, listener and process must have cleanup registered as soon as it exists. Returning a disposer is also supported when initialization cannot fail after acquisition. +A module exports a default `Plugin`. It declares version 2 of the runtime API and its required/provided services. Its `setup` obtains dependencies through `ctx.get`, installs implementations with `ctx.provide`, and registers cleanup with `ctx.onDispose`. Every acquired connection, timer, listener and process must have cleanup registered as soon as it exists. Cleanup may be asynchronous; callers must await `runtime.stop()`. Returning a disposer is also supported when initialization cannot fail after acquisition. Read `plugins/ai-extractive.ts` for a small complete implementation, `plugins/clinical.ts` for stateful workflow behavior, and `plugins/storage-sqlite.ts` for transactional infrastructure. These are real modules used by the application, not template stubs. The `Services` interface can be extended with TypeScript declaration merging by out-of-tree plugins. Service keys are validated names, not a fixed allowlist. New service consumers must declare their dependencies. @@ -39,6 +39,10 @@ The shell itself can also be replaced: the JSON APIs are independent of its DOM/ ## Compatibility And Trust +The persistence release explicitly moves stateful services to promises and runtime API version 2. Version 1 manifests fail startup. Await all `Store`, `Access`, `Clinical`, `Workforce` (except pure `actor`), `Identity`, `CareTeam`, `Medications`, `Laboratories`, `Fhir`, and `AIReview` operations. Terminology/country lookups and chart-renderer signatures remain unchanged. Replace synchronous array predicates with awaited loops when they call authorization; `filter(async ...)` is never an access check. + +`Store.transaction(async () => ...)` callbacks must be database-only and replayable: PostgreSQL may retry the complete callback for a serialization failure or deadlock, with bounded backoff. Stale expected versions remain explicit conflicts and are not retried as newer writes. Nested failures poison the entire transaction. Model inference, network calls and other external effects must remain outside the callback. Domain code rechecks permissions and reference versions inside the committing transaction. See [PERSISTENCE.md](PERSISTENCE.md). + Medication/result profiles add `Medications` and `Laboratories` providers. The default providers are independently replaceable; schemas and API requests are documented in [medication/result contracts](MEDICATIONS-AND-RESULTS.md). Custom `CareTeam` providers need the two transaction-aware linked-task operations, and must prevent generic task completion from bypassing report review. The default shell needs both services; removing a provider requires an alternate shell/profile rather than leaving nonfunctional controls visible. The care-team release requires a `CareTeam` provider in each clinical profile and an `Access.allowed` predicate consistent with audited `Access.check`. The default profiles include both. See [care-team contracts and compatibility](CARE-TEAM.md) before upgrading custom providers. `apps/web/care-team.js` and `draft-editor.js` are separate shell modules; neither bypasses clinical authorization or record-version checks. diff --git a/docs/PROJECT-STATUS.md b/docs/PROJECT-STATUS.md new file mode 100644 index 0000000..658f6cd --- /dev/null +++ b/docs/PROJECT-STATUS.md @@ -0,0 +1,63 @@ +# Eir EHR: Project Overview + +Updated 2026-09-19. Development software, not an approved clinical deployment. + +## What We Are Building + +An Apache-2.0 electronic health record for Swedish primary care, designed for later country-specific EU deployments. Clinical workflows, storage, identity, terminology, AI providers and chart rendering are replaceable modules. There is no proprietary application core or mandatory paid model API. + +## Working Today + +| Area | Current capability | +| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Clinical work | Patient registration and search; encounters; notes with autosave, signing and amendments; vital signs; diagnoses; allergies | +| Swedish terminology | Official ICD-10-SE 2026 search by code or text, with release metadata and canonical coding | +| Care team | Appointments, check-in, assigned tasks, handover and encounter-linked completion | +| Medicines | Documented medication use and versioned medication/allergy reconciliation, not electronic prescribing | +| Results | Local lab orders, manually entered source-labelled results, corrections, assigned review and explicit critical-result acknowledgement | +| Identity and access | Tested OIDC adapter; staff assignments; care-unit, patient and action permissions; revocation; protected-record exclusion; manual access-log review | +| AI | Replaceable extractive and local-model providers; evidence-linked proposals, clinician review and draft-only acceptance; changed-source detection | +| Interoperability | Authenticated JSON APIs, record history/change feed and FHIR R4 projections; not a complete FHIR server or national implementation-guide certification | +| Persistence | Replaceable SQLite/PostgreSQL storage, role-bound provider isolation, version-conflict checks, encrypted logical backups and a tested EHR restore | + +The public website remains a separate disposable synthetic demo. Persistent staging is a separate environment. Neither is permission to enter real patient data. + +Backend and browser tests exercise real PostgreSQL transactions, independent concurrent editors, access boundaries and restoration of application records. This is engineering verification, not clinical validation, service approval or an independent security certification. + +## Not Yet Connected + +See [SWEDISH-INTEGRATIONS.md](SWEDISH-INTEGRATIONS.md) for the service owners, provider responsibilities and recommended first contacts. + +No live SITHS/HSA provisioning, NLL prescribing/dispensing, NPÖ/Journalen, external laboratory, Webcert or regional referral integration is claimed. OIDC protocol tests do not establish national identity-service approval. Medication documentation is not a prescription service, and manual result entry is not a laboratory connection. + +Before real patient use, the project needs a clinical partner, service-specific onboarding, workflow validation, independent security and privacy review, operational ownership and an intended-use/regulatory assessment. Model evaluation and approval are separate from checking that a citation exists. In-process plugins are trusted code, not sandboxed vendor extensions. + +## How To Contribute + +- Clinicians: review complete consultation scenarios, record workflow problems and help define clinical acceptance tests. +- Swedish integration specialists: contribute verified identity, laboratory and national-service adapters with contract tests. +- Engineers: open focused pull requests for modules, tests, migrations and reliability improvements. +- Designers and accessibility specialists: test real clinical tasks with keyboard, assistive technology and compact workspaces. +- Security and privacy specialists: review authorization boundaries, recovery procedures and threat models; report vulnerabilities privately through SECURITY.md. + +Read [CONTRIBUTING.md](../CONTRIBUTING.md) before submitting a pull request. Use fictional examples in issues, screenshots and tests; never submit patient information or credentials. + +## LinkedIn Draft + +We are building Eir EHR: an open-source electronic health record for Sweden, with an architecture designed to support other EU countries over time. + +The project already has working clinical workflows: patient records, appointments, notes with autosave and signing, ICD-10-SE diagnosis lookup, medication reconciliation, and a local lab order/result review process. + +AI is part of the architecture, with a clear boundary: proposals cite their source records, clinicians review them, and accepted text becomes a draft rather than an automatically signed clinical action. + +Modularity is central. Storage, identity, terminology, AI providers and the way the record is displayed can be replaced. The application is Apache-2.0 licensed, without a proprietary core. + +The latest backend milestone adds PostgreSQL persistence, provider isolation, concurrent-edit protection and encrypted backups with a tested restore workflow. + +This is a working development system, not yet ready for live patient care. National integrations and clinical validation are still ahead of us. + +We are looking for Swedish clinicians, integration engineers, designers and security specialists who want to help build it. Try the demo, challenge the workflows, open an issue or contribute a focused pull request. + +Demo: https://ehr.eir.space/ + +Code and contributions: https://github.com/Eir-Space/eir-ehr diff --git a/docs/RECOVERY.md b/docs/RECOVERY.md new file mode 100644 index 0000000..5046d32 --- /dev/null +++ b/docs/RECOVERY.md @@ -0,0 +1,239 @@ +# Encrypted PostgreSQL Recovery + +These tools implement encrypted, consistent **logical** backups and an isolated +restore drill. They do not implement point-in-time recovery (PITR), automatic +failover, clinical certification, or a complete production disaster-recovery service. + +## Operator Prerequisites + +- Node 22.13 or newer, this project's dependencies, and matching PostgreSQL + `pg_dump` / `pg_restore` clients. For PostgreSQL 18 use PostgreSQL 18 clients; + an older client installed by an OS image is not sufficient. Binaries come from + `PATH`, or `PG_BIN` names their directory. Never point `PG_BIN` at untrusted code. +- Keep runtime credentials separate from migration/backup credentials. Runtime + roles must remain restricted tenant logins. The backup login needs complete + read access, including every tenant under FORCE RLS; use the migration owner + with its operator policies, or a separately governed backup operator. Never + silently substitute the runtime URL for the backup URL. +- A different, isolated recovery instance is strongly preferred. This restore + implementation requires a recovery **superuser** so it can set the target's + connection limit to zero and still restore. Managed services without a true + recovery superuser need a separately reviewed isolation/restore procedure; + do not remove the fence merely to make the command work. +- Provision the same owning roles and restricted runtime role names on the + recovery cluster before restore. Keep their passwords in the secret manager, + not the dump. In particular preserve the owner of `eir.append_audit`, its + SECURITY DEFINER properties, the `operator_access` policies, `eir.tenant_roles`, + and `eir.audit_heads`. Changing owners can break or weaken tenant enforcement. +- Create the target database from `template0`, with no application schema, + extensions, tables, or other clients. Do not boot the application or run its + migrations first. Permit only recovery operators at the network/auth boundary. +- Protect backup directories (0700), encrypted storage, and the recovery scratch + filesystem. Restore temporarily writes plaintext to a private 0700 directory + and 0600 file. Set `EIR_RESTORE_TMPDIR` to an adequately sized, encrypted local + filesystem; do not use a shared or snapshotted unencrypted scratch volume. + +## Configuration + +Secrets are environment variables, not CLI arguments: + +| Variable | Purpose | +| ----------------------------- | ------------------------------------------------------------------------------------ | +| `EIR_BACKUP_DATABASE_URL` | Explicit source URL using the backup/operator role | +| `EIR_RESTORE_DATABASE_URL` | Explicit, separate recovery target URL using the recovery superuser | +| `EIR_DATABASE_URL` | Optional runtime URL, checked to reject that target; never used as a backup fallback | +| `EIR_BACKUP_KEY` | Canonical base64 of exactly 32 cryptographically random bytes | +| `PG_BIN` | Optional directory containing `pg_dump` and `pg_restore` | +| `EIR_RESTORE_TMPDIR` | Optional encrypted recovery scratch directory | +| `EIR_BACKUP_DIRECTORY` | Required archive directory for the scheduled loop | +| `EIR_BACKUP_INTERVAL_MINUTES` | Required loop delay, integer 1 through 35791 | + +Use a secret manager to generate, inject, escrow, and rotate `EIR_BACKUP_KEY`. +For example, the key bytes can be produced by +`randomBytes(32).toString('base64')` from Node's `node:crypto`. Do not put a literal +key in shell history, source control, CI output, or this document. Keep key +escrow separate from archive storage and test recovering a retained archive with +its retained key. There is no key identifier in the file: the operator must keep +the archive-to-key-version inventory without patient identifiers. + +URLs must explicitly name host, user, and database. Remote hosts require +`sslmode=verify-full`; use the appropriate trusted `sslrootcert` when needed. +Only `sslmode`, `sslrootcert`, `sslcert`, and `sslkey` URL parameters are accepted. +`sslmode=disable`, including the normalized default, is allowed only for +`localhost`, `127.0.0.1`, or `[::1]`. Both Node preflight and libpq use the same +validated configuration. No remote `require`, `prefer`, or plaintext fallback. + +## One Backup + +With the source URL and key injected into the process environment: + +```sh +npx tsx scripts/postgres-backup.ts --output /protected/backups/recovery-2026-09-19.eirbak +``` + +The parent directory must exist. `pg_dump --format=custom` provides one consistent +logical snapshot while application writes continue. Output streams directly into +AES-256-GCM encryption; no plaintext dump is created during backup. Schema, +data, sequences, ownership, RLS policies, object ACLs, and functions are included. +The tools do not use schema/table filters, `--no-owner`, or `--no-acl`. + +The archive format is `EIRPGBAK` (8 bytes), version 1 (1 byte), algorithm 1 +(1 byte, AES-256-GCM), random nonce (12 bytes), ciphertext, authentication tag +(16 bytes). The entire 22-byte header is GCM additional authenticated data. +There is no unencrypted patient metadata. Fresh nonces are generated per archive. +AES-GCM's per-message limit applies; these tools are intended for logical archives +below 64 GiB of unencrypted custom-format dump data, not arbitrarily large clusters. + +The archive is written privately, fsynced, and published by an exclusive hard +link on the same filesystem. Existing paths, including symlinks, are never +overwritten. Files have mode 0600. Failed/cancelled runs remove their staging +directory and do not publish an incomplete archive. SIGINT/SIGTERM trigger +cleanup; SIGKILL, machine loss, or filesystem failure can leave private staging +files. Inventory and remove abandoned `.eir-backup-*` / `eir-restore-*` +directories only after confirming there is no live operation. Unlinking is not +secure erasure, which is why scratch storage must itself be encrypted. + +Client stderr is consumed without logging it; even a warning makes the operation +fail. CLI messages never include SQL, row values, tokens, URLs, keys, or raw +driver errors. Underlying database audit/logging policies must also avoid +sensitive statement logging. Privileged host administrators can inspect process +environments; run these tools under a dedicated trusted operating-system account. + +## Scheduled Backups + +Inject the source/key plus `EIR_BACKUP_DIRECTORY` and +`EIR_BACKUP_INTERVAL_MINUTES`, then supervise: + +```sh +npx tsx scripts/postgres-backup-loop.ts +``` + +The loop starts immediately, awaits the complete backup, then waits the configured +interval. It never overlaps its own runs. Names contain UTC time and random UUIDs. +Failures emit a generic failure event and retry after the interval. Shutdown +cancels the active child/stream and stops the timer. The loop does **not delete +any old backup**, even when disk space is low. Run one supervised loop per source; +independent processes are not mutually locked. Test coverage verifies scheduling, +non-overlap, failure reporting, and cancellation. + +Alternatively run the one-shot CLI from an external scheduler with an operator +chosen cadence and non-overlap lock. Operators must configure supervision, +failure and freshness alerts, off-host encrypted replication, capacity monitoring, +retention, immutable copies where appropriate, access reviews, and periodic drills. +Do not delete the last verified backup to make room for an unverified replacement. +Retention expiry and key destruction require a separately governed policy. + +Define the required RPO and RTO for the actual deployment. As an **example only**, +an hourly logical backup schedule is not a guarantee of a one-hour RPO: the loop +waits after completion, snapshots predate completed uploads, and failed runs +increase data loss exposure. Measure the age of the latest successfully restored +snapshot, not merely the most recent filename. RTO includes provisioning roles +and an isolated target, key retrieval, archive download, authentication/decryption, +restore, identity invalidation, evidence checks, and controlled reopening. No +particular RPO/RTO is asserted here. + +PITR still requires managed base backups and WAL archiving/retention, monitoring, +and tested recovery-to-time procedures. This milestone does not supply those. + +## Restore Procedure + +1. Declare a recovery window and isolate the target. Provision matching roles, + extensions' server packages, tablespace locations, and an empty database, for + example `CREATE DATABASE eir_recovery_20260919 TEMPLATE template0`. Database + globals (roles, passwords, tablespaces) are not in a single-database dump. + Configure database-level ownership, ACLs and settings explicitly; this tool + intentionally never uses `--create` and does not restore source database-level + settings/CONNECT ACLs into the target. +2. Set `EIR_RESTORE_DATABASE_URL` and the archive's `EIR_BACKUP_KEY`. Retain + `EIR_BACKUP_DATABASE_URL` and the actual runtime URL in `EIR_DATABASE_URL` as + additional wrong-target guards. Host aliases cannot prove different servers; + verify the destination independently. Confirm the actual database name: + + ```sh + npx tsx scripts/postgres-restore.ts --input /protected/backups/recovery-2026-09-19.eirbak --confirm-fresh-database eir_recovery_20260919 + ``` + +3. Authentication must complete before any database connection or restore write. + Wrong key, tampering, truncation, unknown version, and appended data fail + closed. `pg_restore --list` checks archive compatibility. The target check + rejects nonempty databases, template databases, `postgres`, other connected + sessions and another recovery process. No target is dropped or cleaned. +4. The script sets `CONNECTION LIMIT 0`, rechecks emptiness/other connections, and + runs `pg_restore --single-transaction --exit-on-error`. It never disables + triggers or strips ownership/ACLs. It then transactionally deletes every row + from the single discovered `sessions` and `login_transactions` tables, in all + tenants, without modifying clinical/audit evidence. Current tables are + `eir.sessions` and `eir.login_transactions`. Missing/ambiguous authentication + tables are a failure, not a successful recovery. Keep the target offline; + reconcile the schema and purge those tables manually before boot if needed. +5. A target fenced during recovery stays at connection limit zero on success, + failure, or cancellation. Ordinary runtime connections cannot use it; a + privileged superuser still can, so network/operator isolation remains essential. + Restore failure normally rolls back pg_restore's transaction. A successful + restore followed by failed purge leaves restored data quarantined; never boot + the app or retry into this now-populated target. Investigate and provision a + new empty database for another attempt. +6. Verify migration checksums, table/function ownership, ACLs, RLS and FORCE RLS, + operator/tenant policies and role-to-tenant mapping. Verify signed-note content + and immutability, orders, assignments, full version history, audit hashes/head + continuity and sequence positions. Check both authentication tables are empty. + Preserve the untouched original archive and record drill evidence separately. +7. Stop old application processes, invalidate any external session/login caches, + review restored workforce assignments and access revocations against events + after the snapshot, and require fresh identity-provider login. Restore can + resurrect an assignment revoked after the snapshot; old session invalidation + alone does not fix that. Reconcile before opening access. +8. Apply intended target database CONNECT privileges, then deliberately reopen + with an operator command such as + `ALTER DATABASE eir_recovery_20260919 CONNECTION LIMIT -1`. Only then point the + application at the verified target using its restricted runtime credentials. + Do not give the application the recovery superuser's URL. + +Only restore trusted archives. Encryption authenticates possession of the key; +it does not make SQL from a compromised source operator safe to execute. + +## Automated Drill And Integration + +```sh +node --import tsx --test tests/backup.test.ts +``` + +Without a database URL, generic crypto/safety/scheduler tests run and the real +PostgreSQL drill is explicitly skipped. Set `EIR_TEST_POSTGRES_URL` (or +`EIR_BACKUP_TEST_ADMIN_URL`) to a **disposable administrative test server** and +`PG_BIN` to PostgreSQL 18 clients to run the real custom-format dump/restore. +The test creates unique databases and roles and drops them in cleanup; it never +uses the URL's existing database as a restore target. It checks synthetic signed +note/order/assignment evidence, audit hash rows, ACLs, auth-state purging, +wrong-key zero-write behavior, nonempty and active-target rejection, and the +remaining recovery fence. This generic fixture is not evidence of clinical +workflow validation. + +The separate [application recovery test](../tests/postgres-recovery.test.ts) +creates records through the real EHR services, then verifies a restored signed +note, laboratory order, staff assignment, audit chain and authorized clinical +operation. It also checks that restored sessions cannot authenticate. Run it +alongside the provider and clinical tests with `npm run test:postgres`. These +automated synthetic checks do not replace a deployment-specific recovery drill +or clinical acceptance testing. + +For Docker CI, use executable `PG_BIN/pg_dump` and `PG_BIN/pg_restore` wrappers +which call the running **PostgreSQL 18** service container's real clients. Forward +`PGDATABASE`, `PGUSER`, `PGPASSWORD`, `PGSSLMODE`, `PGCONNECT_TIMEOUT` and +`PGAPPNAME` via `docker exec -e NAME`; use port 5432/loopback _inside that +disposable container_. Preserve stdin with `docker exec -i` for pg_restore. The +wrapper must not print credentials or mock dump contents. Alternatively install +the official PostgreSQL 18 client packages in CI and set their bin directory. + +Main integration APIs in `packages/backup.ts`: + +- `backupKey(environmentValue)` returns the validated 32-byte Buffer. +- `createPostgresBackup({ databaseUrl, outputPath, encryptionKey, pgBin?, signal? })`. +- `restorePostgresBackup({ databaseUrl, inputPath, encryptionKey, confirmFreshDatabase, +sourceDatabaseUrl?, runtimeDatabaseUrl?, pgBin?, temporaryDirectory?, signal? })`. +- `runBackupSchedule(asyncBackup, { intervalMs, signal, onResult?, wait? })` is the + serial scheduler; `wait` is an injectable clock for deterministic tests. No deletion. + +References: [PostgreSQL 18 pg_dump](https://www.postgresql.org/docs/18/app-pgdump.html), +[PostgreSQL 18 pg_restore](https://www.postgresql.org/docs/18/app-pgrestore.html), +[Node authenticated encryption](https://nodejs.org/api/crypto.html). diff --git a/docs/SWEDISH-INTEGRATIONS.md b/docs/SWEDISH-INTEGRATIONS.md new file mode 100644 index 0000000..25c43be --- /dev/null +++ b/docs/SWEDISH-INTEGRATIONS.md @@ -0,0 +1,34 @@ +# Who Owns The Swedish Integrations? + +Checked against primary service-owner documentation on 2026-09-19. This is an onboarding map, not a claim that Eir has agreements, approval or production access. Routes and requirements must be confirmed for the partner provider and selected service scope. + +## Responsible Parties + +| Integration | Service owner and counterparties | Eir's practical next action | +| ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Professional identity: SITHS | Inera; the healthcare organization's SITHS administrator and approved intermediary where applicable. Private healthcare providers use an ombud route. | Choose the partner's actual identity provider/intermediary; obtain the test integration and assurance requirements. | +| Organizations and professional assignments: HSA | Inera; the healthcare organization's HSA administrator or intermediary | Map provider/unit identifiers and approved assignments; establish authoritative provisioning, updates and revocation. | +| NPÖ and 1177 journal | Inera; participating healthcare providers; their supplier/agent or regional integration organization | Select producer/consumer scope, confirm agent/customer arrangements and applicable service contracts. These are separate services, not one generic FHIR connection. | +| NLL and prescription services | E-hälsomyndigheten; system supplier in the approval process; healthcare organization using the approved system | Open a supplier onboarding discussion with a defined read/prescribing scope and a provider partner. | +| Webcert | Inera; healthcare provider or system-supplier agent; regional route where applicable | Agree the actual integration route and pilot customers before implementation. | +| Laboratory orders/results | The laboratory serving the clinic; its LIS/interface supplier; regional integration organization where applicable | Obtain the real message contract, test endpoints, identifiers, analysis catalogue, acknowledgements and operational escalation agreement. | +| Referrals | Sending/receiving providers and their systems; Inera where Elektronisk remiss is the chosen route | Select one destination and transport, including status/acknowledgement semantics and operational ownership. | + +Sources: [SITHS connection routes](https://www.inera.se/tjanster/alla-tjanster-a-o/siths-identifieringstjanst/), [HSA's role](https://www.inera.se/tjanster/alla-tjanster-a-o/katalogtjanst-hsa/om-katalogtjanst-hsa/), [Inera's agent model](https://www.inera.se/tjanster/stod-i-teknisk-anslutning/anslut-via-agent/), [NPÖ](https://www.inera.se/tjanster/alla-tjanster-a-o/npo---nationell-patientoversikt/), [E-hälsomyndigheten system approval](https://samarbetsyta.ehalsomyndigheten.se/handboken/latest/godkaennande-av-anslutande-system), [Webcert integration](https://www.inera.se/tjanster/alla-tjanster-a-o/intygstjanster/webcert/for-dig-som-ska-integrera-webcert-i-ett-vardinformationssystem/), [Elektronisk remiss](https://www.inera.se/tjanster/alla-tjanster-a-o/elektronisk-remiss/). + +Laboratory arrangements are destination-specific. For example, Karolinska describes agreements and interconnected systems for electronic result delivery in its [referral guidance](https://www.karolinska.se/vard/funktion/funktion-medicinsk-diagnostik-karolinska/patologi-och-cancerdiagnostik/punktionsmottagning-sodersjukhuset/punktionsmottagningarna---remissinformation/). Do not assume that example is the universal Swedish laboratory contract. + +## The Healthcare Partner Is Essential + +The first project stakeholder should be a named Swedish healthcare provider with a clinical lead, IT/integration lead, identity administrators, information-security owner and privacy expertise. The provider determines its care workflows and access needs; it is responsible for the personal-data processing it performs. [IMY: provider responsibility](https://www.imy.se/verksamhet/dataskydd/dataskydd-pa-olika-omraden/vard/den-registrerades-rattigheter-for-vardgivare/), [IMY: access allocation](https://www.imy.se/verksamhet/dataskydd/dataskydd-pa-olika-omraden/vard/informationssakerhet--for-vardgivare/tilldelning-av-behorighet-till-uppgifter-om-patienter--for-vardgivare/). + +Recommended division for Eir: a named supplier/integration lead implements and maintains adapters; a clinical owner validates workflows and hazards; an operations owner handles availability, backup, alerts and incidents. Open-source licensing does not remove those responsibilities. IMY is a regulator, not the operator of an API connection or a general EHR approval service. + +## Recommended First Conversations + +1. A Swedish primary-care provider willing to be a design and test partner, initially using fictional cases. +2. That provider's SITHS/HSA/IdP counterpart, to establish verified staff identity and assignment updates. +3. The provider's laboratory and integration team, to scope one complete order/result/correction workflow. +4. Inera's supplier/agent onboarding and E-hälsomyndigheten's system-approval team, in parallel with clinical validation. + +The [national infrastructure portal](https://portal.ehalsomyndigheten.se/) is also relevant for emerging national/EHDS infrastructure. It does not replace the service-specific onboarding paths above. diff --git a/eir.staging.config.json b/eir.staging.config.json new file mode 100644 index 0000000..2617581 --- /dev/null +++ b/eir.staging.config.json @@ -0,0 +1,28 @@ +{ + "profile": "persistent-synthetic-staging", + "plugins": [ + { + "module": "./plugins/storage-postgres.ts", + "config": { + "tenant": "eir-synthetic-staging", + "connectionStringEnv": "EIR_STAGING_DATABASE_URL", + "localDevelopmentOnly": true + } + }, + { "module": "./plugins/country-se.ts" }, + { "module": "./plugins/terminology-icd-se.ts" }, + { "module": "./plugins/workforce.ts" }, + { "module": "./plugins/identity-staff-local.ts", "config": { "localDevelopmentOnly": true } }, + { "module": "./plugins/access-clinic.ts" }, + { "module": "./plugins/access-review.ts" }, + { "module": "./plugins/care-team.ts" }, + { "module": "./plugins/clinical.ts" }, + { "module": "./plugins/medications.ts" }, + { "module": "./plugins/laboratories.ts" }, + { "module": "./plugins/ai-extractive.ts" }, + { "module": "./plugins/ai-review.ts" }, + { "module": "./plugins/fhir-r4.ts" } + ], + "chartRenderers": ["timeline", "table"], + "defaultRenderer": "timeline" +} diff --git a/package-lock.json b/package-lock.json index 74700e7..7ae944e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@eir-space/eir-ehr", - "version": "0.1.0", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@eir-space/eir-ehr", - "version": "0.1.0", + "version": "0.2.0", "license": "Apache-2.0", "dependencies": { "@fastify/cookie": "^11.1.2", @@ -18,12 +18,14 @@ "lucide": "^0.468.0", "openid-client": "^6.8.8", "personnummer": "3.2.1", + "pg": "^8.23.0", "tsx": "^4.23.13", "zod": "^4.1.0" }, "devDependencies": { "@playwright/test": "^1.55.0", "@types/node": "^22.18.0", + "@types/pg": "^8.23.1", "jose": "^6.2.12", "prettier": "^3.9.8", "typescript": "^5.9.0" @@ -762,6 +764,18 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/pg": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.23.1.tgz", + "integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, "node_modules/abstract-logging": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/abstract-logging/-/abstract-logging-2.0.1.tgz", @@ -1351,6 +1365,95 @@ "url": "https://opencollective.com/sweidproject" } }, + "node_modules/pg": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.0.tgz", + "integrity": "sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==", + "license": "MIT", + "dependencies": { + "pg-connection-string": "^2.14.0", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.0", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "engines": { + "node": ">= 16.0.0" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.0" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-cloudflare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz", + "integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==", + "license": "MIT", + "optional": true + }, + "node_modules/pg-connection-string": { + "version": "2.14.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.0.tgz", + "integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==", + "license": "MIT" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "license": "ISC", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz", + "integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==", + "license": "MIT", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.0.tgz", + "integrity": "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==", + "license": "MIT" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "license": "MIT", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + } + }, "node_modules/pino": { "version": "10.3.1", "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", @@ -1417,6 +1520,45 @@ "node": ">=20" } }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz", + "integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "license": "MIT", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/prettier": { "version": "3.9.8", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.9.8.tgz", @@ -1671,6 +1813,15 @@ "dev": true, "license": "MIT" }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "license": "MIT", + "engines": { + "node": ">=0.4" + } + }, "node_modules/zod": { "version": "4.6.5", "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", diff --git a/package.json b/package.json index 07efee8..c84255d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@eir-space/eir-ehr", - "version": "0.1.0", + "version": "0.2.0", "private": true, "type": "module", "license": "Apache-2.0", @@ -9,6 +9,12 @@ }, "scripts": { "dev": "tsx apps/server.ts", + "staging": "tsx apps/staging-server.ts", + "db:migrate": "tsx scripts/migrate-postgres.ts", + "test:postgres": "tsx scripts/test-postgres.ts", + "backup:postgres": "tsx scripts/postgres-backup.ts", + "backup:schedule": "tsx scripts/postgres-backup-loop.ts", + "restore:postgres": "tsx scripts/postgres-restore.ts", "terminology:import": "tsx scripts/import-icd.ts", "start": "tsx apps/server.ts", "demo:public": "tsx apps/public-server.ts", @@ -36,12 +42,14 @@ "lucide": "^0.468.0", "openid-client": "^6.8.8", "personnummer": "3.2.1", + "pg": "^8.23.0", "tsx": "^4.23.13", "zod": "^4.1.0" }, "devDependencies": { "@playwright/test": "^1.55.0", "@types/node": "^22.18.0", + "@types/pg": "^8.23.1", "jose": "^6.2.12", "prettier": "^3.9.8", "typescript": "^5.9.0" diff --git a/packages/backup.ts b/packages/backup.ts new file mode 100644 index 0000000..9c73d28 --- /dev/null +++ b/packages/backup.ts @@ -0,0 +1,533 @@ +import { createCipheriv, createDecipheriv, randomBytes } from 'node:crypto'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { constants, createReadStream } from 'node:fs'; +import { chmod, link, lstat, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises'; +import { dirname, join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Readable, Writable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { setTimeout as delay } from 'node:timers/promises'; +import pg from 'pg'; + +// v1: magic(8), version(1), algorithm(1), nonce(12), ciphertext, GCM tag(16). +// The complete fixed-size header is authenticated as additional data. +const MAGIC = Buffer.from('EIRPGBAK'); +const HEADER_BYTES = 22; +const TAG_BYTES = 16; + +export class BackupError extends Error {} + +export function backupKey(value: string | undefined): Buffer { + if (!value || !/^[A-Za-z0-9+/]{43}=$/.test(value)) + throw new BackupError('EIR_BACKUP_KEY must be canonical base64 encoding of 32 random bytes.'); + const key = Buffer.from(value, 'base64'); + if (key.length !== 32 || key.toString('base64') !== value) + throw new BackupError('EIR_BACKUP_KEY must be canonical base64 encoding of 32 random bytes.'); + return key; +} + +function checkKey(key: Buffer) { + if (!Buffer.isBuffer(key) || key.length !== 32) + throw new BackupError('The encryption key must contain exactly 32 bytes.'); +} + +function safeError(error: unknown, message: string): BackupError { + return error instanceof BackupError ? error : new BackupError(message); +} + +export function backupErrorMessage(error: unknown): string { + return safeError(error, 'Backup operation failed; sensitive diagnostics have been suppressed.') + .message; +} + +async function privateDirectory(parent: string, prefix: string) { + const directory = await mkdtemp(join(parent, prefix)); + try { + await chmod(directory, 0o700); + return directory; + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } +} + +async function absent(path: string) { + try { + await lstat(path); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return; + throw error; + } + throw new BackupError('The output already exists; refusing to overwrite it.'); +} + +// FileHandle writes avoid a stream taking ownership of the descriptor before fsync. +function fileSink(file: FileHandle) { + return new Writable({ + write(chunk: Buffer, _encoding, callback) { + (async () => { + let offset = 0; + while (offset < chunk.length) { + const { bytesWritten } = await file.write(chunk, offset, chunk.length - offset); + if (!bytesWritten) throw new BackupError('Backup file write failed.'); + offset += bytesWritten; + } + })().then( + () => callback(), + () => callback(new BackupError('Backup file write failed.')), + ); + }, + }); +} + +async function writeEncrypted( + source: Readable, + file: FileHandle, + key: Buffer, + signal?: AbortSignal, +) { + const header = Buffer.concat([MAGIC, Buffer.from([1, 1]), randomBytes(12)]); + const cipher = createCipheriv('aes-256-gcm', key, header.subarray(10), { + authTagLength: TAG_BYTES, + }); + cipher.setAAD(header); + await file.writeFile(header); + await pipeline(source, cipher, fileSink(file), { signal }); + await file.writeFile(cipher.getAuthTag()); + await file.sync(); +} + +async function publishEncrypted(outputPath: string, write: (file: FileHandle) => Promise) { + const output = resolve(outputPath); + await absent(output); + const staging = await privateDirectory(dirname(output), '.eir-backup-'); + try { + const temporary = join(staging, 'archive'); + const file = await open(temporary, 'wx', 0o600); + try { + await write(file); + } finally { + await file.close(); + } + // link(), unlike rename(), cannot replace an existing path, including a symlink. + await link(temporary, output); + const parent = await open(dirname(output), 'r'); + try { + await parent.sync(); + } finally { + await parent.close(); + } + } finally { + await rm(staging, { recursive: true, force: true }); + } +} + +export async function encryptBackup( + source: Readable, + outputPath: string, + key: Buffer, + signal?: AbortSignal, +) { + try { + checkKey(key); + await publishEncrypted(outputPath, (file) => writeEncrypted(source, file, key, signal)); + } catch (error) { + source.destroy(); + throw safeError(error, 'Encrypted backup failed; no incomplete archive was published.'); + } +} + +async function readExactly(file: FileHandle, bytes: number, position: number) { + const buffer = Buffer.alloc(bytes); + let offset = 0; + while (offset < bytes) { + const result = await file.read(buffer, offset, bytes - offset, position + offset); + if (!result.bytesRead) throw new BackupError('Backup authentication failed.'); + offset += result.bytesRead; + } + return buffer; +} + +/** The callback cannot run until GCM final() has authenticated the entire archive. */ +export async function withVerifiedBackup( + inputPath: string, + key: Buffer, + consume: (verifiedPath: string) => Promise, + options: { temporaryDirectory?: string; signal?: AbortSignal } = {}, +): Promise { + checkKey(key); + let directory: string | undefined; + let input: FileHandle | undefined; + try { + input = await open(inputPath, constants.O_RDONLY | constants.O_NOFOLLOW); + const info = await input.stat(); + if (!info.isFile() || info.size <= HEADER_BYTES + TAG_BYTES) + throw new BackupError('Backup authentication failed.'); + const header = await readExactly(input, HEADER_BYTES, 0); + if (!header.subarray(0, 8).equals(MAGIC) || header[8] !== 1 || header[9] !== 1) + throw new BackupError('Unsupported or damaged backup header.'); + const tag = await readExactly(input, TAG_BYTES, info.size - TAG_BYTES); + const decipher = createDecipheriv('aes-256-gcm', key, header.subarray(10), { + authTagLength: TAG_BYTES, + }); + decipher.setAAD(header); + decipher.setAuthTag(tag); + directory = await privateDirectory(options.temporaryDirectory ?? tmpdir(), 'eir-restore-'); + const plaintext = join(directory, 'verified.dump'); + const output = await open(plaintext, 'wx', 0o600); + try { + await pipeline( + input.createReadStream({ + start: HEADER_BYTES, + end: info.size - TAG_BYTES - 1, + autoClose: false, + }), + decipher, + fileSink(output), + { signal: options.signal }, + ); + await output.sync(); + } catch { + throw new BackupError('Backup authentication failed.'); + } finally { + await output.close(); + } + options.signal?.throwIfAborted(); + return await consume(plaintext); + } catch (error) { + throw safeError( + error, + 'Backup verification or recovery failed; sensitive diagnostics have been suppressed.', + ); + } finally { + await input?.close(); + if (directory) await rm(directory, { recursive: true, force: true }); + } +} + +function connection(databaseUrl: string) { + try { + const url = new URL(databaseUrl); + const database = decodeURIComponent(url.pathname.slice(1)); + const user = decodeURIComponent(url.username); + if ( + !['postgres:', 'postgresql:'].includes(url.protocol) || + !url.hostname || + !database || + !user || + url.hash + ) + throw new Error(); + if (/[\x00-\x20/=]/.test(database) || /[\x00-\x1f]/.test(user)) throw new Error(); + for (const [name, value] of url.searchParams) { + if (!['sslmode', 'sslrootcert', 'sslcert', 'sslkey'].includes(name)) throw new Error(); + if (name === 'sslmode' && !['disable', 'verify-full'].includes(value)) throw new Error(); + if (url.searchParams.getAll(name).length !== 1) throw new Error(); + } + const hostname = url.hostname.toLowerCase(); + const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(hostname); + if (!loopback && url.searchParams.get('sslmode') !== 'verify-full') + throw new BackupError('Remote PostgreSQL connections require sslmode=verify-full.'); + if (!url.searchParams.has('sslmode')) url.searchParams.set('sslmode', 'disable'); + return { + database, + url: url.toString(), + identity: `${hostname}:${url.port || '5432'}/${database}`, + }; + } catch { + throw new BackupError( + 'Use an explicit PostgreSQL URL with host, user and database. Remote hosts require sslmode=verify-full; disable is allowed only on loopback.', + ); + } +} + +function childEnvironment(databaseUrl: string): NodeJS.ProcessEnv { + // Do not inherit the encryption key, runtime URL, PGOPTIONS or other app secrets. + const env: NodeJS.ProcessEnv = {}; + for (const key of ['PATH', 'HOME', 'TMPDIR', 'SYSTEMROOT', 'LANG', 'LC_ALL']) + if (process.env[key] !== undefined) env[key] = process.env[key]; + const url = new URL(connection(databaseUrl).url); + env.PGDATABASE = decodeURIComponent(url.pathname.slice(1)); + env.PGHOST = url.hostname.replace(/^\[|\]$/g, ''); + env.PGPORT = url.port || '5432'; + env.PGUSER = decodeURIComponent(url.username); + env.PGPASSWORD = decodeURIComponent(url.password); + for (const [name, value] of url.searchParams) env['PG' + name.toUpperCase()] = value; + env.PGCONNECT_TIMEOUT = '15'; + env.PGAPPNAME = 'eir-backup-recovery'; + return env; +} + +function pgProcess( + binary: 'pg_dump' | 'pg_restore', + args: string[], + databaseUrl: string, + pgBin?: string, + signal?: AbortSignal, +) { + signal?.throwIfAborted(); + const child = spawn(pgBin ? join(pgBin, binary) : binary, args, { + env: childEnvironment(databaseUrl), + stdio: ['pipe', 'pipe', 'pipe'], + signal, + }); + let diagnostics = false; + let failed = false; + // Even a successful pg_dump can warn about incomplete contents. Fail closed, + // but never emit stderr, which can contain row data, identifiers or credentials. + child.stderr.on('data', () => { + diagnostics = true; + }); + const completed = new Promise((resolve, reject) => { + // Wait for close even after AbortError: the child may still be alive. + child.once('error', () => { + failed = true; + }); + child.once('close', (code) => { + if (failed) reject(new BackupError(`${binary} could not run or was cancelled.`)); + else if (code === 0 && !diagnostics) resolve(); + else + reject(new BackupError(`${binary} failed or reported warnings; diagnostics suppressed.`)); + }); + }); + // Consumers may still be setting up their stream when spawn fails. + void completed.catch(() => {}); + return { child, completed }; +} + +async function stopChild(child: ChildProcess, completed: Promise) { + if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM'); + const timer = setTimeout(() => child.kill('SIGKILL'), 5000); + timer.unref(); + try { + await completed.catch(() => {}); + } finally { + clearTimeout(timer); + } +} + +export type PostgresBackupOptions = { + databaseUrl: string; + outputPath: string; + encryptionKey: Buffer; + pgBin?: string; + signal?: AbortSignal; +}; + +export async function createPostgresBackup(options: PostgresBackupOptions) { + try { + checkKey(options.encryptionKey); + connection(options.databaseUrl); + await publishEncrypted(options.outputPath, async (file) => { + const { child, completed } = pgProcess( + 'pg_dump', + ['--format=custom', '--no-password', '--lock-wait-timeout=30s'], + options.databaseUrl, + options.pgBin, + options.signal, + ); + child.stdin.end(); + const writing = writeEncrypted(child.stdout, file, options.encryptionKey, options.signal); + try { + await Promise.all([writing, completed]); + } finally { + await stopChild(child, completed); + await writing.catch(() => {}); + } + }); + } catch (error) { + throw safeError(error, 'PostgreSQL backup failed; no incomplete archive was published.'); + } +} + +async function restoreProcess( + path: string, + args: string[], + options: PostgresRestoreOptions, + listing = false, +) { + const { child, completed } = pgProcess( + 'pg_restore', + args, + options.databaseUrl, + options.pgBin, + options.signal, + ); + child.stdout.resume(); + const pumping = pipeline(createReadStream(path), child.stdin, { signal: options.signal }).catch( + (error: NodeJS.ErrnoException) => { + // --list need not consume table data; still require a successful child exit. + if (listing && ['EPIPE', 'ERR_STREAM_PREMATURE_CLOSE'].includes(error.code ?? '')) return; + throw error; + }, + ); + try { + await Promise.all([pumping, completed]); + } finally { + await stopChild(child, completed); + await pumping.catch(() => {}); + } +} + +const identifier = (value: string) => `"${value.replaceAll('"', '""')}"`; + +export type PostgresRestoreOptions = { + databaseUrl: string; + inputPath: string; + encryptionKey: Buffer; + confirmFreshDatabase: string; + sourceDatabaseUrl?: string; + runtimeDatabaseUrl?: string; + temporaryDirectory?: string; + pgBin?: string; + signal?: AbortSignal; +}; + +export async function restorePostgresBackup(options: PostgresRestoreOptions) { + const target = connection(options.databaseUrl); + if ( + options.confirmFreshDatabase !== target.database || + ['postgres', 'template0', 'template1'].includes(target.database) + ) + throw new BackupError('Explicit confirmation must match a dedicated fresh recovery database.'); + for (const other of [options.sourceDatabaseUrl, options.runtimeDatabaseUrl]) + if (other && connection(other).identity === target.identity) + throw new BackupError( + 'The restore target must differ from the source and runtime databases.', + ); + await withVerifiedBackup( + options.inputPath, + options.encryptionKey, + async (path) => { + // No database connection, SQL or pg_restore --dbname before authentication. + await restoreProcess(path, ['--list', '--no-password'], options, true); + const client = new pg.Client({ + connectionString: target.url, + connectionTimeoutMillis: 15000, + query_timeout: 30000, + }); + client.on('error', () => {}); + try { + await client.connect(); + const { + rows: [state], + } = await client.query(` + SELECT current_database() AS name, d.datistemplate AS template, + r.rolsuper AS superuser, pg_try_advisory_lock(1952805425, 1650549611) AS locked + FROM pg_database d JOIN pg_roles r ON r.rolname = current_user + WHERE d.datname = current_database()`); + if (!state || state.name !== target.database || state.template || !state.locked) + throw new BackupError( + 'Recovery target identity or exclusive recovery lock check failed.', + ); + if (!state.superuser) + throw new BackupError( + 'Recovery requires an isolated target and a recovery superuser to fence ordinary connections.', + ); + await assertEmptyIdleTarget(client); + options.signal?.throwIfAborted(); + // Remains zero on success AND failure. Only recovery superusers can connect. + // Operators must finish validation before deliberately reopening the target. + await client.query(`ALTER DATABASE ${identifier(target.database)} CONNECTION LIMIT 0`); + await assertEmptyIdleTarget(client); + await restoreProcess( + path, + [ + '--format=custom', + '--no-password', + '--exit-on-error', + '--single-transaction', + '--dbname=' + target.database, + ], + options, + ); + await client.query('BEGIN'); + try { + const { rows } = await client.query(` + SELECT n.nspname AS schema, c.relname AS name + FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE c.relkind IN ('r','p') AND n.nspname !~ '^pg_' + AND n.nspname <> 'information_schema' + AND c.relname IN ('sessions','login_transactions')`); + if ( + rows.filter((row) => row.name === 'sessions').length !== 1 || + rows.filter((row) => row.name === 'login_transactions').length !== 1 + ) + throw new BackupError( + 'Restored authentication tables do not match the recovery contract; keep the target offline and purge manually.', + ); + for (const row of rows) + await client.query(`DELETE FROM ${identifier(row.schema)}.${identifier(row.name)}`); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => {}); + throw error; + } + } catch (error) { + throw safeError( + error, + 'Restore failed; keep the recovery target isolated and inspect it before any application boot.', + ); + } finally { + await client.end().catch(() => {}); + } + }, + options, + ); +} + +async function assertEmptyIdleTarget(client: pg.Client) { + const { + rows: [state], + } = await client.query(` + SELECT + EXISTS (SELECT 1 FROM pg_stat_activity WHERE datid=(SELECT oid FROM pg_database WHERE datname=current_database()) AND pid<>pg_backend_pid()) AS active, + EXISTS (SELECT 1 FROM pg_namespace WHERE nspname NOT IN ('public','information_schema') AND nspname !~ '^pg_') + OR EXISTS (SELECT 1 FROM pg_prepared_xacts WHERE database=current_database()) + OR EXISTS (SELECT 1 FROM pg_depend WHERE refclassid='pg_namespace'::regclass AND refobjid='public'::regnamespace) + OR EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public') + OR EXISTS (SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace WHERE n.nspname='public') + OR EXISTS (SELECT 1 FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='public') + OR EXISTS (SELECT 1 FROM pg_extension WHERE extname<>'plpgsql') + OR EXISTS (SELECT 1 FROM pg_largeobject_metadata) + OR EXISTS (SELECT 1 FROM pg_event_trigger) + OR EXISTS (SELECT 1 FROM pg_publication) + OR EXISTS (SELECT 1 FROM pg_subscription WHERE subdbid=(SELECT oid FROM pg_database WHERE datname=current_database())) AS populated`); + if (state.active || state.populated) + throw new BackupError('Recovery target must be empty and have no other active connections.'); +} + +/** Run immediately, then wait after each completion; never overlap or delete archives. */ +export async function runBackupSchedule( + backup: () => Promise, + options: { + intervalMs: number; + signal: AbortSignal; + onResult?: (result: 'success' | 'failure') => void; + wait?: (milliseconds: number, signal: AbortSignal) => Promise; + }, +) { + if ( + !Number.isSafeInteger(options.intervalMs) || + options.intervalMs < 1 || + options.intervalMs > 2147483647 + ) + throw new BackupError('Backup interval is outside the supported timer range.'); + const wait = + options.wait ?? ((milliseconds, signal) => delay(milliseconds, undefined, { signal })); + while (!options.signal.aborted) { + try { + await backup(); + options.onResult?.('success'); + } catch { + if (!options.signal.aborted) options.onResult?.('failure'); + } + if (!options.signal.aborted) { + try { + await wait(options.intervalMs, options.signal); + } catch (error) { + if (!options.signal.aborted) throw safeError(error, 'Backup scheduler failed.'); + } + } + } +} diff --git a/packages/contracts.ts b/packages/contracts.ts index 49d7e08..f3ae069 100644 --- a/packages/contracts.ts +++ b/packages/contracts.ts @@ -63,7 +63,10 @@ export type Entity = { updatedAt: string; data: Record; }; -export type Evidence = { ref: string; text: string }; +export type Evidence = { + ref: string; + text: string; +}; export type ProposalOutput = { text: string; citations: Evidence[]; @@ -71,44 +74,82 @@ export type ProposalOutput = { mode: 'extractive' | 'model'; }; export interface Store { - transaction(fn: () => T): T; - get(tenant: string, id: string): Entity | undefined; - list(tenant: string, patientId?: string, kind?: string): Entity[]; - insert(actor: Actor, kind: string, patientId: string | null, data: Record): Entity; + close(): Promise; + health(): Promise; + transaction(fn: () => Promise): Promise; + get(tenant: string, id: string): Promise; + list(tenant: string, patientId?: string, kind?: string): Promise; + insert( + actor: Actor, + kind: string, + patientId: string | null, + data: Record, + ): Promise; revise( actor: Actor, entity: Entity, version: number, data: Record, action: string, - ): Entity; + ): Promise; audit( actor: Actor, action: string, patientId?: string, entityId?: string, outcome?: string, - ): void; - history(tenant: string, id: string): Entity[]; - verifyAudit(): { ok: boolean; count: number }; - grant(tenant: string, patientId: string, actorId: string, role: string, expires: string): void; + ): Promise; + history(tenant: string, id: string): Promise; + verifyAudit(): Promise<{ + ok: boolean; + count: number; + }>; + grant( + tenant: string, + patientId: string, + actorId: string, + role: string, + expires: string, + ): Promise; getGrant( tenant: string, patientId: string, actorId: string, - ): { role: string; expires: string } | undefined; - restrict(tenant: string, patientId: string, blocked: boolean): void; - isBlocked(tenant: string, patientId: string): boolean; - saveSession(hash: string, actor: Actor, expires: string): void; - session(hash: string): { actor: Actor; expires: string; lastSeen: string } | undefined; - updateSession(hash: string, actor: Actor): void; - saveLogin(hash: string, data: Record, expires: string): void; - consumeLogin(hash: string): Record | undefined; - revokeSession(hash: string): void; - auditEntries(tenant: string, patientId?: string): Record[]; - auditPage(tenant: string, query: AuditQuery): AuditRow[]; - auditEntry(tenant: string, seq: number): AuditRow | undefined; - changes(tenant: string, patientId: string, after: number): { cursor: number; record: Entity }[]; + ): Promise< + | { + role: string; + expires: string; + } + | undefined + >; + restrict(tenant: string, patientId: string, blocked: boolean): Promise; + isBlocked(tenant: string, patientId: string): Promise; + saveSession(hash: string, actor: Actor, expires: string): Promise; + session(hash: string): Promise< + | { + actor: Actor; + expires: string; + lastSeen: string; + } + | undefined + >; + updateSession(hash: string, actor: Actor): Promise; + saveLogin(hash: string, data: Record, expires: string): Promise; + consumeLogin(hash: string): Promise | undefined>; + revokeSession(hash: string): Promise; + auditEntries(tenant: string, patientId?: string): Promise[]>; + auditPage(tenant: string, query: AuditQuery): Promise; + auditEntry(tenant: string, seq: number): Promise; + changes( + tenant: string, + patientId: string, + after: number, + ): Promise< + { + cursor: number; + record: Entity; + }[] + >; } export interface Country { code: string; @@ -120,15 +161,24 @@ export interface Country { }; } export interface Access { - permit(actor: Actor, action: Permission, patientId?: string): void; + permit(actor: Actor, action: Permission, patientId?: string): Promise; context?( actor: Actor, patientId?: string, - ): { permissions: Permission[]; unitId: string; name: string }; - eligible?(actor: Actor, targetId: string, patientId: string, action: Permission): boolean; - members?(actor: Actor): TeamMember[]; - allowed(actor: Actor, patientId: string, write?: boolean): boolean; - check(actor: Actor, patientId: string, write?: boolean): void; + ): Promise<{ + permissions: Permission[]; + unitId: string; + name: string; + }>; + eligible?( + actor: Actor, + targetId: string, + patientId: string, + action: Permission, + ): Promise; + members?(actor: Actor): Promise; + allowed(actor: Actor, patientId: string, write?: boolean): Promise; + check(actor: Actor, patientId: string, write?: boolean): Promise; grant( actor: Actor, patientId: string, @@ -136,16 +186,22 @@ export interface Access { role: 'clinician' | 'proxy', expires: string, reason?: string, - ): void; - block(actor: Actor, patientId: string, blocked: boolean): void; + ): Promise; + block(actor: Actor, patientId: string, blocked: boolean): Promise; } export interface Clinical { - patients(actor: Actor): Entity[]; - register(actor: Actor, input: unknown): Entity; - chart(actor: Actor, patientId: string): Entity[]; - create(actor: Actor, patientId: string, kind: string, input: unknown): Entity; - transition(actor: Actor, id: string, action: string, version: number, input: unknown): Entity; - history(actor: Actor, id: string): Entity[]; + patients(actor: Actor): Promise; + register(actor: Actor, input: unknown): Promise; + chart(actor: Actor, patientId: string): Promise; + create(actor: Actor, patientId: string, kind: string, input: unknown): Promise; + transition( + actor: Actor, + id: string, + action: string, + version: number, + input: unknown, + ): Promise; + history(actor: Actor, id: string): Promise; } export interface AIProvider { id: string; @@ -159,44 +215,55 @@ export interface AIReview { version: number, decision: 'accept' | 'reject', text?: string, - ): Entity; + ): Promise; } export interface Fhir { - bundle(actor: Actor, patientId: string): Record; + bundle(actor: Actor, patientId: string): Promise>; } export interface Identity { authenticate(token: string): Promise; - issue?(actor: Actor): string; - revoke?(token: string): void; + issue?(actor: Actor): Promise; + revoke?(token: string): Promise; select?(token: string, assignmentId: string): Promise; browser?: { origin: string; - begin(): Promise<{ url: string; binding: string }>; + begin(): Promise<{ + url: string; + binding: string; + }>; callback(url: URL, binding: string): Promise; }; } export interface Workforce { - current(actor: Actor): Entity; - assignments(actor: Actor): Entity[]; - forIdentity(issuer: string, subject: string): Entity[]; + current(actor: Actor): Promise; + assignments(actor: Actor): Promise; + forIdentity(issuer: string, subject: string): Promise; actor(assignment: Entity, authentication?: Actor['authentication']): Actor; - staff(actor: Actor): Entity[]; - create(actor: Actor, input: unknown): Entity; - update(actor: Actor, id: string, version: number, input: unknown): Entity; - units: { id: string; tenant: string; name: string }[]; + staff(actor: Actor): Promise; + create(actor: Actor, input: unknown): Promise; + update(actor: Actor, id: string, version: number, input: unknown): Promise; + units: { + id: string; + tenant: string; + name: string; + }[]; } export interface AccessReview { list( actor: Actor, query: unknown, - ): { - entries: (AuditRow & { reviews: Entity[] })[]; + ): Promise<{ + entries: (AuditRow & { + reviews: Entity[]; + })[]; nextBefore: number | null; - verification: { ok: boolean }; - }; - review(actor: Actor, input: unknown): Entity; - emergency(actor: Actor, patientId: string, input: unknown): Entity; - protect(actor: Actor, patientId: string, version: number, input: unknown): Entity; + verification: { + ok: boolean; + }; + }>; + review(actor: Actor, input: unknown): Promise; + emergency(actor: Actor, patientId: string, input: unknown): Promise; + protect(actor: Actor, patientId: string, version: number, input: unknown): Promise; } export interface Services { workforce: Workforce; @@ -214,39 +281,66 @@ export interface Services { fhir: Fhir; identity: Identity; } -export type TeamMember = { id: string; tenant: string; name: string; profession: string }; +export type TeamMember = { + id: string; + tenant: string; + name: string; + profession: string; +}; export interface CareTeam { timeZone: string; - members(actor: Actor): TeamMember[]; - workspace(actor: Actor, day: string): { appointments: Entity[]; tasks: Entity[] }; - book(actor: Actor, patientId: string, input: unknown): Entity; - appointment(actor: Actor, id: string, action: string, version: number, input: unknown): Entity; - createTask(actor: Actor, patientId: string, input: unknown): Entity; - task(actor: Actor, id: string, action: string, version: number, input: unknown): Entity; - encounterClosed(actor: Actor, encounterId: string): void; + members(actor: Actor): Promise; + workspace( + actor: Actor, + day: string, + ): Promise<{ + appointments: Entity[]; + tasks: Entity[]; + }>; + book(actor: Actor, patientId: string, input: unknown): Promise; + appointment( + actor: Actor, + id: string, + action: string, + version: number, + input: unknown, + ): Promise; + createTask(actor: Actor, patientId: string, input: unknown): Promise; + task(actor: Actor, id: string, action: string, version: number, input: unknown): Promise; + encounterClosed(actor: Actor, encounterId: string): Promise; // Domain services call these inside their own store transaction. - createLinkedTask(actor: Actor, patientId: string, input: unknown, orderId: string): Entity; + createLinkedTask( + actor: Actor, + patientId: string, + input: unknown, + orderId: string, + ): Promise; syncLinkedTask( actor: Actor, order: Entity, event: 'result' | 'review' | 'cancel', resolution?: string, - ): Entity; + ): Promise; } export interface Medications { list( actor: Actor, patientId: string, - ): { items: Entity[]; snapshot: string[]; review: Entity | null; current: boolean }; - add(actor: Actor, patientId: string, input: unknown): Entity; - update(actor: Actor, id: string, version: number, input: unknown): Entity; - reconcile(actor: Actor, patientId: string, input: unknown): Entity; + ): Promise<{ + items: Entity[]; + snapshot: string[]; + review: Entity | null; + current: boolean; + }>; + add(actor: Actor, patientId: string, input: unknown): Promise; + update(actor: Actor, id: string, version: number, input: unknown): Promise; + reconcile(actor: Actor, patientId: string, input: unknown): Promise; } export interface Laboratories { - order(actor: Actor, patientId: string, input: unknown): Entity; - receive(actor: Actor, id: string, version: number, input: unknown): Entity; - review(actor: Actor, id: string, version: number, input: unknown): Entity; - cancel(actor: Actor, id: string, version: number, input: unknown): Entity; + order(actor: Actor, patientId: string, input: unknown): Promise; + receive(actor: Actor, id: string, version: number, input: unknown): Promise; + review(actor: Actor, id: string, version: number, input: unknown): Promise; + cancel(actor: Actor, id: string, version: number, input: unknown): Promise; } export interface Terminology { source: { @@ -261,23 +355,26 @@ export interface Terminology { search( query: string, limit?: number, - ): { total: number; items: import('./icd.ts').DiagnosisTerm[] }; + ): { + total: number; + items: import('./icd.ts').DiagnosisTerm[]; + }; } export type ServiceName = keyof Services; export type Plugin = { id: string; version: string; - apiVersion: 1; + apiVersion: 2; provides: ServiceName[]; requires: ServiceName[]; setup( ctx: { get(name: K): Services[K]; provide(name: K, value: Services[K]): void; - onDispose(dispose: () => void): void; + onDispose(dispose: () => void | Promise): void; }, config: Record, - ): void | (() => void) | Promise void)>; + ): void | (() => void | Promise) | Promise void | Promise)>; }; export class Fault extends Error { constructor( diff --git a/packages/openapi.ts b/packages/openapi.ts index 17f835d..eae2a85 100644 --- a/packages/openapi.ts +++ b/packages/openapi.ts @@ -299,7 +299,7 @@ export function openApi(clinic = false, secureCookie = false) { if (!clinic) route('/audit', 'get', 'Authorized access audit (legacy policy)'); return { openapi: '3.1.0', - info: { title: 'Eir EHR clinical API', version: '0.1.0' }, + info: { title: 'Eir EHR clinical API', version: '0.2.0' }, servers: [{ url: '/api' }], components: { securitySchemes: { diff --git a/packages/postgres-migrations.ts b/packages/postgres-migrations.ts new file mode 100644 index 0000000..592c419 --- /dev/null +++ b/packages/postgres-migrations.ts @@ -0,0 +1,382 @@ +import { createHash } from 'node:crypto'; +import type { Pool, PoolClient, PoolConfig } from 'pg'; + +export type PostgresConnectionConfig = { + connectionStringEnv: string; + localDevelopmentOnly?: boolean; +}; + +// Do not pass URL SSL options to pg: they can override certificate verification. +export function postgresPoolConfig(config: PostgresConnectionConfig): PoolConfig { + if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(config.connectionStringEnv ?? '')) + throw new Error('PostgreSQL connectionStringEnv is required'); + const value = process.env[config.connectionStringEnv]; + if (!value) throw new Error('PostgreSQL connection environment variable is missing'); + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('Invalid PostgreSQL connection URL'); + } + if (!['postgres:', 'postgresql:'].includes(url.protocol) || !url.hostname || !url.username) + throw new Error('PostgreSQL requires a TCP URL with an explicit database role'); + const local = config.localDevelopmentOnly === true; + if (local && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) + throw new Error('localDevelopmentOnly requires a loopback PostgreSQL host'); + for (const [key, value] of url.searchParams) { + if ( + key !== 'sslmode' || + !['require', 'verify-full', ...(local ? ['disable'] : [])].includes(value) + ) + throw new Error('Unsupported PostgreSQL URL option; TLS verification is mandatory'); + } + url.search = ''; + return { + connectionString: url.toString(), + ssl: local ? false : { rejectUnauthorized: true }, + max: 10, + connectionTimeoutMillis: 10_000, + idleTimeoutMillis: 30_000, + statement_timeout: 30_000, + idle_in_transaction_session_timeout: 30_000, + application_name: 'eir-ehr', + }; +} + +export const postgresDataTables = [ + 'tenant_roles', + 'audit_heads', + 'entities', + 'versions', + 'grants', + 'restrictions', + 'sessions', + 'login_transactions', + 'audit', +] as const; + +const initialSchema = ` +CREATE TABLE eir.tenant_roles ( + runtime_role name PRIMARY KEY, + tenant text NOT NULL CHECK (length(tenant) > 0) +); +CREATE TABLE eir.audit_heads ( + tenant text PRIMARY KEY, + seq bigint NOT NULL DEFAULT 0, + hash text NOT NULL DEFAULT 'GENESIS' +); +CREATE TABLE eir.entities ( + tenant text NOT NULL, + id text NOT NULL, + patient_id text NOT NULL, + kind text NOT NULL, + version integer NOT NULL CHECK (version > 0), + created_at text NOT NULL, + updated_at text NOT NULL, + data jsonb NOT NULL CHECK (jsonb_typeof(data) = 'object'), + PRIMARY KEY (tenant, id) +); +CREATE INDEX chart ON eir.entities (tenant, patient_id, kind); +CREATE UNIQUE INDEX identifier_unique ON eir.entities + (tenant, (data->'identifier'->>'system'), (data->'identifier'->>'value')) WHERE kind = 'patient'; +CREATE TABLE eir.versions ( + cursor bigint GENERATED ALWAYS AS IDENTITY UNIQUE, + tenant text NOT NULL, + id text NOT NULL, + version integer NOT NULL CHECK (version > 0), + snapshot jsonb NOT NULL, + PRIMARY KEY (tenant, id, version), + FOREIGN KEY (tenant, id) REFERENCES eir.entities (tenant, id), + CHECK ((snapshot->>'tenant') IS NOT DISTINCT FROM tenant), + CHECK ((snapshot->>'id') IS NOT DISTINCT FROM id), + CHECK ((snapshot->>'version') IS NOT DISTINCT FROM version::text) +); +CREATE INDEX version_changes ON eir.versions (tenant, (snapshot->>'patientId'), cursor); +CREATE TABLE eir.grants ( + tenant text NOT NULL, + patient_id text NOT NULL, + actor_id text NOT NULL, + role text NOT NULL, + expires text NOT NULL, + PRIMARY KEY (tenant, patient_id, actor_id), + FOREIGN KEY (tenant, patient_id) REFERENCES eir.entities (tenant, id) +); +CREATE TABLE eir.restrictions ( + tenant text NOT NULL, + patient_id text NOT NULL, + blocked boolean NOT NULL, + PRIMARY KEY (tenant, patient_id), + FOREIGN KEY (tenant, patient_id) REFERENCES eir.entities (tenant, id) +); +CREATE TABLE eir.sessions ( + tenant text NOT NULL, + hash text NOT NULL, + actor jsonb NOT NULL, + expires text NOT NULL, + last_seen text NOT NULL, + PRIMARY KEY (tenant, hash), + CHECK ((actor->>'tenant') IS NOT DISTINCT FROM tenant) +); +CREATE TABLE eir.login_transactions ( + tenant text NOT NULL, + hash text NOT NULL, + data jsonb NOT NULL CHECK (jsonb_typeof(data) = 'object'), + expires text NOT NULL, + PRIMARY KEY (tenant, hash) +); +CREATE SEQUENCE eir.audit_seq; +CREATE TABLE eir.audit ( + tenant text NOT NULL, + seq bigint NOT NULL, + body text NOT NULL, + previous text NOT NULL, + hash text NOT NULL, + PRIMARY KEY (tenant, seq), + CHECK ((body::jsonb->>'tenant') IS NOT DISTINCT FROM tenant) +); +CREATE INDEX audit_unit ON eir.audit (tenant, ((body::jsonb)->>'unitId'), seq DESC); + +CREATE FUNCTION eir.reject_mutation() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog AS $$ +BEGIN + RAISE EXCEPTION 'EHR immutable record' USING ERRCODE = '23514'; +END; +$$; +CREATE TRIGGER audit_append_only BEFORE UPDATE OR DELETE OR TRUNCATE ON eir.audit + FOR EACH STATEMENT EXECUTE FUNCTION eir.reject_mutation(); +CREATE TRIGGER versions_append_only BEFORE UPDATE OR DELETE OR TRUNCATE ON eir.versions + FOR EACH STATEMENT EXECUTE FUNCTION eir.reject_mutation(); +CREATE TRIGGER entities_no_delete BEFORE DELETE OR TRUNCATE ON eir.entities + FOR EACH STATEMENT EXECUTE FUNCTION eir.reject_mutation(); +CREATE FUNCTION eir.guard_entity() RETURNS trigger +LANGUAGE plpgsql SET search_path = pg_catalog AS $$ +BEGIN + IF (OLD.kind = 'note' AND OLD.data->>'status' = 'signed') + OR NEW.tenant <> OLD.tenant OR NEW.id <> OLD.id OR NEW.patient_id <> OLD.patient_id + OR NEW.kind <> OLD.kind OR NEW.created_at <> OLD.created_at + OR NEW.version <> OLD.version + 1 THEN + RAISE EXCEPTION 'EHR immutable record or invalid revision' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER entity_revision_guard BEFORE UPDATE ON eir.entities + FOR EACH ROW EXECUTE FUNCTION eir.guard_entity(); + +-- Only this fixed-path trigger can mutate audit heads. Runtime roles have SELECT only. +-- session_user remains the authenticated login inside this SECURITY DEFINER function; +-- the table's independent RLS policy uses current_user at the caller's boundary. +CREATE FUNCTION eir.append_audit() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog AS $$ +DECLARE + prior text; +BEGIN + IF NOT EXISTS (SELECT 1 FROM eir.tenant_roles + WHERE runtime_role = session_user AND tenant = NEW.tenant) THEN + RAISE EXCEPTION 'EHR tenant denied' USING ERRCODE = '42501'; + END IF; + SELECT hash INTO prior FROM eir.audit_heads WHERE tenant = NEW.tenant FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'EHR tenant not provisioned' USING ERRCODE = '42501'; + END IF; + NEW.seq := nextval('eir.audit_seq'::regclass); + NEW.previous := prior; + NEW.hash := encode(sha256(convert_to(prior || NEW.body, 'UTF8')), 'hex'); + UPDATE eir.audit_heads SET seq = NEW.seq, hash = NEW.hash WHERE tenant = NEW.tenant; + RETURN NEW; +END; +$$; +CREATE TRIGGER audit_chain BEFORE INSERT ON eir.audit + FOR EACH ROW EXECUTE FUNCTION eir.append_audit(); + +${postgresDataTables + .map( + (table) => ` +ALTER TABLE eir.${table} ENABLE ROW LEVEL SECURITY; +ALTER TABLE eir.${table} FORCE ROW LEVEL SECURITY; +CREATE POLICY operator_access ON eir.${table} TO CURRENT_USER USING (true) WITH CHECK (true); +CREATE POLICY tenant_scope ON eir.${table} USING (${ + table === 'tenant_roles' + ? 'runtime_role = current_user' + : 'tenant = (SELECT tenant FROM eir.tenant_roles WHERE runtime_role = current_user)' + }) WITH CHECK (${ + table === 'tenant_roles' + ? 'runtime_role = current_user' + : 'tenant = (SELECT tenant FROM eir.tenant_roles WHERE runtime_role = current_user)' + });`, + ) + .join('\n')} +REVOKE ALL ON ALL TABLES IN SCHEMA eir FROM PUBLIC; +REVOKE ALL ON ALL SEQUENCES IN SCHEMA eir FROM PUBLIC; +REVOKE ALL ON ALL FUNCTIONS IN SCHEMA eir FROM PUBLIC; +`; + +export const postgresMigrations = [ + { version: 1, name: 'tenant-role-storage', sql: initialSchema }, +].map((migration) => ({ + ...migration, + checksum: createHash('sha256').update(migration.sql).digest('hex'), +})); + +export async function checkPostgresMigrations(client: PoolClient, complete = true): Promise { + const exists = await client.query("SELECT to_regclass('eir.schema_migrations') AS ledger"); + if (!exists.rows[0].ledger) throw new Error('PostgreSQL migrations have not been applied'); + const { rows } = await client.query( + 'SELECT version, name, checksum FROM eir.schema_migrations ORDER BY version', + ); + for (const [index, row] of rows.entries()) { + const expected = postgresMigrations[index]; + if (!expected || row.version !== expected.version) + throw new Error('PostgreSQL migration version is newer than application or non-contiguous'); + if (row.name !== expected.name || row.checksum !== expected.checksum) + throw new Error('PostgreSQL migration checksum mismatch'); + } + if (complete && rows.length !== postgresMigrations.length) + throw new Error('PostgreSQL migrations are pending; run the operator migration command'); +} + +const quoteIdentifier = (value: string) => '"' + value.replaceAll('"', '""') + '"'; + +export async function checkRuntimeRole(client: PoolClient, role?: string): Promise { + const { rows } = await client.query( + ` + SELECT r.rolname, r.rolsuper, r.rolbypassrls, r.rolcreaterole, r.rolcreatedb, r.rolreplication, + r.rolcanlogin, + EXISTS (SELECT 1 FROM pg_auth_members m WHERE m.member = r.oid) AS member, + EXISTS (SELECT 1 FROM pg_namespace n WHERE n.nspname = 'eir' AND n.nspowner = r.oid) AS schema_owner, + EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid + WHERE n.nspname = 'eir' AND c.relowner = r.oid) AS table_owner, + EXISTS (SELECT 1 FROM pg_proc p JOIN pg_namespace n ON p.pronamespace = n.oid + WHERE n.nspname = 'eir' AND p.proowner = r.oid) AS function_owner, + EXISTS (SELECT 1 FROM pg_database d WHERE d.datname = current_database() AND d.datdba = r.oid) AS db_owner, + has_schema_privilege(r.oid, 'eir', 'CREATE') AS schema_create, + has_database_privilege(r.oid, current_database(), 'CREATE') AS db_create, + session_user = current_user AS direct_login + FROM pg_roles r WHERE r.rolname = COALESCE($1::name, current_user)`, + [role ?? null], + ); + const row = rows[0]; + if ( + !row || + !row.rolcanlogin || + (!role && !row.direct_login) || + [ + 'rolsuper', + 'rolbypassrls', + 'rolcreaterole', + 'rolcreatedb', + 'rolreplication', + 'member', + 'schema_owner', + 'table_owner', + 'function_owner', + 'db_owner', + 'schema_create', + 'db_create', + ].some((key) => row[key]) + ) + throw new Error( + 'PostgreSQL runtime role must be a restricted nonowner login without role memberships', + ); + const { rows: settings } = await client.query( + `SELECT + current_setting('server_version_num')::integer AS version, + current_setting('session_replication_role') AS replication_role, + EXISTS ( + SELECT 1 FROM pg_db_role_setting s + WHERE s.setrole IN (0, (SELECT oid FROM pg_roles WHERE rolname = $1::name)) + AND s.setdatabase IN (0, (SELECT oid FROM pg_database WHERE datname = current_database())) + AND EXISTS (SELECT 1 FROM unnest(s.setconfig) AS option + WHERE option LIKE 'session_replication_role=%' AND option <> 'session_replication_role=origin') + ) AS unsafe_defaults`, + [row.rolname], + ); + if (settings[0].replication_role !== 'origin' || settings[0].unsafe_defaults) + throw new Error('PostgreSQL integrity triggers must remain enabled'); + // Before PG15 only superusers can set this parameter; those were rejected above. + if (settings[0].version >= 150000) { + const { rows: privileges } = await client.query( + `SELECT + has_parameter_privilege($1::name, 'session_replication_role', 'SET') OR + has_parameter_privilege($1::name, 'session_replication_role', 'ALTER SYSTEM') AS unsafe`, + [row.rolname], + ); + if (privileges[0].unsafe) + throw new Error('PostgreSQL runtime role can disable integrity triggers'); + } + return row.rolname; +} + +export async function migratePostgres( + pool: Pool, + provision?: { tenant: string; runtimeRole: string }, +): Promise { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + // Transaction-scoped, cluster-local migration lock; failed DDL and ledger writes roll back together. + await client.query('SELECT pg_advisory_xact_lock(170141, 202601)'); + await client.query(` + CREATE SCHEMA IF NOT EXISTS eir; + REVOKE ALL ON SCHEMA eir FROM PUBLIC; + CREATE TABLE IF NOT EXISTS eir.schema_migrations ( + version integer PRIMARY KEY, name text NOT NULL, checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT now() + ); + ALTER TABLE eir.schema_migrations ENABLE ROW LEVEL SECURITY; + ALTER TABLE eir.schema_migrations FORCE ROW LEVEL SECURITY; + `); + const policies = await client.query( + "SELECT 1 FROM pg_policies WHERE schemaname = 'eir' AND tablename = 'schema_migrations' AND policyname = 'operator_access'", + ); + if (!policies.rowCount) + await client.query(` + CREATE POLICY operator_access ON eir.schema_migrations TO CURRENT_USER USING (true) WITH CHECK (true); + CREATE POLICY runtime_read ON eir.schema_migrations FOR SELECT USING (true); + REVOKE ALL ON eir.schema_migrations FROM PUBLIC; + `); + await checkPostgresMigrations(client, false); + const applied = await client.query('SELECT version FROM eir.schema_migrations'); + for (const migration of postgresMigrations.slice(applied.rowCount ?? 0)) { + await client.query(migration.sql); + await client.query( + 'INSERT INTO eir.schema_migrations (version, name, checksum) VALUES ($1, $2, $3)', + [migration.version, migration.name, migration.checksum], + ); + } + if (provision) { + if (!provision.tenant?.trim() || !provision.runtimeRole?.trim()) + throw new Error('Provisioning requires tenant and an existing restricted runtime role'); + await checkRuntimeRole(client, provision.runtimeRole); + const existing = await client.query( + 'SELECT tenant FROM eir.tenant_roles WHERE runtime_role = $1', + [provision.runtimeRole], + ); + if (existing.rowCount && existing.rows[0].tenant !== provision.tenant) + throw new Error('A PostgreSQL runtime role cannot be remapped to another tenant'); + await client.query( + 'INSERT INTO eir.tenant_roles (runtime_role, tenant) VALUES ($1, $2) ON CONFLICT DO NOTHING', + [provision.runtimeRole, provision.tenant], + ); + await client.query( + 'INSERT INTO eir.audit_heads (tenant) VALUES ($1) ON CONFLICT DO NOTHING', + [provision.tenant], + ); + const role = quoteIdentifier(provision.runtimeRole); + await client.query(` + GRANT USAGE ON SCHEMA eir TO ${role}; + GRANT SELECT ON ALL TABLES IN SCHEMA eir TO ${role}; + GRANT INSERT, UPDATE ON eir.entities, eir.grants, eir.restrictions TO ${role}; + GRANT INSERT, UPDATE, DELETE ON eir.sessions, eir.login_transactions TO ${role}; + GRANT INSERT ON eir.versions, eir.audit TO ${role}; + GRANT USAGE ON SEQUENCE eir.versions_cursor_seq TO ${role}; + `); + } + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + throw error; + } finally { + client.release(); + } +} diff --git a/packages/runtime.ts b/packages/runtime.ts index 3c88280..4202607 100644 --- a/packages/runtime.ts +++ b/packages/runtime.ts @@ -8,13 +8,13 @@ const serviceName = z.string().regex(/^[a-zA-Z][a-zA-Z0-9.]*$/); const manifest = z.object({ id: z.string().regex(/^[a-z][a-z0-9.-]+$/), version: z.string().regex(/^\d+\.\d+\.\d+$/), - apiVersion: z.literal(1), + apiVersion: z.literal(2), provides: z.array(serviceName).min(1), requires: z.array(serviceName), }); export class Runtime { private services = new Map(); - private disposers: (() => void)[] = []; + private disposers: (() => void | Promise)[] = []; readonly active: { id: string; version: string; provides: string[]; requires: string[] }[] = []; has(name: ServiceName) { return this.services.has(name); @@ -74,15 +74,15 @@ export class Runtime { } return this; } catch (error) { - this.stop(); + await this.stop(); throw error; } } - stop() { + async stop() { const errors: unknown[] = []; for (const dispose of this.disposers.reverse()) { try { - dispose(); + await dispose(); } catch (e) { errors.push(e); } diff --git a/packages/staff-sessions.ts b/packages/staff-sessions.ts index c7b7d31..54c4f96 100644 --- a/packages/staff-sessions.ts +++ b/packages/staff-sessions.ts @@ -13,52 +13,74 @@ export function staffSessions( workforce: Workforce, options: { idleMinutes: number; absoluteHours: number }, ) { - const identity: Identity = { - issue(actor) { - workforce.current(actor); - const token = randomBytes(32).toString('base64url'); - store.saveSession( - tokenHash(token), - actor, - new Date(Date.now() + options.absoluteHours * 3600000).toISOString(), + // Return failures from the unit of work so revocation and its audit commit before rejection. + const authenticateSession = async (token: string): Promise => { + assert(/^[A-Za-z0-9_-]{43}$/.test(token), 401, 'Authentication required'); + const hash = tokenHash(token); + const session = await store.session(hash); + if ( + !session || + Date.parse(session.expires) <= Date.now() || + Date.parse(session.lastSeen) + options.idleMinutes * 60000 <= Date.now() + ) { + await store.revokeSession(hash); + return new Fault(401, 'Session expired'); + } + try { + await workforce.current(session.actor); + } catch { + await store.revokeSession(hash); + await store.audit( + session.actor, + 'session.assignment-revoked', + undefined, + undefined, + 'denied', ); - store.audit(actor, 'session.started'); - return token; + return new Fault(401, 'Staff assignment has expired or been revoked'); + } + await store.updateSession(hash, session.actor); + return session.actor; + }; + const identity: Identity = { + async issue(actor) { + return store.transaction(async () => { + await workforce.current(actor); + const token = randomBytes(32).toString('base64url'); + await store.saveSession( + tokenHash(token), + actor, + new Date(Date.now() + options.absoluteHours * 3600000).toISOString(), + ); + await store.audit(actor, 'session.started'); + return token; + }); }, async authenticate(token) { - assert(/^[A-Za-z0-9_-]{43}$/.test(token), 401, 'Authentication required'); - const session = store.session(tokenHash(token)); - if ( - !session || - Date.parse(session.expires) <= Date.now() || - Date.parse(session.lastSeen) + options.idleMinutes * 60000 <= Date.now() - ) { - store.revokeSession(tokenHash(token)); - throw new Fault(401, 'Session expired'); - } - try { - workforce.current(session.actor); - } catch { - store.revokeSession(tokenHash(token)); - store.audit(session.actor, 'session.assignment-revoked', undefined, undefined, 'denied'); - throw new Fault(401, 'Staff assignment has expired or been revoked'); - } - store.updateSession(tokenHash(token), session.actor); - return session.actor; + const result = await store.transaction(async () => authenticateSession(token)); + if (result instanceof Fault) throw result; + return result; }, async select(token, assignmentId) { - const actor = await identity.authenticate(token); - const assignment = workforce.assignments(actor).find((a) => a.id === assignmentId); - assert(assignment, 403, 'Assignment is unavailable'); - const selected = workforce.actor(assignment, actor.authentication); - store.updateSession(tokenHash(token), selected); - store.audit(selected, 'session.assignment-selected'); - return selected; + const result = await store.transaction(async () => { + const actor = await authenticateSession(token); + if (actor instanceof Fault) return actor; + const assignment = (await workforce.assignments(actor)).find((a) => a.id === assignmentId); + assert(assignment, 403, 'Assignment is unavailable'); + const selected = workforce.actor(assignment, actor.authentication); + await store.updateSession(tokenHash(token), selected); + await store.audit(selected, 'session.assignment-selected'); + return selected; + }); + if (result instanceof Fault) throw result; + return result; }, - revoke(token) { - const session = store.session(tokenHash(token)); - if (session) store.audit(session.actor, 'session.ended'); - store.revokeSession(tokenHash(token)); + async revoke(token) { + await store.transaction(async () => { + const session = await store.session(tokenHash(token)); + if (session) await store.audit(session.actor, 'session.ended'); + await store.revokeSession(tokenHash(token)); + }); }, }; return identity; diff --git a/plugins/access-clinic.ts b/plugins/access-clinic.ts index c610132..b5635f1 100644 --- a/plugins/access-clinic.ts +++ b/plugins/access-clinic.ts @@ -4,27 +4,28 @@ import { type Actor, type Permission, type Plugin, + type TeamMember, } from '../packages/contracts.ts'; export default { id: 'eir.access.clinic', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['access'], requires: ['store', 'workforce'], setup(ctx) { const store = ctx.get('store'), workforce = ctx.get('workforce'); - const decision = (actor: Actor, action: Permission, patientId?: string) => { + const decision = async (actor: Actor, action: Permission, patientId?: string) => { try { - const assignment = workforce.current(actor); + const assignment = await workforce.current(actor); if (!assignment.data.permissions.includes(action)) return false; if (!patientId) return true; - const patient = store.get(actor.tenant, patientId); + const patient = await store.get(actor.tenant, patientId); if ( patient?.kind !== 'patient' || patient.data.careUnitId !== actor.unitId || - store.isBlocked(actor.tenant, patientId) + (await store.isBlocked(actor.tenant, patientId)) ) return false; if ( @@ -32,48 +33,46 @@ export default { !assignment.data.permissions.includes('patient.protected') ) return false; - const grant = store.getGrant(actor.tenant, patientId, actor.id); + const grant = await store.getGrant(actor.tenant, patientId, actor.id); if ( grant?.role === 'clinician' && grant.expires > new Date().toISOString() && - store - .list(actor.tenant, patientId, 'careRelationship') - .some( - (r) => - r.data.target === actor.id && - r.data.assignmentId === assignment.id && - r.data.expires > new Date().toISOString(), - ) + (await store.list(actor.tenant, patientId, 'careRelationship')).some( + (r) => + r.data.target === actor.id && + r.data.assignmentId === assignment.id && + r.data.expires > new Date().toISOString(), + ) ) return true; // Exceptional access is read-only, unit-scoped and never overrides a restriction. return ( action === 'chart.read' && - store - .list(actor.tenant, patientId, 'emergencyAccess') - .some( - (r) => - r.data.assignmentId === assignment.id && r.data.expires > new Date().toISOString(), - ) + (await store.list(actor.tenant, patientId, 'emergencyAccess')).some( + (r) => + r.data.assignmentId === assignment.id && r.data.expires > new Date().toISOString(), + ) ); } catch { return false; } }; const access: Access = { - context(actor, patientId) { - const row = workforce.current(actor); + async context(actor, patientId) { + const row = await workforce.current(actor); + const permissions: Permission[] = []; + for (const permission of row.data.permissions) + if (!patientId || (await decision(actor, permission, patientId))) + permissions.push(permission); return { - permissions: patientId - ? row.data.permissions.filter((p: Permission) => decision(actor, p, patientId)) - : row.data.permissions, + permissions, unitId: row.data.unitId, name: row.data.name, }; }, - permit(actor, action, patientId) { - const allowed = decision(actor, action, patientId); - store.audit( + async permit(actor, action, patientId) { + const allowed = await decision(actor, action, patientId); + await store.audit( actor, `permission.${action}`, patientId, @@ -82,84 +81,80 @@ export default { ); assert(allowed, 403, 'Permission or care relationship is missing for the selected unit'); }, - allowed(actor, patientId, write = false) { + async allowed(actor, patientId, write = false) { return decision(actor, write ? 'record.write' : 'chart.read', patientId); }, - check(actor, patientId, write = false) { - access.permit(actor, write ? 'record.write' : 'chart.read', patientId); + async check(actor, patientId, write = false) { + await access.permit(actor, write ? 'record.write' : 'chart.read', patientId); }, - members(actor) { - workforce.current(actor); - const assignments = store.list(actor.tenant, undefined, 'staffAssignment'); - return assignments - .filter( - (r) => - r.data.role === 'clinician' && - r.data.unitId === actor.unitId && - (() => { - try { - workforce.current(workforce.actor(r)); - return true; - } catch { - return false; - } - })(), - ) - .map((r) => ({ + async members(actor) { + await workforce.current(actor); + const assignments = await store.list(actor.tenant, undefined, 'staffAssignment'); + const members: TeamMember[] = []; + for (const r of assignments) { + if (r.data.role !== 'clinician' || r.data.unitId !== actor.unitId) continue; + try { + await workforce.current(workforce.actor(r)); + } catch { + continue; + } + members.push({ id: r.data.actorId, tenant: r.tenant, name: r.data.name, profession: 'Vårdpersonal', - })) - .sort((a, b) => - a.id === actor.id ? -1 : b.id === actor.id ? 1 : a.name.localeCompare(b.name), - ); + }); + } + return members.sort((a, b) => + a.id === actor.id ? -1 : b.id === actor.id ? 1 : a.name.localeCompare(b.name), + ); }, - eligible(actor, targetId, patientId, action) { - workforce.current(actor); - return store - .list(actor.tenant, undefined, 'staffAssignment') - .some( - (row) => - row.data.actorId === targetId && - row.data.unitId === actor.unitId && - decision(workforce.actor(row), action, patientId), - ); + async eligible(actor, targetId, patientId, action) { + await workforce.current(actor); + for (const row of await store.list(actor.tenant, undefined, 'staffAssignment')) + if ( + row.data.actorId === targetId && + row.data.unitId === actor.unitId && + (await decision(workforce.actor(row), action, patientId)) + ) + return true; + return false; }, - grant(actor, patientId, target, role, expires, reason) { - access.permit(actor, 'access.manage', patientId); - assert( - role === 'clinician' && target !== actor.id, - 403, - 'Verified staff assignment required; self-grants and proxy delegation are not supported', - ); - assert( - typeof reason === 'string' && reason.trim().length > 0 && reason.length <= 200, - 422, - 'Reason for care relationship required', - ); - const expiration = new Date(expires).toISOString(); - const targetAssignment = store - .list(actor.tenant, undefined, 'staffAssignment') - .find( + async grant(actor, patientId, target, role, expires, reason) { + await access.permit(actor, 'access.manage', patientId); + await store.transaction(async () => { + await access.permit(actor, 'access.manage', patientId); + assert( + role === 'clinician' && target !== actor.id, + 403, + 'Verified staff assignment required; self-grants and proxy delegation are not supported', + ); + assert( + typeof reason === 'string' && reason.trim().length > 0 && reason.length <= 200, + 422, + 'Reason for care relationship required', + ); + const expiration = new Date(expires).toISOString(); + const targetAssignment = ( + await store.list(actor.tenant, undefined, 'staffAssignment') + ).find( (r) => r.data.actorId === target && r.data.role === 'clinician' && r.data.unitId === actor.unitId, ); - assert(targetAssignment, 403, 'No staff assignment in this unit'); - workforce.current(workforce.actor(targetAssignment)); - assert( - expiration > new Date().toISOString() && - expiration <= targetAssignment.data.validUntil && - Date.parse(expiration) <= Date.now() + 30 * 86400000, - 422, - 'Care relationship must expire within assignment validity and 30 days', - ); - store.transaction(() => { - store.grant(actor.tenant, patientId, target, role, expiration); - store.audit(actor, 'access.grant', patientId, target); - store.insert(actor, 'careRelationship', patientId, { + assert(targetAssignment, 403, 'No staff assignment in this unit'); + await workforce.current(workforce.actor(targetAssignment)); + assert( + expiration > new Date().toISOString() && + expiration <= targetAssignment.data.validUntil && + Date.parse(expiration) <= Date.now() + 30 * 86400000, + 422, + 'Care relationship must expire within assignment validity and 30 days', + ); + await store.grant(actor.tenant, patientId, target, role, expiration); + await store.audit(actor, 'access.grant', patientId, target); + await store.insert(actor, 'careRelationship', patientId, { target, assignmentId: targetAssignment.id, reason: reason.trim(), @@ -167,7 +162,7 @@ export default { }); }); }, - block() { + async block() { assert( false, 403, diff --git a/plugins/access-review.ts b/plugins/access-review.ts index c365c4e..3d503e8 100644 --- a/plugins/access-review.ts +++ b/plugins/access-review.ts @@ -9,91 +9,96 @@ import { export default { id: 'eir.access-review', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['accessReview'], requires: ['store', 'access', 'workforce'], setup(ctx) { const store = ctx.get('store'), access = ctx.get('access'); ctx.provide('accessReview', { - list(actor, input) { - access.permit(actor, 'audit.review'); + async list(actor, input) { + await access.permit(actor, 'audit.review'); const query = auditQuery.parse(input); - const entries = store.auditPage(actor.tenant, { + const entries = await store.auditPage(actor.tenant, { ...query, unitId: actor.unitId!, limit: query.limit + 1, }); const more = entries.length > query.limit; const page = entries.slice(0, query.limit); - const reviews = store.list(actor.tenant, undefined, 'accessReview'); - store.audit(actor, 'audit.page-read'); + const reviews = await store.list(actor.tenant, undefined, 'accessReview'); + await store.audit(actor, 'audit.page-read'); return { entries: page.map((entry) => ({ ...entry, reviews: reviews.filter((r) => r.data.seq === entry.seq && r.data.hash === entry.hash), })), nextBefore: more ? page.at(-1)!.seq : null, - verification: { ok: store.verifyAudit().ok }, + verification: { ok: (await store.verifyAudit()).ok }, }; }, - review(actor, input) { - access.permit(actor, 'audit.review'); - const parsed = auditReviewInput.parse(input); - const entry = store.auditEntry(actor.tenant, parsed.seq); - assert( - entry && - entry.unitId === actor.unitId && - entry.hash === parsed.hash && - entry.actor !== actor.id, - 403, - 'Cannot review this event or your own access', - ); - return store.transaction(() => - store.insert(actor, 'accessReview', null, { + async review(actor, input) { + await access.permit(actor, 'audit.review'); + return store.transaction(async () => { + await access.permit(actor, 'audit.review'); + const parsed = auditReviewInput.parse(input); + const entry = await store.auditEntry(actor.tenant, parsed.seq); + assert( + entry && + entry.unitId === actor.unitId && + entry.hash === parsed.hash && + entry.actor !== actor.id, + 403, + 'Cannot review this event or your own access', + ); + return store.insert(actor, 'accessReview', null, { ...parsed, reviewer: actor.id, unitId: actor.unitId, - }), - ); + }); + }); }, - emergency(actor, patientId, input) { - access.permit(actor, 'access.emergency'); - access.permit(actor, 'chart.read'); - const parsed = reasonInput.parse(input); - const patient = store.get(actor.tenant, patientId); - assert( - patient?.kind === 'patient' && - patient.data.careUnitId === actor.unitId && - !store.isBlocked(actor.tenant, patientId), - 403, - 'Exceptional access is unavailable for this patient', - ); - if (patient.data.protectedIdentity) access.permit(actor, 'patient.protected'); - return store.transaction(() => { - const grant = store.insert(actor, 'emergencyAccess', patientId, { + async emergency(actor, patientId, input) { + await access.permit(actor, 'access.emergency'); + await access.permit(actor, 'chart.read'); + return store.transaction(async () => { + await access.permit(actor, 'access.emergency'); + await access.permit(actor, 'chart.read'); + const parsed = reasonInput.parse(input); + const patient = await store.get(actor.tenant, patientId); + assert( + patient?.kind === 'patient' && + patient.data.careUnitId === actor.unitId && + !(await store.isBlocked(actor.tenant, patientId)), + 403, + 'Exceptional access is unavailable for this patient', + ); + if (patient.data.protectedIdentity) await access.permit(actor, 'patient.protected'); + const grant = await store.insert(actor, 'emergencyAccess', patientId, { ...parsed, assignmentId: actor.assignmentId, expires: new Date(Date.now() + 15 * 60000).toISOString(), }); - store.audit(actor, 'access.emergency-opened', patientId, grant.id); + await store.audit(actor, 'access.emergency-opened', patientId, grant.id); return grant; }); }, - protect(actor, patientId, version, input) { - access.permit(actor, 'access.manage', patientId); - access.permit(actor, 'patient.protected'); - const parsed = protectionInput.parse(input); - const patient = store.get(actor.tenant, patientId)!; - return store.transaction(() => { - const updated = store.revise( + async protect(actor, patientId, version, input) { + await access.permit(actor, 'access.manage', patientId); + await access.permit(actor, 'patient.protected'); + return store.transaction(async () => { + await access.permit(actor, 'access.manage', patientId); + await access.permit(actor, 'patient.protected'); + const parsed = protectionInput.parse(input); + const patient = (await store.get(actor.tenant, patientId))!; + const updated = await store.revise( actor, patient, version, { ...patient.data, protectedIdentity: parsed.protected }, 'patient.protection-changed', ); - store.insert(actor, 'protectionChange', patientId, parsed); + await store.insert(actor, 'protectionChange', patientId, parsed); return updated; }); }, diff --git a/plugins/access.ts b/plugins/access.ts index 87374cf..5e9bd41 100644 --- a/plugins/access.ts +++ b/plugins/access.ts @@ -2,13 +2,13 @@ import { Fault, type Plugin, type Access } from '../packages/contracts.ts'; export default { id: 'eir.access', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['access'], requires: ['store'], setup(ctx) { const store = ctx.get('store'); const access: Access = { - permit(actor, action, patientId) { + async permit(actor, action, patientId) { if (patientId) return access.check( actor, @@ -17,10 +17,10 @@ export default { ); if (actor.role !== 'clinician') throw new Fault(403, 'Clinician role required'); }, - allowed(actor: Parameters[0], patientId: string, write = false) { - const patient = store.get(actor.tenant, patientId); - const grant = store.getGrant(actor.tenant, patientId, actor.id); - const blocked = store.isBlocked(actor.tenant, patientId); + async allowed(actor: Parameters[0], patientId: string, write = false) { + const patient = await store.get(actor.tenant, patientId); + const grant = await store.getGrant(actor.tenant, patientId, actor.id); + const blocked = await store.isBlocked(actor.tenant, patientId); const self = actor.role === 'patient' && actor.patientId === patientId; const assigned = grant && grant.role === actor.role && String(grant.expires) > new Date().toISOString(); @@ -32,9 +32,9 @@ export default { (actor.role === 'clinician' || (actor.role === 'proxy' && !write)))), ); }, - check(actor: Parameters[0], patientId: string, write = false) { - const allowed = access.allowed(actor, patientId, write); - store.audit( + async check(actor: Parameters[0], patientId: string, write = false) { + const allowed = await access.allowed(actor, patientId, write); + await store.audit( actor, write ? 'access.write' : 'access.read', patientId, @@ -44,33 +44,38 @@ export default { if (!allowed) throw new Fault(403, 'No active care relationship or permitted patient/proxy access'); }, - grant( + async grant( actor: Parameters[0], patientId: string, target: string, role: 'clinician' | 'proxy', expires: string, ) { - access.check(actor, patientId, true); - if (actor.role !== 'clinician') throw new Fault(403, 'Clinician role required'); - const expiration = new Date(expires).toISOString(); - if (expiration <= new Date().toISOString()) - throw new Fault(422, 'Grant must expire in the future'); - store.transaction(() => { - store.grant(actor.tenant, patientId, target, role, expiration); - store.audit(actor, 'access.grant', patientId, target); + await access.check(actor, patientId, true); + await store.transaction(async () => { + await access.check(actor, patientId, true); + if (actor.role !== 'clinician') throw new Fault(403, 'Clinician role required'); + const expiration = new Date(expires).toISOString(); + if (expiration <= new Date().toISOString()) + throw new Fault(422, 'Grant must expire in the future'); + await store.grant(actor.tenant, patientId, target, role, expiration); + await store.audit(actor, 'access.grant', patientId, target); }); }, - block(actor: Parameters[0], patientId: string, blocked: boolean) { - if ( - actor.role !== 'patient' || - actor.patientId !== patientId || - store.get(actor.tenant, patientId)?.kind !== 'patient' - ) - throw new Fault(403, 'Patient self-service required'); - store.transaction(() => { - store.restrict(actor.tenant, patientId, blocked); - store.audit(actor, blocked ? 'restriction.applied' : 'restriction.removed', patientId); + async block(actor: Parameters[0], patientId: string, blocked: boolean) { + await store.transaction(async () => { + if ( + actor.role !== 'patient' || + actor.patientId !== patientId || + (await store.get(actor.tenant, patientId))?.kind !== 'patient' + ) + throw new Fault(403, 'Patient self-service required'); + await store.restrict(actor.tenant, patientId, blocked); + await store.audit( + actor, + blocked ? 'restriction.applied' : 'restriction.removed', + patientId, + ); }); }, }; diff --git a/plugins/ai-extractive.ts b/plugins/ai-extractive.ts index 64dc640..ef585ce 100644 --- a/plugins/ai-extractive.ts +++ b/plugins/ai-extractive.ts @@ -2,7 +2,7 @@ import type { Plugin } from '../packages/contracts.ts'; export default { id: 'eir.ai.extractive', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['aiProvider'], requires: [], setup(ctx) { diff --git a/plugins/ai-ollama.ts b/plugins/ai-ollama.ts index 5da4e96..6ca0738 100644 --- a/plugins/ai-ollama.ts +++ b/plugins/ai-ollama.ts @@ -12,7 +12,7 @@ const output = z export default { id: 'eir.ai.ollama', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['aiProvider'], requires: [], setup(ctx, config) { diff --git a/plugins/ai-review.ts b/plugins/ai-review.ts index 74f50ae..ef09dcb 100644 --- a/plugins/ai-review.ts +++ b/plugins/ai-review.ts @@ -58,7 +58,7 @@ const outputSchema = z export default { id: 'eir.ai.review', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['aiReview'], requires: ['store', 'access', 'clinical', 'aiProvider'], setup(ctx) { @@ -68,22 +68,26 @@ export default { provider = ctx.get('aiProvider'); ctx.provide('aiReview', { async propose(actor, patientId, encounterId) { - access.permit(actor, 'ai.use', patientId); - const encounter = store.get(actor.tenant, encounterId); - assert( - encounter?.kind === 'encounter' && - encounter.patientId === patientId && - encounter.data.status === 'in-progress', - 409, - 'Open encounter required', - ); - const evidence = evidenceFor(clinical.chart(actor, patientId), encounterId); - assert( - JSON.stringify(evidence).length < 60000, - 422, - 'Evidence exceeds model context limit', - ); - store.audit(actor, 'ai.requested', patientId, encounterId); + await access.permit(actor, 'ai.use', patientId); + const evidence = await store.transaction(async () => { + await access.permit(actor, 'ai.use', patientId); + const encounter = await store.get(actor.tenant, encounterId); + assert( + encounter?.kind === 'encounter' && + encounter.patientId === patientId && + encounter.data.status === 'in-progress', + 409, + 'Open encounter required', + ); + const evidence = evidenceFor(await clinical.chart(actor, patientId), encounterId); + assert( + JSON.stringify(evidence).length < 60000, + 422, + 'Evidence exceeds model context limit', + ); + await store.audit(actor, 'ai.requested', patientId, encounterId); + return evidence; + }); const output = outputSchema.parse(await provider.generate(structuredClone(evidence))); assert( output.citations.every((c) => @@ -92,36 +96,55 @@ export default { 422, 'AI returned an invalid source reference or quotation', ); - access.permit(actor, 'ai.use', patientId); - return store.transaction(() => - store.insert(actor, 'proposal', patientId, { + await access.permit(actor, 'ai.use', patientId); + return await store.transaction(async () => { + await access.permit(actor, 'ai.use', patientId); + const encounter = await store.get(actor.tenant, encounterId); + assert( + encounter?.kind === 'encounter' && + encounter.patientId === patientId && + encounter.data.status === 'in-progress', + 409, + 'Open encounter required', + ); + const current = evidenceFor(await clinical.chart(actor, patientId), encounterId); + assert( + JSON.stringify(current) === JSON.stringify(evidence), + 409, + 'Clinical context changed; regenerate the proposal', + ); + return await store.insert(actor, 'proposal', patientId, { ...output, evidence, encounterId, provider: provider.id, status: 'pending', requestedBy: actor.id, - }), - ); + }); + }); }, - review(actor, id, version, decision, text) { - const proposal = store.get(actor.tenant, id); + async review(actor, id, version, decision, text) { + const proposal = await store.get(actor.tenant, id); assert(proposal?.kind === 'proposal', 404, 'Proposal not found'); - access.permit(actor, 'ai.use', proposal.patientId); - if (decision === 'accept') access.permit(actor, 'record.write', proposal.patientId); - assert( - proposal.version === version && proposal.data.status === 'pending', - 409, - 'Proposal already reviewed or changed', - ); + await access.permit(actor, 'ai.use', proposal.patientId); + if (decision === 'accept') await access.permit(actor, 'record.write', proposal.patientId); assert(['accept', 'reject'].includes(decision), 422, 'Invalid review decision'); - return store.transaction(() => { + return await store.transaction(async () => { + const proposal = await store.get(actor.tenant, id); + assert(proposal?.kind === 'proposal', 404, 'Proposal not found'); + await access.permit(actor, 'ai.use', proposal.patientId); + if (decision === 'accept') await access.permit(actor, 'record.write', proposal.patientId); + assert( + proposal.version === version && proposal.data.status === 'pending', + 409, + 'Proposal already reviewed or changed', + ); let note: Entity | undefined; if (decision === 'accept') { - const encounter = store.get(actor.tenant, proposal.data.encounterId); + const encounter = await store.get(actor.tenant, proposal.data.encounterId); assert(encounter?.data.status === 'in-progress', 409, 'Encounter closed'); const current = evidenceFor( - store.list(actor.tenant, proposal.patientId), + await store.list(actor.tenant, proposal.patientId), proposal.data.encounterId, ); assert( @@ -135,7 +158,7 @@ export default { .min(1) .max(20000) .parse(text ?? proposal.data.text); - note = store.insert(actor, 'note', proposal.patientId, { + note = await store.insert(actor, 'note', proposal.patientId, { text: reviewedText, encounterId: proposal.data.encounterId, status: 'draft', @@ -143,7 +166,7 @@ export default { proposalId: proposal.id, }); } - return store.revise( + return await store.revise( actor, proposal, version, diff --git a/plugins/care-team.ts b/plugins/care-team.ts index 9148ff0..b7cc901 100644 --- a/plugins/care-team.ts +++ b/plugins/care-team.ts @@ -20,7 +20,7 @@ const activeBooking = (r: Entity) => ['booked', 'arrived', 'in-progress'].includ export default { id: 'eir.care-team', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['careTeam'], requires: ['store', 'access'], setup(ctx, config) { @@ -41,9 +41,9 @@ export default { ); const clinician = (actor: Actor) => assert(actor.role === 'clinician', 403, 'Clinician role required'); - const members = (actor: Actor) => { + const members = async (actor: Actor) => { clinician(actor); - if (access.members) return access.members(actor); + if (access.members) return await access.members(actor); const rows = settings.members.filter((m) => m.tenant === actor.tenant); return rows.some((m) => m.id === actor.id) ? rows @@ -52,36 +52,40 @@ export default { ...rows, ]; }; - const assignee = ( + const assignee = async ( actor: Actor, patientId: string, id: string, permission: Permission = 'task.write', ) => { assert( - members(actor).some((m) => m.id === id), + (await members(actor)).some((m) => m.id === id), 422, 'Unknown team member', ); assert( access.eligible - ? access.eligible(actor, id, patientId, permission) - : access.allowed({ ...actor, id }, patientId, true), + ? await access.eligible(actor, id, patientId, permission) + : await access.allowed({ ...actor, id }, patientId, true), 403, 'The selected team member has no active care relationship', ); }; - const current = (actor: Actor, id: string, kind: string, version: number) => { + const current = async (actor: Actor, id: string, kind: string, version: number) => { clinician(actor); - const row = store.get(actor.tenant, id); + const row = await store.get(actor.tenant, id); assert(row?.kind === kind, 404, 'Record not found'); - access.permit(actor, kind === 'appointment' ? 'schedule.write' : 'task.write', row.patientId); + await access.permit( + actor, + kind === 'appointment' ? 'schedule.write' : 'task.write', + row.patientId, + ); assert(row.version === version, 409, 'Record changed. Reload before saving.'); return row; }; - const slot = (actor: Actor, patientId: string, input: unknown, except?: string) => { + const slot = async (actor: Actor, patientId: string, input: unknown, except?: string) => { const parsed = bookingInput.parse(input); - assignee(actor, patientId, parsed.practitionerId, 'record.write'); + await assignee(actor, patientId, parsed.practitionerId, 'record.write'); let startsAt: string, endsAt: string; try { const start = Temporal.PlainDateTime.from(parsed.localStart).toZonedDateTime( @@ -94,16 +98,14 @@ export default { throw new Fault(422, 'Invalid or ambiguous clinic time. Choose another time.'); } assert( - !store - .list(actor.tenant, undefined, 'appointment') - .some( - (r) => - r.id !== except && - activeBooking(r) && - (r.patientId === patientId || r.data.practitionerId === parsed.practitionerId) && - Date.parse(r.data.startsAt) < Date.parse(endsAt) && - Date.parse(r.data.endsAt) > Date.parse(startsAt), - ), + !(await store.list(actor.tenant, undefined, 'appointment')).some( + (r) => + r.id !== except && + activeBooking(r) && + (r.patientId === patientId || r.data.practitionerId === parsed.practitionerId) && + Date.parse(r.data.startsAt) < Date.parse(endsAt) && + Date.parse(r.data.endsAt) > Date.parse(startsAt), + ), 409, 'The patient or clinician already has an overlapping appointment', ); @@ -112,53 +114,53 @@ export default { const service: CareTeam = { timeZone: settings.timeZone, members, - workspace(actor, day) { + async workspace(actor, day) { clinician(actor); z.iso.date().parse(day); const start = Temporal.PlainDate.from(day).toZonedDateTime(settings.timeZone); const end = start.add({ days: 1 }); - const visible = new Set( - store - .list(actor.tenant, undefined, 'patient') - .filter((p) => access.allowed(actor, p.id)) - .map((p) => p.id), - ); - const appointments = store - .list(actor.tenant, undefined, 'appointment') - .filter( - (r) => - visible.has(r.patientId) && - Date.parse(r.data.startsAt) < end.epochMilliseconds && - Date.parse(r.data.endsAt) > start.epochMilliseconds, - ) - .sort((a, b) => a.data.startsAt.localeCompare(b.data.startsAt)); - const tasks = store - .list(actor.tenant, undefined, 'task') - .filter((r) => visible.has(r.patientId)) - .sort((a, b) => a.data.due.localeCompare(b.data.due) || a.id.localeCompare(b.id)); - for (const id of new Set([...appointments, ...tasks].map((r) => r.patientId))) - access.check(actor, id); - store.audit(actor, 'care-team.workspace'); - return { appointments, tasks }; + return await store.transaction(async () => { + const visible = new Set(); + for (const patient of await store.list(actor.tenant, undefined, 'patient')) { + if (await access.allowed(actor, patient.id)) visible.add(patient.id); + } + const appointments = (await store.list(actor.tenant, undefined, 'appointment')) + .filter( + (r) => + visible.has(r.patientId) && + Date.parse(r.data.startsAt) < end.epochMilliseconds && + Date.parse(r.data.endsAt) > start.epochMilliseconds, + ) + .sort((a, b) => a.data.startsAt.localeCompare(b.data.startsAt)); + const tasks = (await store.list(actor.tenant, undefined, 'task')) + .filter((r) => visible.has(r.patientId)) + .sort((a, b) => a.data.due.localeCompare(b.data.due) || a.id.localeCompare(b.id)); + for (const id of new Set([...appointments, ...tasks].map((r) => r.patientId))) + await access.check(actor, id); + await store.audit(actor, 'care-team.workspace'); + return { appointments, tasks }; + }); }, - book(actor, patientId, input) { + async book(actor, patientId, input) { clinician(actor); - access.permit(actor, 'schedule.write', patientId); - return store.transaction(() => - store.insert(actor, 'appointment', patientId, { - ...slot(actor, patientId, input), + await access.permit(actor, 'schedule.write', patientId); + return await store.transaction(async () => { + await access.permit(actor, 'schedule.write', patientId); + return await store.insert(actor, 'appointment', patientId, { + ...(await slot(actor, patientId, input)), status: 'booked', author: actor.id, - }), - ); + }); + }); }, - appointment(actor, id, action, version, input) { - const row = current(actor, id, 'appointment', version); - return store.transaction(() => { + async appointment(actor, id, action, version, input) { + await current(actor, id, 'appointment', version); + return await store.transaction(async () => { + const row = await current(actor, id, 'appointment', version); let data = { ...row.data }; if (action === 'reschedule') { assert(data.status === 'booked', 409, 'Only a booked appointment can be rescheduled'); - data = { ...data, ...slot(actor, row.patientId, input, id) }; + data = { ...data, ...(await slot(actor, row.patientId, input, id)) }; } else if (action === 'cancel' || action === 'no-show') { const parsed = reason.parse(input); assert( @@ -183,7 +185,7 @@ export default { assert(data.status === 'booked', 409, 'Appointment is not booked'); data = { ...data, status: 'arrived', arrivedAt: new Date().toISOString() }; } else if (action === 'start') { - access.permit(actor, 'record.write', row.patientId); + await access.permit(actor, 'record.write', row.patientId); empty.parse(input); assert( ['booked', 'arrived'].includes(data.status), @@ -195,20 +197,18 @@ export default { 403, 'Only the booked clinician can start this appointment', ); - let encounter = store - .list(actor.tenant, row.patientId, 'encounter') - .find((r) => r.data.status === 'in-progress'); + let encounter = (await store.list(actor.tenant, row.patientId, 'encounter')).find( + (r) => r.data.status === 'in-progress', + ); assert( !encounter || - !store - .list(actor.tenant, row.patientId, 'appointment') - .some( - (r) => r.data.status === 'in-progress' && r.data.encounterId === encounter!.id, - ), + !(await store.list(actor.tenant, row.patientId, 'appointment')).some( + (r) => r.data.status === 'in-progress' && r.data.encounterId === encounter!.id, + ), 409, 'The current encounter is already linked to another appointment', ); - encounter ??= store.insert(actor, 'encounter', row.patientId, { + encounter ??= await store.insert(actor, 'encounter', row.patientId, { reason: data.reason, status: 'in-progress', author: actor.id, @@ -220,20 +220,20 @@ export default { startedAt: new Date().toISOString(), }; } else throw new Fault(422, 'Unsupported appointment action'); - return store.revise(actor, row, version, data, `appointment.${action}`); + return await store.revise(actor, row, version, data, `appointment.${action}`); }); }, - encounterClosed(actor, encounterId) { - const encounter = store.get(actor.tenant, encounterId); + async encounterClosed(actor, encounterId) { + const encounter = await store.get(actor.tenant, encounterId); assert( encounter?.kind === 'encounter' && encounter.data.status === 'finished', 409, 'Encounter is not finished', ); - access.permit(actor, 'record.write', encounter.patientId); - for (const row of store.list(actor.tenant, encounter.patientId, 'appointment')) { + await access.permit(actor, 'record.write', encounter.patientId); + for (const row of await store.list(actor.tenant, encounter.patientId, 'appointment')) { if (row.data.encounterId === encounterId && row.data.status === 'in-progress') { - store.revise( + await store.revise( actor, row, row.version, @@ -243,41 +243,42 @@ export default { } } }, - createTask(actor, patientId, input) { + async createTask(actor, patientId, input) { clinician(actor); - access.permit(actor, 'task.write', patientId); + await access.permit(actor, 'task.write', patientId); const parsed = taskInput.parse(input); const assigneeId = parsed.assigneeId ?? actor.id; - assignee(actor, patientId, assigneeId); - return store.transaction(() => - store.insert(actor, 'task', patientId, { + return await store.transaction(async () => { + await access.permit(actor, 'task.write', patientId); + await assignee(actor, patientId, assigneeId); + return await store.insert(actor, 'task', patientId, { ...parsed, assigneeId, status: 'requested', author: actor.id, - }), - ); + }); + }); }, - createLinkedTask(actor, patientId, input, orderId) { + async createLinkedTask(actor, patientId, input, orderId) { clinician(actor); - access.permit(actor, 'lab.order', patientId); + await access.permit(actor, 'lab.order', patientId); const parsed = taskInput.parse(input); const assigneeId = parsed.assigneeId ?? actor.id; - assignee(actor, patientId, assigneeId, 'lab.review'); - const order = store.get(actor.tenant, orderId); + await assignee(actor, patientId, assigneeId, 'lab.review'); + const order = await store.get(actor.tenant, orderId); assert( order?.kind === 'labOrder' && order.patientId === patientId, 409, 'Invalid linked order', ); assert( - !store - .list(actor.tenant, patientId, 'task') - .some((r) => r.data.linkedOrderId === orderId), + !(await store.list(actor.tenant, patientId, 'task')).some( + (r) => r.data.linkedOrderId === orderId, + ), 409, 'Order already has follow-up', ); - return store.insert(actor, 'task', patientId, { + return await store.insert(actor, 'task', patientId, { ...parsed, assigneeId, linkedOrderId: orderId, @@ -285,18 +286,18 @@ export default { author: actor.id, }); }, - syncLinkedTask(actor, order, event, resolution) { + async syncLinkedTask(actor, order, event, resolution) { clinician(actor); - access.permit( + await access.permit( actor, event === 'result' ? 'lab.receive' : event === 'review' ? 'lab.review' : 'lab.order', order.patientId, ); - const saved = store.get(actor.tenant, order.id); + const saved = await store.get(actor.tenant, order.id); assert(saved?.kind === 'labOrder' && saved.version === order.version, 409, 'Order changed'); - const row = store - .list(actor.tenant, order.patientId, 'task') - .find((r) => r.data.linkedOrderId === order.id); + const row = (await store.list(actor.tenant, order.patientId, 'task')).find( + (r) => r.data.linkedOrderId === order.id, + ); assert(row, 409, 'Order follow-up is missing'); let data = { ...row.data }; if (event === 'result') { @@ -336,22 +337,23 @@ export default { completedBy: actor.id, }; } - return store.revise(actor, row, row.version, data, `task.lab-${event}`); + return await store.revise(actor, row, row.version, data, `task.lab-${event}`); }, - task(actor, id, action, version, input) { - const row = current(actor, id, 'task', version); - assert( - !row.data.linkedOrderId || ['assign', 'start'].includes(action), - 409, - 'Linked lab follow-up must be resolved through the lab order and current report', - ); - return store.transaction(() => { + async task(actor, id, action, version, input) { + await current(actor, id, 'task', version); + return await store.transaction(async () => { + const row = await current(actor, id, 'task', version); + assert( + !row.data.linkedOrderId || ['assign', 'start'].includes(action), + 409, + 'Linked lab follow-up must be resolved through the lab order and current report', + ); let data = { ...row.data }; const owner = data.assigneeId ?? data.author; if (action === 'assign') { const parsed = z.object({ assigneeId: short, reason: short }).strict().parse(input); assert(['requested', 'in-progress'].includes(data.status), 409, 'Task is closed'); - assignee( + await assignee( actor, row.patientId, parsed.assigneeId, @@ -370,7 +372,7 @@ export default { } else if (action === 'reopen') { const parsed = reason.parse(input); assert(['completed', 'cancelled'].includes(data.status), 409, 'Task is already open'); - assignee(actor, row.patientId, owner); + await assignee(actor, row.patientId, owner); data = { ...data, status: 'requested', reopenedReason: parsed.reason }; delete data.completedAt; delete data.completedBy; @@ -402,7 +404,7 @@ export default { }; } else throw new Fault(422, 'Unsupported task action'); } - return store.revise(actor, row, version, data, `task.${action}`); + return await store.revise(actor, row, version, data, `task.${action}`); }); }, }; diff --git a/plugins/clinical.ts b/plugins/clinical.ts index 07ad2db..5484407 100644 --- a/plugins/clinical.ts +++ b/plugins/clinical.ts @@ -1,5 +1,5 @@ import { z } from 'zod'; -import { assert, Fault, type Clinical, type Plugin } from '../packages/contracts.ts'; +import { assert, Fault, type Clinical, type Entity, type Plugin } from '../packages/contracts.ts'; import { taskInput } from '../packages/care-team.ts'; import { visibleRecord } from '../packages/visibility.ts'; @@ -53,7 +53,7 @@ export const inputs: Record = { export default { id: 'eir.clinical', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['clinical'], requires: ['store', 'country', 'access', 'terminology', 'careTeam'], setup(ctx) { @@ -63,19 +63,21 @@ export default { const terminology = ctx.get('terminology'); const careTeam = ctx.get('careTeam'); const clinical: Clinical = { - patients(actor) { - store.audit(actor, 'patient.directory'); - return store - .list(actor.tenant, undefined, 'patient') - .filter((patient) => access.allowed(actor, patient.id)) - .map((patient) => { - access.check(actor, patient.id); - return patient; - }); + async patients(actor) { + return await store.transaction(async () => { + await store.audit(actor, 'patient.directory'); + const patients: Entity[] = []; + for (const patient of await store.list(actor.tenant, undefined, 'patient')) { + if (!(await access.allowed(actor, patient.id))) continue; + await access.check(actor, patient.id); + patients.push(patient); + } + return patients; + }); }, - register(actor, input) { + async register(actor, input) { assert(actor.role === 'clinician', 403, 'Clinician role required'); - access.permit(actor, 'patient.register'); + await access.permit(actor, 'patient.register'); const parsed = patientInput.parse(input); assert( parsed.birthDate <= new Date().toISOString().slice(0, 10), @@ -84,23 +86,24 @@ export default { ); const identifier = country.identifier(parsed.identifier); try { - return store.transaction(() => { - const patient = store.insert(actor, 'patient', null, { + return await store.transaction(async () => { + await access.permit(actor, 'patient.register'); + const patient = await store.insert(actor, 'patient', null, { ...parsed, identifier, country: country.code, - ...(access.context ? { careUnitId: access.context(actor).unitId } : {}), + ...(access.context ? { careUnitId: (await access.context(actor)).unitId } : {}), }); - store.grant( + await store.grant( actor.tenant, patient.id, actor.id, 'clinician', new Date(Date.now() + 86400000 * 30).toISOString(), ); - store.audit(actor, 'care-relationship.created', patient.id); + await store.audit(actor, 'care-relationship.created', patient.id); if (access.context) - store.insert(actor, 'careRelationship', patient.id, { + await store.insert(actor, 'careRelationship', patient.id, { target: actor.id, assignmentId: actor.assignmentId, reason: 'Patient registered for care in the active unit', @@ -109,18 +112,21 @@ export default { return patient; }); } catch (error: any) { - if (String(error.message).includes('UNIQUE constraint')) + if (error.code === '23505' || String(error.message).includes('UNIQUE constraint')) throw new Fault(409, 'Identifier already registered in this organisation'); throw error; } }, - chart(actor, patientId) { - access.check(actor, patientId); - return store.list(actor.tenant, patientId).filter((e) => visibleRecord(actor, e)); + async chart(actor, patientId) { + await access.check(actor, patientId); + return await store.transaction(async () => { + await access.check(actor, patientId); + return (await store.list(actor.tenant, patientId)).filter((e) => visibleRecord(actor, e)); + }); }, - create(actor, patientId, kind, input) { - access.permit(actor, kind === 'task' ? 'task.write' : 'record.write', patientId); - if (kind === 'task') return careTeam.createTask(actor, patientId, input); + async create(actor, patientId, kind, input) { + await access.permit(actor, kind === 'task' ? 'task.write' : 'record.write', patientId); + if (kind === 'task') return await careTeam.createTask(actor, patientId, input); assert(inputs[kind], 422, 'Unsupported clinical record type'); const parsed = inputs[kind].parse(input) as Record; if (kind === 'condition') { @@ -143,16 +149,6 @@ export default { display: term.display, }; } - if (parsed.encounterId) { - const encounter = store.get(actor.tenant, parsed.encounterId); - assert( - encounter?.kind === 'encounter' && - encounter.patientId === patientId && - encounter.data.status === 'in-progress', - 409, - 'An open encounter for this patient is required', - ); - } if (kind === 'observation') { const definition = vitals[parsed.code]; assert( @@ -179,11 +175,22 @@ export default { task: 'requested', } as Record )[kind]; - return store.transaction(() => { + return await store.transaction(async () => { + await access.permit(actor, 'record.write', patientId); + if (parsed.encounterId) { + const encounter = await store.get(actor.tenant, parsed.encounterId); + assert( + encounter?.kind === 'encounter' && + encounter.patientId === patientId && + encounter.data.status === 'in-progress', + 409, + 'An open encounter for this patient is required', + ); + } if (kind === 'note' && parsed.clientId) { - const previous = store - .list(actor.tenant, patientId, 'note') - .find((r) => r.data.clientId === parsed.clientId); + const previous = (await store.list(actor.tenant, patientId, 'note')).find( + (r) => r.data.clientId === parsed.clientId, + ); if (previous) { assert( previous.data.author === actor.id && @@ -198,32 +205,44 @@ export default { } if (kind === 'encounter') assert( - !store - .list(actor.tenant, patientId, 'encounter') - .some((e) => e.data.status === 'in-progress'), + !(await store.list(actor.tenant, patientId, 'encounter')).some( + (e) => e.data.status === 'in-progress', + ), 409, 'This patient already has an open encounter', ); - return store.insert(actor, kind, patientId, { ...parsed, status, author: actor.id }); + return await store.insert(actor, kind, patientId, { + ...parsed, + status, + author: actor.id, + }); }); }, - transition(actor, entityId, action, version, input) { - const entity = store.get(actor.tenant, entityId); + async transition(actor, entityId, action, version, input) { + const entity = await store.get(actor.tenant, entityId); assert(entity, 404, 'Record not found'); - if (entity.kind === 'task') return careTeam.task(actor, entityId, action, version, input); - access.permit( + if (entity.kind === 'task') + return await careTeam.task(actor, entityId, action, version, input); + await access.permit( actor, entity.kind === 'note' && action === 'sign' ? 'note.sign' : 'record.write', entity.patientId, ); - assert(entity.version === version, 409, 'Record changed. Reload before saving.'); - return store.transaction(() => { + return await store.transaction(async () => { + const entity = await store.get(actor.tenant, entityId); + assert(entity, 404, 'Record not found'); + await access.permit( + actor, + entity.kind === 'note' && action === 'sign' ? 'note.sign' : 'record.write', + entity.patientId, + ); + assert(entity.version === version, 409, 'Record changed. Reload before saving.'); let data = { ...entity.data }; if (entity.kind === 'note') { if (action === 'amend') { assert(data.status === 'signed', 409, 'Only signed notes can be amended'); const amendment = z.object({ text, reason: short }).strict().parse(input); - return store.insert(actor, 'note', entity.patientId, { + return await store.insert(actor, 'note', entity.patientId, { ...amendment, status: 'draft', author: actor.id, @@ -261,11 +280,9 @@ export default { } else if (entity.kind === 'encounter' && action === 'close') { assert(data.status === 'in-progress', 409, 'Encounter is already closed'); assert( - !store - .list(actor.tenant, entity.patientId, 'note') - .some( - (note) => note.data.encounterId === entity.id && note.data.status === 'draft', - ), + !(await store.list(actor.tenant, entity.patientId, 'note')).some( + (note) => note.data.encounterId === entity.id && note.data.status === 'draft', + ), 409, 'Sign draft notes before closing the encounter', ); @@ -278,17 +295,30 @@ export default { assert(data.status !== 'entered-in-error', 409, 'Record already corrected'); data = { ...data, status: 'entered-in-error', correctionReason: reason }; } else throw new Fault(422, 'Unsupported clinical transition'); - const updated = store.revise(actor, entity, version, data, `${entity.kind}.${action}`); + const updated = await store.revise( + actor, + entity, + version, + data, + `${entity.kind}.${action}`, + ); if (entity.kind === 'encounter' && action === 'close') - careTeam.encounterClosed(actor, entity.id); + await careTeam.encounterClosed(actor, entity.id); return updated; }); }, - history(actor, entityId) { - const entity = store.get(actor.tenant, entityId); + async history(actor, entityId) { + const entity = await store.get(actor.tenant, entityId); assert(entity, 404, 'Record not found'); - access.check(actor, entity.patientId); - return store.history(actor.tenant, entityId).filter((e) => visibleRecord(actor, e)); + await access.check(actor, entity.patientId); + return await store.transaction(async () => { + const entity = await store.get(actor.tenant, entityId); + assert(entity, 404, 'Record not found'); + await access.check(actor, entity.patientId); + return (await store.history(actor.tenant, entityId)).filter((e) => + visibleRecord(actor, e), + ); + }); }, }; ctx.provide('clinical', clinical); diff --git a/plugins/country-eu-local.ts b/plugins/country-eu-local.ts index 76ce3cf..bb26247 100644 --- a/plugins/country-eu-local.ts +++ b/plugins/country-eu-local.ts @@ -2,7 +2,7 @@ import { Fault, type Plugin } from '../packages/contracts.ts'; export default { id: 'eir.country.eu-local', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['country'], requires: [], setup(ctx, config) { diff --git a/plugins/country-se.ts b/plugins/country-se.ts index ddcb163..41f6680 100644 --- a/plugins/country-se.ts +++ b/plugins/country-se.ts @@ -7,7 +7,7 @@ const Personnummer = createRequire(import.meta.url)( export default { id: 'eir.country.se', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, requires: [], provides: ['country'], setup(ctx) { diff --git a/plugins/fhir-r4.ts b/plugins/fhir-r4.ts index 07885e4..799cb5e 100644 --- a/plugins/fhir-r4.ts +++ b/plugins/fhir-r4.ts @@ -238,31 +238,34 @@ export function project(e: Entity): Record | null { export default { id: 'eir.fhir.r4-export', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['fhir'], requires: ['clinical', 'store', 'access'], setup(ctx) { const clinical = ctx.get('clinical'), store = ctx.get('store'); ctx.provide('fhir', { - bundle(actor, patientId) { - ctx.get('access').permit(actor, 'chart.export', patientId); - const entities = clinical.chart(actor, patientId); - // Superseded reports stay in the clinical history, not alongside current reports in an export. - const currentReports = new Set( - entities.filter((r) => r.kind === 'labOrder').map((r) => r.data.reportId), - ); - const resources = entities - .filter((r) => r.kind !== 'labReport' || currentReports.has(r.id)) - .map(project) - .filter((r): r is Record => r !== null); - store.audit(actor, 'fhir.export', patientId); - return { - resourceType: 'Bundle', - type: 'collection', - timestamp: new Date().toISOString(), - entry: resources.map((resource) => ({ fullUrl: `urn:uuid:${resource.id}`, resource })), - }; + async bundle(actor, patientId) { + await ctx.get('access').permit(actor, 'chart.export', patientId); + return await store.transaction(async () => { + await ctx.get('access').permit(actor, 'chart.export', patientId); + const entities = await clinical.chart(actor, patientId); + // Superseded reports stay in the clinical history, not alongside current reports in an export. + const currentReports = new Set( + entities.filter((r) => r.kind === 'labOrder').map((r) => r.data.reportId), + ); + const resources = entities + .filter((r) => r.kind !== 'labReport' || currentReports.has(r.id)) + .map(project) + .filter((r): r is Record => r !== null); + await store.audit(actor, 'fhir.export', patientId); + return { + resourceType: 'Bundle', + type: 'collection', + timestamp: new Date().toISOString(), + entry: resources.map((resource) => ({ fullUrl: `urn:uuid:${resource.id}`, resource })), + }; + }); }, }); }, diff --git a/plugins/identity-local.ts b/plugins/identity-local.ts index 5035f01..b0e5d70 100644 --- a/plugins/identity-local.ts +++ b/plugins/identity-local.ts @@ -4,26 +4,30 @@ const digest = (value: string) => createHash('sha256').update(value).digest('hex export default { id: 'eir.identity.local', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['identity'], requires: ['store'], setup(ctx) { const store = ctx.get('store'); ctx.provide('identity', { - issue(actor) { + async issue(actor) { const token = randomBytes(32).toString('base64url'); - store.saveSession(digest(token), actor, new Date(Date.now() + 8 * 3600000).toISOString()); + await store.saveSession( + digest(token), + actor, + new Date(Date.now() + 8 * 3600000).toISOString(), + ); return token; }, async authenticate(token) { if (!token || token.length > 2048) throw new Fault(401, 'Authentication required'); - const session = store.session(digest(token)); + const session = await store.session(digest(token)); if (!session || String(session.expires) <= new Date().toISOString()) throw new Fault(401, 'Session expired or invalid'); return session.actor; }, - revoke(token) { - store.revokeSession(digest(token)); + async revoke(token) { + await store.revokeSession(digest(token)); }, }); }, diff --git a/plugins/identity-oidc.ts b/plugins/identity-oidc.ts index 66cc08d..766f798 100644 --- a/plugins/identity-oidc.ts +++ b/plugins/identity-oidc.ts @@ -7,7 +7,7 @@ const loopback = (url: URL) => ['127.0.0.1', '[::1]', 'localhost'].includes(url. export default { id: 'eir.identity.oidc', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['identity'], requires: ['store', 'workforce'], async setup(ctx, config) { @@ -83,7 +83,7 @@ export default { nonce = oidc.randomNonce(), binding = oidc.randomState(), verifier = oidc.randomPKCECodeVerifier(); - store.saveLogin( + await store.saveLogin( tokenHash(binding), { state, nonce, verifier }, new Date(Date.now() + 5 * 60000).toISOString(), @@ -110,7 +110,7 @@ export default { 401, 'Invalid authentication response', ); - const transaction = store.consumeLogin(tokenHash(binding)); + const transaction = await store.consumeLogin(tokenHash(binding)); assert(transaction, 401, 'Authentication request expired or already used'); try { const tokens = await oidc.authorizationCodeGrant(client, url, { @@ -131,16 +131,19 @@ export default { 401, 'Required authentication assurance was not met', ); - const assignments = workforce.forIdentity(settings.issuer, claims.sub); - assert(assignments.length, 403, 'No provisioned active staff assignment'); - const actor = workforce.actor(assignments[0], { - method: 'oidc', - issuer: settings.issuer, - subject: claims.sub, - acr: claims.acr, - authenticatedAt: claims.auth_time, + const { sub, acr, auth_time: authenticatedAt } = claims; + return await store.transaction(async () => { + const assignments = await workforce.forIdentity(settings.issuer, sub); + assert(assignments.length, 403, 'No provisioned active staff assignment'); + const actor = workforce.actor(assignments[0], { + method: 'oidc', + issuer: settings.issuer, + subject: sub, + acr, + authenticatedAt, + }); + return sessions.issue!(actor); }); - return sessions.issue!(actor); } catch (cause) { throw Object.assign( new Fault(401, 'Authentication failed or staff assignment unavailable'), diff --git a/plugins/identity-staff-local.ts b/plugins/identity-staff-local.ts index ebb66aa..6c680a4 100644 --- a/plugins/identity-staff-local.ts +++ b/plugins/identity-staff-local.ts @@ -4,7 +4,7 @@ import { staffSessions } from '../packages/staff-sessions.ts'; export default { id: 'eir.identity.staff-local', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['identity'], requires: ['store', 'workforce'], setup(ctx, config) { @@ -13,23 +13,26 @@ export default { .strict() .parse(config); void settings; - const workforce = ctx.get('workforce'); - const sessions = staffSessions(ctx.get('store'), workforce, { + const workforce = ctx.get('workforce'), + store = ctx.get('store'); + const sessions = staffSessions(store, workforce, { idleMinutes: 15, absoluteHours: 8, }); ctx.provide('identity', { ...sessions, - issue(actor) { - const assignment = workforce.current(actor); - return sessions.issue!( - workforce.actor(assignment, { - method: 'local', - issuer: assignment.data.issuer, - subject: assignment.data.subject, - authenticatedAt: Math.floor(Date.now() / 1000), - }), - ); + async issue(actor) { + return store.transaction(async () => { + const assignment = await workforce.current(actor); + return sessions.issue!( + workforce.actor(assignment, { + method: 'local', + issuer: assignment.data.issuer, + subject: assignment.data.subject, + authenticatedAt: Math.floor(Date.now() / 1000), + }), + ); + }); }, }); }, diff --git a/plugins/laboratories.ts b/plugins/laboratories.ts index 398a6cf..25e85c3 100644 --- a/plugins/laboratories.ts +++ b/plugins/laboratories.ts @@ -9,39 +9,40 @@ import { export default { id: 'eir.laboratories', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['laboratories'], requires: ['store', 'access', 'careTeam'], setup(ctx) { const store = ctx.get('store'), access = ctx.get('access'), team = ctx.get('careTeam'); - const check = ( + const check = async ( actor: Actor, patientId: string, action: 'lab.order' | 'lab.receive' | 'lab.review' = 'lab.order', ) => { assert(actor.role === 'clinician', 403, 'Clinician role required'); - access.permit(actor, action, patientId); + await access.permit(actor, action, patientId); }; - const order = ( + const order = async ( actor: Actor, id: string, action: 'lab.order' | 'lab.receive' | 'lab.review' = 'lab.order', ) => { - const row = store.get(actor.tenant, id); + const row = await store.get(actor.tenant, id); assert(row?.kind === 'labOrder', 404, 'Lab order not found'); - check(actor, row.patientId, action); + await check(actor, row.patientId, action); return row; }; ctx.provide('laboratories', { - order(actor, patientId, input) { - check(actor, patientId); + async order(actor, patientId, input) { + await check(actor, patientId); const parsed = labOrderInput.parse(input); - return store.transaction(() => { - const previous = store - .list(actor.tenant, patientId, 'labOrder') - .find((r) => r.data.clientId === parsed.clientId); + return await store.transaction(async () => { + await check(actor, patientId); + const previous = (await store.list(actor.tenant, patientId, 'labOrder')).find( + (r) => r.data.clientId === parsed.clientId, + ); if (previous) { assert( previous.data.author === actor.id && @@ -51,7 +52,7 @@ export default { ); return previous; } - const encounter = store.get(actor.tenant, parsed.encounterId); + const encounter = await store.get(actor.tenant, parsed.encounterId); assert( encounter?.kind === 'encounter' && encounter.patientId === patientId && @@ -59,13 +60,13 @@ export default { 409, 'An open encounter for this patient is required', ); - const row = store.insert(actor, 'labOrder', patientId, { + const row = await store.insert(actor, 'labOrder', patientId, { ...parsed, status: 'requested', author: actor.id, originalInput: JSON.stringify(parsed), }); - team.createLinkedTask( + await team.createLinkedTask( actor, patientId, { @@ -79,8 +80,8 @@ export default { return row; }); }, - receive(actor, id, version, input) { - const row = order(actor, id, 'lab.receive'); + async receive(actor, id, version, input) { + await order(actor, id, 'lab.receive'); const parsed = labReportInput.parse(input); assert( Date.parse(parsed.collectedAt) <= Date.parse(parsed.reportedAt) && @@ -88,10 +89,11 @@ export default { 422, 'Collection must precede reporting; neither time may be in the future', ); - return store.transaction(() => { - const previous = store - .list(actor.tenant, undefined, 'labReport') - .find((r) => r.data.source === parsed.source && r.data.messageId === parsed.messageId); + return await store.transaction(async () => { + const row = await order(actor, id, 'lab.receive'); + const previous = (await store.list(actor.tenant, undefined, 'labReport')).find( + (r) => r.data.source === parsed.source && r.data.messageId === parsed.messageId, + ); if (previous) { assert( previous.patientId === row.patientId && @@ -114,7 +116,7 @@ export default { 422, 'There is no report to correct', ); - const report = store.insert(actor, 'labReport', row.patientId, { + const report = await store.insert(actor, 'labReport', row.patientId, { ...parsed, orderId: id, encounterId: row.data.encounterId, @@ -124,7 +126,7 @@ export default { status: row.data.reportId ? 'corrected' : 'final', originalInput: JSON.stringify(parsed), }); - const updated = store.revise( + const updated = await store.revise( actor, row, version, @@ -137,14 +139,15 @@ export default { }, 'labOrder.result', ); - team.syncLinkedTask(actor, updated, 'result'); + await team.syncLinkedTask(actor, updated, 'result'); return report; }); }, - review(actor, id, version, input) { - const row = order(actor, id, 'lab.review'), - parsed = labReviewInput.parse(input); - return store.transaction(() => { + async review(actor, id, version, input) { + await order(actor, id, 'lab.review'); + const parsed = labReviewInput.parse(input); + return await store.transaction(async () => { + const row = await order(actor, id, 'lab.review'); assert( row.version === version && row.data.status === 'received' && @@ -152,9 +155,9 @@ export default { 409, 'The report changed or was already reviewed. Reload before reviewing.', ); - const task = store - .list(actor.tenant, row.patientId, 'task') - .find((r) => r.data.linkedOrderId === id); + const task = (await store.list(actor.tenant, row.patientId, 'task')).find( + (r) => r.data.linkedOrderId === id, + ); assert( task && task.version === parsed.taskVersion, 409, @@ -170,13 +173,13 @@ export default { 422, 'Explicit acknowledgement of a critical report is required', ); - const review = store.insert(actor, 'labReview', row.patientId, { + const review = await store.insert(actor, 'labReview', row.patientId, { ...parsed, orderId: id, author: actor.id, reviewedAt: new Date().toISOString(), }); - const updated = store.revise( + const updated = await store.revise( actor, row, version, @@ -188,28 +191,29 @@ export default { }, 'labOrder.review', ); - team.syncLinkedTask(actor, updated, 'review', parsed.action); + await team.syncLinkedTask(actor, updated, 'review', parsed.action); return review; }); }, - cancel(actor, id, version, input) { - const row = order(actor, id), - parsed = labCancelInput.parse(input); - return store.transaction(() => { + async cancel(actor, id, version, input) { + await order(actor, id); + const parsed = labCancelInput.parse(input); + return await store.transaction(async () => { + const row = await order(actor, id); assert(row.version === version, 409, 'Order changed. Reload before cancelling.'); assert( row.data.status === 'requested', 409, 'A received report must be reviewed, not cancelled', ); - const updated = store.revise( + const updated = await store.revise( actor, row, version, { ...row.data, status: 'cancelled', cancelReason: parsed.reason }, 'labOrder.cancel', ); - team.syncLinkedTask(actor, updated, 'cancel', parsed.reason); + await team.syncLinkedTask(actor, updated, 'cancel', parsed.reason); return updated; }); }, diff --git a/plugins/medications.ts b/plugins/medications.ts index 60f230d..4b8072b 100644 --- a/plugins/medications.ts +++ b/plugins/medications.ts @@ -4,44 +4,47 @@ import { medicationInput, medicationUpdate, reconciliationInput } from '../packa export default { id: 'eir.medications', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['medications'], requires: ['store', 'access'], setup(ctx) { const store = ctx.get('store'), access = ctx.get('access'); - const check = (actor: Actor, patientId: string, write = false) => { + const check = async (actor: Actor, patientId: string, write = false) => { assert(actor.role === 'clinician', 403, 'Clinician role required'); - access.permit(actor, write ? 'medication.write' : 'chart.read', patientId); + await access.permit(actor, write ? 'medication.write' : 'chart.read', patientId); }; - const snapshot = (actor: Actor, patientId: string) => - store - .list(actor.tenant, patientId) + const snapshot = async (actor: Actor, patientId: string) => + (await store.list(actor.tenant, patientId)) .filter((r) => ['medication', 'allergy'].includes(r.kind)) .map((r) => `${r.id}@${r.version}`) .sort(); ctx.provide('medications', { - list(actor, patientId) { - check(actor, patientId); - const current = snapshot(actor, patientId); - const review = - store - .list(actor.tenant, patientId, 'medicationReview') - .sort((a, b) => b.data.reviewNumber - a.data.reviewNumber)[0] ?? null; - return { - items: store.list(actor.tenant, patientId, 'medication'), - snapshot: current, - review, - current: !!review && JSON.stringify(current) === JSON.stringify(review.data.snapshot), - }; + async list(actor, patientId) { + await check(actor, patientId); + return await store.transaction(async () => { + await check(actor, patientId); + const current = await snapshot(actor, patientId); + const review = + (await store.list(actor.tenant, patientId, 'medicationReview')).sort( + (a, b) => b.data.reviewNumber - a.data.reviewNumber, + )[0] ?? null; + return { + items: await store.list(actor.tenant, patientId, 'medication'), + snapshot: current, + review, + current: !!review && JSON.stringify(current) === JSON.stringify(review.data.snapshot), + }; + }); }, - add(actor, patientId, input) { - check(actor, patientId, true); + async add(actor, patientId, input) { + await check(actor, patientId, true); const parsed = medicationInput.parse(input); - return store.transaction(() => { - const previous = store - .list(actor.tenant, patientId, 'medication') - .find((r) => r.data.clientId === parsed.clientId); + return await store.transaction(async () => { + await check(actor, patientId, true); + const previous = (await store.list(actor.tenant, patientId, 'medication')).find( + (r) => r.data.clientId === parsed.clientId, + ); if (previous) { assert( previous.data.author === actor.id && @@ -51,26 +54,29 @@ export default { ); return previous; } - return store.insert(actor, 'medication', patientId, { + return await store.insert(actor, 'medication', patientId, { ...parsed, author: actor.id, originalInput: JSON.stringify(parsed), }); }); }, - update(actor, id, version, input) { - const row = store.get(actor.tenant, id); + async update(actor, id, version, input) { + const row = await store.get(actor.tenant, id); assert(row?.kind === 'medication', 404, 'Medication not found'); - check(actor, row.patientId, true); + await check(actor, row.patientId, true); const parsed = medicationUpdate.parse(input); - assert(row.version === version, 409, 'Medication changed. Reload before saving.'); - assert( - row.data.status !== 'entered-in-error', - 409, - 'A voided statement cannot be restored; create a new statement', - ); - return store.transaction(() => - store.revise( + return await store.transaction(async () => { + const row = await store.get(actor.tenant, id); + assert(row?.kind === 'medication', 404, 'Medication not found'); + await check(actor, row.patientId, true); + assert(row.version === version, 409, 'Medication changed. Reload before saving.'); + assert( + row.data.status !== 'entered-in-error', + 409, + 'A voided statement cannot be restored; create a new statement', + ); + return await store.revise( actor, row, version, @@ -80,17 +86,18 @@ export default { changedBy: actor.id, }, 'medication.update', - ), - ); + ); + }); }, - reconcile(actor, patientId, input) { - access.permit(actor, 'medication.reconcile', patientId); + async reconcile(actor, patientId, input) { + await access.permit(actor, 'medication.reconcile', patientId); const parsed = reconciliationInput.parse(input); parsed.snapshot.sort(); - return store.transaction(() => { - const previous = store - .list(actor.tenant, patientId, 'medicationReview') - .find((r) => r.data.clientId === parsed.clientId); + return await store.transaction(async () => { + await access.permit(actor, 'medication.reconcile', patientId); + const previous = (await store.list(actor.tenant, patientId, 'medicationReview')).find( + (r) => r.data.clientId === parsed.clientId, + ); if (previous) { assert( previous.data.author === actor.id && @@ -101,19 +108,19 @@ export default { return previous; } assert( - JSON.stringify(parsed.snapshot) === JSON.stringify(snapshot(actor, patientId)), + JSON.stringify(parsed.snapshot) === JSON.stringify(await snapshot(actor, patientId)), 409, 'Medication or allergy list changed. Reload and reconcile again.', ); - const current = store - .list(actor.tenant, patientId, 'medication') - .filter((r) => ['active', 'on-hold'].includes(r.data.status)); + const current = (await store.list(actor.tenant, patientId, 'medication')).filter((r) => + ['active', 'on-hold'].includes(r.data.status), + ); assert( parsed.noCurrentMedicines === (current.length === 0), 422, 'Explicitly confirm whether there are current medicines', ); - return store.insert(actor, 'medicationReview', patientId, { + return await store.insert(actor, 'medicationReview', patientId, { ...parsed, author: actor.id, reviewedAt: new Date().toISOString(), @@ -122,9 +129,9 @@ export default { 1 + Math.max( 0, - ...store - .list(actor.tenant, patientId, 'medicationReview') - .map((r) => r.data.reviewNumber), + ...(await store.list(actor.tenant, patientId, 'medicationReview')).map( + (r) => r.data.reviewNumber, + ), ), }); }); diff --git a/plugins/storage-postgres.ts b/plugins/storage-postgres.ts new file mode 100644 index 0000000..e8fee6d --- /dev/null +++ b/plugins/storage-postgres.ts @@ -0,0 +1,700 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { createHash, randomUUID } from 'node:crypto'; +import pg, { type PoolClient, type QueryResult, type QueryResultRow } from 'pg'; +import type { Actor, AuditQuery, AuditRow, Entity, Plugin, Store } from '../packages/contracts.ts'; +import { Fault } from '../packages/contracts.ts'; +import { + checkPostgresMigrations, + checkRuntimeRole, + postgresDataTables, + postgresPoolConfig, + type PostgresConnectionConfig, +} from '../packages/postgres-migrations.ts'; + +export type PostgresStoreConfig = PostgresConnectionConfig & { tenant: string }; +type Transaction = { + client: PoolClient; + active: boolean; + failure?: unknown; + failed: boolean; + auditQueue: Promise; +}; +const digest = (body: string) => createHash('sha256').update(body).digest('hex'); + +class RetryableTransactionConflict extends Fault { + constructor() { + super(409, 'Concurrent transaction conflict. Reload before saving.'); + } +} + +function databaseFault(error: unknown): Fault { + const code = (error as { code?: string })?.code; + if (code === '40001' || code === '40P01') return new RetryableTransactionConflict(); + if (['23505', '23514', '23503'].includes(code ?? '')) + return new Fault(409, 'Record changed or conflicts with stored data. Reload before saving.'); + if (code === '42501') return new Fault(403, 'Database access denied.'); + // Never expose pg.detail, SQL, connection strings, or raw server messages to callers/logs. + return new Fault(503, 'PostgreSQL storage unavailable.'); +} + +function entityRow(row: QueryResultRow): Entity { + return { + id: row.id, + tenant: row.tenant, + patientId: row.patient_id, + kind: row.kind, + version: row.version, + createdAt: row.created_at, + updatedAt: row.updated_at, + data: row.data, + }; +} +function auditRow(row: QueryResultRow): AuditRow { + return { ...JSON.parse(row.body), seq: Number(row.seq), hash: row.hash }; +} + +export class PostgresStore implements Store { + private readonly context = new AsyncLocalStorage(); + private readonly leases = new WeakMap(); + private readonly clientClosures = new Set>(); + private closed = false; + private closing?: Promise; + + private constructor( + private readonly pool: pg.Pool, + readonly tenant: string, + ) { + pool.on('connect', (client) => { + const closed = new Promise((resolve) => { + client.once('end', () => { + this.clientClosures.delete(closed); + resolve(); + }); + }); + this.clientClosures.add(closed); + // pg-pool removes its idle error listener while a client is checked out. + // A disconnect between queries must poison the transaction, not crash Node. + client.on('error', () => { + const state = this.leases.get(client); + if (state) this.fail(state, new Fault(503, 'PostgreSQL storage unavailable.')); + }); + }); + // Idle socket errors are handled by pg's eviction. Deliberately do not log driver errors. + pool.on('error', () => undefined); + } + + static async open(config: PostgresStoreConfig): Promise { + if (typeof config.tenant !== 'string' || !config.tenant.trim()) + throw new Error('PostgreSQL requires one configured tenant per runtime database role'); + const store = new PostgresStore(new pg.Pool(postgresPoolConfig(config)), config.tenant); + try { + await store.startup(); + return store; + } catch (error) { + await store.close(); + throw error; + } + } + + private async startup(): Promise { + const client = await this.connect(); + try { + await client.query('BEGIN READ ONLY'); + await client.query('SET LOCAL search_path = pg_catalog'); + await checkPostgresMigrations(client); + await checkRuntimeRole(client); + const protectedTables = [...postgresDataTables, 'schema_migrations']; + const tables = await client.query( + ` + SELECT c.relname, c.relrowsecurity, c.relforcerowsecurity + FROM pg_class c JOIN pg_namespace n ON c.relnamespace = n.oid + WHERE n.nspname = 'eir' AND c.relkind = 'r' AND c.relname = ANY($1::text[])`, + [protectedTables], + ); + if ( + tables.rowCount !== protectedTables.length || + tables.rows.some((r) => !r.relrowsecurity || !r.relforcerowsecurity) + ) + throw new Error('PostgreSQL row-level security is missing or disabled'); + for (const table of protectedTables) { + const privileges = await client.query( + `SELECT has_table_privilege(current_user, $1, 'TRUNCATE') OR + has_table_privilege(current_user, $1, 'TRIGGER') AS unsafe`, + [`eir.${table}`], + ); + if (privileges.rows[0].unsafe) + throw new Error('PostgreSQL runtime role has unsafe mutation privileges'); + } + for (const table of [ + 'schema_migrations', + 'tenant_roles', + 'audit_heads', + 'audit', + 'versions', + ]) { + const privileges = await client.query( + `SELECT + has_any_column_privilege(current_user, $1, 'UPDATE') OR + has_table_privilege(current_user, $1, 'DELETE') AS unsafe`, + [`eir.${table}`], + ); + if (privileges.rows[0].unsafe) + throw new Error('PostgreSQL runtime role has unsafe mutation privileges'); + if (['schema_migrations', 'tenant_roles', 'audit_heads'].includes(table)) { + const insert = await client.query( + "SELECT has_any_column_privilege(current_user, $1, 'INSERT') AS unsafe", + [`eir.${table}`], + ); + if (insert.rows[0].unsafe) + throw new Error('PostgreSQL runtime role can alter tenant or migration metadata'); + } + } + await this.checkPolicies(client, protectedTables); + const mapping = await client.query( + 'SELECT tenant FROM eir.tenant_roles WHERE runtime_role = current_user', + ); + if (mapping.rowCount !== 1 || mapping.rows[0].tenant !== this.tenant) + throw new Error('PostgreSQL configured tenant does not match authenticated runtime role'); + await client.query('COMMIT'); + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined); + if ((error as { code?: string })?.code) throw databaseFault(error); + throw error; + } finally { + client.release(); + } + if (!(await this.verifyAudit()).ok) throw new Error('PostgreSQL audit verification failed'); + } + + private async checkPolicies(client: PoolClient, tables: string[]): Promise { + const { rows } = await client.query( + ` + SELECT c.relname, p.polname, p.polcmd, p.polpermissive, + p.polroles = ARRAY[c.relowner] AS owner_only, + p.polroles = ARRAY[0::oid] AS public_only, + pg_get_expr(p.polqual, p.polrelid, false) AS predicate, + pg_get_expr(p.polwithcheck, p.polrelid, false) AS check_predicate + FROM pg_policy p JOIN pg_class c ON c.oid = p.polrelid + JOIN pg_namespace n ON n.oid = c.relnamespace + WHERE n.nspname = 'eir' AND c.relname = ANY($1::text[])`, + [tables], + ); + // pg_get_expr uses PostgreSQL's parser/deparser under the fixed pg_catalog search + // path above. Ignore whitespace only; any policy or semantic change fails closed. + const canonical = (value: string | null) => value?.replace(/\s+/g, ' ').trim() ?? null; + const tenantPredicate = + '(tenant = ( SELECT tenant_roles.tenant FROM eir.tenant_roles WHERE (tenant_roles.runtime_role = CURRENT_USER)))'; + for (const table of tables) { + const policies = rows.filter((row) => row.relname === table); + const operator = policies.find((row) => row.polname === 'operator_access'); + const scope = policies.find( + (row) => row.polname === (table === 'schema_migrations' ? 'runtime_read' : 'tenant_scope'), + ); + const expected = + table === 'schema_migrations' + ? 'true' + : table === 'tenant_roles' + ? '(runtime_role = CURRENT_USER)' + : tenantPredicate; + if ( + policies.length !== 2 || + !operator?.owner_only || + !operator.polpermissive || + operator.polcmd !== '*' || + canonical(operator.predicate) !== 'true' || + canonical(operator.check_predicate) !== 'true' || + !scope?.public_only || + !scope.polpermissive || + scope.polcmd !== (table === 'schema_migrations' ? 'r' : '*') || + canonical(scope.predicate) !== expected || + canonical(scope.check_predicate) !== (table === 'schema_migrations' ? null : expected) + ) + throw new Error('PostgreSQL row-level security policy definitions do not match migrations'); + } + } + + private async connect(): Promise { + if (this.closed) throw new Fault(503, 'PostgreSQL storage is closed.'); + try { + return await this.pool.connect(); + } catch (error) { + throw databaseFault(error); + } + } + + private fail(state: Transaction, error: unknown): void { + if (!state.failed) { + state.failed = true; + state.failure = error; + } + } + + private assertTenant(tenant: string): void { + if (tenant !== this.tenant) + throw new Fault(403, 'Tenant does not match this storage provider.'); + } + + private async query( + sql: string, + values: unknown[] = [], + ): Promise> { + const state = this.context.getStore(); + if (state && (!state.active || state.failed)) + throw state.failure ?? new Fault(409, 'Transaction is no longer active.'); + if (this.closed && !state) throw new Fault(503, 'PostgreSQL storage is closed.'); + try { + return await (state ? state.client : this.pool).query(sql, values); + } catch (error) { + const fault = databaseFault(error); + if (state) this.fail(state, fault); + throw fault; + } + } + + async transaction(fn: () => Promise): Promise { + const parent = this.context.getStore(); + if (parent) { + if (!parent.active || parent.failed) + throw parent.failure ?? new Fault(409, 'Transaction is no longer active.'); + try { + return await fn(); + } catch (error) { + this.fail(parent, error); + throw error; + } + } + // Callbacks must be replayable database-only work. Never put inference, network calls, + // notifications, or other external effects inside a storage transaction callback. + for (let attempt = 0; ; attempt++) { + try { + return await this.executeTransaction(fn); + } catch (error) { + if (!(error instanceof RetryableTransactionConflict) || attempt >= 3) throw error; + await new Promise((resolve) => + setTimeout(resolve, (10 + Math.random() * 30) * 2 ** attempt), + ); + } + } + } + + private async executeTransaction(fn: () => Promise): Promise { + const client = await this.connect(); + const state: Transaction = { + client, + active: true, + failed: false, + auditQueue: Promise.resolve(), + }; + this.leases.set(client, state); + let discard = false; + try { + try { + await client.query('BEGIN ISOLATION LEVEL SERIALIZABLE'); + } catch (error) { + throw databaseFault(error); + } + return await this.context.run(state, async () => { + const result = await fn(); + await state.auditQueue; + if (state.failed) throw state.failure; + try { + await client.query('COMMIT'); + } catch (error) { + throw databaseFault(error); + } + return result; + }); + } catch (error) { + state.active = false; + try { + await client.query('ROLLBACK'); + } catch { + discard = true; + } + throw error; + } finally { + state.active = false; + this.leases.delete(client); + client.release(discard); + } + } + + async health(): Promise { + await this.query('SELECT 1'); + } + + async close(): Promise { + if (this.context.getStore()?.active) + throw new Error('Close PostgreSQL storage outside its transaction'); + if (!this.closing) { + this.closed = true; + this.closing = (async () => { + await this.pool.end(); + // Some pg-pool versions resolve end() before idle clients finish closing. + await Promise.all(this.clientClosures); + })(); + } + await this.closing; + } + + async get(tenant: string, id: string): Promise { + this.assertTenant(tenant); + const { rows } = await this.query('SELECT * FROM eir.entities WHERE tenant = $1 AND id = $2', [ + tenant, + id, + ]); + return rows[0] ? entityRow(rows[0]) : undefined; + } + + async list(tenant: string, patientId?: string, kind?: string): Promise { + this.assertTenant(tenant); + const { rows } = await this.query( + `SELECT * FROM eir.entities WHERE tenant = $1 + AND ($2::text IS NULL OR patient_id = $2) AND ($3::text IS NULL OR kind = $3) + ORDER BY created_at DESC, id`, + [tenant, patientId ?? null, kind ?? null], + ); + return rows.map(entityRow); + } + + async insert( + actor: Actor, + kind: string, + patientId: string | null, + data: Record, + ): Promise { + return this.transaction(async () => { + this.assertTenant(actor.tenant); + const id = randomUUID(), + at = new Date().toISOString(); + const { rows } = await this.query( + `INSERT INTO eir.entities + (id, tenant, patient_id, kind, version, created_at, updated_at, data) + VALUES ($1, $2, $3, $4, 1, $5, $5, $6::jsonb) RETURNING *`, + [id, this.tenant, patientId ?? id, kind, at, JSON.stringify(data)], + ); + const entity = entityRow(rows[0]); + await this.audit(actor, `${kind}.created`, entity.patientId, id); + // Allocate change cursors only after taking the tenant audit-head write lock, so + // a later committed cursor cannot overtake an earlier uncommitted version. + await this.version(entity); + return entity; + }); + } + + async revise( + actor: Actor, + entity: Entity, + version: number, + data: Record, + action: string, + ): Promise { + return this.transaction(async () => { + this.assertTenant(actor.tenant); + this.assertTenant(entity.tenant); + if (!Number.isSafeInteger(version) || version < 1 || version !== entity.version) + throw new Fault(409, 'Record changed. Reload before saving.'); + const { rows } = await this.query( + `UPDATE eir.entities SET version = version + 1, updated_at = $4, data = $5::jsonb + WHERE tenant = $1 AND id = $2 AND version = $3 RETURNING *`, + [this.tenant, entity.id, version, new Date().toISOString(), JSON.stringify(data)], + ); + if (!rows[0]) throw new Fault(409, 'Record changed. Reload before saving.'); + // Use the database row, never caller-supplied immutable fields, for the version and audit. + const next = entityRow(rows[0]); + await this.audit(actor, action, next.patientId, next.id); + await this.version(next); + return next; + }); + } + + private async version(entity: Entity): Promise { + await this.query( + 'INSERT INTO eir.versions (id, tenant, version, snapshot) VALUES ($1, $2, $3, $4::jsonb)', + [entity.id, this.tenant, entity.version, JSON.stringify(entity)], + ); + } + + async history(tenant: string, id: string): Promise { + this.assertTenant(tenant); + const { rows } = await this.query( + 'SELECT snapshot FROM eir.versions WHERE tenant = $1 AND id = $2 ORDER BY version', + [tenant, id], + ); + return rows.map((row) => row.snapshot as Entity); + } + + async audit( + actor: Actor, + action: string, + patientId?: string, + entityId?: string, + outcome = 'success', + ): Promise { + await this.transaction(async () => { + this.assertTenant(actor.tenant); + const state = this.context.getStore()!; + const body = JSON.stringify({ + at: new Date().toISOString(), + actor: actor.id, + tenant: this.tenant, + role: actor.role, + unitId: actor.unitId ?? null, + assignmentId: actor.assignmentId ?? null, + authentication: actor.authentication?.method ?? 'local', + purpose: actor.role === 'clinician' ? 'treatment' : actor.role, + action, + patientId: patientId ?? null, + entityId: entityId ?? null, + outcome, + }); + // Parallel callers within one transaction must append in a single ordered queue. + // Across clients, the trigger locks and updates the tenant's protected audit head. + const append = state.auditQueue.then(async () => { + await this.query('INSERT INTO eir.audit (tenant, body) VALUES ($1, $2)', [ + this.tenant, + body, + ]); + }); + state.auditQueue = append.catch((error) => { + this.fail(state, error); + }); + await append; + }); + } + + async verifyAudit(): Promise<{ ok: boolean; count: number }> { + return this.transaction(async () => { + let previous = 'GENESIS', + after = 0, + count = 0; + for (;;) { + const { rows } = await this.query( + `SELECT tenant, seq, body, previous, hash FROM eir.audit + WHERE tenant = $1 AND seq > $2 ORDER BY seq LIMIT 1000`, + [this.tenant, after], + ); + if (!rows.length) break; + for (const row of rows) { + const seq = Number(row.seq); + let body: Record; + try { + body = JSON.parse(row.body); + } catch { + return { ok: false, count }; + } + if ( + row.tenant !== this.tenant || + body.tenant !== this.tenant || + !Number.isSafeInteger(seq) || + seq <= after || + row.previous !== previous || + row.hash !== digest(previous + row.body) + ) + return { ok: false, count }; + previous = row.hash; + after = seq; + count++; + } + } + const head = await this.query('SELECT seq, hash FROM eir.audit_heads WHERE tenant = $1', [ + this.tenant, + ]); + return { + ok: + head.rowCount === 1 && + Number(head.rows[0].seq) === after && + head.rows[0].hash === previous, + count, + }; + }); + } + + async grant( + tenant: string, + patientId: string, + actorId: string, + role: string, + expires: string, + ): Promise { + await this.transaction(async () => { + this.assertTenant(tenant); + await this.query( + `INSERT INTO eir.grants (tenant, patient_id, actor_id, role, expires) VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (tenant, patient_id, actor_id) DO UPDATE SET role = EXCLUDED.role, expires = EXCLUDED.expires`, + [tenant, patientId, actorId, role, expires], + ); + }); + } + + async getGrant( + tenant: string, + patientId: string, + actorId: string, + ): Promise<{ role: string; expires: string } | undefined> { + this.assertTenant(tenant); + const { rows } = await this.query( + 'SELECT role, expires FROM eir.grants WHERE tenant = $1 AND patient_id = $2 AND actor_id = $3', + [tenant, patientId, actorId], + ); + return rows[0] as { role: string; expires: string } | undefined; + } + + async restrict(tenant: string, patientId: string, blocked: boolean): Promise { + await this.transaction(async () => { + this.assertTenant(tenant); + await this.query( + `INSERT INTO eir.restrictions (tenant, patient_id, blocked) VALUES ($1, $2, $3) + ON CONFLICT (tenant, patient_id) DO UPDATE SET blocked = EXCLUDED.blocked`, + [tenant, patientId, blocked], + ); + }); + } + + async isBlocked(tenant: string, patientId: string): Promise { + this.assertTenant(tenant); + const { rows } = await this.query( + 'SELECT blocked FROM eir.restrictions WHERE tenant = $1 AND patient_id = $2', + [tenant, patientId], + ); + return rows[0]?.blocked === true; + } + + async saveSession(hash: string, actor: Actor, expires: string): Promise { + await this.transaction(async () => { + this.assertTenant(actor.tenant); + await this.query( + 'INSERT INTO eir.sessions (tenant, hash, actor, expires, last_seen) VALUES ($1, $2, $3::jsonb, $4, $5)', + [this.tenant, hash, JSON.stringify(actor), expires, new Date().toISOString()], + ); + }); + } + + async session( + hash: string, + ): Promise<{ actor: Actor; expires: string; lastSeen: string } | undefined> { + const { rows } = await this.query( + 'SELECT actor, expires, last_seen FROM eir.sessions WHERE tenant = $1 AND hash = $2', + [this.tenant, hash], + ); + return rows[0] + ? { actor: rows[0].actor, expires: rows[0].expires, lastSeen: rows[0].last_seen } + : undefined; + } + + async updateSession(hash: string, actor: Actor): Promise { + await this.transaction(async () => { + this.assertTenant(actor.tenant); + await this.query( + 'UPDATE eir.sessions SET actor = $3::jsonb, last_seen = $4 WHERE tenant = $1 AND hash = $2', + [this.tenant, hash, JSON.stringify(actor), new Date().toISOString()], + ); + }); + } + + async saveLogin(hash: string, data: Record, expires: string): Promise { + await this.transaction(async () => { + await this.query('DELETE FROM eir.login_transactions WHERE tenant = $1 AND expires <= $2', [ + this.tenant, + new Date().toISOString(), + ]); + await this.query( + 'INSERT INTO eir.login_transactions (tenant, hash, data, expires) VALUES ($1, $2, $3::jsonb, $4)', + [this.tenant, hash, JSON.stringify(data), expires], + ); + }); + } + + async consumeLogin(hash: string): Promise | undefined> { + return this.transaction(async () => { + const { rows } = await this.query( + 'DELETE FROM eir.login_transactions WHERE tenant = $1 AND hash = $2 RETURNING data, expires', + [this.tenant, hash], + ); + return rows[0] && rows[0].expires > new Date().toISOString() + ? (rows[0].data as Record) + : undefined; + }); + } + + async revokeSession(hash: string): Promise { + await this.transaction(async () => { + await this.query('DELETE FROM eir.sessions WHERE tenant = $1 AND hash = $2', [ + this.tenant, + hash, + ]); + }); + } + + async auditEntries(tenant: string, patientId?: string): Promise[]> { + this.assertTenant(tenant); + const { rows } = await this.query( + `SELECT seq, body, hash FROM eir.audit WHERE tenant = $1 + AND ($2::text IS NULL OR body::jsonb->>'patientId' = $2) ORDER BY seq DESC LIMIT 200`, + [tenant, patientId ?? null], + ); + return rows.map(auditRow); + } + + async auditPage(tenant: string, q: AuditQuery): Promise { + this.assertTenant(tenant); + const { rows } = await this.query( + `SELECT seq, body, hash FROM eir.audit WHERE tenant = $1 + AND body::jsonb->>'unitId' = $2 AND seq < $3 + AND ($4::text IS NULL OR body::jsonb->>'actor' = $4) + AND ($5::text IS NULL OR body::jsonb->>'patientId' = $5) + AND ($6::text IS NULL OR body::jsonb->>'outcome' = $6) + ORDER BY seq DESC LIMIT $7`, + [ + tenant, + q.unitId, + q.before ?? Number.MAX_SAFE_INTEGER, + q.actorId ?? null, + q.patientId ?? null, + q.outcome ?? null, + q.limit, + ], + ); + return rows.map(auditRow); + } + + async auditEntry(tenant: string, seq: number): Promise { + this.assertTenant(tenant); + const { rows } = await this.query( + 'SELECT seq, body, hash FROM eir.audit WHERE tenant = $1 AND seq = $2', + [tenant, seq], + ); + return rows[0] ? auditRow(rows[0]) : undefined; + } + + async changes( + tenant: string, + patientId: string, + after: number, + ): Promise<{ cursor: number; record: Entity }[]> { + this.assertTenant(tenant); + const { rows } = await this.query( + `SELECT cursor, snapshot FROM eir.versions WHERE tenant = $1 + AND snapshot->>'patientId' = $2 AND cursor > $3 ORDER BY cursor LIMIT 100`, + [tenant, patientId, after], + ); + return rows.map((row) => ({ cursor: Number(row.cursor), record: row.snapshot as Entity })); + } +} + +export default { + id: 'eir.storage.postgres', + version: '1.0.0', + apiVersion: 2, + provides: ['store'], + requires: [], + async setup(ctx, config) { + const store = await PostgresStore.open({ + tenant: config.tenant as string, + connectionStringEnv: config.connectionStringEnv as string, + localDevelopmentOnly: config.localDevelopmentOnly === true, + }); + ctx.onDispose(() => store.close()); + ctx.provide('store', store); + }, +} satisfies Plugin; diff --git a/plugins/storage-sqlite.ts b/plugins/storage-sqlite.ts index 3f561a6..96f8d62 100644 --- a/plugins/storage-sqlite.ts +++ b/plugins/storage-sqlite.ts @@ -2,11 +2,12 @@ import { DatabaseSync } from 'node:sqlite'; import { createHash, randomUUID } from 'node:crypto'; import { mkdirSync } from 'node:fs'; import { dirname, resolve } from 'node:path'; +import { AsyncLocalStorage } from 'node:async_hooks'; import type { Actor, Entity, Plugin, Store, AuditQuery, AuditRow } from '../packages/contracts.ts'; import { Fault } from '../packages/contracts.ts'; export const digest = (value: string) => createHash('sha256').update(value).digest('hex'); -export class SqliteStore implements Store { +class SqliteDatabase { db: DatabaseSync; constructor(path: string) { if (path !== ':memory:') mkdirSync(dirname(resolve(path)), { recursive: true, mode: 0o700 }); @@ -99,8 +100,18 @@ export class SqliteStore implements Store { return entity; } revise(actor: Actor, entity: Entity, version: number, data: Record, action: string) { + if (actor.tenant !== entity.tenant) throw new Fault(403, 'Tenant does not match the record.'); + const current = this.get(actor.tenant, entity.id); + if ( + !current || + !Number.isSafeInteger(version) || + version < 1 || + current.version !== version || + entity.version !== version + ) + throw new Fault(409, 'Record changed. Reload before saving.'); const next: Entity = { - ...entity, + ...current, version: version + 1, updatedAt: new Date().toISOString(), data: structuredClone(data), @@ -112,7 +123,7 @@ export class SqliteStore implements Store { .run(next.version, next.updatedAt, JSON.stringify(data), actor.tenant, entity.id, version); if (result.changes !== 1) throw new Fault(409, 'Record changed. Reload before saving.'); this.version(next); - this.audit(actor, action, entity.patientId, entity.id); + this.audit(actor, action, next.patientId, next.id); return next; } version(entity: Entity) { @@ -282,15 +293,103 @@ export class SqliteStore implements Store { function decode(row: any): Entity | undefined { return row ? { ...row, data: JSON.parse(row.data) } : undefined; } +type DatabaseMethod = Exclude; +type TransactionState = { active: boolean; failed: boolean }; + +// One connection cannot interleave transactions across awaited domain operations. +export class SqliteStore implements Store { + readonly db: DatabaseSync; + private readonly engine: SqliteDatabase; + private readonly context = new AsyncLocalStorage(); + private tail: Promise = Promise.resolve(); + private closing = false; + private closed?: Promise; + + constructor(path: string) { + this.engine = new SqliteDatabase(path); + this.db = this.engine.db; + } + + async transaction(fn: () => Promise): Promise { + const current = this.context.getStore(); + if (current) { + if (!current.active) throw new Error('Transaction already finished'); + try { + return await fn(); + } catch (error) { + current.failed = true; + throw error; + } + } + if (this.closing) throw new Error('Storage is closing'); + const run = this.tail.then(async () => { + const state = { active: true, failed: false }; + this.db.exec('BEGIN IMMEDIATE'); + try { + const result = await this.context.run(state, fn); + if (state.failed) throw new Fault(409, 'Transaction failed. Reload before retrying.'); + this.db.exec('COMMIT'); + return result; + } catch (error) { + this.db.exec('ROLLBACK'); + throw error; + } finally { + state.active = false; + } + }); + this.tail = run.catch(() => {}); + return run; + } + + private method(name: K): Store[K] { + return ((...args: unknown[]) => + this.transaction(async () => + (this.engine[name] as (...args: unknown[]) => unknown).apply(this.engine, args), + )) as Store[K]; + } + get = this.method('get'); + list = this.method('list'); + insert = this.method('insert'); + revise = this.method('revise'); + audit = this.method('audit'); + history = this.method('history'); + verifyAudit = this.method('verifyAudit'); + grant = this.method('grant'); + getGrant = this.method('getGrant'); + restrict = this.method('restrict'); + isBlocked = this.method('isBlocked'); + saveSession = this.method('saveSession'); + session = this.method('session'); + updateSession = this.method('updateSession'); + saveLogin = this.method('saveLogin'); + consumeLogin = this.method('consumeLogin'); + revokeSession = this.method('revokeSession'); + auditEntries = this.method('auditEntries'); + auditPage = this.method('auditPage'); + auditEntry = this.method('auditEntry'); + changes = this.method('changes'); + + async health() { + await this.transaction(async () => { + this.db.prepare('SELECT 1').get(); + }); + } + close() { + if (this.context.getStore()?.active) + return Promise.reject(new Error('Close SQLite storage outside its transaction')); + this.closing = true; + return (this.closed ??= this.tail.then(() => this.db.close())); + } +} export default { id: 'eir.storage.sqlite', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['store'], requires: [], setup(ctx, config) { const store = new SqliteStore(String(config.path ?? '.data/ehr.sqlite')); - ctx.onDispose(() => store.db.close()); + ctx.onDispose(() => store.close()); ctx.provide('store', store); }, } satisfies Plugin; diff --git a/plugins/terminology-icd-se.ts b/plugins/terminology-icd-se.ts index 008e09e..37ec2e3 100644 --- a/plugins/terminology-icd-se.ts +++ b/plugins/terminology-icd-se.ts @@ -70,7 +70,7 @@ async function load(): Promise { export default { id: 'eir.terminology.icd-se', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['terminology'], requires: [], async setup(ctx) { diff --git a/plugins/workforce.ts b/plugins/workforce.ts index 36f3547..503bb30 100644 --- a/plugins/workforce.ts +++ b/plugins/workforce.ts @@ -11,10 +11,10 @@ import { assignmentInput, assignmentChange, activeAssignment } from '../packages export default { id: 'eir.workforce', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, provides: ['workforce'], requires: ['store'], - setup(ctx, config) { + async setup(ctx, config) { const store = ctx.get('store'); const settings = z .object({ @@ -42,8 +42,14 @@ export default { assert(u, 422, 'Unknown care unit'); return u; }; - const validateIdentity = (input: z.infer) => { - const all = [...new Set(settings.units.map((u) => u.tenant))].flatMap(rows); + const allRows = async () => { + const all: Entity[] = []; + for (const tenant of new Set(settings.units.map((u) => u.tenant))) + all.push(...(await rows(tenant))); + return all; + }; + const validateIdentity = async (input: z.infer) => { + const all = await allRows(); // One identity may have several assignments, never several local staff identities. assert( !all.some( @@ -70,8 +76,10 @@ export default { }; const workforce: Workforce = { units: settings.units, - current(actor) { - const row = actor.assignmentId ? store.get(actor.tenant, actor.assignmentId) : undefined; + async current(actor) { + const row = actor.assignmentId + ? await store.get(actor.tenant, actor.assignmentId) + : undefined; assert( row?.kind === 'staffAssignment' && activeAssignment(row) && @@ -95,9 +103,9 @@ export default { ); return row; }, - assignments(actor) { - const current = workforce.current(actor); - return rows(actor.tenant).filter( + async assignments(actor) { + const current = await workforce.current(actor); + return (await rows(actor.tenant)).filter( (a) => a.data.actorId === actor.id && sameIdentity(a, current) && @@ -105,16 +113,14 @@ export default { settings.units.some((u) => u.id === a.data.unitId && u.tenant === a.tenant), ); }, - forIdentity(issuer, subject) { - return [...new Set(settings.units.map((u) => u.tenant))] - .flatMap(rows) - .filter( - (a) => - activeAssignment(a) && - a.data.issuer === issuer && - a.data.subject === subject && - settings.units.some((u) => u.id === a.data.unitId && u.tenant === a.tenant), - ); + async forIdentity(issuer, subject) { + return (await allRows()).filter( + (a) => + activeAssignment(a) && + a.data.issuer === issuer && + a.data.subject === subject && + settings.units.some((u) => u.id === a.data.unitId && u.tenant === a.tenant), + ); }, actor(row, authentication) { return { @@ -126,45 +132,51 @@ export default { ...(authentication ? { authentication } : {}), }; }, - staff(actor) { - const current = workforce.current(actor); + async staff(actor) { + const current = await workforce.current(actor); assert( current.data.permissions.includes('workforce.manage'), 403, 'Workforce administration required', ); - store.audit(actor, 'workforce.directory'); - return rows(actor.tenant).filter((a) => a.data.unitId === actor.unitId); + await store.audit(actor, 'workforce.directory'); + return (await rows(actor.tenant)).filter((a) => a.data.unitId === actor.unitId); }, - create(actor, input) { - workforce.staff(actor); - const parsed = assignmentInput.parse(input); - assert( - parsed.unitId === actor.unitId && parsed.actorId !== actor.id, - 403, - 'Cannot administer yourself or another unit', - ); - return store.transaction(() => { - validateIdentity(parsed); + async create(actor, input) { + return store.transaction(async () => { + await workforce.staff(actor); + const parsed = assignmentInput.parse(input); + assert( + parsed.unitId === actor.unitId && parsed.actorId !== actor.id, + 403, + 'Cannot administer yourself or another unit', + ); + await validateIdentity(parsed); return store.insert(actor, 'staffAssignment', null, parsed); }); }, - update(actor, id, version, input) { - workforce.staff(actor); - const row = store.get(actor.tenant, id); - assert( - row?.kind === 'staffAssignment' && - row.data.unitId === actor.unitId && - row.data.actorId !== actor.id, - 403, - 'Cannot administer yourself or another unit', - ); - const parsed = assignmentChange.parse(input); - const { reason, ...changes } = parsed; - const data = assignmentInput.parse({ ...row.data, ...changes }); - return store.transaction(() => { - const updated = store.revise(actor, row, version, data, 'workforce.assignment-changed'); - store.insert(actor, 'assignmentChange', null, { + async update(actor, id, version, input) { + return store.transaction(async () => { + await workforce.staff(actor); + const row = await store.get(actor.tenant, id); + assert( + row?.kind === 'staffAssignment' && + row.data.unitId === actor.unitId && + row.data.actorId !== actor.id, + 403, + 'Cannot administer yourself or another unit', + ); + const parsed = assignmentChange.parse(input); + const { reason, ...changes } = parsed; + const data = assignmentInput.parse({ ...row.data, ...changes }); + const updated = await store.revise( + actor, + row, + version, + data, + 'workforce.assignment-changed', + ); + await store.insert(actor, 'assignmentChange', null, { assignmentId: id, reason, fromVersion: version, @@ -176,14 +188,14 @@ export default { }; // Bootstrap once per store; restarts must never restore revoked assignments. for (const tenant of new Set(settings.units.map((u) => u.tenant))) { - if (store.list(tenant, undefined, 'workforceBootstrap').length) continue; - store.transaction(() => { + await store.transaction(async () => { + if ((await store.list(tenant, undefined, 'workforceBootstrap')).length) return; const admin: Actor = { id: 'workforce-bootstrap', tenant, role: 'administrator' }; for (const input of settings.bootstrap.filter((a) => unit(a.unitId).tenant === tenant)) { - validateIdentity(input); - store.insert({ ...admin, unitId: input.unitId }, 'staffAssignment', null, input); + await validateIdentity(input); + await store.insert({ ...admin, unitId: input.unitId }, 'staffAssignment', null, input); } - store.insert(admin, 'workforceBootstrap', null, { completed: true }); + await store.insert(admin, 'workforceBootstrap', null, { completed: true }); }); } ctx.provide('workforce', workforce); diff --git a/scripts/migrate-postgres.ts b/scripts/migrate-postgres.ts new file mode 100644 index 0000000..de35355 --- /dev/null +++ b/scripts/migrate-postgres.ts @@ -0,0 +1,43 @@ +import { parseArgs } from 'node:util'; +import pg from 'pg'; +import { migratePostgres, postgresPoolConfig } from '../packages/postgres-migrations.ts'; + +const { values } = parseArgs({ + options: { + 'connection-string-env': { type: 'string', default: 'EIR_POSTGRES_MIGRATION_URL' }, + tenant: { type: 'string' }, + 'runtime-role': { type: 'string' }, + 'local-development-only': { type: 'boolean', default: false }, + }, +}); +if (!!values.tenant !== !!values['runtime-role']) + throw new Error('--tenant and --runtime-role must be supplied together'); +const pool = new pg.Pool( + postgresPoolConfig({ + connectionStringEnv: values['connection-string-env'], + localDevelopmentOnly: values['local-development-only'], + }), +); +pool.on('error', () => { + process.exitCode = 1; +}); +try { + await migratePostgres( + pool, + values.tenant + ? { + tenant: values.tenant, + runtimeRole: values['runtime-role']!, + } + : undefined, + ); + console.log('PostgreSQL migrations and requested tenant provisioning completed.'); +} catch { + // Driver errors can contain URLs, SQL values, or identifying database details. + console.error( + 'PostgreSQL migration failed. Check operator credentials, role restrictions, and migration integrity.', + ); + process.exitCode = 1; +} finally { + await pool.end(); +} diff --git a/scripts/plugins.ts b/scripts/plugins.ts index 41b87f0..c6316b0 100644 --- a/scripts/plugins.ts +++ b/scripts/plugins.ts @@ -11,4 +11,4 @@ console.table( requires: p.requires.join(', '), })), ); -runtime.stop(); +await runtime.stop(); diff --git a/scripts/postgres-backup-loop.ts b/scripts/postgres-backup-loop.ts new file mode 100644 index 0000000..0e4bce6 --- /dev/null +++ b/scripts/postgres-backup-loop.ts @@ -0,0 +1,61 @@ +import { mkdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { randomUUID } from 'node:crypto'; +import { + backupErrorMessage, + backupKey, + createPostgresBackup, + runBackupSchedule, +} from '../packages/backup.ts'; + +const abort = new AbortController(); +for (const signal of ['SIGINT', 'SIGTERM'] as const) process.once(signal, () => abort.abort()); +let key: Buffer | undefined; +try { + const directory = process.env.EIR_BACKUP_DIRECTORY; + const databaseUrl = process.env.EIR_BACKUP_DATABASE_URL; + const minutes = Number(process.env.EIR_BACKUP_INTERVAL_MINUTES); + if ( + process.argv.length !== 2 || + !directory || + !databaseUrl || + !Number.isInteger(minutes) || + minutes < 1 || + minutes > 35791 + ) + throw new Error('Invalid scheduler configuration'); + key = backupKey(process.env.EIR_BACKUP_KEY); + const encryptionKey = key; + await mkdir(directory, { recursive: true, mode: 0o700 }); + await runBackupSchedule( + async () => { + const filename = `postgres-${new Date().toISOString().replaceAll(':', '-')}-${randomUUID()}.eirbak`; + await createPostgresBackup({ + databaseUrl, + outputPath: join(directory, filename), + encryptionKey, + pgBin: process.env.PG_BIN, + signal: abort.signal, + }); + }, + { + intervalMs: minutes * 60000, + signal: abort.signal, + onResult(result) { + if (result === 'success') console.log('Scheduled encrypted PostgreSQL backup completed.'); + else + console.error( + 'Scheduled PostgreSQL backup failed; investigate backup freshness. Sensitive diagnostics suppressed.', + ); + }, + }, + ); +} catch (error) { + console.error(backupErrorMessage(error)); + console.error( + 'Set EIR_BACKUP_DIRECTORY, EIR_BACKUP_INTERVAL_MINUTES, EIR_BACKUP_DATABASE_URL and EIR_BACKUP_KEY.', + ); + process.exitCode = 1; +} finally { + key?.fill(0); +} diff --git a/scripts/postgres-backup.ts b/scripts/postgres-backup.ts new file mode 100644 index 0000000..1974d5f --- /dev/null +++ b/scripts/postgres-backup.ts @@ -0,0 +1,32 @@ +import { backupErrorMessage, backupKey, createPostgresBackup } from '../packages/backup.ts'; + +const abort = new AbortController(); +for (const signal of ['SIGINT', 'SIGTERM'] as const) process.once(signal, () => abort.abort()); +let key: Buffer | undefined; +try { + const args = process.argv.slice(2); + if ( + args.length !== 2 || + args[0] !== '--output' || + !args[1] || + !process.env.EIR_BACKUP_DATABASE_URL + ) + throw new Error('Invalid arguments'); + key = backupKey(process.env.EIR_BACKUP_KEY); + await createPostgresBackup({ + outputPath: args[1], + databaseUrl: process.env.EIR_BACKUP_DATABASE_URL, + encryptionKey: key, + pgBin: process.env.PG_BIN, + signal: abort.signal, + }); + console.log('Encrypted PostgreSQL backup completed.'); +} catch (error) { + console.error(backupErrorMessage(error)); + console.error( + 'Usage: tsx scripts/postgres-backup.ts --output NEW_FILE; set EIR_BACKUP_DATABASE_URL and EIR_BACKUP_KEY.', + ); + process.exitCode = 1; +} finally { + key?.fill(0); +} diff --git a/scripts/postgres-restore.ts b/scripts/postgres-restore.ts new file mode 100644 index 0000000..6c06570 --- /dev/null +++ b/scripts/postgres-restore.ts @@ -0,0 +1,40 @@ +import { backupErrorMessage, backupKey, restorePostgresBackup } from '../packages/backup.ts'; + +const abort = new AbortController(); +for (const signal of ['SIGINT', 'SIGTERM'] as const) process.once(signal, () => abort.abort()); +let key: Buffer | undefined; +try { + const args = process.argv.slice(2); + if ( + args.length !== 4 || + args[0] !== '--input' || + !args[1] || + args[2] !== '--confirm-fresh-database' || + !args[3] || + !process.env.EIR_RESTORE_DATABASE_URL + ) + throw new Error('Invalid arguments'); + key = backupKey(process.env.EIR_BACKUP_KEY); + await restorePostgresBackup({ + inputPath: args[1], + confirmFreshDatabase: args[3], + databaseUrl: process.env.EIR_RESTORE_DATABASE_URL, + sourceDatabaseUrl: process.env.EIR_BACKUP_DATABASE_URL, + runtimeDatabaseUrl: process.env.EIR_DATABASE_URL, + encryptionKey: key, + pgBin: process.env.PG_BIN, + temporaryDirectory: process.env.EIR_RESTORE_TMPDIR, + signal: abort.signal, + }); + console.log( + 'Restore completed and authentication rows purged. Target remains fenced (connection limit 0); validate before application boot.', + ); +} catch (error) { + console.error(backupErrorMessage(error)); + console.error( + 'Usage: tsx scripts/postgres-restore.ts --input FILE --confirm-fresh-database NAME; set EIR_RESTORE_DATABASE_URL and EIR_BACKUP_KEY.', + ); + process.exitCode = 1; +} finally { + key?.fill(0); +} diff --git a/scripts/prepare-postgres-test-clients.ts b/scripts/prepare-postgres-test-clients.ts new file mode 100644 index 0000000..0012ef2 --- /dev/null +++ b/scripts/prepare-postgres-test-clients.ts @@ -0,0 +1,41 @@ +import { parseArgs } from 'node:util'; +import { mkdir, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; + +const { values } = parseArgs({ + options: { + container: { type: 'string' }, + output: { type: 'string' }, + docker: { type: 'string', default: 'docker' }, + }, +}); +const url = new URL(process.env.EIR_TEST_POSTGRES_URL ?? ''); +if ( + !values.container || + !/^[A-Za-z0-9][A-Za-z0-9_.-]+$/.test(values.container) || + !values.output || + !['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) +) + throw new Error( + 'Supply --container, --output and a loopback EIR_TEST_POSTGRES_URL for disposable tests only.', + ); +const output = resolve(values.output); +await mkdir(output, { recursive: true, mode: 0o700 }); +for (const binary of ['pg_dump', 'pg_restore']) { + // These wrappers forward bytes to actual PostgreSQL clients, never emulate a dump. + const source = `#!${process.execPath} +const { spawn } = require('node:child_process'); +if (process.env.PGHOST !== ${JSON.stringify(url.hostname.replace(/^\[|\]$/g, ''))} || + (process.env.PGPORT || '5432') !== ${JSON.stringify(url.port || '5432')}) process.exit(2); +const names = ['PGDATABASE', 'PGUSER', 'PGPASSWORD', 'PGSSLMODE', 'PGCONNECT_TIMEOUT', 'PGAPPNAME']; +const envArgs = names.filter(name => process.env[name] !== undefined).flatMap(name => ['--env', name]); +const child = spawn(${JSON.stringify(values.docker)}, ['exec', '-i', ...envArgs, + '--env', 'PGHOST=127.0.0.1', '--env', 'PGPORT=5432', ${JSON.stringify(values.container)}, + ${JSON.stringify(binary)}, ...process.argv.slice(2)], { stdio: 'inherit' }); +child.once('error', () => { process.exitCode = 1; }); +child.once('exit', code => { process.exitCode = code ?? 1; }); +for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => child.kill(signal)); +`; + await writeFile(join(output, binary), source, { flag: 'wx', mode: 0o700 }); +} +console.log('Real PostgreSQL test-client wrappers prepared.'); diff --git a/scripts/smoke-model.ts b/scripts/smoke-model.ts index 0a00279..aa10db7 100644 --- a/scripts/smoke-model.ts +++ b/scripts/smoke-model.ts @@ -15,5 +15,5 @@ try { throw new Error('Invalid citation from live model'); console.log(JSON.stringify(output, null, 2)); } finally { - runtime.stop(); + await runtime.stop(); } diff --git a/scripts/test-postgres.ts b/scripts/test-postgres.ts new file mode 100644 index 0000000..577e624 --- /dev/null +++ b/scripts/test-postgres.ts @@ -0,0 +1,21 @@ +import { readdir } from 'node:fs/promises'; +import { spawn } from 'node:child_process'; + +if (!process.env.EIR_TEST_POSTGRES_URL) + throw new Error( + 'EIR_TEST_POSTGRES_URL must name an isolated PostgreSQL test database. No tests were run.', + ); +const files = (await readdir('tests')).filter( + (name) => name.startsWith('postgres') && name.endsWith('.test.ts'), +); +const child = spawn( + process.execPath, + ['--import', 'tsx', '--test', ...files.map((name) => 'tests/' + name)], + { stdio: 'inherit' }, +); +child.once('error', () => { + process.exitCode = 1; +}); +child.once('exit', (code) => { + process.exitCode = code ?? 1; +}); diff --git a/tests/backup.test.ts b/tests/backup.test.ts new file mode 100644 index 0000000..5512129 --- /dev/null +++ b/tests/backup.test.ts @@ -0,0 +1,421 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes, randomUUID, createHash } from 'node:crypto'; +import { mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { Readable } from 'node:stream'; +import pg from 'pg'; +import { + backupErrorMessage, + backupKey, + createPostgresBackup, + encryptBackup, + restorePostgresBackup, + runBackupSchedule, + withVerifiedBackup, +} from '../packages/backup.ts'; + +async function temporary(t: { after: (fn: () => Promise) => void }) { + const path = await mkdtemp(join(tmpdir(), 'eir-backup-test-')); + t.after(() => rm(path, { recursive: true, force: true })); + return path; +} + +test('backup key requires exactly 32 bytes of canonical base64', () => { + const key = randomBytes(32); + assert.deepEqual(backupKey(key.toString('base64')), key); + for (const value of [ + undefined, + '', + key.toString('hex'), + key.toString('base64url'), + randomBytes(31).toString('base64'), + key.toString('base64') + '\n', + 'A'.repeat(42) + 'B=', + ]) + assert.throws(() => backupKey(value), /canonical base64/); +}); + +test('streaming encryption round trip, random nonce, authenticated callback and private cleanup', async (t) => { + const directory = await temporary(t); + const key = randomBytes(32); + const data = randomBytes(4 * 1024 * 1024); + const files = [join(directory, 'one'), join(directory, 'two')]; + for (const file of files) { + await encryptBackup( + Readable.from( + (function* () { + for (let at = 0; at < data.length; at += 4096) yield data.subarray(at, at + 4096); + })(), + ), + file, + key, + ); + assert.equal((await stat(file)).mode & 0o777, 0o600); + let plaintext = ''; + await withVerifiedBackup( + file, + key, + async (path) => { + plaintext = path; + assert.equal((await stat(path)).mode & 0o777, 0o600); + assert.equal((await stat(join(path, '..'))).mode & 0o777, 0o700); + assert.deepEqual(await readFile(path), data); + }, + { temporaryDirectory: directory }, + ); + await assert.rejects(stat(plaintext), { code: 'ENOENT' }); + } + assert.notDeepEqual(await readFile(files[0]), await readFile(files[1])); + assert.deepEqual((await readdir(directory)).sort(), ['one', 'two']); +}); + +test('wrong key, modified header/nonce/ciphertext/tag, truncation and appended data never reach consumer', async (t) => { + const directory = await temporary(t); + const key = randomBytes(32); + const original = join(directory, 'original'); + await encryptBackup( + Readable.from([Buffer.from('synthetic confidential payload')]), + original, + key, + ); + const bytes = await readFile(original); + let calls = 0; + const consume = async () => { + calls++; + }; + await assert.rejects( + withVerifiedBackup(original, randomBytes(32), consume, { temporaryDirectory: directory }), + /authentication/, + ); + const variants: Buffer[] = []; + for (const index of [0, 8, 9, 10, 21, 22, bytes.length - 1]) { + const changed = Buffer.from(bytes); + changed[index] ^= 1; + variants.push(changed); + } + for (const length of [0, 8, 22, 38, bytes.length - 1, bytes.length - 16]) + variants.push(bytes.subarray(0, length)); + variants.push(Buffer.concat([bytes, Buffer.from([0])])); + for (const variant of variants) { + const file = join(directory, 'bad'); + await writeFile(file, variant, { mode: 0o600 }); + await assert.rejects( + withVerifiedBackup(file, key, consume, { temporaryDirectory: directory }), + /authentication|header/, + ); + assert.ok(!(await readdir(directory)).some((name) => name.startsWith('eir-restore-'))); + } + assert.equal(calls, 0); +}); + +test('output is exclusive even for symlinks and racing writers', async (t) => { + const directory = await temporary(t); + const file = join(directory, 'archive'); + const key = randomBytes(32); + const results = await Promise.allSettled( + ['one', 'two'].map((value) => encryptBackup(Readable.from([value]), file, key)), + ); + assert.equal(results.filter((result) => result.status === 'fulfilled').length, 1); + const before = await readFile(file); + await assert.rejects(encryptBackup(Readable.from(['replacement']), file, key), /exists/); + assert.deepEqual(await readFile(file), before); + const alias = join(directory, 'alias'); + await symlink(file, alias); + await assert.rejects(encryptBackup(Readable.from(['replacement']), alias, key), /exists/); + assert.deepEqual(await readFile(file), before); + assert.deepEqual((await readdir(directory)).sort(), ['alias', 'archive']); +}); + +test('failed streams, cancellations and failed consumers clean partial files without exposing diagnostics', async (t) => { + const directory = await temporary(t); + const key = randomBytes(32); + const file = join(directory, 'archive'); + const secret = 'SYNTHETIC-PHI-and-token-not-for-logs'; + const broken = Readable.from( + (async function* () { + yield Buffer.from('partial'); + throw new Error(secret); + })(), + ); + await assert.rejects( + encryptBackup(broken, file, key), + (error: Error) => !error.message.includes(secret), + ); + assert.deepEqual(await readdir(directory), []); + const abort = new AbortController(); + abort.abort(); + await assert.rejects(encryptBackup(Readable.from(['partial']), file, key, abort.signal)); + assert.deepEqual(await readdir(directory), []); + await encryptBackup(Readable.from(['complete']), file, key); + await assert.rejects( + withVerifiedBackup( + file, + key, + async () => { + throw new Error(secret); + }, + { temporaryDirectory: directory }, + ), + /suppressed/, + ); + assert.deepEqual(await readdir(directory), ['archive']); + assert.ok(!backupErrorMessage(new Error(secret)).includes(secret)); +}); + +test('restore rejects unsafe confirmation and authenticates before starting any client or connection', async (t) => { + const directory = await temporary(t); + const file = join(directory, 'archive'); + const key = randomBytes(32); + await encryptBackup(Readable.from(['payload']), file, key); + const options = { + databaseUrl: 'postgresql://nobody:secret@127.0.0.1:1/fresh_recovery', + inputPath: file, + encryptionKey: key, + confirmFreshDatabase: 'fresh_recovery', + pgBin: join(directory, 'no-binaries'), + temporaryDirectory: directory, + }; + await assert.rejects( + restorePostgresBackup({ ...options, confirmFreshDatabase: '' }), + /confirmation/, + ); + await assert.rejects( + restorePostgresBackup({ ...options, sourceDatabaseUrl: options.databaseUrl }), + /differ/, + ); + await assert.rejects( + restorePostgresBackup({ ...options, runtimeDatabaseUrl: options.databaseUrl }), + /differ/, + ); + await assert.rejects( + restorePostgresBackup({ ...options, encryptionKey: randomBytes(32) }), + /authentication/, + ); + assert.deepEqual(await readdir(directory), ['archive']); +}); + +test('missing pg_dump fails without publishing a partial encrypted backup', async (t) => { + const directory = await temporary(t); + await assert.rejects( + createPostgresBackup({ + databaseUrl: 'postgresql://nobody:secret@127.0.0.1:1/source', + encryptionKey: randomBytes(32), + outputPath: join(directory, 'archive'), + pgBin: join(directory, 'missing'), + }), + /pg_dump/, + ); + assert.deepEqual(await readdir(directory), []); +}); + +test('scheduler serializes backups, waits after completion, reports failures and stops on abort', async () => { + const abort = new AbortController(); + const events: string[] = []; + let active = 0, + calls = 0; + await runBackupSchedule( + async () => { + assert.equal(active++, 0); + events.push('start'); + await new Promise((resolve) => setImmediate(resolve)); + calls++; + active--; + events.push('end'); + if (calls === 1) throw new Error('synthetic secret'); + }, + { + intervalMs: 1234, + signal: abort.signal, + onResult: (result) => { + events.push(result); + }, + wait: async (milliseconds) => { + assert.equal(milliseconds, 1234); + assert.equal(active, 0); + events.push('wait'); + if (calls === 2) abort.abort(); + }, + }, + ); + assert.deepEqual(events, ['start', 'end', 'failure', 'wait', 'start', 'end', 'success', 'wait']); + await assert.rejects( + runBackupSchedule(async () => {}, { intervalMs: NaN, signal: abort.signal }), + /interval/, + ); +}); + +test('remote connections require verified TLS before any subprocess or network connection', async (t) => { + const directory = await temporary(t); + for (const suffix of ['', '?sslmode=disable', '?sslmode=require', '?sslmode=prefer']) { + const databaseUrl = 'postgresql://owner:secret@database.example/recovery' + suffix; + await assert.rejects( + createPostgresBackup({ + databaseUrl, + outputPath: join(directory, 'backup'), + encryptionKey: randomBytes(32), + }), + /Remote hosts require sslmode=verify-full/, + ); + await assert.rejects( + restorePostgresBackup({ + databaseUrl, + inputPath: join(directory, 'missing'), + encryptionKey: randomBytes(32), + confirmFreshDatabase: 'recovery', + }), + /Remote hosts require sslmode=verify-full/, + ); + } + assert.deepEqual(await readdir(directory), []); +}); + +const adminUrl = process.env.EIR_BACKUP_TEST_ADMIN_URL ?? process.env.EIR_TEST_POSTGRES_URL; +test( + 'real PostgreSQL encrypted backup/restore drill preserves evidence and permissions, purges login state, rejects unsafe targets', + { + skip: + !adminUrl && + 'Set EIR_BACKUP_TEST_ADMIN_URL and PG_BIN (or install PostgreSQL clients) for the real drill.', + timeout: 120000, + }, + async (t) => { + const directory = await temporary(t); + const admin = new pg.Client({ connectionString: adminUrl }); + await admin.connect(); + const suffix = randomUUID().replaceAll('-', ''); + const sourceName = `backup_source_${suffix}`, + targetName = `backup_target_${suffix}`; + const readerRole = `backup_reader_${suffix}`; + const urlFor = (database: string) => { + const url = new URL(adminUrl!); + url.pathname = '/' + database; + return url.toString(); + }; + const source = new pg.Client({ connectionString: urlFor(sourceName) }); + t.after(async () => { + await source.end(); + await admin.query(`DROP DATABASE IF EXISTS "${sourceName}" WITH (FORCE)`); + await admin.query(`DROP DATABASE IF EXISTS "${targetName}" WITH (FORCE)`); + await admin.query(`DROP ROLE IF EXISTS "${readerRole}"`); + await admin.end(); + }); + await admin.query(`CREATE ROLE "${readerRole}" NOLOGIN`); + await admin.query(`CREATE DATABASE "${sourceName}" TEMPLATE template0`); + await admin.query(`CREATE DATABASE "${targetName}" TEMPLATE template0`); + await source.connect(); + await source.query(` + CREATE TABLE evidence (id text PRIMARY KEY, kind text NOT NULL, body jsonb NOT NULL); + CREATE TABLE audit (seq bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, body text NOT NULL, previous text NOT NULL, hash text NOT NULL); + CREATE TABLE sessions (hash text PRIMARY KEY); + CREATE TABLE login_transactions (hash text PRIMARY KEY); + GRANT SELECT ON evidence TO "${readerRole}"; + INSERT INTO sessions VALUES ('synthetic-session-hash'); + INSERT INTO login_transactions VALUES ('synthetic-login-hash'); + `); + const evidence = [ + ['signed-note', 'note', { status: 'signed', text: 'Synthetic signed note', version: 2 }], + ['order', 'medication-order', { status: 'signed', authoredBy: 'synthetic-doctor' }], + ['assignment', 'assignment', { practitionerId: 'synthetic-doctor', active: true }], + // Exceeds pipe buffers so the real --list process exercises early stdin close. + ['large-synthetic', 'test-payload', { data: randomBytes(1024 * 1024).toString('hex') }], + ]; + for (const [id, kind, body] of evidence) + await source.query('INSERT INTO evidence VALUES ($1,$2,$3)', [ + id, + kind, + JSON.stringify(body), + ]); + let previous = 'GENESIS'; + for (const action of ['note.signed', 'order.signed', 'assignment.created']) { + const body = JSON.stringify({ action, actor: 'synthetic-doctor' }); + const hash = createHash('sha256') + .update(previous + body) + .digest('hex'); + await source.query('INSERT INTO audit(body,previous,hash) VALUES ($1,$2,$3)', [ + body, + previous, + hash, + ]); + previous = hash; + } + const key = randomBytes(32), + archive = join(directory, 'recovery.eirbak'); + const backupOptions = { + databaseUrl: urlFor(sourceName), + outputPath: archive, + encryptionKey: key, + pgBin: process.env.PG_BIN, + }; + await createPostgresBackup(backupOptions); + assert.equal((await stat(archive)).mode & 0o777, 0o600); + const restoreOptions = { + databaseUrl: urlFor(targetName), + inputPath: archive, + encryptionKey: key, + confirmFreshDatabase: targetName, + sourceDatabaseUrl: urlFor(sourceName), + pgBin: process.env.PG_BIN, + temporaryDirectory: directory, + }; + const connectTarget = async () => { + const client = new pg.Client({ connectionString: urlFor(targetName) }); + await client.connect(); + return client; + }; + await assert.rejects( + restorePostgresBackup({ ...restoreOptions, encryptionKey: randomBytes(32) }), + /authentication/, + ); + assert.equal( + (await admin.query('SELECT datconnlimit FROM pg_database WHERE datname=$1', [targetName])) + .rows[0].datconnlimit, + -1, + ); + let target = await connectTarget(); + await target.query('CREATE TABLE must_not_overwrite (id integer)'); + await target.end(); + await assert.rejects(restorePostgresBackup(restoreOptions), /empty/); + target = await connectTarget(); + await target.query('DROP TABLE must_not_overwrite'); + await assert.rejects(restorePostgresBackup(restoreOptions), /active connections/); + await target.end(); + await restorePostgresBackup(restoreOptions); + target = await connectTarget(); + try { + assert.deepEqual( + (await target.query('SELECT * FROM evidence ORDER BY id')).rows, + (await source.query('SELECT * FROM evidence ORDER BY id')).rows, + ); + assert.deepEqual( + (await target.query('SELECT * FROM audit ORDER BY seq')).rows, + (await source.query('SELECT * FROM audit ORDER BY seq')).rows, + ); + assert.equal((await target.query('SELECT count(*)::int AS n FROM sessions')).rows[0].n, 0); + assert.equal( + (await target.query('SELECT count(*)::int AS n FROM login_transactions')).rows[0].n, + 0, + ); + assert.equal( + ( + await target.query('SELECT has_table_privilege($1, $2, $3) AS allowed', [ + readerRole, + 'evidence', + 'SELECT', + ]) + ).rows[0].allowed, + true, + ); + assert.equal( + (await admin.query('SELECT datconnlimit FROM pg_database WHERE datname=$1', [targetName])) + .rows[0].datconnlimit, + 0, + ); + } finally { + await target.end(); + } + await assert.rejects(restorePostgresBackup(restoreOptions), /empty/); + assert.deepEqual(await readdir(directory), ['recovery.eirbak']); + }, +); diff --git a/tests/care-team.e2e.ts b/tests/care-team.e2e.ts index 38cfede..d9df003 100644 --- a/tests/care-team.e2e.ts +++ b/tests/care-team.e2e.ts @@ -4,8 +4,7 @@ import { chromium, expect } from '@playwright/test'; import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; import { createPublicDemo } from '../apps/public-demo.ts'; - -test('care team books, checks in, signs, closes, assigns and resolves work at desktop and mobile sizes', async (t) => { +await test('care team books, checks in, signs, closes, assigns and resolves work at desktop and mobile sizes', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); const address = await app.listen({ port: 0, host: '127.0.0.1' }); @@ -13,9 +12,9 @@ test('care team books, checks in, signs, closes, assigns and resolves work at de t.after(async () => { await browser?.close(); await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); - f.runtime + await f.runtime .get('access') .grant(doctor, f.patient.id, 'nurse-a', 'clinician', '2099-01-01T00:00:00Z'); browser = await chromium.launch(); @@ -27,7 +26,7 @@ test('care team books, checks in, signs, closes, assigns and resolves work at de const errors: string[] = []; page.on('pageerror', (error) => errors.push(error.message)); await page.goto(address); - await page.getByLabel('Sessionsnyckel').fill(f.runtime.get('identity').issue!(doctor)); + await page.getByLabel('Sessionsnyckel').fill(await f.runtime.get('identity').issue!(doctor)); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); await page.getByRole('button', { name: 'Arbetslista', exact: true }).click(); await page.getByRole('button', { name: 'Boka besök', exact: true }).click(); @@ -109,8 +108,7 @@ test('care team books, checks in, signs, closes, assigns and resolves work at de await page.screenshot({ path: root + 'test-results/care-team-mobile.png', fullPage: true }); assert.deepEqual(errors, []); }); - -test('autosave recovers after reload, preserves text offline, and refuses concurrent overwrite', async (t) => { +await test('autosave recovers after reload, preserves text offline, and refuses concurrent overwrite', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); const f = await fixture(); @@ -118,13 +116,13 @@ test('autosave recovers after reload, preserves text offline, and refuses concur const address = await app.listen({ port: 0, host: '127.0.0.1' }); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); browser = await chromium.launch(); const context = await browser.newContext(), page = await context.newPage(); page.setDefaultTimeout(10000); - const token = f.runtime.get('identity').issue!(doctor); + const token = await f.runtime.get('identity').issue!(doctor); async function login() { await page.getByLabel('Sessionsnyckel').fill(token); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); @@ -153,13 +151,15 @@ test('autosave recovers after reload, preserves text offline, and refuses concur await context.setOffline(false); await page.getByRole('button', { name: 'Försök spara igen' }).click(); await expect(page.locator('.draft-status')).toContainText('Sparat'); - const note = f.store.list(doctor.tenant, f.patient.id, 'note')[0]; - f.clinical.transition(doctor, note.id, 'save', note.version, { text: 'Kollegans uppdatering' }); + const note = (await f.store.list(doctor.tenant, f.patient.id, 'note'))[0]; + await f.clinical.transition(doctor, note.id, 'save', note.version, { + text: 'Kollegans uppdatering', + }); await page.getByLabel('Journaltext', { exact: true }).fill('Mitt andra utkast'); await expect(page.locator('.draft-conflict')).toBeVisible(); await expect(page.getByLabel('Journaltext', { exact: true })).toHaveValue('Mitt andra utkast'); - assert.equal(f.store.get(doctor.tenant, note.id)?.data.text, 'Kollegans uppdatering'); - page.once('dialog', (dialog) => dialog.accept()); + assert.equal((await f.store.get(doctor.tenant, note.id))?.data.text, 'Kollegans uppdatering'); + page.once('dialog', async (dialog) => await dialog.accept()); await page.getByRole('button', { name: 'Läs in sparad version' }).click(); await expect(page.getByLabel('Journaltext', { exact: true })).toHaveValue( 'Kollegans uppdatering', @@ -167,15 +167,14 @@ test('autosave recovers after reload, preserves text offline, and refuses concur await page.getByRole('dialog').getByRole('button', { name: 'Stäng', exact: true }).click(); assert.deepEqual(await page.evaluate(() => [localStorage.length, sessionStorage.length]), [0, 0]); }); - -test('public care-team release exposes seeded worklists and working inbox on the deployed API', async (t) => { +await test('public care-team release exposes seeded worklists and working inbox on the deployed API', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); let address = process.env.EIR_DEMO_TEST_URL; if (!address) { const app = await createPublicDemo(root); address = await app.listen({ host: '127.0.0.1', port: 0 }); - t.after(() => app.close()); + t.after(async () => await app.close()); } browser = await chromium.launch(); const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); @@ -217,8 +216,7 @@ test('public care-team release exposes seeded worklists and working inbox on the await page.getByRole('button', { name: 'Logga ut', exact: true }).click(); await expect(page.locator('#login')).toBeVisible(); }); - -test('a lost create response does not duplicate a draft and closing drains newer text after an in-flight save', async (t) => { +await test('a lost create response does not duplicate a draft and closing drains newer text after an in-flight save', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); const address = await app.listen({ port: 0, host: '127.0.0.1' }); @@ -227,13 +225,13 @@ test('a lost create response does not duplicate a draft and closing drains newer // Close the browser before Fastify waits for its last in-flight chart refresh. await browser?.close(); await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); browser = await chromium.launch(); const page = await browser.newPage(); page.setDefaultTimeout(10000); await page.goto(address); - await page.getByLabel('Sessionsnyckel').fill(f.runtime.get('identity').issue!(doctor)); + await page.getByLabel('Sessionsnyckel').fill(await f.runtime.get('identity').issue!(doctor)); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); await page.getByRole('button', { name: 'Anteckningar', exact: true }).click(); await page.getByRole('button', { name: 'Ny anteckning' }).click(); @@ -247,7 +245,7 @@ test('a lost create response does not duplicate a draft and closing drains newer ); await page.getByLabel('Journaltext', { exact: true }).fill('Servern tog emot texten'); await expect(page.locator('.draft-status')).toContainText('Sparat'); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'note').length, 1); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'note')).length, 1); let release!: () => void; const gate = new Promise((resolve) => { release = resolve; @@ -271,7 +269,7 @@ test('a lost create response does not duplicate a draft and closing drains newer release(); } await expect(page.getByRole('dialog')).not.toBeVisible(); - const notes = f.store.list(doctor.tenant, f.patient.id, 'note'); + const notes = await f.store.list(doctor.tenant, f.patient.id, 'note'); assert.equal(notes.length, 1); assert.equal(notes[0].data.text, 'Senaste uppdateringen'); assert.equal(notes[0].version, 3); diff --git a/tests/care-team.test.ts b/tests/care-team.test.ts index 63546a8..1684223 100644 --- a/tests/care-team.test.ts +++ b/tests/care-team.test.ts @@ -15,162 +15,188 @@ const booking = { type: 'visit', }; const nurse = { ...doctor, id: 'nurse-a' }; - test('appointments reject provider/patient overlaps, allow adjacent slots, reschedule and retain versions', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const team = f.runtime.get('careTeam'); - f.runtime + await f.runtime .get('access') .grant(doctor, f.patient.id, nurse.id, 'clinician', '2099-01-01T00:00:00Z'); - const a = team.book(doctor, f.patient.id, booking); + const a = await team.book(doctor, f.patient.id, booking); assert.equal(a.data.startsAt, '2026-09-21T07:00:00Z'); - assert.throws(() => team.book(doctor, f.patient.id, booking), status(409)); - assert.throws( - () => team.book(doctor, f.patient.id, { ...booking, practitionerId: nurse.id }), + await assert.rejects(async () => await team.book(doctor, f.patient.id, booking), status(409)); + await assert.rejects( + async () => await team.book(doctor, f.patient.id, { ...booking, practitionerId: nurse.id }), status(409), ); - const p = f.clinical.register(doctor, { + const p = await f.clinical.register(doctor, { name: 'Other patient', birthDate: '2000-01-01', identifier: { type: 'local', value: 'OTHER' }, }); - assert.throws(() => team.book(doctor, p.id, booking), status(409)); - team.book(doctor, p.id, { ...booking, localStart: '2026-09-21T09:30' }); - const moved = team.appointment(doctor, a.id, 'reschedule', a.version, { + await assert.rejects(async () => await team.book(doctor, p.id, booking), status(409)); + await team.book(doctor, p.id, { ...booking, localStart: '2026-09-21T09:30' }); + const moved = await team.appointment(doctor, a.id, 'reschedule', a.version, { ...booking, localStart: '2026-09-21T11:00', }); - assert.throws(() => team.appointment(doctor, a.id, 'arrive', a.version, {}), status(409)); - const cancelled = team.appointment(doctor, a.id, 'cancel', moved.version, { + await assert.rejects( + async () => await team.appointment(doctor, a.id, 'arrive', a.version, {}), + status(409), + ); + const cancelled = await team.appointment(doctor, a.id, 'cancel', moved.version, { reason: 'Patienten bokar om senare', }); assert.equal(cancelled.data.status, 'cancelled'); - assert.equal(f.clinical.history(doctor, a.id).length, 3); - assert.throws(() => team.appointment(doctor, a.id, 'start', cancelled.version, {}), status(409)); - team.book(doctor, f.patient.id, { ...booking, localStart: '2026-09-21T11:00' }); + assert.equal((await f.clinical.history(doctor, a.id)).length, 3); + await assert.rejects( + async () => await team.appointment(doctor, a.id, 'start', cancelled.version, {}), + status(409), + ); + await team.book(doctor, f.patient.id, { ...booking, localStart: '2026-09-21T11:00' }); }); - test('clinic time is independent of server/browser zone and rejects invalid/ambiguous daylight-saving times', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const team = f.runtime.get('careTeam'); for (const localStart of ['2026-03-29T02:30', '2026-10-25T02:30', '2026-02-30T10:00']) { - assert.throws(() => team.book(doctor, f.patient.id, { ...booking, localStart }), status(422)); + await assert.rejects( + async () => await team.book(doctor, f.patient.id, { ...booking, localStart }), + status(422), + ); } - const winter = team.book(doctor, f.patient.id, { ...booking, localStart: '2026-12-01T09:00' }); + const winter = await team.book(doctor, f.patient.id, { + ...booking, + localStart: '2026-12-01T09:00', + }); assert.equal(winter.data.startsAt, '2026-12-01T08:00:00Z'); - const overnight = team.book(doctor, f.patient.id, { ...booking, localStart: '2026-09-21T23:50' }); - assert(team.workspace(doctor, '2026-09-22').appointments.some((r) => r.id === overnight.id)); - assert.throws(() => team.appointment(doctor, winter.id, 'no-show', 1, {})); + const overnight = await team.book(doctor, f.patient.id, { + ...booking, + localStart: '2026-09-21T23:50', + }); + assert( + (await team.workspace(doctor, '2026-09-22')).appointments.some((r) => r.id === overnight.id), + ); + await assert.rejects(async () => await team.appointment(doctor, winter.id, 'no-show', 1, {})); }); - test('check-in/start links an encounter; signing and closing completes the booking atomically', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const team = f.runtime.get('careTeam'); - const a = team.book(doctor, f.patient.id, booking); - const arrived = team.appointment(doctor, a.id, 'arrive', 1, {}); - const started = team.appointment(doctor, a.id, 'start', arrived.version, {}); + const a = await team.book(doctor, f.patient.id, booking); + const arrived = await team.appointment(doctor, a.id, 'arrive', 1, {}); + const started = await team.appointment(doctor, a.id, 'start', arrived.version, {}); assert.equal(started.data.encounterId, f.encounter.id); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Anteckning', }); - assert.throws(() => f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), status(409)); - assert.equal(f.store.get(doctor.tenant, a.id)?.data.status, 'in-progress'); - f.clinical.transition(doctor, note.id, 'sign', 1, {}); - f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}); - assert.equal(f.store.get(doctor.tenant, a.id)?.data.status, 'completed'); - const b = team.book(doctor, f.patient.id, { ...booking, localStart: '2026-09-22T09:00' }); - const next = team.appointment(doctor, b.id, 'start', 1, {}); + await assert.rejects( + async () => await f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), + status(409), + ); + assert.equal((await f.store.get(doctor.tenant, a.id))?.data.status, 'in-progress'); + await f.clinical.transition(doctor, note.id, 'sign', 1, {}); + await f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}); + assert.equal((await f.store.get(doctor.tenant, a.id))?.data.status, 'completed'); + const b = await team.book(doctor, f.patient.id, { ...booking, localStart: '2026-09-22T09:00' }); + const next = await team.appointment(doctor, b.id, 'start', 1, {}); assert.notEqual(next.data.encounterId, f.encounter.id); - assert.equal(f.store.get(doctor.tenant, next.data.encounterId)?.data.status, 'in-progress'); + assert.equal( + (await f.store.get(doctor.tenant, next.data.encounterId))?.data.status, + 'in-progress', + ); }); - test('task handover requires a known colleague with active access; only current owner completes', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); - const row = f.clinical.create(doctor, f.patient.id, 'task', { + t.after(async () => await f.runtime.stop()); + const row = await f.clinical.create(doctor, f.patient.id, 'task', { title: 'Ring patienten', due: '2026-09-20', }); assert.equal(row.data.assigneeId, doctor.id); - assert.throws( - () => - f.clinical.transition(doctor, row.id, 'assign', 1, { + await assert.rejects( + async () => + await f.clinical.transition(doctor, row.id, 'assign', 1, { assigneeId: nurse.id, reason: 'Överlämning', }), status(403), ); - assert.throws( - () => - f.clinical.transition(doctor, row.id, 'assign', 1, { + await assert.rejects( + async () => + await f.clinical.transition(doctor, row.id, 'assign', 1, { assigneeId: 'doctor-b', reason: 'Överlämning', }), status(422), ); - f.runtime + await f.runtime .get('access') .grant(doctor, f.patient.id, nurse.id, 'clinician', '2099-01-01T00:00:00Z'); - const assigned = f.clinical.transition(doctor, row.id, 'assign', 1, { + const assigned = await f.clinical.transition(doctor, row.id, 'assign', 1, { assigneeId: nurse.id, reason: 'Frånvarotäckning', }); - assert.throws( - () => f.clinical.transition(doctor, row.id, 'complete', assigned.version, {}), + await assert.rejects( + async () => await f.clinical.transition(doctor, row.id, 'complete', assigned.version, {}), status(403), ); - const started = f.clinical.transition(nurse, row.id, 'start', assigned.version, {}); - const done = f.clinical.transition(nurse, row.id, 'complete', started.version, { + const started = await f.clinical.transition(nurse, row.id, 'start', assigned.version, {}); + const done = await f.clinical.transition(nurse, row.id, 'complete', started.version, { resolution: 'Patienten kontaktad', }); assert.equal(done.data.completedBy, nurse.id); - assert.throws( - () => f.clinical.transition(nurse, row.id, 'complete', started.version, {}), + await assert.rejects( + async () => await f.clinical.transition(nurse, row.id, 'complete', started.version, {}), status(409), ); - const reopened = f.clinical.transition(doctor, row.id, 'reopen', done.version, { + const reopened = await f.clinical.transition(doctor, row.id, 'reopen', done.version, { reason: 'Ny uppföljning behövs', }); assert.equal(reopened.data.status, 'requested'); assert.equal(reopened.data.completedBy, undefined); - const moved = f.clinical.transition(doctor, row.id, 'reschedule', reopened.version, { + const moved = await f.clinical.transition(doctor, row.id, 'reschedule', reopened.version, { due: '2026-09-22', reason: 'Överenskommet', }); assert.equal(moved.data.due, '2026-09-22'); - assert.equal(f.clinical.history(doctor, row.id).length, 6); + assert.equal((await f.clinical.history(doctor, row.id)).length, 6); }); - test('workspace, patient chart/history/change feed cannot disclose internal work or other tenants', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); const team = f.runtime.get('careTeam'); - const a = team.book(doctor, f.patient.id, booking); - const task = team.createTask(doctor, f.patient.id, { + const a = await team.book(doctor, f.patient.id, booking); + const task = await team.createTask(doctor, f.patient.id, { title: 'Internal follow-up', due: '2026-09-21', }); - assert.equal(team.workspace(doctor, '2026-09-21').appointments.length, 1); - assert.equal(team.workspace({ ...doctor, id: 'unassigned' }, '2026-09-21').tasks.length, 0); - assert.equal(team.workspace({ ...doctor, tenant: 'other' }, '2026-09-21').appointments.length, 0); + assert.equal((await team.workspace(doctor, '2026-09-21')).appointments.length, 1); + assert.equal( + (await team.workspace({ ...doctor, id: 'unassigned' }, '2026-09-21')).tasks.length, + 0, + ); + assert.equal( + (await team.workspace({ ...doctor, tenant: 'other' }, '2026-09-21')).appointments.length, + 0, + ); const self = { id: 'self', tenant: doctor.tenant, role: 'patient' as const, patientId: f.patient.id, }; - assert.throws(() => team.workspace(self, '2026-09-21'), status(403)); - assert.equal(f.clinical.history(self, task.id).length, 0); - assert(!f.clinical.chart(self, f.patient.id).some((r) => r.id === a.id || r.id === task.id)); - const token = f.runtime.get('identity').issue!(self); + await assert.rejects(async () => await team.workspace(self, '2026-09-21'), status(403)); + assert.equal((await f.clinical.history(self, task.id)).length, 0); + assert( + !(await f.clinical.chart(self, f.patient.id)).some((r) => r.id === a.id || r.id === task.id), + ); + const token = await f.runtime.get('identity').issue!(self); const response = await app.inject({ url: `/api/patients/${f.patient.id}/changes`, headers: { authorization: `Bearer ${token}` }, @@ -178,56 +204,89 @@ test('workspace, patient chart/history/change feed cannot disclose internal work assert( !response.json().entries.some((r: any) => ['task', 'appointment'].includes(r.record.kind)), ); - f.runtime.get('access').block(self, f.patient.id, true); - assert.equal(team.workspace(doctor, '2026-09-21').appointments.length, 0); - assert.throws(() => team.appointment(doctor, a.id, 'arrive', 1, {}), status(403)); - assert(f.store.auditEntries(doctor.tenant).some((r) => r.outcome === 'denied')); + await f.runtime.get('access').block(self, f.patient.id, true); + assert.equal((await team.workspace(doctor, '2026-09-21')).appointments.length, 0); + await assert.rejects( + async () => await team.appointment(doctor, a.id, 'arrive', 1, {}), + status(403), + ); + assert((await f.store.auditEntries(doctor.tenant)).some((r) => r.outcome === 'denied')); }); - test('draft retry is idempotent and never overwrites another version or signed text', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const input = { encounterId: f.encounter.id, clientId: randomUUID(), text: 'Recovered draft' }; - const note = f.clinical.create(doctor, f.patient.id, 'note', input); - assert.equal(f.clinical.create(doctor, f.patient.id, 'note', input).id, note.id); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'note').length, 1); - assert.throws( - () => f.clinical.create(doctor, f.patient.id, 'note', { ...input, text: 'Other' }), + const note = await f.clinical.create(doctor, f.patient.id, 'note', input); + assert.equal((await f.clinical.create(doctor, f.patient.id, 'note', input)).id, note.id); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'note')).length, 1); + await assert.rejects( + async () => await f.clinical.create(doctor, f.patient.id, 'note', { ...input, text: 'Other' }), + status(409), + ); + await f.clinical.transition(doctor, note.id, 'sign', 1, {}); + await assert.rejects( + async () => await f.clinical.create(doctor, f.patient.id, 'note', input), status(409), ); - f.clinical.transition(doctor, note.id, 'sign', 1, {}); - assert.throws(() => f.clinical.create(doctor, f.patient.id, 'note', input), status(409)); }); - test('booking/task/draft state survives restart and encounter completion rolls back on audit failure', async (t) => { const dir = mkdtempSync(tmpdir() + '/eir-team-'); t.after(() => rmSync(dir, { recursive: true, force: true })); const path = dir + '/ehr.sqlite'; const f = await fixture(path); const team = f.runtime.get('careTeam'); - const a = team.book(doctor, f.patient.id, booking); - team.appointment(doctor, a.id, 'start', 1, {}); + const a = await team.book(doctor, f.patient.id, booking); + await team.appointment(doctor, a.id, 'start', 1, {}); f.store.db.exec( "CREATE TRIGGER fail_booking_audit BEFORE INSERT ON audit WHEN json_extract(NEW.body,'$.action')='appointment.completed' BEGIN SELECT RAISE(ABORT,'audit failure'); END", ); - assert.throws( - () => f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), + await assert.rejects( + async () => await f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), /audit failure/, ); - assert.equal(f.store.get(doctor.tenant, f.encounter.id)?.data.status, 'in-progress'); - const task = team.createTask(doctor, f.patient.id, { + assert.equal((await f.store.get(doctor.tenant, f.encounter.id))?.data.status, 'in-progress'); + const task = await team.createTask(doctor, f.patient.id, { title: 'Persistent task', due: '2026-09-21', }); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Server-side draft', }); - f.runtime.stop(); + await f.runtime.stop(); const store = new SqliteStore(path); - t.after(() => store.db.close()); - assert.equal(store.get(doctor.tenant, a.id)?.data.status, 'in-progress'); - assert.equal(store.get(doctor.tenant, task.id)?.data.assigneeId, doctor.id); - assert.equal(store.get(doctor.tenant, note.id)?.data.text, 'Server-side draft'); - assert(store.verifyAudit().ok); + t.after(() => store.close()); + assert.equal((await store.get(doctor.tenant, a.id))?.data.status, 'in-progress'); + assert.equal((await store.get(doctor.tenant, task.id))?.data.assigneeId, doctor.id); + assert.equal((await store.get(doctor.tenant, note.id))?.data.text, 'Server-side draft'); + assert((await store.verifyAudit()).ok); +}); + +test('concurrent bookings and appointment starts preserve overlap and encounter ownership', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const team = f.runtime.get('careTeam'); + const bookings = await Promise.allSettled([ + team.book(doctor, f.patient.id, booking), + team.book(doctor, f.patient.id, booking), + ]); + assert.equal(bookings.filter((r) => r.status === 'fulfilled').length, 1); + assert.equal(bookings.find((r) => r.status === 'rejected')?.reason.status, 409); + const first = (await f.store.list(doctor.tenant, f.patient.id, 'appointment'))[0]; + const second = await team.book(doctor, f.patient.id, { + ...booking, + localStart: '2026-09-22T09:00', + }); + const starts = await Promise.allSettled([ + team.appointment(doctor, first.id, 'start', 1, {}), + team.appointment(doctor, second.id, 'start', 1, {}), + ]); + assert.equal(starts.filter((r) => r.status === 'fulfilled').length, 1); + assert.equal(starts.find((r) => r.status === 'rejected')?.reason.status, 409); + const active = (await f.store.list(doctor.tenant, f.patient.id, 'appointment')).filter( + (r) => r.data.status === 'in-progress', + ); + assert.equal(active.length, 1); + assert.equal(active[0].data.encounterId, f.encounter.id); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'encounter')).length, 1); }); diff --git a/tests/clinical.test.ts b/tests/clinical.test.ts index bd5330d..b44c909 100644 --- a/tests/clinical.test.ts +++ b/tests/clinical.test.ts @@ -5,68 +5,70 @@ import { tmpdir } from 'node:os'; import { fixture, doctor } from './helpers.ts'; import { SqliteStore } from '../plugins/storage-sqlite.ts'; const status = (code: number) => (error: any) => error.status === code; - test('draft/save/sign/immutable/amend lifecycle with optimistic concurrency', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + t.after(async () => await f.runtime.stop()); + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Original', }); - const revised = f.clinical.transition(doctor, note.id, 'save', 1, { text: 'Reviewed' }); - assert.throws( - () => f.clinical.transition(doctor, note.id, 'save', 1, { text: 'Lost update' }), + const revised = await f.clinical.transition(doctor, note.id, 'save', 1, { text: 'Reviewed' }); + await assert.rejects( + async () => await f.clinical.transition(doctor, note.id, 'save', 1, { text: 'Lost update' }), status(409), ); - const signed = f.clinical.transition(doctor, note.id, 'sign', revised.version, {}); + const signed = await f.clinical.transition(doctor, note.id, 'sign', revised.version, {}); assert.equal(signed.data.signedBy, doctor.id); - assert.throws( - () => f.clinical.transition(doctor, note.id, 'save', 3, { text: 'Overwrite' }), + await assert.rejects( + async () => await f.clinical.transition(doctor, note.id, 'save', 3, { text: 'Overwrite' }), status(409), ); assert.throws( () => f.store.db.prepare('UPDATE entities SET data=? WHERE id=?').run('{}', note.id), /immutable/, ); - const amendment = f.clinical.transition(doctor, note.id, 'amend', 3, { + const amendment = await f.clinical.transition(doctor, note.id, 'amend', 3, { text: 'Correction', reason: 'New information', }); assert.equal(amendment.data.amends, note.id); assert.equal(amendment.data.status, 'draft'); - assert.equal(f.store.get(doctor.tenant, note.id)?.data.text, 'Reviewed'); - assert.equal(f.clinical.history(doctor, note.id).length, 3); + assert.equal((await f.store.get(doctor.tenant, note.id))?.data.text, 'Reviewed'); + assert.equal((await f.clinical.history(doctor, note.id)).length, 3); }); test('encounters require signed notes before close and enforce patient reference integrity', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); - assert.throws( - () => f.clinical.create(doctor, f.patient.id, 'encounter', { reason: 'Duplicate' }), + t.after(async () => await f.runtime.stop()); + await assert.rejects( + async () => await f.clinical.create(doctor, f.patient.id, 'encounter', { reason: 'Duplicate' }), status(409), ); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Draft', }); - assert.throws(() => f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), status(409)); - f.clinical.transition(doctor, note.id, 'sign', 1, {}); - f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}); - assert.throws( - () => - f.clinical.create(doctor, f.patient.id, 'note', { + await assert.rejects( + async () => await f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), + status(409), + ); + await f.clinical.transition(doctor, note.id, 'sign', 1, {}); + await f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}); + await assert.rejects( + async () => + await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Late', }), status(409), ); - const other = f.clinical.register(doctor, { + const other = await f.clinical.register(doctor, { name: 'Other', birthDate: '1980-01-01', identifier: { type: 'local', value: 'TEST-002' }, }); - assert.throws( - () => - f.clinical.create(doctor, other.id, 'note', { + await assert.rejects( + async () => + await f.clinical.create(doctor, other.id, 'note', { encounterId: f.encounter.id, text: 'Wrong patient', }), @@ -75,7 +77,7 @@ test('encounters require signed notes before close and enforce patient reference }); test('quantities enforce code/unit/value contracts and preserve correction history', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const input = { encounterId: f.encounter.id, code: '8310-5', @@ -83,47 +85,115 @@ test('quantities enforce code/unit/value contracts and preserve correction histo unit: 'Cel', effectiveAt: new Date().toISOString(), }; - assert.throws( - () => f.clinical.create(doctor, f.patient.id, 'observation', { ...input, unit: 'kg' }), + await assert.rejects( + async () => + await f.clinical.create(doctor, f.patient.id, 'observation', { ...input, unit: 'kg' }), status(422), ); - const o = f.clinical.create(doctor, f.patient.id, 'observation', input); - f.clinical.transition(doctor, o.id, 'correct', 1, { reason: 'Wrong measurement' }); - assert.equal(f.store.get(doctor.tenant, o.id)?.data.status, 'entered-in-error'); - assert.equal(f.clinical.history(doctor, o.id)[0].data.value, 37); + const o = await f.clinical.create(doctor, f.patient.id, 'observation', input); + await f.clinical.transition(doctor, o.id, 'correct', 1, { reason: 'Wrong measurement' }); + assert.equal((await f.store.get(doctor.tenant, o.id))?.data.status, 'entered-in-error'); + assert.equal((await f.clinical.history(doctor, o.id))[0].data.value, 37); }); test('records and audit survive restart; audit failure rolls back a clinical write', async (t) => { const dir = mkdtempSync(tmpdir() + '/eir-test-'); t.after(() => rmSync(dir, { recursive: true, force: true })); const path = dir + '/ehr.sqlite'; const f = await fixture(path); - const before = f.store.list(doctor.tenant).length; + const before = (await f.store.list(doctor.tenant)).length; f.store.db.exec( "CREATE TRIGGER fail_audit BEFORE INSERT ON audit WHEN json_extract(NEW.body,'$.action')='task.created' BEGIN SELECT RAISE(ABORT,'disk-like failure'); END", ); - assert.throws( - () => f.clinical.create(doctor, f.patient.id, 'task', { title: 'Rollback', due: '2027-01-01' }), + await assert.rejects( + async () => + await f.clinical.create(doctor, f.patient.id, 'task', { + title: 'Rollback', + due: '2027-01-01', + }), /disk-like/, ); - assert.equal(f.store.list(doctor.tenant).length, before); - f.runtime.stop(); + assert.equal((await f.store.list(doctor.tenant)).length, before); + await f.runtime.stop(); const reopened = new SqliteStore(path); - t.after(() => reopened.db.close()); - assert.equal(reopened.get(doctor.tenant, f.patient.id)?.data.name, 'Syntetisk Patient'); - assert.equal(reopened.verifyAudit().ok, true); + t.after(() => reopened.close()); + assert.equal((await reopened.get(doctor.tenant, f.patient.id))?.data.name, 'Syntetisk Patient'); + assert.equal((await reopened.verifyAudit()).ok, true); assert.throws(() => reopened.db.exec("UPDATE audit SET hash='tampered'"), /append-only/); }); test('duplicate identifiers rejected without adding a second patient', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); - assert.throws( - () => - f.clinical.register(doctor, { + t.after(async () => await f.runtime.stop()); + await assert.rejects( + async () => + await f.clinical.register(doctor, { name: 'Duplicate', birthDate: '1980-01-01', identifier: { type: 'local', value: 'TEST-001' }, }), status(409), ); - assert.equal(f.clinical.patients(doctor).length, 1); + assert.equal((await f.clinical.patients(doctor)).length, 1); +}); + +test('concurrent encounter closure and note creation cannot leave a draft in a closed encounter', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const outcomes = await Promise.allSettled([ + f.clinical.transition(doctor, f.encounter.id, 'close', 1, {}), + f.clinical.create(doctor, f.patient.id, 'note', { + encounterId: f.encounter.id, + text: 'Concurrent draft', + }), + ]); + assert.equal(outcomes.filter((r) => r.status === 'fulfilled').length, 1); + const rejected = outcomes.find((r) => r.status === 'rejected'); + assert.equal(rejected?.reason.status, 409); + const encounter = await f.store.get(doctor.tenant, f.encounter.id); + const notes = await f.store.list(doctor.tenant, f.patient.id, 'note'); + assert.equal(notes.length, encounter?.data.status === 'finished' ? 0 : 1); + assert.equal((await f.store.verifyAudit()).ok, true); +}); + +test('async access preserves note author restrictions and signature provenance', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const access = f.runtime.get('access'); + const colleague = { ...doctor, id: 'nurse-a' }; + await access.grant(doctor, f.patient.id, colleague.id, 'clinician', '2099-01-01T00:00:00Z'); + access.context = async () => ({ + permissions: ['record.write', 'note.sign'], + unitId: 'unit-a', + name: 'Unit A', + }); + const signer = { + ...doctor, + assignmentId: 'assignment-a', + unitId: 'unit-a', + authentication: { + method: 'oidc' as const, + issuer: 'https://identity.example', + subject: doctor.id, + authenticatedAt: 1, + acr: 'test-mfa', + }, + }; + const note = await f.clinical.create(signer, f.patient.id, 'note', { + encounterId: f.encounter.id, + text: 'Author-owned draft', + }); + await assert.rejects( + () => f.clinical.transition(colleague, note.id, 'save', 1, { text: 'Other author' }), + status(403), + ); + await assert.rejects(() => f.clinical.transition(colleague, note.id, 'sign', 1, {}), status(403)); + const signed = await f.clinical.transition(signer, note.id, 'sign', 1, {}); + assert.equal(signed.data.author, doctor.id); + assert.equal(signed.data.signedBy, doctor.id); + assert.deepEqual(signed.data.signedUnder, { + assignmentId: 'assignment-a', + unitId: 'unit-a', + authentication: 'oidc', + acr: 'test-mfa', + }); + assert.equal((await f.clinical.history(signer, note.id)).length, 2); }); diff --git a/tests/helpers.ts b/tests/helpers.ts index 9669075..253b67f 100644 --- a/tests/helpers.ts +++ b/tests/helpers.ts @@ -17,11 +17,13 @@ export async function fixture(path = ':memory:') { }); const clinical = runtime.get('clinical'), store = runtime.get('store') as SqliteStore; - const patient = clinical.register(doctor, { + const patient = await clinical.register(doctor, { name: 'Syntetisk Patient', birthDate: '1985-03-12', identifier: { type: 'local', value: 'TEST-001' }, }); - const encounter = clinical.create(doctor, patient.id, 'encounter', { reason: 'Testkontakt' }); + const encounter = await clinical.create(doctor, patient.id, 'encounter', { + reason: 'Testkontakt', + }); return { runtime, clinical, store, patient, encounter }; } diff --git a/tests/integration.test.ts b/tests/integration.test.ts index 5741d0a..304919f 100644 --- a/tests/integration.test.ts +++ b/tests/integration.test.ts @@ -1,24 +1,24 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { AsyncLocalStorage } from 'node:async_hooks'; import { backup, DatabaseSync } from 'node:sqlite'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; - test('change feed resumes without duplicates and never reveals patient-hidden versions', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); - const token = f.runtime.get('identity').issue!(doctor); + const token = await f.runtime.get('identity').issue!(doctor); const headers = { authorization: `Bearer ${token}` }; const path = `/api/patients/${f.patient.id}/changes`; const initial = (await app.inject({ url: path, headers })).json(); assert.equal(initial.entries.length, 2); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + const note = await f.clinical.create(doctor, f.patient.id, 'note', { text: 'Unreleased draft', encounterId: f.encounter.id, }); @@ -29,7 +29,7 @@ test('change feed resumes without duplicates and never reveals patient-hidden ve (await app.inject({ url: path + '?after=' + next.nextCursor, headers })).json().entries.length, 0, ); - const self = f.runtime.get('identity').issue!({ + const self = await f.runtime.get('identity').issue!({ id: 'self', tenant: doctor.tenant, role: 'patient', @@ -48,11 +48,97 @@ test('change feed resumes without duplicates and never reveals patient-hidden ve 6, ); }); + +test('clinical read services share authorization, records and audit in one transaction', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const team = f.runtime.get('careTeam'); + const task = await team.createTask(doctor, f.patient.id, { + title: 'Read scope', + due: '2026-09-21', + }); + const context = new AsyncLocalStorage(); + const reads = new Set(); + const checks = new Set(); + const audits = new Set(); + const transaction = f.store.transaction.bind(f.store); + f.store.transaction = (fn) => transaction(() => context.run(context.getStore() ?? {}, fn)); + const access = f.runtime.get('access'); + const check = access.check.bind(access); + access.check = async (...args) => { + await check(...args); + const scope = context.getStore(); + if (scope) checks.add(scope); + }; + const list = f.store.list.bind(f.store); + f.store.list = async (...args) => { + const scope = context.getStore(); + assert(scope, 'Record lists must be read inside the service transaction'); + reads.add(scope); + return await list(...args); + }; + const history = f.store.history.bind(f.store); + f.store.history = async (...args) => { + const scope = context.getStore(); + assert(scope, 'History must be read inside the service transaction'); + reads.add(scope); + return await history(...args); + }; + const audit = f.store.audit.bind(f.store); + f.store.audit = async (...args) => { + const scope = context.getStore(); + if (scope) audits.add(scope); + await audit(...args); + }; + const services = [ + () => f.clinical.patients(doctor), + () => f.clinical.chart(doctor, f.patient.id), + () => f.clinical.history(doctor, task.id), + () => f.runtime.get('fhir').bundle(doctor, f.patient.id), + () => f.runtime.get('medications').list(doctor, f.patient.id), + () => team.workspace(doctor, '2026-09-21'), + ]; + for (const read of services) { + reads.clear(); + checks.clear(); + audits.clear(); + await read(); + assert.equal(reads.size, 1); + const [scope] = reads; + assert(checks.has(scope), 'Authorization must use the same transaction as the records'); + assert(audits.has(scope), 'Read audit must use the same transaction as the records'); + } +}); + +test('read services recheck authorization when access is revoked after preflight', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const access = f.runtime.get('access'); + const check = access.check.bind(access); + const services = [ + () => f.clinical.chart(doctor, f.patient.id), + () => f.clinical.history(doctor, f.encounter.id), + () => f.runtime.get('fhir').bundle(doctor, f.patient.id), + () => f.runtime.get('medications').list(doctor, f.patient.id), + ]; + for (const read of services) { + await f.store.restrict(doctor.tenant, f.patient.id, false); + let revoke = true; + access.check = async (...args) => { + await check(...args); + if (revoke) { + revoke = false; + await f.store.restrict(doctor.tenant, f.patient.id, true); + } + }; + await assert.rejects(read, (error: any) => error.status === 403); + } +}); test('online backup produces a restorable consistent clinical snapshot', async (t) => { const dir = mkdtempSync(tmpdir() + '/eir-backup-'); t.after(() => rmSync(dir, { recursive: true, force: true })); const f = await fixture(dir + '/live.sqlite'); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); await backup(f.store.db, dir + '/backup.sqlite'); const restored = new DatabaseSync(dir + '/backup.sqlite', { readOnly: true }); t.after(() => restored.close()); diff --git a/tests/medication-results.e2e.ts b/tests/medication-results.e2e.ts index 46a94f2..b2aa8b4 100644 --- a/tests/medication-results.e2e.ts +++ b/tests/medication-results.e2e.ts @@ -4,8 +4,7 @@ import { chromium, expect } from '@playwright/test'; import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; import { createPublicDemo } from '../apps/public-demo.ts'; - -test('clinician reconciles medicines, records critical results, reviews and handles a corrected report', async (t) => { +await test('clinician reconciles medicines, records critical results, reviews and handles a corrected report', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); const f = await fixture(), @@ -13,7 +12,7 @@ test('clinician reconciles medicines, records critical results, reviews and hand const address = await app.listen({ host: '127.0.0.1', port: 0 }); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); browser = await chromium.launch(); const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); @@ -21,7 +20,7 @@ test('clinician reconciles medicines, records critical results, reviews and hand const errors: string[] = []; page.on('pageerror', (error) => errors.push(error.message)); await page.goto(address); - await page.getByLabel('Sessionsnyckel').fill(f.runtime.get('identity').issue!(doctor)); + await page.getByLabel('Sessionsnyckel').fill(await f.runtime.get('identity').issue!(doctor)); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); await page.getByRole('button', { name: 'Läkemedel', exact: true }).click(); await expect(page.getByText('Inte avstämd', { exact: true })).toBeVisible(); @@ -116,18 +115,17 @@ test('clinician reconciles medicines, records critical results, reviews and hand await expect(page.locator('.task-row')).toHaveCount(0); await page.getByLabel('Status', { exact: true }).selectOption('closed'); await expect(page.locator('.task-row')).toHaveCount(1); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labReview').length, 2); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReview')).length, 2); assert.deepEqual(errors, []); }); - -test('public medication and lab release exposes seeded data and completes result review', async (t) => { +await test('public medication and lab release exposes seeded data and completes result review', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); let address = process.env.EIR_DEMO_TEST_URL; if (!address) { const app = await createPublicDemo(root); address = await app.listen({ host: '127.0.0.1', port: 0 }); - t.after(() => app.close()); + t.after(async () => await app.close()); } browser = await chromium.launch(); const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); diff --git a/tests/medication-results.test.ts b/tests/medication-results.test.ts index 7907825..c1223d5 100644 --- a/tests/medication-results.test.ts +++ b/tests/medication-results.test.ts @@ -6,7 +6,6 @@ import { tmpdir } from 'node:os'; import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; import { fromConfig } from '../packages/runtime.ts'; - const fails = (status: number) => (error: any) => error.status === status; const med = () => ({ clientId: randomUUID(), @@ -50,16 +49,18 @@ const reviewInput = (reportId: string, taskVersion: number) => ({ communication: 'Patient contacted', criticalAcknowledged: true, }); - test('medication reconciliation snapshots medicines and allergies, rejects stale reviews and preserves history', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const meds = f.runtime.get('medications'), input = med(); - const added = meds.add(doctor, f.patient.id, input); - assert.equal(meds.add(doctor, f.patient.id, input).id, added.id); - assert.throws(() => meds.add(doctor, f.patient.id, { ...input, name: 'Different' }), fails(409)); - const state = meds.list(doctor, f.patient.id); + const added = await meds.add(doctor, f.patient.id, input); + assert.equal((await meds.add(doctor, f.patient.id, input)).id, added.id); + await assert.rejects( + async () => await meds.add(doctor, f.patient.id, { ...input, name: 'Different' }), + fails(409), + ); + const state = await meds.list(doctor, f.patient.id); const check = { clientId: randomUUID(), snapshot: state.snapshot, @@ -68,51 +69,57 @@ test('medication reconciliation snapshots medicines and allergies, rejects stale confirmed: true, noCurrentMedicines: false, }; - const review = meds.reconcile(doctor, f.patient.id, check); - assert.equal(meds.reconcile(doctor, f.patient.id, check).id, review.id); - assert.equal(meds.list(doctor, f.patient.id).current, true); + const review = await meds.reconcile(doctor, f.patient.id, check); + assert.equal((await meds.reconcile(doctor, f.patient.id, check)).id, review.id); + assert.equal((await meds.list(doctor, f.patient.id)).current, true); const { clientId, ...fields } = input; - const updated = meds.update(doctor, added.id, 1, { + const updated = await meds.update(doctor, added.id, 1, { ...fields, status: 'on-hold', reason: 'Patient reports temporary interruption', }); assert.equal(updated.version, 2); - assert.throws( - () => meds.update(doctor, added.id, 1, { ...fields, reason: 'Stale edit' }), + await assert.rejects( + async () => await meds.update(doctor, added.id, 1, { ...fields, reason: 'Stale edit' }), fails(409), ); - assert.equal(meds.list(doctor, f.patient.id).current, false); - assert.throws( - () => meds.reconcile(doctor, f.patient.id, { ...check, clientId: randomUUID() }), + assert.equal((await meds.list(doctor, f.patient.id)).current, false); + await assert.rejects( + async () => await meds.reconcile(doctor, f.patient.id, { ...check, clientId: randomUUID() }), fails(409), ); - const snap = meds.list(doctor, f.patient.id).snapshot; - f.clinical.create(doctor, f.patient.id, 'allergy', { + const snap = (await meds.list(doctor, f.patient.id)).snapshot; + await f.clinical.create(doctor, f.patient.id, 'allergy', { substance: 'Test', reaction: 'Reported reaction', criticality: 'unable-to-assess', }); - assert.throws( - () => - meds.reconcile(doctor, f.patient.id, { ...check, clientId: randomUUID(), snapshot: snap }), + await assert.rejects( + async () => + await meds.reconcile(doctor, f.patient.id, { + ...check, + clientId: randomUUID(), + snapshot: snap, + }), fails(409), ); - meds.reconcile(doctor, f.patient.id, { + await meds.reconcile(doctor, f.patient.id, { ...check, clientId: randomUUID(), - snapshot: meds.list(doctor, f.patient.id).snapshot, + snapshot: (await meds.list(doctor, f.patient.id)).snapshot, }); - assert.equal(meds.list(doctor, f.patient.id).review?.data.reviewNumber, 2); - assert.equal(f.clinical.history(doctor, added.id)[0].data.status, 'active'); - assert.throws(() => f.clinical.transition(doctor, review.id, 'save', 1, {}), fails(422)); + assert.equal((await meds.list(doctor, f.patient.id)).review?.data.reviewNumber, 2); + assert.equal((await f.clinical.history(doctor, added.id))[0].data.status, 'active'); + await assert.rejects( + async () => await f.clinical.transition(doctor, review.id, 'save', 1, {}), + fails(422), + ); }); - test('absence of medication entries is unknown until explicitly reconciled; voided entries cannot be restored', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const meds = f.runtime.get('medications'); - assert.equal(meds.list(doctor, f.patient.id).current, false); + assert.equal((await meds.list(doctor, f.patient.id)).current, false); const data = { clientId: randomUUID(), snapshot: [], @@ -121,206 +128,244 @@ test('absence of medication entries is unknown until explicitly reconciled; void confirmed: true, noCurrentMedicines: false, }; - assert.throws(() => meds.reconcile(doctor, f.patient.id, data), fails(422)); - meds.reconcile(doctor, f.patient.id, { ...data, noCurrentMedicines: true }); - assert.equal(meds.list(doctor, f.patient.id).current, true); + await assert.rejects(async () => await meds.reconcile(doctor, f.patient.id, data), fails(422)); + await meds.reconcile(doctor, f.patient.id, { ...data, noCurrentMedicines: true }); + assert.equal((await meds.list(doctor, f.patient.id)).current, true); const input = med(), - r = meds.add(doctor, f.patient.id, input); + r = await meds.add(doctor, f.patient.id, input); const { clientId, ...fields } = input; - meds.update(doctor, r.id, 1, { + await meds.update(doctor, r.id, 1, { ...fields, status: 'entered-in-error', reason: 'Wrong statement', }); - assert.throws(() => meds.update(doctor, r.id, 2, { ...fields, reason: 'Restore' }), fails(409)); - assert.equal(meds.list(doctor, f.patient.id).current, false); + await assert.rejects( + async () => await meds.update(doctor, r.id, 2, { ...fields, reason: 'Restore' }), + fails(409), + ); + assert.equal((await meds.list(doctor, f.patient.id)).current, false); }); - test('orders create owned follow-up atomically; source message retries are idempotent and cannot replace content', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const labs = f.runtime.get('laboratories'); const input = orderInput(f.encounter.id), - order = labs.order(doctor, f.patient.id, input); - assert.equal(labs.order(doctor, f.patient.id, input).id, order.id); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'task').length, 1); + order = await labs.order(doctor, f.patient.id, input); + assert.equal((await labs.order(doctor, f.patient.id, input)).id, order.id); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'task')).length, 1); const reportData = reportInput(), - report = labs.receive(doctor, order.id, 1, reportData); - assert.equal(labs.receive(doctor, order.id, 1, reportData).id, report.id); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labReport').length, 1); - assert.throws( - () => - labs.receive(doctor, order.id, 2, { + report = await labs.receive(doctor, order.id, 1, reportData); + assert.equal((await labs.receive(doctor, order.id, 1, reportData)).id, report.id); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReport')).length, 1); + await assert.rejects( + async () => + await labs.receive(doctor, order.id, 2, { ...reportData, results: [{ ...reportData.results[0], value: '8' }], }), fails(409), ); - assert.throws(() => labs.receive(doctor, order.id, 2, reportInput()), fails(422)); - const task = f.store.list(doctor.tenant, f.patient.id, 'task')[0]; + await assert.rejects( + async () => await labs.receive(doctor, order.id, 2, reportInput()), + fails(422), + ); + const task = (await f.store.list(doctor.tenant, f.patient.id, 'task'))[0]; assert.equal(task.data.priority, 'urgent'); for (const action of ['complete', 'cancel', 'reopen', 'reschedule']) - assert.throws( - () => f.clinical.transition(doctor, task.id, action, task.version, { resolution: 'Bypass' }), + await assert.rejects( + async () => + await f.clinical.transition(doctor, task.id, action, task.version, { + resolution: 'Bypass', + }), fails(409), ); - assert.throws(() => labs.cancel(doctor, order.id, 2, { reason: 'Hide result' }), fails(409)); - assert.throws( - () => - labs.review(doctor, order.id, 2, { + await assert.rejects( + async () => await labs.cancel(doctor, order.id, 2, { reason: 'Hide result' }), + fails(409), + ); + await assert.rejects( + async () => + await labs.review(doctor, order.id, 2, { ...reviewInput(report.id, task.version), criticalAcknowledged: false, }), fails(422), ); - const reviewed = labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)); + const reviewed = await labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)); assert.equal(reviewed.data.author, doctor.id); - assert.equal(f.store.get(doctor.tenant, task.id)?.data.status, 'completed'); - assert.throws( - () => labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)), + assert.equal((await f.store.get(doctor.tenant, task.id))?.data.status, 'completed'); + await assert.rejects( + async () => await labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)), fails(409), ); }); - test('corrected reports reopen review, preserve previous acknowledgement and reject stale or reassigned reviews', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const labs = f.runtime.get('laboratories'), team = f.runtime.get('careTeam'); - const order = labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); - const first = labs.receive(doctor, order.id, 1, reportInput()); - let task = f.store.list(doctor.tenant, f.patient.id, 'task')[0]; - labs.review(doctor, order.id, 2, reviewInput(first.id, task.version)); - const corrected = labs.receive(doctor, order.id, 3, { + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + const first = await labs.receive(doctor, order.id, 1, reportInput()); + let task = (await f.store.list(doctor.tenant, f.patient.id, 'task'))[0]; + await labs.review(doctor, order.id, 2, reviewInput(first.id, task.version)); + const corrected = await labs.receive(doctor, order.id, 3, { ...reportInput(), correctionReason: 'Laboratory corrected value', }); - task = f.store.get(doctor.tenant, task.id)!; + task = (await f.store.get(doctor.tenant, task.id))!; assert.equal(task.data.status, 'requested'); assert.equal(task.data.completedAt, undefined); assert.equal(corrected.data.supersedes, first.id); - assert.throws( - () => labs.review(doctor, order.id, 4, reviewInput(first.id, task.version)), + await assert.rejects( + async () => await labs.review(doctor, order.id, 4, reviewInput(first.id, task.version)), fails(409), ); const nurse = { ...doctor, id: 'nurse-a' }; - assert.throws( - () => - team.task(doctor, task.id, 'assign', task.version, { assigneeId: nurse.id, reason: 'Cover' }), + await assert.rejects( + async () => + await team.task(doctor, task.id, 'assign', task.version, { + assigneeId: nurse.id, + reason: 'Cover', + }), fails(403), ); - f.runtime + await f.runtime .get('access') .grant(doctor, f.patient.id, nurse.id, 'clinician', '2099-01-01T00:00:00Z'); - const assigned = team.task(doctor, task.id, 'assign', task.version, { + const assigned = await team.task(doctor, task.id, 'assign', task.version, { assigneeId: nurse.id, reason: 'Cover', }); - assert.throws( - () => labs.review(doctor, order.id, 4, reviewInput(corrected.id, task.version)), + await assert.rejects( + async () => await labs.review(doctor, order.id, 4, reviewInput(corrected.id, task.version)), fails(409), ); - assert.throws( - () => labs.review(doctor, order.id, 4, reviewInput(corrected.id, assigned.version)), + await assert.rejects( + async () => await labs.review(doctor, order.id, 4, reviewInput(corrected.id, assigned.version)), fails(403), ); - labs.review(nurse, order.id, 4, reviewInput(corrected.id, assigned.version)); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labReview').length, 2); - assert.equal(f.store.get(doctor.tenant, first.id)?.data.status, 'final'); + await labs.review(nurse, order.id, 4, reviewInput(corrected.id, assigned.version)); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReview')).length, 2); + assert.equal((await f.store.get(doctor.tenant, first.id))?.data.status, 'final'); }); - test('lab orders validate references/times and cancellation cannot leave orphaned follow-up', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const labs = f.runtime.get('laboratories'); - assert.throws( - () => - labs.order(doctor, f.patient.id, { ...orderInput(f.encounter.id), assigneeId: 'unknown' }), + await assert.rejects( + async () => + await labs.order(doctor, f.patient.id, { + ...orderInput(f.encounter.id), + assigneeId: 'unknown', + }), fails(422), ); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labOrder').length, 0); - const order = labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); - assert.throws( - () => - labs.receive(doctor, order.id, 1, { ...reportInput(), collectedAt: '2099-01-01T00:00:00Z' }), + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labOrder')).length, 0); + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + await assert.rejects( + async () => + await labs.receive(doctor, order.id, 1, { + ...reportInput(), + collectedAt: '2099-01-01T00:00:00Z', + }), fails(422), ); - assert.throws(() => labs.receive(doctor, order.id, 1, { ...reportInput(), results: [] })); - labs.cancel(doctor, order.id, 1, { reason: 'No longer needed' }); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'task')[0].data.status, 'cancelled'); - assert.throws(() => labs.receive(doctor, order.id, 2, reportInput()), fails(409)); - const other = f.clinical.register(doctor, { + await assert.rejects( + async () => await labs.receive(doctor, order.id, 1, { ...reportInput(), results: [] }), + ); + await labs.cancel(doctor, order.id, 1, { reason: 'No longer needed' }); + assert.equal( + (await f.store.list(doctor.tenant, f.patient.id, 'task'))[0].data.status, + 'cancelled', + ); + await assert.rejects( + async () => await labs.receive(doctor, order.id, 2, reportInput()), + fails(409), + ); + const other = await f.clinical.register(doctor, { name: 'Other', birthDate: '1980-01-01', identifier: { type: 'local', value: 'OTHER-2' }, }); - assert.throws(() => labs.order(doctor, other.id, orderInput(f.encounter.id)), fails(409)); + await assert.rejects( + async () => await labs.order(doctor, other.id, orderInput(f.encounter.id)), + fails(409), + ); }); - test('result and review writes roll back together with their tasks; restart preserves reconciled state', async (t) => { const dir = mkdtempSync(tmpdir() + '/eir-meds-labs-'); t.after(() => rmSync(dir, { recursive: true, force: true })); const f = await fixture(dir + '/ehr.sqlite'); const labs = f.runtime.get('laboratories'), meds = f.runtime.get('medications'); - const medication = meds.add(doctor, f.patient.id, med()); - meds.reconcile(doctor, f.patient.id, { + const medication = await meds.add(doctor, f.patient.id, med()); + await meds.reconcile(doctor, f.patient.id, { clientId: randomUUID(), - snapshot: meds.list(doctor, f.patient.id).snapshot, + snapshot: (await meds.list(doctor, f.patient.id)).snapshot, source: 'Patient', note: 'Dose to verify', confirmed: true, noCurrentMedicines: false, }); - const order = labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); f.store.db.exec( "CREATE TRIGGER fail_result BEFORE INSERT ON audit WHEN json_extract(NEW.body,'$.action')='task.lab-result' BEGIN SELECT RAISE(ABORT,'write failure'); END", ); - assert.throws(() => labs.receive(doctor, order.id, 1, reportInput()), /write failure/); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labReport').length, 0); - assert.equal(f.store.get(doctor.tenant, order.id)?.version, 1); + await assert.rejects( + async () => await labs.receive(doctor, order.id, 1, reportInput()), + /write failure/, + ); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReport')).length, 0); + assert.equal((await f.store.get(doctor.tenant, order.id))?.version, 1); f.store.db.exec('DROP TRIGGER fail_result'); - const report = labs.receive(doctor, order.id, 1, reportInput()); - const task = f.store.list(doctor.tenant, f.patient.id, 'task')[0]; + const report = await labs.receive(doctor, order.id, 1, reportInput()); + const task = (await f.store.list(doctor.tenant, f.patient.id, 'task'))[0]; f.store.db.exec( "CREATE TRIGGER fail_review BEFORE INSERT ON audit WHEN json_extract(NEW.body,'$.action')='task.lab-review' BEGIN SELECT RAISE(ABORT,'write failure'); END", ); - assert.throws( - () => labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)), + await assert.rejects( + async () => await labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)), /write failure/, ); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'labReview').length, 0); - assert.equal(f.store.get(doctor.tenant, task.id)?.data.status, 'requested'); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReview')).length, 0); + assert.equal((await f.store.get(doctor.tenant, task.id))?.data.status, 'requested'); f.store.db.exec('DROP TRIGGER fail_review'); - labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)); - f.runtime.stop(); + await labs.review(doctor, order.id, 2, reviewInput(report.id, task.version)); + await f.runtime.stop(); const reopened = await fromConfig(root + 'eir.config.json', { 'eir.storage.sqlite': { path: dir + '/ehr.sqlite' }, }); - t.after(() => reopened.runtime.stop()); - assert.equal(reopened.runtime.get('medications').list(doctor, f.patient.id).current, true); + t.after(async () => await reopened.runtime.stop()); + assert.equal( + (await reopened.runtime.get('medications').list(doctor, f.patient.id)).current, + true, + ); assert.equal( - reopened.runtime.get('store').get(doctor.tenant, medication.id)?.data.name, + (await reopened.runtime.get('store').get(doctor.tenant, medication.id))?.data.name, 'Test medicine', ); - assert.equal(reopened.runtime.get('store').get(doctor.tenant, task.id)?.data.status, 'completed'); - assert.equal(reopened.runtime.get('store').verifyAudit().ok, true); + assert.equal( + (await reopened.runtime.get('store').get(doctor.tenant, task.id))?.data.status, + 'completed', + ); + assert.equal((await reopened.runtime.get('store').verifyAudit()).ok, true); }); - test('workflow APIs enforce identity, tenant and role across chart, history, feed and export', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); const meds = f.runtime.get('medications'), labs = f.runtime.get('laboratories'); - const medication = meds.add(doctor, f.patient.id, med()); - const order = labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); - const report = labs.receive(doctor, order.id, 1, reportInput()); - const token = (a: any) => ({ authorization: `Bearer ${f.runtime.get('identity').issue!(a)}` }); - const headers = token(doctor); + const medication = await meds.add(doctor, f.patient.id, med()); + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + const report = await labs.receive(doctor, order.id, 1, reportInput()); + const token = async (a: any) => ({ + authorization: `Bearer ${await f.runtime.get('identity').issue!(a)}`, + }); + const headers = await token(doctor); assert.equal( (await app.inject({ url: `/api/patients/${f.patient.id}/medications` })).statusCode, 401, @@ -330,7 +375,7 @@ test('workflow APIs enforce identity, tenant and role across chart, history, fee await app.inject({ method: 'POST', url: `/api/lab-orders/${order.id}/cancel`, - headers: token({ ...doctor, tenant: 'another' }), + headers: await token({ ...doctor, tenant: 'another' }), payload: { version: 2, data: { reason: 'Wrong tenant' } }, }) ).statusCode, @@ -338,9 +383,11 @@ test('workflow APIs enforce identity, tenant and role across chart, history, fee ); const self = { ...doctor, id: 'self', role: 'patient', patientId: f.patient.id }; const proxy = { ...doctor, id: 'proxy', role: 'proxy', patientId: f.patient.id }; - f.runtime.get('access').grant(doctor, f.patient.id, proxy.id, 'proxy', '2099-01-01T00:00:00Z'); + await f.runtime + .get('access') + .grant(doctor, f.patient.id, proxy.id, 'proxy', '2099-01-01T00:00:00Z'); for (const actor of [self, proxy]) { - const auth = token(actor); + const auth = await token(actor); assert.equal( (await app.inject({ url: `/api/patients/${f.patient.id}/medications`, headers: auth })) .statusCode, @@ -387,21 +434,20 @@ test('workflow APIs enforce identity, tenant and role across chart, history, fee payload: { version: 1, data: { ...med(), role: 'clinician' } }, }); assert.equal(response.statusCode, 422); - f.runtime.get('access').block(self as any, f.patient.id, true); + await f.runtime.get('access').block(self as any, f.patient.id, true); assert.equal( (await app.inject({ url: `/api/patients/${f.patient.id}/medications`, headers })).statusCode, 403, ); }); - test('AI evidence includes medication provenance and only latest reports; any clinical change invalidates drafts', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const meds = f.runtime.get('medications'), labs = f.runtime.get('laboratories'), ai = f.runtime.get('aiReview'); const input = med(), - medication = meds.add(doctor, f.patient.id, input); + medication = await meds.add(doctor, f.patient.id, input); const proposal = await ai.propose(doctor, f.patient.id, f.encounter.id); assert.ok( proposal.data.evidence.some( @@ -409,24 +455,24 @@ test('AI evidence includes medication provenance and only latest reports; any cl ), ); const { clientId, ...fields } = input; - meds.update(doctor, medication.id, 1, { + await meds.update(doctor, medication.id, 1, { ...fields, status: 'stopped', reason: 'Reported stopped', }); - assert.throws(() => ai.review(doctor, proposal.id, 1, 'accept'), fails(409)); - const order = labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); - const report = labs.receive(doctor, order.id, 1, reportInput()); + await assert.rejects(async () => await ai.review(doctor, proposal.id, 1, 'accept'), fails(409)); + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + const report = await labs.receive(doctor, order.id, 1, reportInput()); const before = await ai.propose(doctor, f.patient.id, f.encounter.id); - const corrected = labs.receive(doctor, order.id, 2, { + const corrected = await labs.receive(doctor, order.id, 2, { ...reportInput(), correctionReason: 'Corrected source', }); - assert.throws(() => ai.review(doctor, before.id, 1, 'accept'), fails(409)); + await assert.rejects(async () => await ai.review(doctor, before.id, 1, 'accept'), fails(409)); const after = await ai.propose(doctor, f.patient.id, f.encounter.id); assert.ok(after.data.evidence.some((e: any) => e.ref === `${corrected.id}@1`)); assert.ok(!after.data.evidence.some((e: any) => e.ref === `${report.id}@1`)); - const bundle = f.runtime.get('fhir').bundle(doctor, f.patient.id); + const bundle = await f.runtime.get('fhir').bundle(doctor, f.patient.id); const resources = bundle.entry.map((e: any) => e.resource); assert.equal(resources.filter((r: any) => r.resourceType === 'MedicationStatement').length, 1); assert.equal( @@ -443,3 +489,78 @@ test('AI evidence includes medication provenance and only latest reports; any cl assert.equal(diagnostic.result[0].reference, '#' + diagnostic.contained[0].id); assert.ok(bundle.entry.some((r: any) => r.fullUrl === diagnostic.basedOn[0].reference)); }); + +test('concurrent lab corrections retain one current report and reviews acknowledge it only once', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const labs = f.runtime.get('laboratories'); + const order = await labs.order(doctor, f.patient.id, orderInput(f.encounter.id)); + const original = await labs.receive(doctor, order.id, 1, reportInput()); + const corrections = await Promise.allSettled([ + labs.receive(doctor, order.id, 2, { ...reportInput(), correctionReason: 'First correction' }), + labs.receive(doctor, order.id, 2, { + ...reportInput(), + correctionReason: 'Competing correction', + }), + ]); + assert.equal(corrections.filter((r) => r.status === 'fulfilled').length, 1); + assert.equal(corrections.find((r) => r.status === 'rejected')?.reason.status, 409); + const current = await f.store.get(doctor.tenant, order.id); + assert(current); + const report = await f.store.get(doctor.tenant, current.data.reportId); + assert.equal(report?.data.supersedes, original.id); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReport')).length, 2); + const task = (await f.store.list(doctor.tenant, f.patient.id, 'task'))[0]; + const reviews = await Promise.allSettled([ + labs.review( + doctor, + order.id, + current.version, + reviewInput(current.data.reportId, task.version), + ), + labs.review( + doctor, + order.id, + current.version, + reviewInput(current.data.reportId, task.version), + ), + ]); + assert.equal(reviews.filter((r) => r.status === 'fulfilled').length, 1); + assert.equal(reviews.find((r) => r.status === 'rejected')?.reason.status, 409); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'labReview')).length, 1); + assert.equal((await f.store.get(doctor.tenant, task.id))?.data.status, 'completed'); + assert.equal((await f.store.get(doctor.tenant, order.id))?.data.reviewedReportId, report?.id); +}); + +test('concurrent reconciliations preserve review numbering and allergy changes invalidate their snapshot', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const meds = f.runtime.get('medications'); + await meds.add(doctor, f.patient.id, med()); + const input = { + snapshot: (await meds.list(doctor, f.patient.id)).snapshot, + source: 'Patient interview', + note: 'Concurrent reconciliation', + confirmed: true, + noCurrentMedicines: false, + }; + const reviews = await Promise.all([ + meds.reconcile(doctor, f.patient.id, { ...input, clientId: randomUUID() }), + meds.reconcile(doctor, f.patient.id, { ...input, clientId: randomUUID() }), + ]); + assert.deepEqual(reviews.map((r) => r.data.reviewNumber).sort(), [1, 2]); + const outcomes = await Promise.allSettled([ + f.clinical.create(doctor, f.patient.id, 'allergy', { + substance: 'Newly reported substance', + reaction: 'Patient reported reaction', + criticality: 'unable-to-assess', + }), + meds.reconcile(doctor, f.patient.id, { ...input, clientId: randomUUID() }), + ]); + assert.equal(outcomes[0].status, 'fulfilled'); + if (outcomes[1].status === 'rejected') assert.equal(outcomes[1].reason.status, 409); + const state = await meds.list(doctor, f.patient.id); + assert.equal(state.current, false); + assert.notDeepEqual(state.snapshot, input.snapshot); + assert.deepEqual(state.review?.data.snapshot, input.snapshot); +}); diff --git a/tests/oidc.e2e.ts b/tests/oidc.e2e.ts index 29ff9a2..3a24878 100644 --- a/tests/oidc.e2e.ts +++ b/tests/oidc.e2e.ts @@ -50,8 +50,8 @@ test('federated browser login keeps tokens HttpOnly, rejects CSRF, signs with id } const runtime = await new Runtime().start(entries); const workforce = runtime.get('workforce'); - const doctor = workforce.actor(workforce.forIdentity(provider.issuer, 'emma')[0]); - runtime.get('clinical').register(doctor, { + const doctor = workforce.actor((await workforce.forIdentity(provider.issuer, 'emma'))[0]); + await runtime.get('clinical').register(doctor, { name: 'Anna Lindberg', birthDate: '1980-01-01', identifier: { type: 'local', value: 'OIDC-TEST' }, @@ -62,7 +62,7 @@ test('federated browser login keeps tokens HttpOnly, rejects CSRF, signs with id t.after(async () => { await browser.close(); await app.close(); - runtime.stop(); + await runtime.stop(); delete process.env.EIR_BROWSER_OIDC_SECRET; }); const page = await browser.newPage(); @@ -108,12 +108,12 @@ test('federated browser login keeps tokens HttpOnly, rejects CSRF, signs with id await page.locator('#dialog').getByRole('button', { name: 'Signera', exact: true }).click(); await page.locator('#content').getByText('Signerad', { exact: true }).waitFor(); const store = runtime.get('store'); - const signed = store.list(doctor.tenant, undefined, 'note')[0]; + const signed = (await store.list(doctor.tenant, undefined, 'note'))[0]; assert.equal(signed.data.signedBy, doctor.id); assert.equal(signed.data.signedUnder.authentication, 'oidc'); assert.equal(signed.data.signedUnder.acr, 'urn:eir:test:strong'); - const assignment = workforce.current(doctor); - store.transaction(() => + const assignment = await workforce.current(doctor); + await store.transaction(async () => store.revise( { ...doctor, role: 'administrator' }, assignment, diff --git a/tests/oidc.test.ts b/tests/oidc.test.ts index 1233cc7..6028ce8 100644 --- a/tests/oidc.test.ts +++ b/tests/oidc.test.ts @@ -28,15 +28,19 @@ test('OIDC validates signed issuer/audience/nonce/assurance, PKCE, identity mapp }, }, ]); - t.after(() => { - runtime.stop(); + t.after(async () => { + await runtime.stop(); delete process.env.EIR_TEST_OIDC_SECRET; }); const identity = runtime.get('identity'), browser = identity.browser!; + const store = runtime.get('store') as import('../plugins/storage-sqlite.ts').SqliteStore; assert.equal(identity.issue, undefined); const flow = async () => { const start = await browser.begin(); + const authorization = new URL(start.url); + assert.equal(authorization.searchParams.get('code_challenge_method'), 'S256'); + assert.match(authorization.searchParams.get('code_challenge')!, /^[A-Za-z0-9_-]{43}$/); const response = await fetch(start.url, { redirect: 'manual' }); return { ...start, callback: new URL(response.headers.get('location')!) }; }; @@ -49,7 +53,7 @@ test('OIDC validates signed issuer/audience/nonce/assurance, PKCE, identity mapp assert.equal(actor.authentication?.subject, 'emma'); assert.equal(actor.authentication?.acr, 'urn:eir:test:strong'); await assert.rejects(browser.callback(valid.callback, valid.binding), /already used/); - identity.revoke!(token); + await identity.revoke!(token); await assert.rejects(identity.authenticate(token)); const swapped = await flow(), wrongBrowser = await flow(); @@ -60,14 +64,24 @@ test('OIDC validates signed issuer/audience/nonce/assurance, PKCE, identity mapp const badState = await flow(); badState.callback.searchParams.set('state', 'wrong'); await assert.rejects(browser.callback(badState.callback, badState.binding)); + const wrongPkce = await browser.begin(); + const changedChallenge = new URL(wrongPkce.url); + changedChallenge.searchParams.set('code_challenge', 'A'.repeat(43)); + const pkceResponse = await fetch(changedChallenge, { redirect: 'manual' }); + const pkceCallback = new URL(pkceResponse.headers.get('location')!); + await assert.rejects(browser.callback(pkceCallback, wrongPkce.binding), /Authentication failed/); + await assert.rejects(browser.callback(pkceCallback, wrongPkce.binding), /already used/); for (const claims of [ { aud: 'other-app' }, { iss: 'https://untrusted.invalid' }, { nonce: 'wrong' }, { exp: 1 }, { acr: 'weak' }, + { acr: null }, { sub: 'unprovisioned' }, + { sub: null }, { auth_time: 1 }, + { auth_time: null }, { auth_time: Math.floor(Date.now() / 1000) + 1000 }, ]) { provider.control.claims = claims; @@ -82,8 +96,30 @@ test('OIDC validates signed issuer/audience/nonce/assurance, PKCE, identity mapp const forged = await flow(); await assert.rejects(browser.callback(forged.callback, forged.binding), /Authentication failed/); provider.control.badSignature = false; + const oneUse = await flow(); + const simultaneous = await Promise.allSettled([ + browser.callback(oneUse.callback, oneUse.binding), + browser.callback(oneUse.callback, oneUse.binding), + ]); + assert.equal(simultaneous.filter((result) => result.status === 'fulfilled').length, 1); + const reused = simultaneous.find((result) => result.status === 'rejected'); + assert(reused?.status === 'rejected'); + assert.match(reused.reason.message, /already used/); + const failedSession = await flow(); + const sessionFailure = new Error('Session write failed'); + const saveSession = t.mock.method(store, 'saveSession', async () => { + throw sessionFailure; + }); + await assert.rejects(browser.callback(failedSession.callback, failedSession.binding), { + message: 'Authentication failed or staff assignment unavailable', + cause: sessionFailure, + }); + saveSession.mock.restore(); + await assert.rejects( + browser.callback(failedSession.callback, failedSession.binding), + /already used/, + ); const expired = await flow(); - const store = runtime.get('store') as import('../plugins/storage-sqlite.ts').SqliteStore; store.db.exec("UPDATE login_transactions SET expires='2000-01-01T00:00:00.000Z'"); await assert.rejects(browser.callback(expired.callback, expired.binding), /expired/); await assert.rejects( diff --git a/tests/plugins-ai.test.ts b/tests/plugins-ai.test.ts index a671504..eb868f9 100644 --- a/tests/plugins-ai.test.ts +++ b/tests/plugins-ai.test.ts @@ -1,5 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; +import { AsyncLocalStorage } from 'node:async_hooks'; import { fixture, doctor } from './helpers.ts'; import { Runtime } from '../packages/runtime.ts'; import type { Plugin } from '../packages/contracts.ts'; @@ -7,7 +8,7 @@ import countrySE from '../plugins/country-se.ts'; import countryEU from '../plugins/country-eu-local.ts'; test('Swedish identifiers use established validation with explicit century and namespaces', async (t) => { const runtime = await new Runtime().start([{ plugin: countrySE }]); - t.after(() => runtime.stop()); + t.after(async () => await runtime.stop()); const country = runtime.get('country'); const valid = country.identifier({ type: 'personnummer', value: '199001010017' }); assert.equal(valid.system, 'http://electronichealth.se/identifier/personnummer'); @@ -23,7 +24,7 @@ test('country provider can be replaced; duplicate providers and dependency cycle { plugin: countryEU, config: { code: 'DK', locale: 'da-DK' } }, ]); assert.equal(runtime.get('country').code, 'DK'); - runtime.stop(); + await runtime.stop(); await assert.rejects( new Runtime().start([{ plugin: countrySE }, { plugin: countryEU }]), /Duplicate provider/, @@ -45,7 +46,7 @@ test('plugin failure unwinds previously acquired resources', async () => { const fail: Plugin = { id: 'test.fail', version: '1.0.0', - apiVersion: 1, + apiVersion: 2, requires: ['country'], provides: ['aiProvider'], setup() { @@ -57,26 +58,32 @@ test('plugin failure unwinds previously acquired resources', async () => { }); test('AI proposal requires review, creates only draft, and rejects replay or stale context', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const ai = f.runtime.get('aiReview'); const proposal = await ai.propose(doctor, f.patient.id, f.encounter.id); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'note').length, 0); - const accepted = ai.review(doctor, proposal.id, 1, 'accept'); - assert.equal(f.store.get(doctor.tenant, accepted.data.noteId)?.data.status, 'draft'); - assert.throws(() => ai.review(doctor, proposal.id, 1, 'accept'), /already reviewed/); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'note')).length, 0); + const accepted = await ai.review(doctor, proposal.id, 1, 'accept'); + assert.equal((await f.store.get(doctor.tenant, accepted.data.noteId))?.data.status, 'draft'); + await assert.rejects( + async () => await ai.review(doctor, proposal.id, 1, 'accept'), + /already reviewed/, + ); const stale = await ai.propose(doctor, f.patient.id, f.encounter.id); - f.clinical.create(doctor, f.patient.id, 'allergy', { + await f.clinical.create(doctor, f.patient.id, 'allergy', { substance: 'Synthetic substance', reaction: 'Synthetic reaction', criticality: 'unable-to-assess', }); - assert.throws(() => ai.review(doctor, stale.id, 1, 'accept'), /context changed/); - const rejected = ai.review(doctor, stale.id, 1, 'reject'); + await assert.rejects( + async () => await ai.review(doctor, stale.id, 1, 'accept'), + /context changed/, + ); + const rejected = await ai.review(doctor, stale.id, 1, 'reject'); assert.equal(rejected.data.status, 'rejected'); }); test('AI rejects invented citations and rechecks access after inference', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); + t.after(async () => await f.runtime.stop()); const provider = f.runtime.get('aiProvider'); provider.generate = async () => ({ text: 'Invented', @@ -89,7 +96,7 @@ test('AI rejects invented citations and rechecks access after inference', async /invalid source/, ); provider.generate = async (evidence) => { - f.runtime + await f.runtime .get('access') .block( { id: 'patient', role: 'patient', tenant: doctor.tenant, patientId: f.patient.id }, @@ -102,18 +109,18 @@ test('AI rejects invented citations and rechecks access after inference', async f.runtime.get('aiReview').propose(doctor, f.patient.id, f.encounter.id), /No active/, ); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'proposal').length, 0); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'proposal')).length, 0); }); test('FHIR export maps supported records with resolvable patient references and no AI proposal leakage', async (t) => { const f = await fixture(); - t.after(() => f.runtime.stop()); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + t.after(async () => await f.runtime.stop()); + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Svensk journaltext åäö', }); - f.clinical.transition(doctor, note.id, 'sign', 1, {}); + await f.clinical.transition(doctor, note.id, 'sign', 1, {}); await f.runtime.get('aiReview').propose(doctor, f.patient.id, f.encounter.id); - const bundle = f.runtime.get('fhir').bundle(doctor, f.patient.id); + const bundle = await f.runtime.get('fhir').bundle(doctor, f.patient.id); assert.equal(bundle.type, 'collection'); assert.equal(bundle.entry.length, 3); const doc = bundle.entry.find( @@ -126,3 +133,26 @@ test('FHIR export maps supported records with resolvable patient references and assert.equal(doc.docStatus, 'final'); assert.ok(bundle.entry.some((e: any) => e.fullUrl === doc.subject.reference)); }); + +test('AI inference runs outside transactions and rejects evidence changed during generation', async (t) => { + const f = await fixture(); + t.after(() => f.runtime.stop()); + const context = new AsyncLocalStorage(); + const transaction = f.store.transaction.bind(f.store); + f.store.transaction = (fn) => transaction(() => context.run(true, fn)); + f.runtime.get('aiProvider').generate = async (evidence) => { + assert.equal(context.getStore(), undefined); + await f.clinical.create(doctor, f.patient.id, 'allergy', { + substance: 'Updated during inference', + reaction: 'Reported reaction', + criticality: 'unable-to-assess', + }); + return { text: evidence[0].text, mode: 'model', model: 'test', citations: [evidence[0]] }; + }; + await assert.rejects( + () => f.runtime.get('aiReview').propose(doctor, f.patient.id, f.encounter.id), + /context changed/, + ); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'proposal')).length, 0); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'allergy')).length, 1); +}); diff --git a/tests/postgres-clinical-helpers.ts b/tests/postgres-clinical-helpers.ts new file mode 100644 index 0000000..e956877 --- /dev/null +++ b/tests/postgres-clinical-helpers.ts @@ -0,0 +1,156 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import type { Actor, Entity, Plugin } from '../packages/contracts.ts'; +import { Runtime } from '../packages/runtime.ts'; +import { createApp } from '../apps/app.ts'; +import { demoWorkforce } from '../apps/demo-workforce.ts'; +import postgres from '../plugins/storage-postgres.ts'; +import { postgresFixture } from './postgres-helpers.ts'; + +type Session = 'doctor' | 'colleague'; +type HttpResult = { status: number; body: T }; + +export function expectStatus(result: HttpResult, status = 200): T { + assert.equal(result.status, status, JSON.stringify(result.body)); + return result.body; +} + +export async function postgresClinicalFixture() { + const database = await postgresFixture(); + const root = fileURLToPath(new URL('../', import.meta.url)); + const runtimes: Runtime[] = []; + const apps: Awaited>[] = []; + const urls: string[] = []; + const actors: Record[] = []; + const tokens: Record[] = []; + const cleanup = async () => { + const errors: unknown[] = []; + for (const app of apps) { + try { + await app.close(); + } catch (error) { + errors.push(error); + } + } + for (const runtime of runtimes) { + try { + await runtime.stop(); + } catch (error) { + errors.push(error); + } + } + try { + await database.cleanup(); + } catch (error) { + errors.push(error); + } + if (errors.length) + throw new AggregateError(errors, 'PostgreSQL clinical fixture cleanup failed'); + }; + const http = async ( + replica: 0 | 1, + session: Session, + path: string, + data?: unknown, + ): Promise> => { + const response = await fetch(urls[replica] + '/api' + path, { + method: data === undefined ? 'GET' : 'POST', + headers: { + authorization: `Bearer ${tokens[replica][session]}`, + ...(data === undefined ? {} : { 'content-type': 'application/json' }), + }, + ...(data === undefined ? {} : { body: JSON.stringify(data) }), + signal: AbortSignal.timeout(15_000), + }); + return { status: response.status, body: (await response.json()) as T }; + }; + try { + const config = JSON.parse( + await readFile(new URL('../eir.demo.config.json', import.meta.url), 'utf8'), + ) as { + plugins: { module: string; config?: Record }[]; + }; + for (let replica = 0; replica < 2; replica++) { + const entries: { plugin: Plugin; config?: Record }[] = []; + for (const entry of config.plugins) { + if (entry.module === './plugins/storage-sqlite.ts') { + entries.push({ plugin: postgres, config: { ...database.configA } }); + } else { + const plugin: Plugin = (await import(new URL('../' + entry.module, import.meta.url).href)) + .default; + entries.push({ + plugin, + config: + plugin.id === 'eir.workforce' ? demoWorkforce(database.configA.tenant) : entry.config, + }); + } + } + const runtime = await new Runtime().start(entries); + runtimes.push(runtime); + assert(runtime.active.some((entry) => entry.id === postgres.id)); + assert(!runtime.active.some((entry) => entry.id === 'eir.storage.sqlite')); + const workforce = runtime.get('workforce'); + const find = async (subject: string) => { + const assignment = (await workforce.forIdentity('https://local.eir.invalid', subject)).find( + (row) => row.data.role === 'clinician', + ); + assert(assignment); + return workforce.actor(assignment); + }; + const doctor = await find('emma'), + colleague = await find('linnea'); + actors.push({ doctor, colleague }); + tokens.push({ + doctor: await runtime.get('identity').issue!(doctor), + colleague: await runtime.get('identity').issue!(colleague), + }); + const app = await createApp(runtime, root); + apps.push(app); + urls.push(await app.listen({ host: '127.0.0.1', port: 0 })); + } + assert.notEqual(runtimes[0].get('store'), runtimes[1].get('store')); + assert.notEqual(tokens[0].doctor, tokens[1].doctor); + const patient = expectStatus( + await http(0, 'doctor', '/patients', { + name: 'Synthetic PostgreSQL patient', + birthDate: '1980-01-01', + identifier: { type: 'local', value: 'PG-CLINICAL-001' }, + }), + 201, + ); + const encounter = expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/records/encounter`, { + reason: 'Synthetic follow-up', + }), + 201, + ); + expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/access`, { + actorId: actors[1].colleague.id, + role: 'clinician', + expires: new Date(Date.now() + 86400000).toISOString(), + reason: 'Shared synthetic care responsibility', + }), + ); + return { ...database, cleanup, runtimes, urls, actors, http, patient, encounter }; + } catch (error) { + await cleanup(); + throw error; + } +} + +export async function failClinicalAudit( + admin: Awaited>['admin'], + action: 'task.created' | 'task.lab-result' | 'task.lab-review' | 'appointment.completed', +) { + await admin.query(`CREATE OR REPLACE FUNCTION eir.fail_clinical_audit() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.body::jsonb->>'action' = TG_ARGV[0] THEN + RAISE EXCEPTION 'synthetic-clinical-failure-must-not-leak'; + END IF; + RETURN NEW; + END; $$; + CREATE TRIGGER zz_clinical_audit_failure BEFORE INSERT ON eir.audit + FOR EACH ROW EXECUTE FUNCTION eir.fail_clinical_audit('${action}');`); +} diff --git a/tests/postgres-clinical.test.ts b/tests/postgres-clinical.test.ts new file mode 100644 index 0000000..a252f9b --- /dev/null +++ b/tests/postgres-clinical.test.ts @@ -0,0 +1,497 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import type { Actor, Entity } from '../packages/contracts.ts'; +import { postgresTestOptions } from './postgres-helpers.ts'; +import { + expectStatus, + failClinicalAudit, + postgresClinicalFixture, +} from './postgres-clinical-helpers.ts'; + +const booking = (practitionerId: string) => ({ + practitionerId, + localStart: '2027-01-11T09:00', + durationMinutes: 30, + reason: 'Synthetic follow-up', + type: 'visit', +}); +const medication = () => ({ + clientId: randomUUID(), + name: 'Synthetic medication statement', + dosageText: null, + indication: '', + source: 'patient', + sourceDetail: 'Synthetic patient interview', + status: 'active', +}); +const orderInput = (encounterId: string, assigneeId: string) => ({ + clientId: randomUUID(), + encounterId, + assigneeId, + test: 'Synthetic analysis', + question: 'Synthetic clinical question', + specimen: 'Plasma', + due: '2027-01-12', + priority: 'routine', +}); +const reportInput = () => ({ + source: 'Synthetic laboratory', + messageId: randomUUID(), + collectedAt: '2026-01-01T09:00:00Z', + reportedAt: '2026-01-01T10:00:00Z', + results: [ + { + name: 'Synthetic analyte', + value: '7.1', + unit: 'mmol/L', + reference: 'Source range', + flag: 'critical', + }, + ], +}); +const reviewInput = (reportId: string, taskVersion: number) => ({ + reportId, + taskVersion, + assessment: 'Synthetic source reviewed', + action: 'Synthetic follow-up recorded', + communication: 'Synthetic patient contacted', + criticalAcknowledged: true, +}); + +test( + 'postgres HTTP: independent runtimes share staff sessions, own notes, stale CAS and signed lifecycle', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const { http, patient, encounter } = f; + const doctor = f.actors[0].doctor, + colleague = f.actors[1].colleague; + const sessionA = expectStatus(await http<{ actor: Actor }>(0, 'doctor', '/session')); + const sessionB = expectStatus(await http<{ actor: Actor }>(1, 'doctor', '/session')); + assert.equal(sessionA.actor.id, doctor.id); + assert.equal(sessionB.actor.assignmentId, sessionA.actor.assignmentId); + assert.equal( + expectStatus(await http<{ actor: Actor }>(1, 'colleague', '/session')).actor.id, + colleague.id, + ); + assert.equal((await fetch(f.urls[1] + `/api/patients/${patient.id}/chart`)).status, 401); + const [doctorNote, colleagueNote] = ( + await Promise.all([ + http(0, 'doctor', `/patients/${patient.id}/records/note`, { + encounterId: encounter.id, + clientId: randomUUID(), + text: 'Doctor draft', + }), + http(1, 'colleague', `/patients/${patient.id}/records/note`, { + encounterId: encounter.id, + clientId: randomUUID(), + text: 'Colleague draft', + }), + ]) + ).map((response) => expectStatus(response, 201)); + assert.equal(doctorNote.data.author, doctor.id); + assert.equal(colleagueNote.data.author, colleague.id); + expectStatus( + await http(1, 'colleague', `/records/${doctorNote.id}/save`, { + version: 1, + data: { text: 'Wrong author' }, + }), + 403, + ); + expectStatus( + await http(0, 'doctor', `/records/${colleagueNote.id}/sign`, { version: 1, data: {} }), + 403, + ); + + const saves = await Promise.all([ + http(0, 'doctor', `/records/${doctorNote.id}/save`, { + version: 1, + data: { text: 'Session A revision' }, + }), + http(1, 'doctor', `/records/${doctorNote.id}/save`, { + version: 1, + data: { text: 'Session B revision' }, + }), + ]); + assert.deepEqual(saves.map((r) => r.status).sort(), [200, 409], JSON.stringify(saves)); + const winner = saves.find((r) => r.status === 200)!.body; + assert.equal(winner.version, 2); + const history = expectStatus( + await http(1, 'doctor', `/records/${doctorNote.id}/history`), + ); + assert.deepEqual( + history.map((r) => r.version), + [1, 2], + ); + assert.equal(history[1].data.text, winner.data.text); + expectStatus( + await http(0, 'doctor', `/records/${encounter.id}/close`, { version: 1, data: {} }), + 409, + ); + const signed = expectStatus( + await http(1, 'doctor', `/records/${doctorNote.id}/sign`, { version: 2, data: {} }), + ); + assert.equal(signed.data.signedBy, doctor.id); + assert.deepEqual(signed.data.signedUnder, { + assignmentId: doctor.assignmentId, + unitId: doctor.unitId, + authentication: 'local', + acr: null, + }); + expectStatus( + await http(0, 'doctor', `/records/${doctorNote.id}/save`, { + version: signed.version, + data: { text: 'Overwrite signature' }, + }), + 409, + ); + expectStatus( + await http(1, 'colleague', `/records/${colleagueNote.id}/sign`, { version: 1, data: {} }), + ); + const closed = expectStatus( + await http(0, 'doctor', `/records/${encounter.id}/close`, { version: 1, data: {} }), + ); + assert.equal(closed.data.status, 'finished'); + const chart = expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/chart`), + ); + assert.equal(chart.filter((r) => r.kind === 'note' && r.data.status === 'signed').length, 2); + const bundle = expectStatus( + await http<{ entry: { resource: { resourceType: string; docStatus?: string } }[] }>( + 0, + 'doctor', + `/patients/${patient.id}/export/fhir`, + ), + ); + assert.equal( + bundle.entry.filter( + (r) => r.resource.resourceType === 'DocumentReference' && r.resource.docStatus === 'final', + ).length, + 2, + ); + assert.equal((await f.runtimes[1].get('store').verifyAudit()).ok, true); + }, +); + +test( + 'postgres HTTP: concurrent overlapping appointments admit one booking across runtimes', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const input = booking(f.actors[0].doctor.id); + const responses = await Promise.all([ + f.http(0, 'doctor', `/patients/${f.patient.id}/appointments`, input), + f.http(1, 'colleague', `/patients/${f.patient.id}/appointments`, input), + ]); + assert.deepEqual(responses.map((r) => r.status).sort(), [201, 409], JSON.stringify(responses)); + const first = responses.find((r) => r.status === 201)!.body; + assert.equal(first.data.startsAt, '2027-01-11T08:00:00Z'); + const workspace = expectStatus( + await f.http<{ appointments: Entity[] }>(1, 'colleague', '/care-team?day=2027-01-11'), + ); + assert.deepEqual( + workspace.appointments.map((r) => r.id), + [first.id], + ); + expectStatus( + await f.http(1, 'colleague', `/patients/${f.patient.id}/appointments`, { + ...input, + localStart: '2027-01-11T09:30', + }), + 201, + ); + assert.equal( + (await f.runtimes[0].get('store').list(f.configA.tenant, f.patient.id, 'appointment')).length, + 2, + ); + assert.equal((await f.runtimes[1].get('store').verifyAudit()).ok, true); + }, +); + +test( + 'postgres HTTP: duplicate concurrent lab deliveries return one report and update follow-up once', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const { http, patient, encounter } = f; + const order = expectStatus( + await http( + 0, + 'doctor', + `/patients/${patient.id}/lab-orders`, + orderInput(encounter.id, f.actors[1].colleague.id), + ), + 201, + ); + const data = reportInput(); + const reports = ( + await Promise.all([ + http(0, 'doctor', `/lab-orders/${order.id}/receive`, { version: 1, data }), + http(1, 'colleague', `/lab-orders/${order.id}/receive`, { version: 1, data }), + ]) + ).map((response) => expectStatus(response)); + assert.equal(reports[0].id, reports[1].id); + const store = f.runtimes[1].get('store'); + const storedReports = await store.list(f.configA.tenant, patient.id, 'labReport'); + const tasks = await store.list(f.configA.tenant, patient.id, 'task'); + assert.equal(storedReports.length, 1); + assert.equal(tasks.length, 1); + assert.equal(tasks[0].version, 2); + assert.equal(tasks[0].data.reportId, reports[0].id); + assert.equal(tasks[0].data.priority, 'urgent'); + assert.equal((await store.get(f.configA.tenant, order.id))?.version, 2); + expectStatus( + await http(0, 'doctor', `/lab-orders/${order.id}/receive`, { + version: 2, + data: { ...data, results: [{ ...data.results[0], value: 'Changed' }] }, + }), + 409, + ); + expectStatus( + await http(0, 'doctor', `/lab-orders/${order.id}/review`, { + version: 2, + data: reviewInput(reports[0].id, tasks[0].version), + }), + 403, + ); + expectStatus( + await http(1, 'colleague', `/lab-orders/${order.id}/review`, { + version: 2, + data: reviewInput(reports[0].id, tasks[0].version), + }), + ); + assert.equal((await store.get(f.configA.tenant, tasks[0].id))?.data.status, 'completed'); + const audits = await store.auditEntries(f.configA.tenant, patient.id); + assert.equal(audits.filter((r) => r.action === 'labReport.created').length, 1); + assert.equal(audits.filter((r) => r.action === 'task.lab-result').length, 1); + assert.equal((await store.verifyAudit()).ok, true); + }, +); + +test( + 'postgres HTTP: medication and allergy changes across replicas reject stale reconciliation', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const { http, patient } = f; + const input = medication(); + const added = expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/medications`, input), + 201, + ); + type MedicationState = { snapshot: string[]; current: boolean; review: Entity | null }; + const before = expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medications`), + ); + const review = { + clientId: randomUUID(), + snapshot: before.snapshot, + source: 'Synthetic interview', + note: 'Reconciled synthetic statement', + confirmed: true, + noCurrentMedicines: false, + }; + const { clientId, ...fields } = input; + expectStatus( + await http(0, 'doctor', `/medications/${added.id}`, { + version: 1, + data: { ...fields, status: 'on-hold', reason: 'Synthetic temporary interruption' }, + }), + ); + expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medication-reviews`, review), + 409, + ); + assert.equal( + (await f.runtimes[0].get('store').list(f.configA.tenant, patient.id, 'medicationReview')) + .length, + 0, + ); + const updated = expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medications`), + ); + expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/records/allergy`, { + substance: 'Synthetic substance', + reaction: 'Synthetic reaction', + criticality: 'unable-to-assess', + }), + 201, + ); + expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medication-reviews`, { + ...review, + snapshot: updated.snapshot, + }), + 409, + ); + const current = expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medications`), + ); + expectStatus( + await http(1, 'colleague', `/patients/${patient.id}/medication-reviews`, { + ...review, + snapshot: current.snapshot, + }), + 201, + ); + const reconciled = expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/medications`), + ); + assert.equal(reconciled.current, true); + assert.deepEqual(reconciled.review?.data.snapshot, current.snapshot); + assert.equal(reconciled.review?.data.author, f.actors[1].colleague.id); + assert.equal((await f.runtimes[0].get('store').verifyAudit()).ok, true); + }, +); + +test( + 'postgres HTTP: lab lifecycle failures roll back orders, reports, reviews and linked task versions', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const { http, patient, encounter, admin } = f; + const store = f.runtimes[1].get('store'); + const input = orderInput(encounter.id, f.actors[0].doctor.id); + await failClinicalAudit(admin, 'task.created'); + const failedOrder = await http(0, 'doctor', `/patients/${patient.id}/lab-orders`, input); + expectStatus(failedOrder, 503); + assert.doesNotMatch(JSON.stringify(failedOrder.body), /synthetic-clinical-failure/); + assert.deepEqual(await store.list(f.configA.tenant, patient.id, 'labOrder'), []); + assert.deepEqual(await store.list(f.configA.tenant, patient.id, 'task'), []); + await admin.query('DROP TRIGGER zz_clinical_audit_failure ON eir.audit'); + const order = expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/lab-orders`, input), + 201, + ); + const task = (await store.list(f.configA.tenant, patient.id, 'task'))[0]; + + await failClinicalAudit(admin, 'task.lab-result'); + const reportData = reportInput(); + expectStatus( + await http(1, 'colleague', `/lab-orders/${order.id}/receive`, { + version: 1, + data: reportData, + }), + 503, + ); + assert.deepEqual(await store.list(f.configA.tenant, patient.id, 'labReport'), []); + assert.deepEqual(await store.get(f.configA.tenant, order.id), order); + assert.deepEqual(await store.get(f.configA.tenant, task.id), task); + assert.equal((await store.history(f.configA.tenant, order.id)).length, 1); + await admin.query('DROP TRIGGER zz_clinical_audit_failure ON eir.audit'); + const report = expectStatus( + await http(1, 'colleague', `/lab-orders/${order.id}/receive`, { + version: 1, + data: reportData, + }), + ); + const receivedOrder = await store.get(f.configA.tenant, order.id); + const receivedTask = await store.get(f.configA.tenant, task.id); + assert(receivedTask); + await failClinicalAudit(admin, 'task.lab-review'); + expectStatus( + await http(0, 'doctor', `/lab-orders/${order.id}/review`, { + version: 2, + data: reviewInput(report.id, receivedTask.version), + }), + 503, + ); + assert.deepEqual(await store.list(f.configA.tenant, patient.id, 'labReview'), []); + assert.deepEqual(await store.get(f.configA.tenant, order.id), receivedOrder); + assert.deepEqual(await store.get(f.configA.tenant, task.id), receivedTask); + assert.equal((await store.history(f.configA.tenant, order.id)).length, 2); + assert.equal((await store.history(f.configA.tenant, task.id)).length, 2); + const failedAudits = await store.auditEntries(f.configA.tenant, patient.id); + assert.equal( + failedAudits.filter((r) => r.action === 'labReview.created' || r.action === 'labOrder.review') + .length, + 0, + ); + await admin.query('DROP TRIGGER zz_clinical_audit_failure ON eir.audit'); + expectStatus( + await http(0, 'doctor', `/lab-orders/${order.id}/review`, { + version: 2, + data: reviewInput(report.id, receivedTask.version), + }), + ); + assert.equal((await store.get(f.configA.tenant, task.id))?.data.status, 'completed'); + assert.equal((await store.verifyAudit()).ok, true); + }, +); + +test( + 'postgres HTTP: encounter completion publishes no partial state when booking audit fails', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + t.after(f.cleanup); + const { http, patient, encounter, admin } = f; + const appointment = expectStatus( + await http( + 0, + 'doctor', + `/patients/${patient.id}/appointments`, + booking(f.actors[0].doctor.id), + ), + 201, + ); + const started = expectStatus( + await http(0, 'doctor', `/appointments/${appointment.id}/start`, { version: 1, data: {} }), + ); + assert.equal(started.data.encounterId, encounter.id); + const note = expectStatus( + await http(0, 'doctor', `/patients/${patient.id}/records/note`, { + encounterId: encounter.id, + text: 'Synthetic completed visit', + }), + 201, + ); + expectStatus(await http(0, 'doctor', `/records/${note.id}/sign`, { version: 1, data: {} })); + const feed = expectStatus( + await http<{ nextCursor: number }>(1, 'colleague', `/patients/${patient.id}/changes`), + ); + await failClinicalAudit(admin, 'appointment.completed'); + expectStatus( + await http(0, 'doctor', `/records/${encounter.id}/close`, { version: 1, data: {} }), + 503, + ); + const store = f.runtimes[1].get('store'); + assert.deepEqual(await store.get(f.configA.tenant, encounter.id), encounter); + assert.deepEqual(await store.get(f.configA.tenant, appointment.id), started); + assert.equal((await store.history(f.configA.tenant, encounter.id)).length, 1); + const unchanged = expectStatus( + await http<{ entries: unknown[] }>( + 1, + 'colleague', + `/patients/${patient.id}/changes?after=${feed.nextCursor}`, + ), + ); + assert.deepEqual(unchanged.entries, []); + await admin.query('DROP TRIGGER zz_clinical_audit_failure ON eir.audit'); + expectStatus( + await http(1, 'doctor', `/records/${encounter.id}/close`, { version: 1, data: {} }), + ); + const changed = expectStatus( + await http<{ entries: { record: Entity }[] }>( + 0, + 'doctor', + `/patients/${patient.id}/changes?after=${feed.nextCursor}`, + ), + ); + assert.deepEqual( + changed.entries.map((r) => [r.record.kind, r.record.data.status]), + [ + ['encounter', 'finished'], + ['appointment', 'completed'], + ], + ); + assert.equal((await store.verifyAudit()).ok, true); + }, +); diff --git a/tests/postgres-helpers.ts b/tests/postgres-helpers.ts new file mode 100644 index 0000000..0724225 --- /dev/null +++ b/tests/postgres-helpers.ts @@ -0,0 +1,155 @@ +import { randomBytes } from 'node:crypto'; +import pg from 'pg'; +import type { Actor } from '../packages/contracts.ts'; +import { migratePostgres, postgresPoolConfig } from '../packages/postgres-migrations.ts'; +import { PostgresStore, type PostgresStoreConfig } from '../plugins/storage-postgres.ts'; + +export const postgresEnabled = !!process.env.EIR_TEST_POSTGRES_URL; +export const postgresTestOptions = { skip: !postgresEnabled, timeout: 60_000 }; +export const identifier = (value: string) => '"' + value.replaceAll('"', '""') + '"'; + +export async function dropTestDatabase( + pool: pg.Pool, + name: string, + timeoutMs = 5_000, +): Promise { + if (!/^eir_(?:test|recovery)_[a-f0-9]+$/.test(name)) + throw new Error('Only uniquely named EIR fixture databases may be dropped'); + const deadline = Date.now() + timeoutMs; + // pg-pool can resolve end() before its client.end callbacks run. A forced DROP + // races those socket closes and delivers an asynchronous 57P01 to closing clients. + for (;;) { + const { rows } = await pool.query( + 'SELECT count(*)::integer AS connections FROM pg_stat_activity WHERE datname = $1', + [name], + ); + if (rows[0].connections === 0) break; + if (Date.now() >= deadline) + throw new Error( + `PostgreSQL fixture connection leak: ${name} still has ${rows[0].connections} connection(s)`, + ); + await new Promise((resolve) => setTimeout(resolve, 25)); + } + // A new connection after the drain is a test failure, never something to kill silently. + await pool.query(`DROP DATABASE IF EXISTS ${identifier(name)}`); +} + +// The supplied URL must be an isolated administrative test database. Each fixture creates +// and drops its own database and two login roles; no existing application's schema is used. +export async function postgresFixture(options: { migrate?: boolean } = {}) { + const source = process.env.EIR_TEST_POSTGRES_URL; + if (!source) throw new Error('EIR_TEST_POSTGRES_URL is required for real PostgreSQL tests'); + const url = new URL(source); + const localDevelopmentOnly = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname); + const suffix = randomBytes(8).toString('hex'); + const database = `eir_test_${suffix}`; + const roleA = `eir_a_${suffix}`, + roleB = `eir_b_${suffix}`; + const password = randomBytes(24).toString('hex'); + const envs: string[] = []; + const setUrl = (key: string, value: URL) => { + envs.push(key); + process.env[key] = value.toString(); + return key; + }; + const root = new pg.Pool( + postgresPoolConfig({ connectionStringEnv: 'EIR_TEST_POSTGRES_URL', localDevelopmentOnly }), + ); + const stores: PostgresStore[] = [], + clients: pg.Client[] = []; + let admin: pg.Pool | undefined; + const cleanup = async () => { + for (const store of stores) await store.close(); + for (const client of clients) await client.end(); + await admin?.end(); + try { + await dropTestDatabase(root, database); + await root.query(`DROP ROLE IF EXISTS ${identifier(roleA)}`); + await root.query(`DROP ROLE IF EXISTS ${identifier(roleB)}`); + } finally { + await root.end(); + for (const key of envs) delete process.env[key]; + } + }; + try { + await root.query(`CREATE DATABASE ${identifier(database)}`); + for (const role of [roleA, roleB]) + await root.query(`CREATE ROLE ${identifier(role)} + LOGIN PASSWORD '${password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT`); + const adminUrl = new URL(url); + adminUrl.pathname = '/' + database; + const adminEnv = setUrl(`EIR_PG_ADMIN_${suffix}`, adminUrl); + admin = new pg.Pool( + postgresPoolConfig({ connectionStringEnv: adminEnv, localDevelopmentOnly }), + ); + const makeConfig = (role: string, tenant: string): PostgresStoreConfig => { + const runtimeUrl = new URL(adminUrl); + runtimeUrl.username = role; + runtimeUrl.password = password; + return { + tenant, + localDevelopmentOnly, + connectionStringEnv: setUrl(`EIR_PG_${role}`, runtimeUrl), + }; + }; + const configA = makeConfig(roleA, 'tenant-a'), + configB = makeConfig(roleB, 'tenant-b'); + if (options.migrate !== false) { + await migratePostgres(admin, { tenant: configA.tenant, runtimeRole: roleA }); + await migratePostgres(admin, { tenant: configB.tenant, runtimeRole: roleB }); + } + const open = async (config = configA) => { + const store = await PostgresStore.open(config); + stores.push(store); + return store; + }; + const raw = async (config = configA) => { + const client = new pg.Client(postgresPoolConfig(config)); + await client.connect(); + clients.push(client); + return client; + }; + const actorA: Actor = { + id: 'synthetic-doctor-a', + tenant: 'tenant-a', + role: 'clinician', + unitId: 'unit-a', + assignmentId: 'assignment-a', + }; + const actorB: Actor = { + id: 'synthetic-doctor-b', + tenant: 'tenant-b', + role: 'clinician', + unitId: 'unit-b', + }; + return { + admin, + root, + adminEnv, + roleA, + roleB, + configA, + configB, + actorA, + actorB, + open, + raw, + cleanup, + }; + } catch (error) { + await cleanup(); + throw error; + } +} + +export function barrier(parties = 2): () => Promise { + let arrived = 0; + let release!: () => void; + const ready = new Promise((resolve) => { + release = resolve; + }); + return async () => { + if (++arrived === parties) release(); + await ready; + }; +} diff --git a/tests/postgres-http.test.ts b/tests/postgres-http.test.ts new file mode 100644 index 0000000..39fbe72 --- /dev/null +++ b/tests/postgres-http.test.ts @@ -0,0 +1,82 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; +import type { Plugin } from '../packages/contracts.ts'; +import { Runtime } from '../packages/runtime.ts'; +import { createApp } from '../apps/app.ts'; +import { demoWorkforce } from '../apps/demo-workforce.ts'; +import { postgresFixture, postgresTestOptions } from './postgres-helpers.ts'; + +test( + 'postgres: two full HTTP runtimes serve parallel chart, medication, session, and workspace requests', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + const runtimes: Runtime[] = []; + const apps: Awaited>[] = []; + t.after(async () => { + for (const app of apps) await app.close(); + for (const runtime of runtimes) await runtime.stop(); + await f.cleanup(); + }); + const root = fileURLToPath(new URL('../', import.meta.url)); + const config = JSON.parse( + await readFile(new URL('../eir.demo.config.json', import.meta.url), 'utf8'), + ); + for (let i = 0; i < 2; i++) { + const entries: { plugin: Plugin; config?: Record }[] = []; + for (const entry of config.plugins) { + const module = + entry.module === './plugins/storage-sqlite.ts' + ? './plugins/storage-postgres.ts' + : entry.module; + const plugin = (await import(new URL('../' + module, import.meta.url).href)) + .default as Plugin; + const settings = + plugin.id === 'eir.storage.postgres' + ? f.configA + : plugin.id === 'eir.workforce' + ? demoWorkforce(f.configA.tenant) + : entry.config; + entries.push({ plugin, config: settings }); + } + const runtime = await new Runtime().start(entries); + runtimes.push(runtime); + apps.push(await createApp(runtime, root)); + } + const workforce = runtimes[0].get('workforce'); + const assignment = (await workforce.forIdentity('https://local.eir.invalid', 'emma')).find( + (row) => row.data.role === 'clinician', + )!; + const doctor = workforce.actor(assignment); + const patient = await runtimes[0].get('clinical').register(doctor, { + name: 'Synthetic PostgreSQL HTTP patient', + birthDate: '1980-01-01', + identifier: { type: 'local', value: 'POSTGRES-HTTP-001' }, + }); + await runtimes[0] + .get('clinical') + .create(doctor, patient.id, 'encounter', { reason: 'Synthetic integration test' }); + const token = await runtimes[0].get('identity').issue!(doctor); + const headers = { authorization: `Bearer ${token}` }; + const paths = [ + '/api/session', + '/api/patients', + `/api/patients/${patient.id}/chart`, + `/api/patients/${patient.id}/medications`, + '/api/care-team?day=2026-09-21', + `/api/patients/${patient.id}/permissions`, + `/api/patients/${patient.id}/changes`, + ]; + for (let wave = 0; wave < 3; wave++) { + const responses = await Promise.all( + paths.map((url, i) => apps[i % 2].inject({ url, headers })), + ); + for (const [i, response] of responses.entries()) + assert.equal(response.statusCode, 200, `${paths[i]} wave ${wave}: ${response.body}`); + } + assert.equal((await runtimes[0].get('store').verifyAudit()).ok, true); + assert.equal((await runtimes[1].get('store').verifyAudit()).ok, true); + }, +); diff --git a/tests/postgres-lifecycle.test.ts b/tests/postgres-lifecycle.test.ts new file mode 100644 index 0000000..bc59a85 --- /dev/null +++ b/tests/postgres-lifecycle.test.ts @@ -0,0 +1,134 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import pg from 'pg'; +import { Fault } from '../packages/contracts.ts'; +import { postgresPoolConfig } from '../packages/postgres-migrations.ts'; +import { + dropTestDatabase, + identifier, + postgresFixture, + postgresTestOptions, +} from './postgres-helpers.ts'; + +test( + 'postgres: fixture drop reports live connections and never terminates them', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + const name = `eir_recovery_${randomBytes(8).toString('hex')}`; + const config = postgresPoolConfig({ + connectionStringEnv: f.adminEnv, + localDevelopmentOnly: f.configA.localDevelopmentOnly, + }); + const url = new URL(config.connectionString!); + url.pathname = '/' + name; + const client = new pg.Client({ ...config, connectionString: url.toString() }); + const errors: Error[] = []; + client.on('error', (error) => { + errors.push(error); + }); + t.after(async () => { + await client.end(); + await dropTestDatabase(f.root, name); + await f.cleanup(); + assert.deepEqual(errors, [], 'no asynchronous disconnect errors may be discarded'); + }); + await f.root.query(`CREATE DATABASE ${identifier(name)}`); + await client.connect(); + await assert.rejects(dropTestDatabase(f.root, name, 50), /connection leak/); + assert.equal((await client.query('SELECT 1 AS alive')).rows[0].alive, 1); + }, +); + +test( + 'postgres: pool shutdown followed by fixture drop drains sockets without forced disconnections', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + const name = `eir_recovery_${randomBytes(8).toString('hex')}`; + const config = postgresPoolConfig({ + connectionStringEnv: f.adminEnv, + localDevelopmentOnly: f.configA.localDevelopmentOnly, + }); + const url = new URL(config.connectionString!); + url.pathname = '/' + name; + const pool = new pg.Pool({ ...config, connectionString: url.toString() }); + const errors: Error[] = []; + pool.on('error', (error) => { + errors.push(error); + }); + let end: Promise | undefined; + t.after(async () => { + await (end ??= pool.end()); + await dropTestDatabase(f.root, name); + await f.cleanup(); + assert.deepEqual(errors, [], 'closing sockets must not receive administrative termination'); + }); + await f.root.query(`CREATE DATABASE ${identifier(name)}`); + await pool.query('SELECT 1'); + await (end = pool.end()); + await dropTestDatabase(f.root, name); + assert.equal( + ( + await f.root.query( + 'SELECT count(*)::integer AS count FROM pg_stat_activity WHERE datname = $1', + [name], + ) + ).rows[0].count, + 0, + ); + }, +); + +test( + 'postgres: checked-out client disconnect rejects its transaction, rolls back, and permits recovery', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const store = await f.open(); + let entered!: () => void, resume!: () => void; + const ready = new Promise((resolve) => { + entered = resolve; + }); + const pause = new Promise((resolve) => { + resume = resolve; + }); + const outcome = assert.rejects( + store.transaction(async () => { + await store.insert(f.actorA, 'patient', null, { name: 'Uncommitted synthetic record' }); + entered(); + await pause; + }), + (error: unknown) => error instanceof Fault && error.status === 503, + ); + try { + await ready; + const killed = await f.admin.query( + `SELECT pg_terminate_backend(pid) AS terminated FROM pg_stat_activity + WHERE usename = $1 AND state = 'idle in transaction'`, + [f.roleA], + ); + assert.equal(killed.rowCount, 1); + assert.equal(killed.rows[0].terminated, true); + await new Promise((resolve) => setTimeout(resolve, 50)); + } finally { + resume(); + } + await outcome; + assert.deepEqual(await store.list(f.actorA.tenant), []); + assert.deepEqual(await store.verifyAudit(), { ok: true, count: 0 }); + await store.health(); + await store.close(); + assert.equal( + ( + await f.admin.query( + 'SELECT count(*)::integer AS count FROM pg_stat_activity WHERE usename = $1', + [f.roleA], + ) + ).rows[0].count, + 0, + ); + }, +); diff --git a/tests/postgres-recovery.test.ts b/tests/postgres-recovery.test.ts new file mode 100644 index 0000000..5420943 --- /dev/null +++ b/tests/postgres-recovery.test.ts @@ -0,0 +1,172 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes, randomUUID } from 'node:crypto'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { + postgresFixture, + postgresTestOptions, + identifier, + dropTestDatabase, +} from './postgres-helpers.ts'; +import { Runtime } from '../packages/runtime.ts'; +import type { Plugin } from '../packages/contracts.ts'; +import postgres from '../plugins/storage-postgres.ts'; +import { demoWorkforce } from '../apps/demo-workforce.ts'; +import { createPostgresBackup, restorePostgresBackup } from '../packages/backup.ts'; +import { root } from './helpers.ts'; + +test( + 'postgres: encrypted recovery restores the real EHR, its clinical workflow and RLS without reviving sessions', + { + ...postgresTestOptions, + timeout: 120000, + }, + async (t) => { + const f = await postgresFixture(); + const recoveryName = 'eir_recovery_' + randomBytes(8).toString('hex'); + const directory = await mkdtemp(join(tmpdir(), 'eir-real-recovery-')); + const restoredEnv = 'EIR_RECOVERY_' + randomBytes(8).toString('hex'); + const runtimes: Runtime[] = []; + t.after(async () => { + for (const runtime of runtimes) await runtime.stop(); + await dropTestDatabase(f.root, recoveryName); + await f.cleanup(); + delete process.env[restoredEnv]; + await rm(directory, { recursive: true, force: true }); + }); + const composition = JSON.parse(await readFile(join(root, 'eir.demo.config.json'), 'utf8')); + const start = async (config = f.configA) => { + const entries = []; + for (const entry of composition.plugins) { + const plugin: Plugin = entry.module.endsWith('storage-sqlite.ts') + ? postgres + : (await import(pathToFileURL(join(root, entry.module)).href)).default; + entries.push({ + plugin, + config: + plugin.id === 'eir.storage.postgres' + ? config + : plugin.id === 'eir.workforce' + ? demoWorkforce(config.tenant) + : entry.config, + }); + } + const runtime = await new Runtime().start(entries); + runtimes.push(runtime); + return runtime; + }; + const runtime = await start(); + const workforce = runtime.get('workforce'); + const doctor = workforce.actor( + (await workforce.forIdentity('https://local.eir.invalid', 'emma')).find( + (r) => r.data.role === 'clinician', + )!, + ); + const clinical = runtime.get('clinical'), + store = runtime.get('store'); + const patient = await clinical.register(doctor, { + name: 'Synthetic Recovery Patient', + birthDate: '1980-01-01', + identifier: { type: 'local', value: 'RECOVERY-001' }, + }); + const encounter = await clinical.create(doctor, patient.id, 'encounter', { + reason: 'Recovery verification', + }); + const draft = await clinical.create(doctor, patient.id, 'note', { + encounterId: encounter.id, + text: 'Synthetic signed record for recovery.', + }); + const signed = await clinical.transition(doctor, draft.id, 'sign', draft.version, {}); + const order = await runtime.get('laboratories').order(doctor, patient.id, { + clientId: randomUUID(), + encounterId: encounter.id, + test: 'Synthetic analysis', + question: 'Recovery case', + specimen: 'Synthetic sample', + assigneeId: doctor.id, + due: '2027-01-01', + priority: 'routine', + }); + const token = await runtime.get('identity').issue!(doctor); + await store.saveLogin('recovery-login', { nonce: 'synthetic' }, '2099-01-01T00:00:00.000Z'); + const beforeRecords = await store.list(doctor.tenant); + const beforeHistory = await clinical.history(doctor, signed.id); + const beforeAudit = await store.verifyAudit(); + const archive = join(directory, 'clinic.eirbak'), + key = randomBytes(32); + const sourceUrl = process.env[f.adminEnv]!; + await createPostgresBackup({ + databaseUrl: sourceUrl, + outputPath: archive, + encryptionKey: key, + pgBin: process.env.PG_BIN, + }); + await f.root.query(`CREATE DATABASE ${identifier(recoveryName)} TEMPLATE template0`); + const targetUrl = new URL(sourceUrl); + targetUrl.pathname = '/' + recoveryName; + await restorePostgresBackup({ + databaseUrl: targetUrl.toString(), + sourceDatabaseUrl: sourceUrl, + runtimeDatabaseUrl: process.env[f.configA.connectionStringEnv], + inputPath: archive, + confirmFreshDatabase: recoveryName, + encryptionKey: key, + temporaryDirectory: directory, + pgBin: process.env.PG_BIN, + }); + assert.equal( + (await f.root.query('SELECT datconnlimit FROM pg_database WHERE datname=$1', [recoveryName])) + .rows[0].datconnlimit, + 0, + ); + const restoredUrl = new URL(process.env[f.configA.connectionStringEnv]!); + restoredUrl.pathname = '/' + recoveryName; + process.env[restoredEnv] = restoredUrl.toString(); + const restoredConfig = { ...f.configA, connectionStringEnv: restoredEnv }; + await assert.rejects(start(restoredConfig), /unavailable/); + // Only the isolated test operator deliberately unfences the restored database. + await f.root.query(`ALTER DATABASE ${identifier(recoveryName)} CONNECTION LIMIT -1`); + const restored = await start(restoredConfig); + const restoredStore = restored.get('store'); + assert.deepEqual(await restoredStore.list(doctor.tenant), beforeRecords); + assert.deepEqual(await restoredStore.verifyAudit(), beforeAudit); + assert.deepEqual(await restoredStore.history(doctor.tenant, signed.id), beforeHistory); + await assert.rejects( + restored.get('identity').authenticate(token), + (e: any) => e.status === 401, + ); + assert.equal(await restoredStore.consumeLogin('recovery-login'), undefined); + const chart = await restored.get('clinical').chart(doctor, patient.id); + assert.deepEqual( + chart.find((r) => r.id === signed.id), + signed, + ); + assert.deepEqual( + chart.find((r) => r.id === order.id), + order, + ); + assert.ok( + (await restored.get('careTeam').workspace(doctor, '2027-01-01')).tasks.some( + (r) => r.data.linkedOrderId === order.id, + ), + ); + await assert.rejects( + restored + .get('clinical') + .transition(doctor, signed.id, 'save', signed.version, { text: 'Forbidden overwrite' }), + (e: any) => e.status === 409, + ); + const amendment = await restored + .get('clinical') + .transition(doctor, signed.id, 'amend', signed.version, { + text: 'Synthetic amendment after restore', + reason: 'Recovery verification', + }); + assert.equal(amendment.data.amends, signed.id); + assert.equal((await restoredStore.verifyAudit()).ok, true); + key.fill(0); + }, +); diff --git a/tests/postgres-security.test.ts b/tests/postgres-security.test.ts new file mode 100644 index 0000000..9264ec3 --- /dev/null +++ b/tests/postgres-security.test.ts @@ -0,0 +1,303 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import pg from 'pg'; +import { Fault } from '../packages/contracts.ts'; +import { + migratePostgres, + postgresDataTables, + postgresMigrations, + postgresPoolConfig, +} from '../packages/postgres-migrations.ts'; +import { identifier, postgresFixture, postgresTestOptions } from './postgres-helpers.ts'; + +const denied = (error: any) => error.code === '42501'; + +test('postgres: TLS is verified by default and plaintext is explicitly loopback-only', () => { + const key = 'EIR_POSTGRES_SECURITY_CONFIG_TEST'; + try { + process.env[key] = 'postgresql://runtime:synthetic@db.example.invalid/ehr?sslmode=require'; + const config = postgresPoolConfig({ connectionStringEnv: key }); + assert.deepEqual(config.ssl, { rejectUnauthorized: true }); + assert.ok(!config.connectionString?.includes('sslmode')); + assert.throws( + () => postgresPoolConfig({ connectionStringEnv: key, localDevelopmentOnly: true }), + /loopback/, + ); + for (const option of [ + 'sslmode=disable', + 'sslmode=no-verify', + 'sslrootcert=x', + 'host=127.0.0.1', + 'options=-c%20role%3Dpostgres', + ]) { + process.env[key] = `postgresql://runtime:synthetic@127.0.0.1/ehr?${option}`; + assert.throws(() => postgresPoolConfig({ connectionStringEnv: key }), /TLS verification/); + } + process.env[key] = 'postgresql://runtime:synthetic@127.0.0.1/ehr?sslmode=disable'; + assert.equal( + postgresPoolConfig({ connectionStringEnv: key, localDevelopmentOnly: true }).ssl, + false, + ); + process.env[key] = 'not a url containing synthetic-secret'; + assert.throws( + () => postgresPoolConfig({ connectionStringEnv: key }), + (error: any) => !error.message.includes('synthetic-secret'), + ); + } finally { + delete process.env[key]; + } +}); + +test( + 'postgres: raw SQL RLS protects every data table, sessions/login included, despite tenant reset attempts', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + b = await f.open(f.configB); + const pa = await a.insert(f.actorA, 'patient', null, { name: 'Synthetic A' }); + const pb = await b.insert(f.actorB, 'patient', null, { name: 'Synthetic B' }); + const expires = '2099-01-01T00:00:00.000Z'; + for (const [store, actor, patient] of [ + [a, f.actorA, pa], + [b, f.actorB, pb], + ] as const) { + await store.grant(actor.tenant, patient.id, 'proxy', 'proxy', expires); + await store.restrict(actor.tenant, patient.id, true); + await store.saveSession('same-session', actor, expires); + await store.saveLogin('same-login', { nonce: actor.tenant }, expires); + } + await assert.rejects( + a.get(f.actorB.tenant, pb.id), + (e: any) => e instanceof Fault && e.status === 403, + ); + await assert.rejects( + a.saveSession('forged', f.actorB, expires), + (e: any) => e instanceof Fault && e.status === 403, + ); + const raw = await f.raw(); + const assertScope = async () => { + for (const table of postgresDataTables) { + const { rows } = await raw.query(`SELECT * FROM eir.${table}`); + assert.ok(rows.length > 0, `seeded ${table}`); + assert.ok( + rows.every((row) => row.tenant === f.actorA.tenant), + `RLS on ${table}`, + ); + } + }; + await assertScope(); + await raw.query( + "SET app.tenant = 'tenant-b'; SET app.current_tenant = 'tenant-b'; SET eir.tenant = 'tenant-b'", + ); + await assertScope(); + await raw.query('RESET ALL; SET ROLE NONE; RESET ROLE'); + await assertScope(); + await assert.rejects(raw.query(`SET ROLE ${identifier(f.roleB)}`), denied); + await assert.rejects(raw.query(`SET SESSION AUTHORIZATION ${identifier(f.roleB)}`), denied); + await raw.query('SET row_security = off'); + await assert.rejects(raw.query('SELECT * FROM eir.entities'), denied); + await raw.query('RESET row_security'); + await assertScope(); + for (const sql of [ + "UPDATE eir.tenant_roles SET tenant = 'tenant-b'", + "INSERT INTO eir.tenant_roles VALUES (current_user, 'tenant-b')", + "UPDATE eir.audit_heads SET hash = 'GENESIS'", + 'ALTER TABLE eir.sessions DISABLE ROW LEVEL SECURITY', + 'CREATE TABLE eir.bypass (id text)', + "UPDATE eir.schema_migrations SET checksum = 'forged'", + ]) + await assert.rejects(raw.query(sql), denied); + await assert.rejects( + raw.query(`INSERT INTO eir.entities + (tenant, id, patient_id, kind, version, created_at, updated_at, data) + VALUES ('tenant-b', 'forged', 'forged', 'patient', 1, 'now', 'now', '{}')`), + denied, + ); + await assert.rejects( + raw.query( + 'INSERT INTO eir.sessions (tenant, hash, actor, expires, last_seen) VALUES ($1, $2, $3, $4, $4)', + ['tenant-b', 'forged', JSON.stringify(f.actorB), expires], + ), + denied, + ); + await assert.rejects( + raw.query("INSERT INTO eir.login_transactions VALUES ('tenant-b', 'forged', '{}', $1)", [ + expires, + ]), + denied, + ); + await assert.rejects( + raw.query('INSERT INTO eir.audit (tenant, body) VALUES ($1, $2)', [ + 'tenant-b', + JSON.stringify({ tenant: 'tenant-b' }), + ]), + denied, + ); + await assert.rejects( + raw.query('INSERT INTO eir.versions (tenant, id, version, snapshot) VALUES ($1, $2, 2, $3)', [ + 'tenant-b', + pb.id, + JSON.stringify({ ...pb, version: 2 }), + ]), + denied, + ); + await assert.rejects( + raw.query('INSERT INTO eir.grants VALUES ($1, $2, $3, $4, $5)', [ + 'tenant-a', + pb.id, + 'forged', + 'proxy', + expires, + ]), + (e: any) => e.code === '23503', + ); + for (const table of ['sessions', 'login_transactions']) { + assert.equal( + (await raw.query(`DELETE FROM eir.${table} WHERE tenant = 'tenant-b'`)).rowCount, + 0, + ); + assert.equal( + (await raw.query(`UPDATE eir.${table} SET expires = '2000' WHERE tenant = 'tenant-b'`)) + .rowCount, + 0, + ); + } + assert.equal((await b.session('same-session'))?.actor.tenant, 'tenant-b'); + assert.deepEqual(await b.consumeLogin('same-login'), { nonce: 'tenant-b' }); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 1 }); + assert.deepEqual(await b.verifyAudit(), { ok: true, count: 1 }); + }, +); + +test( + 'postgres: startup rejects tenant mismatch, privileged or inherited roles, unsafe grants, and missing RLS', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + await assert.rejects(f.open({ ...f.configA, tenant: 'tenant-b' }), /configured tenant/); + await assert.rejects( + f.open({ ...f.configA, connectionStringEnv: f.adminEnv }), + /restricted nonowner/, + ); + await f.admin.query(`GRANT ${identifier(f.roleB)} TO ${identifier(f.roleA)}`); + await assert.rejects(f.open(), /without role memberships/); + await f.admin.query(`REVOKE ${identifier(f.roleB)} FROM ${identifier(f.roleA)}`); + await f.admin.query(`ALTER ROLE ${identifier(f.roleA)} BYPASSRLS`); + await assert.rejects(f.open(), /restricted nonowner/); + await f.admin.query(`ALTER ROLE ${identifier(f.roleA)} NOBYPASSRLS`); + await f.admin.query(`GRANT UPDATE ON eir.audit TO ${identifier(f.roleA)}`); + await assert.rejects(f.open(), /unsafe mutation privileges/); + await f.admin.query(`REVOKE UPDATE ON eir.audit FROM ${identifier(f.roleA)}`); + await f.admin.query('ALTER TABLE eir.login_transactions DISABLE ROW LEVEL SECURITY'); + await assert.rejects(f.open(), /row-level security/); + await f.admin.query('ALTER TABLE eir.login_transactions ENABLE ROW LEVEL SECURITY'); + const store = await f.open(); + await store.health(); + }, +); + +test( + 'postgres: migration lock is idempotent and failed provisioning rolls DDL and ledger back', + postgresTestOptions, + async (t) => { + const f = await postgresFixture({ migrate: false }); + t.after(f.cleanup); + const adminRole = (await f.admin.query('SELECT current_user AS role')).rows[0].role; + await assert.rejects( + migratePostgres(f.admin, { tenant: 'tenant-a', runtimeRole: adminRole }), + /restricted nonowner/, + ); + assert.equal( + (await f.admin.query("SELECT to_regnamespace('eir') AS schema")).rows[0].schema, + null, + ); + await Promise.all([ + migratePostgres(f.admin, { tenant: 'tenant-a', runtimeRole: f.roleA }), + migratePostgres(f.admin, { tenant: 'tenant-b', runtimeRole: f.roleB }), + ]); + assert.equal( + (await f.admin.query('SELECT * FROM eir.schema_migrations')).rowCount, + postgresMigrations.length, + ); + assert.equal((await f.admin.query('SELECT * FROM eir.tenant_roles')).rowCount, 2); + await assert.rejects( + migratePostgres(f.admin, { tenant: 'tenant-b', runtimeRole: f.roleA }), + /cannot be remapped/, + ); + const store = await f.open(); + await store.health(); + }, +); + +test( + 'postgres: future, corrupt, and missing migrations fail closed without runtime migration', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + await f.admin.query( + "INSERT INTO eir.schema_migrations VALUES (999, 'future', 'unknown', now())", + ); + await assert.rejects(f.open(), /newer than application/); + await assert.rejects(migratePostgres(f.admin), /newer than application/); + await f.admin.query('DELETE FROM eir.schema_migrations WHERE version = 999'); + await f.admin.query("UPDATE eir.schema_migrations SET checksum = 'corrupt' WHERE version = 1"); + await assert.rejects(f.open(), /checksum mismatch/); + await assert.rejects(migratePostgres(f.admin), /checksum mismatch/); + await f.admin.query('UPDATE eir.schema_migrations SET checksum = $1 WHERE version = 1', [ + postgresMigrations[0].checksum, + ]); + await f.admin.query('DELETE FROM eir.schema_migrations'); + await assert.rejects(f.open(), /migrations are pending/); + assert.equal((await f.admin.query('SELECT * FROM eir.schema_migrations')).rowCount, 0); + }, +); + +test( + 'postgres: audit tampering and tail deletion are detected at restart', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(); + await a.audit(f.actorA, 'synthetic.test'); + await a.close(); + await assert.rejects( + f.admin.query('UPDATE eir.audit SET body = body'), + (e: any) => e.code === '23514', + ); + await assert.rejects(f.admin.query('TRUNCATE eir.audit'), (e: any) => e.code === '23514'); + const original = (await f.admin.query('SELECT body FROM eir.audit')).rows[0].body; + await f.admin.query('ALTER TABLE eir.audit DISABLE TRIGGER audit_append_only'); + await f.admin.query( + "UPDATE eir.audit SET body = jsonb_set(body::jsonb, '{action}', '\"tampered\"')::text", + ); + await assert.rejects(f.open(), /audit verification failed/); + await f.admin.query('UPDATE eir.audit SET body = $1', [original]); + await f.admin.query('DELETE FROM eir.audit'); + await assert.rejects(f.open(), /audit verification failed/); + }, +); + +test( + 'postgres: non-superuser operator-owned migrations and audit trigger work with forced RLS', + postgresTestOptions, + async (t) => { + const f = await postgresFixture({ migrate: false }); + t.after(f.cleanup); + const db = (await f.admin.query('SELECT current_database() AS name')).rows[0].name; + await f.admin.query(`GRANT CREATE ON DATABASE ${identifier(db)} TO ${identifier(f.roleB)}`); + const operator = new pg.Pool(postgresPoolConfig(f.configB)); + try { + await migratePostgres(operator, { tenant: 'tenant-a', runtimeRole: f.roleA }); + } finally { + await operator.end(); + } + const a = await f.open(); + await a.insert(f.actorA, 'patient', null, { name: 'Synthetic operator fixture' }); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 1 }); + }, +); diff --git a/tests/postgres-startup.test.ts b/tests/postgres-startup.test.ts new file mode 100644 index 0000000..f1dd0d0 --- /dev/null +++ b/tests/postgres-startup.test.ts @@ -0,0 +1,247 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { postgresDataTables } from '../packages/postgres-migrations.ts'; +import { identifier, postgresFixture, postgresTestOptions } from './postgres-helpers.ts'; + +test( + 'postgres: startup rejects effective column-only mutation privileges on protected metadata and evidence', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + const cases = [ + { table: 'tenant_roles', columns: 'tenant', privilege: 'UPDATE', grantee: role }, + { + table: 'tenant_roles', + columns: 'runtime_role, tenant', + privilege: 'INSERT', + grantee: role, + }, + { table: 'tenant_roles', columns: 'tenant', privilege: 'UPDATE', grantee: 'PUBLIC' }, + { table: 'schema_migrations', columns: 'checksum', privilege: 'UPDATE', grantee: role }, + { + table: 'schema_migrations', + columns: 'version, name, checksum', + privilege: 'INSERT', + grantee: role, + }, + { table: 'audit_heads', columns: 'hash', privilege: 'UPDATE', grantee: role }, + { table: 'audit_heads', columns: 'tenant', privilege: 'INSERT', grantee: role }, + { table: 'audit', columns: 'body', privilege: 'UPDATE', grantee: role }, + { table: 'versions', columns: 'snapshot', privilege: 'UPDATE', grantee: role }, + ]; + for (const { table, columns, privilege, grantee } of cases) { + await f.admin.query(`GRANT ${privilege} (${columns}) ON eir.${table} TO ${grantee}`); + try { + const { rows } = await f.admin.query( + `SELECT + has_table_privilege($1::name, $2, $3) AS table_grant, + has_any_column_privilege($1::name, $2, $3) AS column_grant`, + [f.roleA, `eir.${table}`, privilege], + ); + assert.equal( + rows[0].table_grant, + false, + 'table-level checks alone cannot detect this grant', + ); + assert.equal(rows[0].column_grant, true); + await assert.rejects( + f.open(), + /unsafe mutation privileges|alter tenant or migration metadata/, + ); + } finally { + await f.admin.query(`REVOKE ${privilege} (${columns}) ON eir.${table} FROM ${grantee}`); + } + } + await (await f.open()).health(); + }, +); + +test( + 'postgres: startup rejects TRUNCATE privileges on every data table including access and login state', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + for (const table of [...postgresDataTables, 'schema_migrations']) { + await f.admin.query(`GRANT TRUNCATE ON eir.${table} TO ${role}`); + try { + await assert.rejects(f.open(), /unsafe mutation privileges/); + } finally { + await f.admin.query(`REVOKE TRUNCATE ON eir.${table} FROM ${role}`); + } + } + await f.admin.query('GRANT TRUNCATE ON eir.sessions TO PUBLIC'); + try { + await assert.rejects(f.open(), /unsafe mutation privileges/); + } finally { + await f.admin.query('REVOKE TRUNCATE ON eir.sessions FROM PUBLIC'); + } + await (await f.open()).health(); + }, +); + +test( + 'postgres: startup rejects permission to disable integrity triggers through session_replication_role', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + for (const privilege of ['SET', 'ALTER SYSTEM']) { + await f.admin.query(`GRANT ${privilege} ON PARAMETER session_replication_role TO ${role}`); + try { + await assert.rejects(f.open(), /can disable integrity triggers/); + if (privilege === 'SET') { + const client = await f.raw(); + await client.query("SET session_replication_role = 'replica'"); + assert.equal( + (await client.query('SHOW session_replication_role')).rows[0].session_replication_role, + 'replica', + ); + await client.query('RESET session_replication_role'); + } + } finally { + await f.admin.query( + `REVOKE ${privilege} ON PARAMETER session_replication_role FROM ${role}`, + ); + } + } + await (await f.open()).health(); + }, +); + +test( + 'postgres: startup rejects unsafe effective, role, and database replication-role defaults', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + const db = identifier((await f.admin.query('SELECT current_database() AS name')).rows[0].name); + await f.admin.query(`ALTER ROLE ${role} SET session_replication_role = 'replica'`); + try { + await assert.rejects(f.open(), /integrity triggers must remain enabled/); + } finally { + await f.admin.query(`ALTER ROLE ${role} RESET session_replication_role`); + } + await f.admin.query(`ALTER DATABASE ${db} SET session_replication_role = 'replica'`); + try { + await assert.rejects(f.open(), /integrity triggers must remain enabled/); + await f.admin.query(`ALTER ROLE ${role} SET session_replication_role = 'origin'`); + try { + const client = await f.raw(); + assert.equal( + (await client.query('SHOW session_replication_role')).rows[0].session_replication_role, + 'origin', + ); + await assert.rejects(f.open(), /integrity triggers must remain enabled/); + } finally { + await f.admin.query(`ALTER ROLE ${role} RESET session_replication_role`); + } + } finally { + await f.admin.query(`ALTER DATABASE ${db} RESET session_replication_role`); + } + await f.admin.query( + `ALTER ROLE ${role} IN DATABASE ${db} SET session_replication_role = 'replica'`, + ); + try { + await assert.rejects(f.open(), /integrity triggers must remain enabled/); + } finally { + await f.admin.query(`ALTER ROLE ${role} IN DATABASE ${db} RESET session_replication_role`); + } + await (await f.open()).health(); + }, +); + +test( + 'postgres: startup rejects extra permissive policies despite valid migration checksums and RLS flags', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + for (const table of postgresDataTables) { + await f.admin.query( + `CREATE POLICY review_bypass ON eir.${table} FOR SELECT TO ${role} USING (true)`, + ); + try { + await assert.rejects(f.open(), /policy definitions do not match migrations/); + } finally { + await f.admin.query(`DROP POLICY review_bypass ON eir.${table}`); + } + } + await (await f.open()).health(); + }, +); + +test( + 'postgres: startup validates policy predicates, roles, command scopes, and permissiveness', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const role = identifier(f.roleA); + const owner = identifier((await f.admin.query('SELECT current_user AS role')).rows[0].role); + const predicate = + 'tenant = (SELECT tenant FROM eir.tenant_roles WHERE runtime_role = current_user)'; + const cases = [ + { + alter: 'ALTER POLICY tenant_scope ON eir.entities USING (true)', + restore: `ALTER POLICY tenant_scope ON eir.entities USING (${predicate})`, + }, + { + alter: 'ALTER POLICY tenant_scope ON eir.entities WITH CHECK (true)', + restore: `ALTER POLICY tenant_scope ON eir.entities WITH CHECK (${predicate})`, + }, + { + alter: 'ALTER POLICY tenant_scope ON eir.tenant_roles USING (true)', + restore: + 'ALTER POLICY tenant_scope ON eir.tenant_roles USING (runtime_role = current_user)', + }, + { + alter: `ALTER POLICY tenant_scope ON eir.entities TO ${role}`, + restore: 'ALTER POLICY tenant_scope ON eir.entities TO PUBLIC', + }, + { + alter: 'ALTER POLICY operator_access ON eir.entities TO PUBLIC', + restore: `ALTER POLICY operator_access ON eir.entities TO ${owner}`, + }, + { + alter: `ALTER POLICY operator_access ON eir.entities TO ${owner}, ${role}`, + restore: `ALTER POLICY operator_access ON eir.entities TO ${owner}`, + }, + ]; + for (const { alter, restore } of cases) { + await f.admin.query(alter); + try { + await assert.rejects(f.open(), /policy definitions do not match migrations/); + } finally { + await f.admin.query(restore); + } + } + for (const scope of ['AS RESTRICTIVE', 'FOR SELECT']) { + await f.admin.query('DROP POLICY tenant_scope ON eir.entities'); + await f.admin.query( + `CREATE POLICY tenant_scope ON eir.entities ${scope} USING (${predicate})`, + ); + try { + await assert.rejects(f.open(), /policy definitions do not match migrations/); + } finally { + await f.admin.query('DROP POLICY tenant_scope ON eir.entities'); + await f.admin.query( + `CREATE POLICY tenant_scope ON eir.entities USING (${predicate}) WITH CHECK (${predicate})`, + ); + } + } + // A caller-controlled search path must not change canonical policy verification. + await f.admin.query(`ALTER ROLE ${role} SET search_path = eir, public`); + try { + await (await f.open()).health(); + } finally { + await f.admin.query(`ALTER ROLE ${role} RESET search_path`); + } + }, +); diff --git a/tests/postgres-workflow.e2e.ts b/tests/postgres-workflow.e2e.ts new file mode 100644 index 0000000..e233375 --- /dev/null +++ b/tests/postgres-workflow.e2e.ts @@ -0,0 +1,89 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { chromium, expect } from '@playwright/test'; +import { postgresClinicalFixture, expectStatus } from './postgres-clinical-helpers.ts'; +import { postgresTestOptions } from './postgres-helpers.ts'; +import { root } from './helpers.ts'; + +test( + 'two PostgreSQL-backed browser sessions preserve the losing draft and recover explicitly', + postgresTestOptions, + async (t) => { + const f = await postgresClinicalFixture(); + const browser = await chromium.launch(); + t.after(async () => { + await browser.close(); + await f.cleanup(); + }); + const note = expectStatus( + await f.http(0, 'doctor', `/patients/${f.patient.id}/records/note`, { + encounterId: f.encounter.id, + text: 'Ursprunglig journaltext', + }), + 201, + ); + const pages = []; + const errors: string[] = []; + for (const index of [0, 1]) { + const page = await browser.newPage({ viewport: { width: 1440, height: 950 } }); + page.on('pageerror', (error) => errors.push(error.message)); + const token = await f.runtimes[index].get('identity').issue!(f.actors[index].doctor); + await page.goto(f.urls[index]); + await page.getByLabel('Sessionsnyckel').fill(token); + await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); + await page.getByRole('heading', { name: 'Synthetic PostgreSQL patient' }).waitFor(); + await page.getByRole('button', { name: 'Anteckningar', exact: true }).click(); + await page.getByRole('button', { name: 'Redigera', exact: true }).click(); + await expect(page.getByLabel('Journaltext', { exact: true })).toHaveValue( + 'Ursprunglig journaltext', + ); + pages.push(page); + } + await pages[0] + .getByLabel('Journaltext', { exact: true }) + .fill('Sparad text från första sessionen'); + await expect(pages[0].locator('.draft-status')).toContainText('Sparat'); + await pages[1] + .getByLabel('Journaltext', { exact: true }) + .fill('Bevarad osparad text från andra sessionen'); + await expect(pages[1].locator('.draft-conflict')).toBeVisible(); + await expect(pages[1].getByLabel('Journaltext', { exact: true })).toHaveValue( + 'Bevarad osparad text från andra sessionen', + ); + await expect(pages[1].locator('.draft-conflict p')).toHaveText( + 'Sparad text från första sessionen', + ); + assert.equal( + (await f.runtimes[0].get('store').get(f.actors[0].doctor.tenant, note.id))!.data.text, + 'Sparad text från första sessionen', + ); + await pages[1].screenshot({ + path: root + 'test-results/postgres-conflict-desktop.png', + fullPage: true, + }); + await pages[1].setViewportSize({ width: 390, height: 844 }); + assert.equal( + await pages[1].evaluate(() => document.documentElement.scrollWidth > innerWidth), + false, + ); + await pages[1].screenshot({ + path: root + 'test-results/postgres-conflict-mobile.png', + fullPage: true, + }); + pages[1].once('dialog', (dialog) => dialog.accept()); + await pages[1].getByRole('button', { name: 'Läs in sparad version' }).click(); + await expect(pages[1].getByLabel('Journaltext', { exact: true })).toHaveValue( + 'Sparad text från första sessionen', + ); + await pages[1] + .getByLabel('Journaltext', { exact: true }) + .fill('Sammanställd och sparad journaltext'); + await expect(pages[1].locator('.draft-status')).toContainText('Sparat'); + assert.equal( + (await f.runtimes[0].get('store').get(f.actors[0].doctor.tenant, note.id))!.data.text, + 'Sammanställd och sparad journaltext', + ); + assert.equal((await f.runtimes[0].get('store').verifyAudit()).ok, true); + assert.deepEqual(errors, []); + }, +); diff --git a/tests/postgres.test.ts b/tests/postgres.test.ts new file mode 100644 index 0000000..9c71a60 --- /dev/null +++ b/tests/postgres.test.ts @@ -0,0 +1,324 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { Fault } from '../packages/contracts.ts'; +import { barrier, postgresFixture, postgresTestOptions } from './postgres-helpers.ts'; + +const conflict = (error: unknown) => error instanceof Fault && error.status === 409; + +test( + 'postgres: Store contract survives restart, with scoped sessions and one-use login state', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + b = await f.open(f.configB); + const patient = await a.insert(f.actorA, 'patient', null, { + name: 'Synthetic', + identifier: { system: 'test', value: '001' }, + }); + assert.deepEqual(await a.get(f.actorA.tenant, patient.id), patient); + assert.equal((await a.list(f.actorA.tenant, undefined, 'patient')).length, 1); + const revised = await a.revise( + f.actorA, + { ...patient, patientId: 'untrusted' }, + 1, + { name: 'Synthetic revised' }, + 'patient.updated', + ); + assert.equal(revised.patientId, patient.id); + assert.deepEqual(await a.history(f.actorA.tenant, patient.id), [patient, revised]); + const changes = await a.changes(f.actorA.tenant, patient.id, 0); + assert.deepEqual( + changes.map((row) => row.record), + [patient, revised], + ); + assert.equal((await a.changes(f.actorA.tenant, patient.id, changes[0].cursor)).length, 1); + const expires = new Date(Date.now() + 60_000).toISOString(); + await a.grant(f.actorA.tenant, patient.id, 'synthetic-proxy', 'proxy', expires); + assert.deepEqual(await a.getGrant(f.actorA.tenant, patient.id, 'synthetic-proxy'), { + role: 'proxy', + expires, + }); + await a.restrict(f.actorA.tenant, patient.id, true); + assert.equal(await a.isBlocked(f.actorA.tenant, patient.id), true); + await a.saveSession('same-hash', f.actorA, expires); + await b.saveSession('same-hash', f.actorB, expires); + await a.updateSession('same-hash', { ...f.actorA, assignmentId: 'new-assignment' }); + assert.equal((await a.session('same-hash'))?.actor.assignmentId, 'new-assignment'); + assert.deepEqual((await b.session('same-hash'))?.actor, f.actorB); + await a.saveLogin('same-login', { nonce: 'nonce-a' }, expires); + await b.saveLogin('same-login', { nonce: 'nonce-b' }, expires); + assert.deepEqual(await a.consumeLogin('same-login'), { nonce: 'nonce-a' }); + assert.equal(await a.consumeLogin('same-login'), undefined); + assert.deepEqual(await b.consumeLogin('same-login'), { nonce: 'nonce-b' }); + await a.saveLogin('expired', { nonce: 'expired' }, '2000-01-01T00:00:00.000Z'); + assert.equal(await a.consumeLogin('expired'), undefined); + await a.audit(f.actorA, 'chart.read', patient.id, undefined, 'denied'); + const page = await a.auditPage(f.actorA.tenant, { + unitId: 'unit-a', + limit: 1, + outcome: 'denied', + actorId: f.actorA.id, + patientId: patient.id, + }); + assert.equal(page.length, 1); + assert.equal(page[0].tenant, f.actorA.tenant); + assert.deepEqual(await a.auditEntry(f.actorA.tenant, page[0].seq), page[0]); + assert.equal( + (await a.auditPage(f.actorA.tenant, { unitId: 'unit-a', limit: 10, before: page[0].seq })) + .length, + 2, + ); + assert.equal((await a.auditEntries(f.actorA.tenant, patient.id)).length, 3); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 3 }); + await a.health(); + await a.close(); + await a.close(); + await assert.rejects(a.health(), (error: any) => error.status === 503); + const restarted = await f.open(); + assert.deepEqual(await restarted.get(f.actorA.tenant, patient.id), revised); + assert.equal((await restarted.session('same-hash'))?.actor.assignmentId, 'new-assignment'); + await restarted.revokeSession('same-hash'); + assert.equal(await restarted.session('same-hash'), undefined); + assert.deepEqual((await b.session('same-hash'))?.actor, f.actorB); + assert.deepEqual(await restarted.verifyAudit(), { ok: true, count: 3 }); + }, +); + +test( + 'postgres: independent clients reject stale CAS and preserve signed notes', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + other = await f.open(); + const note = await a.insert(f.actorA, 'note', null, { + status: 'draft', + text: 'Synthetic note', + }); + const stale = (await other.get(f.actorA.tenant, note.id))!; + const signed = await a.revise( + f.actorA, + note, + note.version, + { status: 'signed', text: 'Synthetic note' }, + 'note.signed', + ); + let casCalls = 0; + await assert.rejects( + other.transaction(async () => { + casCalls++; + return other.revise( + f.actorA, + stale, + stale.version, + { status: 'draft', text: 'Stale' }, + 'note.updated', + ); + }), + conflict, + ); + assert.equal(casCalls, 1, 'stale CAS must not replay the callback'); + await assert.rejects( + other.revise(f.actorA, signed, signed.version, { status: 'draft' }, 'note.updated'), + conflict, + ); + const raw = await f.raw(); + await assert.rejects( + raw.query( + 'UPDATE eir.entities SET data = \'{"status":"draft"}\', version = version + 1 WHERE id = $1', + [note.id], + ), + (e: any) => e.code === '23514', + ); + for (const sql of [ + 'UPDATE eir.versions SET snapshot = snapshot', + 'DELETE FROM eir.versions', + 'TRUNCATE eir.versions', + 'UPDATE eir.audit SET body = body', + 'DELETE FROM eir.audit', + 'TRUNCATE eir.audit', + 'DELETE FROM eir.entities', + ]) + await assert.rejects(raw.query(sql), (e: any) => e.code === '42501'); + assert.deepEqual(await other.get(f.actorA.tenant, note.id), signed); + assert.equal((await other.history(f.actorA.tenant, note.id)).length, 2); + assert.deepEqual(await other.verifyAudit(), { ok: true, count: 2 }); + }, +); + +test( + 'postgres: nested transactions join and caught failures leave the entire transaction rollback-only', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(); + await assert.rejects( + a.transaction(async () => { + await a.insert(f.actorA, 'patient', null, { name: 'Rolled back' }); + try { + await a.transaction(async () => { + await a.saveSession('rolled-back', f.actorA, '2099-01-01T00:00:00.000Z'); + throw new Error('nested failure'); + }); + } catch { + /* Caller cannot rescue a failed nested transaction. */ + } + }), + /nested failure/, + ); + assert.deepEqual(await a.list(f.actorA.tenant), []); + assert.equal(await a.session('rolled-back'), undefined); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 0 }); + await a.transaction(async () => { + await a.transaction(async () => { + await a.insert(f.actorA, 'patient', null, { name: 'Committed' }); + }); + await Promise.all(Array.from({ length: 8 }, (_, i) => a.audit(f.actorA, `test.${i}`))); + }); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 9 }); + }, +); + +test( + 'postgres: audit failure rolls back standalone insert and revision including version and head', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(); + const entity = await a.insert(f.actorA, 'patient', null, { name: 'Before failure' }); + await f.admin + .query(`CREATE FUNCTION eir.inject_audit_failure() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'synthetic-secret-must-not-leak' USING DETAIL = 'synthetic-sensitive-value'; END; $$; + CREATE TRIGGER zz_audit_failure BEFORE INSERT ON eir.audit FOR EACH ROW EXECUTE FUNCTION eir.inject_audit_failure();`); + const safeError = (error: any) => + error instanceof Fault && + error.status === 503 && + !JSON.stringify(error).includes('synthetic'); + await assert.rejects( + a.insert(f.actorA, 'patient', null, { name: 'Should not exist' }), + safeError, + ); + await assert.rejects( + a.revise(f.actorA, entity, 1, { name: 'Should not change' }, 'patient.updated'), + safeError, + ); + assert.deepEqual(await a.list(f.actorA.tenant), [entity]); + assert.deepEqual(await a.history(f.actorA.tenant, entity.id), [entity]); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 1 }); + await f.admin.query('DROP TRIGGER zz_audit_failure ON eir.audit'); + await a.audit(f.actorA, 'recovered'); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 2 }); + }, +); + +test( + 'postgres: serializable clinical predicate race admits only one writer across independent pools', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + b = await f.open(); + const ready = barrier(); + const book = (store: typeof a) => + store.transaction(async () => { + const appointments = await store.list(f.actorA.tenant, undefined, 'appointment'); + if (appointments.length) throw new Fault(409, 'Appointment slot no longer available'); + await ready(); + return store.insert(f.actorA, 'appointment', null, { slot: 'synthetic-exclusive-slot' }); + }); + const results = await Promise.allSettled([book(a), book(b)]); + assert.equal(results.filter((r) => r.status === 'fulfilled').length, 1); + assert.equal(results.filter((r) => r.status === 'rejected' && conflict(r.reason)).length, 1); + assert.equal((await a.list(f.actorA.tenant, undefined, 'appointment')).length, 1); + assert.deepEqual(await b.verifyAudit(), { ok: true, count: 1 }); + }, +); + +test( + 'postgres: database deadlocks replay whole transactions and concurrent audit writers keep one chain', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + b = await f.open(); + const patient1 = await a.insert(f.actorA, 'patient', null, {}); + const patient2 = await a.insert(f.actorA, 'patient', null, {}); + const expires = '2099-01-01T00:00:00.000Z'; + for (const patient of [patient1, patient2]) + await a.grant(f.actorA.tenant, patient.id, 'proxy', 'proxy', expires); + const ready = barrier(); + let attempts = 0; + const write = (store: typeof a, first: string, second: string) => + store.transaction(async () => { + attempts++; + await store.grant(f.actorA.tenant, first, 'proxy', 'clinician', expires); + await ready(); + await store.grant(f.actorA.tenant, second, 'proxy', 'clinician', expires); + }); + const results = await Promise.allSettled([ + write(a, patient1.id, patient2.id), + write(b, patient2.id, patient1.id), + ]); + assert.equal(results.filter((r) => r.status === 'fulfilled').length, 2); + assert.ok(attempts >= 3, 'the deadlocked callback must replay'); + await Promise.all([a.audit(f.actorA, 'client.a'), b.audit(f.actorA, 'client.b')]); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 4 }); + }, +); + +test( + 'postgres: parallel independent inserts and audited chart reads succeed without caller retries', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(), + b = await f.open(); + const patients = await Promise.all([ + a.insert(f.actorA, 'patient', null, { name: 'One' }), + b.insert(f.actorA, 'patient', null, { name: 'Two' }), + ]); + await Promise.all( + Array.from({ length: 8 }, (_, i) => { + const store = i % 2 ? a : b; + return store.transaction(async () => { + assert.equal((await store.list(f.actorA.tenant, patients[i % 2].id)).length, 1); + await store.audit(f.actorA, 'chart.read', patients[i % 2].id); + }); + }), + ); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 10 }); + }, +); + +test( + 'postgres: persistent serialization failure is bounded and surfaces Fault409 without partial writes', + postgresTestOptions, + async (t) => { + const f = await postgresFixture(); + t.after(f.cleanup); + const a = await f.open(); + await f.admin + .query(`CREATE FUNCTION eir.inject_serialization_failure() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'forced serialization failure' USING ERRCODE = '40001'; END; $$; + CREATE TRIGGER zz_serialization_failure BEFORE INSERT ON eir.audit FOR EACH ROW EXECUTE FUNCTION eir.inject_serialization_failure();`); + let attempts = 0; + await assert.rejects( + a.transaction(async () => { + attempts++; + await a.insert(f.actorA, 'patient', null, { name: 'Must roll back every attempt' }); + }), + conflict, + ); + assert.equal(attempts, 4, 'one initial attempt plus at most three retries'); + assert.deepEqual(await a.list(f.actorA.tenant), []); + assert.deepEqual(await a.verifyAudit(), { ok: true, count: 0 }); + }, +); diff --git a/tests/public.e2e.ts b/tests/public.e2e.ts index abd2775..f5c0b96 100644 --- a/tests/public.e2e.ts +++ b/tests/public.e2e.ts @@ -3,8 +3,7 @@ import assert from 'node:assert/strict'; import { chromium } from '@playwright/test'; import { createPublicDemo } from '../apps/public-demo.ts'; import { root } from './helpers.ts'; - -test('public visitor can start, use the real chart and read the contributor guide', async (t) => { +await test('public visitor can start, use the real chart and read the contributor guide', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); const remote = process.env.EIR_DEMO_TEST_URL; @@ -57,12 +56,14 @@ test('public visitor can start, use the real chart and read the contributor guid .locator('#content') .getByText('Allergisk rinit orsakad av pollen', { exact: true }) .waitFor(); - await page.route('**/api/terminology/diagnoses?*', (route) => - route.fulfill({ - status: 503, - contentType: 'application/json', - body: JSON.stringify({ error: 'Test outage' }), - }), + await page.route( + '**/api/terminology/diagnoses?*', + async (route) => + await route.fulfill({ + status: 503, + contentType: 'application/json', + body: JSON.stringify({ error: 'Test outage' }), + }), ); await page.getByRole('button', { name: 'Lägg till', exact: true }).click(); await page.getByText('Kunde inte hämta diagnoser.', { exact: true }).waitFor(); diff --git a/tests/security.test.ts b/tests/security.test.ts index fffd60a..d00c6a0 100644 --- a/tests/security.test.ts +++ b/tests/security.test.ts @@ -6,35 +6,38 @@ test('care relationship, tenant, role, restriction and proxy expiry all constrai const f = await fixture(); t.after(() => f.runtime.stop()); const access = f.runtime.get('access'); - assert.throws( + await assert.rejects( () => f.clinical.chart({ ...doctor, tenant: 'clinic-b' }, f.patient.id), /No active/, ); - assert.throws(() => f.clinical.chart({ ...doctor, id: 'unassigned' }, f.patient.id), /No active/); + await assert.rejects( + () => f.clinical.chart({ ...doctor, id: 'unassigned' }, f.patient.id), + /No active/, + ); const proxy = { id: 'guardian', tenant: doctor.tenant, role: 'proxy' as const }; - assert.throws(() => f.clinical.chart(proxy, f.patient.id), /No active/); - access.grant(doctor, f.patient.id, proxy.id, 'proxy', '2099-01-01T00:00:00Z'); - assert.equal(f.clinical.chart(proxy, f.patient.id).length, 2); - assert.throws( + await assert.rejects(() => f.clinical.chart(proxy, f.patient.id), /No active/); + await access.grant(doctor, f.patient.id, proxy.id, 'proxy', '2099-01-01T00:00:00Z'); + assert.equal((await f.clinical.chart(proxy, f.patient.id)).length, 2); + await assert.rejects( () => f.clinical.create(proxy, f.patient.id, 'task', { title: 'Write', due: '2027-01-01' }), /No active/, ); f.store.db .prepare('UPDATE grants SET expires=? WHERE actorId=?') .run('2000-01-01T00:00:00.000Z', proxy.id); - assert.throws(() => f.clinical.chart(proxy, f.patient.id), /No active/); + await assert.rejects(() => f.clinical.chart(proxy, f.patient.id), /No active/); const self = { id: 'patient-login', tenant: doctor.tenant, role: 'patient' as const, patientId: f.patient.id, }; - access.block(self, f.patient.id, true); - assert.throws(() => f.clinical.chart(doctor, f.patient.id), /No active/); - assert.equal(f.clinical.patients(doctor).length, 0); - assert.equal(f.clinical.chart(self, f.patient.id).length, 2); - access.block(self, f.patient.id, false); - assert.equal(f.clinical.chart(doctor, f.patient.id).length, 2); + await access.block(self, f.patient.id, true); + await assert.rejects(() => f.clinical.chart(doctor, f.patient.id), /No active/); + assert.equal((await f.clinical.patients(doctor)).length, 0); + assert.equal((await f.clinical.chart(self, f.patient.id)).length, 2); + await access.block(self, f.patient.id, false); + assert.equal((await f.clinical.chart(doctor, f.patient.id)).length, 2); assert.ok( f.store.db .prepare("SELECT count(*) AS n FROM audit WHERE json_extract(body,'$.outcome')='denied'") @@ -44,7 +47,7 @@ test('care relationship, tenant, role, restriction and proxy expiry all constrai test('patients do not see draft notes or AI proposals, including in history/export', async (t) => { const f = await fixture(); t.after(() => f.runtime.stop()); - const note = f.clinical.create(doctor, f.patient.id, 'note', { + const note = await f.clinical.create(doctor, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Draft', }); @@ -55,24 +58,24 @@ test('patients do not see draft notes or AI proposals, including in history/expo role: 'patient' as const, patientId: f.patient.id, }; - assert.equal(f.clinical.chart(self, f.patient.id).length, 2); - assert.equal(f.clinical.history(self, note.id).length, 0); - f.clinical.transition(doctor, note.id, 'sign', 1, {}); - assert.equal(f.clinical.history(self, note.id).length, 1); + assert.equal((await f.clinical.chart(self, f.patient.id)).length, 2); + assert.equal((await f.clinical.history(self, note.id)).length, 0); + await f.clinical.transition(doctor, note.id, 'sign', 1, {}); + assert.equal((await f.clinical.history(self, note.id)).length, 1); }); test('HTTP fails closed, ignores spoofed roles, blocks audit and expires/revokes tokens', async (t) => { const f = await fixture(); const app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); assert.equal((await app.inject('/api/patients')).statusCode, 401); assert.equal( (await app.inject({ url: '/api/patients', headers: { 'x-eir-role': 'admin' } })).statusCode, 401, ); - const token = f.runtime.get('identity').issue!(doctor); + const token = await f.runtime.get('identity').issue!(doctor); const headers = { authorization: `Bearer ${token}` }; assert.equal((await app.inject({ url: '/api/patients', headers })).json().length, 1); assert.equal((await app.inject({ url: '/api/audit', headers })).statusCode, 403); @@ -94,7 +97,7 @@ test('HTTP fails closed, ignores spoofed roles, blocks audit and expires/revokes assert.equal(denied.statusCode, 422); await app.inject({ method: 'POST', url: '/api/logout', headers, payload: {} }); assert.equal((await app.inject({ url: '/api/patients', headers })).statusCode, 401); - const expired = f.runtime.get('identity').issue!(doctor); + const expired = await f.runtime.get('identity').issue!(doctor); f.store.db.exec("UPDATE sessions SET expires='2000-01-01T00:00:00.000Z'"); assert.equal( (await app.inject({ url: '/api/patients', headers: { authorization: `Bearer ${expired}` } })) diff --git a/tests/storage-async.test.ts b/tests/storage-async.test.ts new file mode 100644 index 0000000..02d51e9 --- /dev/null +++ b/tests/storage-async.test.ts @@ -0,0 +1,133 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { SqliteStore } from '../plugins/storage-sqlite.ts'; +import { doctor, fixture, root } from './helpers.ts'; +import { createApp } from '../apps/app.ts'; +import { Runtime } from '../packages/runtime.ts'; +import country from '../plugins/country-se.ts'; +import type { Plugin } from '../packages/contracts.ts'; + +test('runtime rejects synchronous v1 plugins and awaits asynchronous teardown', async () => { + await assert.rejects( + new Runtime().start([{ plugin: { ...country, apiVersion: 1 } as unknown as Plugin }]), + ); + let disposed = false; + const runtime = await new Runtime().start([ + { + plugin: { + ...country, + setup(ctx) { + country.setup(ctx); + ctx.onDispose(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + disposed = true; + }); + }, + }, + }, + ]); + await runtime.stop(); + assert.equal(disposed, true); +}); + +test('SQLite awaited transactions isolate independent callers and roll back nested failures', async (t) => { + const store = new SqliteStore(':memory:'); + t.after(() => store.close()); + let enter!: () => void; + const entered = new Promise((resolve) => { + enter = resolve; + }); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const writing = store.transaction(async () => { + await store.insert(doctor, 'patient', null, { name: 'Uncommitted' }); + enter(); + await gate; + throw new Error('forced rollback'); + }); + const failed = assert.rejects(writing, /forced rollback/); + await entered; + let disclosed = false; + const reading = store.list(doctor.tenant).then((rows) => { + disclosed = true; + return rows; + }); + await new Promise((resolve) => setTimeout(resolve, 10)); + assert.equal(disclosed, false); + release(); + await failed; + assert.deepEqual(await reading, []); + assert.deepEqual(await store.verifyAudit(), { ok: true, count: 0 }); + await assert.rejects( + store.transaction(async () => { + await store.insert(doctor, 'patient', null, { name: 'Must not commit' }); + try { + await store.transaction(async () => { + throw new Error('nested'); + }); + } catch { + /* The transaction remains rollback-only. */ + } + }), + /Transaction failed/, + ); + assert.deepEqual(await store.list(doctor.tenant), []); +}); + +test('standalone inserts atomically roll back when audit append fails', async (t) => { + const store = new SqliteStore(':memory:'); + t.after(() => store.close()); + store.db.exec( + "CREATE TRIGGER test_failure BEFORE INSERT ON audit BEGIN SELECT RAISE(ABORT,'audit failure'); END", + ); + await assert.rejects( + store.insert(doctor, 'patient', null, { name: 'Rollback' }), + /audit failure/, + ); + assert.deepEqual(await store.list(doctor.tenant), []); + assert.equal(store.db.prepare('SELECT count(*) AS n FROM versions').get()!.n, 0); +}); + +test('SQLite revisions use stored immutable fields and closing inside a transaction is rejected', async (t) => { + const store = new SqliteStore(':memory:'); + t.after(() => store.close()); + const patient = await store.insert(doctor, 'patient', null, { name: 'Synthetic' }); + const revised = await store.revise( + doctor, + { ...patient, patientId: 'forged', kind: 'note' }, + 1, + { name: 'Revised' }, + 'patient.updated', + ); + assert.equal(revised.patientId, patient.id); + assert.equal(revised.kind, 'patient'); + await assert.rejects( + store.transaction(async () => { + await store.close(); + }), + /outside its transaction/, + ); + await store.health(); +}); + +test('storage shutdown drains writes and readiness fails without disclosing database details', async (t) => { + const f = await fixture(); + const app = await createApp(f.runtime, root); + t.after(async () => { + await app.close(); + await f.runtime.stop(); + }); + assert.equal((await app.inject('/ready')).statusCode, 200); + const record = f.store.insert(doctor, 'task', f.patient.id, { + title: 'Committed before shutdown', + }); + const closing = f.store.close(); + await record; + await closing; + const response = await app.inject('/ready'); + assert.equal(response.statusCode, 503); + assert.deepEqual(response.json(), { status: 'unavailable' }); + assert.equal((await app.inject('/health')).statusCode, 200); +}); diff --git a/tests/terminology.test.ts b/tests/terminology.test.ts index afc4ab1..c13ae94 100644 --- a/tests/terminology.test.ts +++ b/tests/terminology.test.ts @@ -4,10 +4,9 @@ import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; import { importIcd, icdSource } from '../packages/icd.ts'; import { seedDemo } from '../apps/seed.ts'; - -test('verified Swedish catalogue supports codes, accents, synonyms, categories and bounded results', async (t) => { +await test('verified Swedish catalogue supports codes, accents, synonyms, categories and bounded results', async (t) => { const { runtime } = await fixture(); - t.after(() => runtime.stop()); + t.after(async () => await runtime.stop()); const terms = runtime.get('terminology'); assert.equal(terms.source.count, 38631); assert.equal(terms.source.version, '2026-01-01'); @@ -30,15 +29,14 @@ test('verified Swedish catalogue supports codes, accents, synonyms, categories a assert.throws(() => terms.search('x', 51)); assert.throws(() => importIcd(Buffer.from('unreviewed release')), /checksum/); }); - -test('diagnosis API authenticates, canonicalizes coding and exports its release version', async (t) => { +await test('diagnosis API authenticates, canonicalizes coding and exports its release version', async (t) => { const { runtime, patient } = await fixture(); const app = await createApp(runtime, root); t.after(async () => { await app.close(); - runtime.stop(); + await runtime.stop(); }); - const token = runtime.get('identity').issue!(doctor); + const token = await runtime.get('identity').issue!(doctor); const headers = { authorization: `Bearer ${token}` }; assert.equal((await app.inject({ url: '/api/terminology/diagnoses?q=I10' })).statusCode, 401); const search = await app.inject({ url: '/api/terminology/diagnoses?q=I109&limit=5', headers }); @@ -49,8 +47,8 @@ test('diagnosis API authenticates, canonicalizes coding and exports its release (await app.inject({ url: `/api/terminology/diagnoses?${query}`, headers })).statusCode, 422, ); - const create = (code: Record) => - app.inject({ + const create = async (code: Record) => + await app.inject({ method: 'POST', url: `/api/patients/${patient.id}/records/condition`, headers, @@ -82,20 +80,19 @@ test('diagnosis API authenticates, canonicalizes coding and exports its release icdSource.version, ); }); - -test('fictional patient scenarios have distinct records, open work and immutable signed history', async (t) => { +await test('fictional patient scenarios have distinct records, open work and immutable signed history', async (t) => { const { runtime, clinical } = await fixture(); - t.after(() => runtime.stop()); + t.after(async () => await runtime.stop()); const actor = { ...doctor, tenant: 'demo-clinic' }; - seedDemo(runtime, actor); - const patients = clinical.patients(actor); + await seedDemo(runtime, actor); + const patients = await clinical.patients(actor); assert.equal(patients.length, 4); assert.equal(patients[0].data.name, 'Anna Lindberg'); assert.equal(new Set(patients.map((p) => p.data.identifier.value)).size, 4); for (const patient of patients) { assert.equal(patient.data.identifier.type, 'local'); assert.match(patient.data.identifier.value, /^DEMO-00[1-4]$/); - const chart = clinical.chart(actor, patient.id); + const chart = await clinical.chart(actor, patient.id); assert.equal( chart.filter((r) => r.kind === 'encounter' && r.data.status === 'in-progress').length, 1, diff --git a/tests/workflow.e2e.ts b/tests/workflow.e2e.ts index b931c02..d5dd226 100644 --- a/tests/workflow.e2e.ts +++ b/tests/workflow.e2e.ts @@ -3,8 +3,7 @@ import assert from 'node:assert/strict'; import { chromium } from '@playwright/test'; import { fixture, doctor, root } from './helpers.ts'; import { createApp } from '../apps/app.ts'; - -test('clinician workflow, plugin renderers, responsive layout and persisted source review', async (t) => { +await test('clinician workflow, plugin renderers, responsive layout and persisted source review', async (t) => { let browser: Awaited> | undefined; t.after(() => browser?.close()); const f = await fixture(); @@ -12,7 +11,7 @@ test('clinician workflow, plugin renderers, responsive layout and persisted sour const address = await app.listen({ port: 0, host: '127.0.0.1' }); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); browser = await chromium.launch({ headless: true }); const page = await browser.newPage({ viewport: { width: 1440, height: 950 } }); @@ -20,7 +19,7 @@ test('clinician workflow, plugin renderers, responsive layout and persisted sour const errors: string[] = []; page.on('pageerror', (error) => errors.push(error.message)); await page.goto(address); - await page.getByLabel('Sessionsnyckel').fill(f.runtime.get('identity').issue!(doctor)); + await page.getByLabel('Sessionsnyckel').fill(await f.runtime.get('identity').issue!(doctor)); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); await page.getByRole('heading', { name: 'Syntetisk Patient' }).waitFor(); await page.getByRole('button', { name: 'Anteckningar', exact: true }).click(); @@ -35,7 +34,7 @@ test('clinician workflow, plugin renderers, responsive layout and persisted sour await page.getByRole('button', { name: 'Skapa journalförslag' }).click(); await page.getByRole('button', { name: 'Spara granskat utkast' }).click(); await page.getByText('accepted', { exact: true }).waitFor(); - assert.equal(f.store.list(doctor.tenant, f.patient.id, 'note').length, 2); + assert.equal((await f.store.list(doctor.tenant, f.patient.id, 'note')).length, 2); await page.getByRole('button', { name: 'Journal', exact: true }).click(); await page.getByLabel('Visning').selectOption('table'); await page.locator('table').waitFor(); diff --git a/tests/workforce-helpers.ts b/tests/workforce-helpers.ts index ca9905f..7ef344d 100644 --- a/tests/workforce-helpers.ts +++ b/tests/workforce-helpers.ts @@ -27,22 +27,22 @@ export async function staffFixture( const runtime = loaded.runtime, workforce = runtime.get('workforce'), store = runtime.get('store') as SqliteStore; - const find = (subject: string, role = 'clinician', unit = 'demo-primary-care') => + const find = async (subject: string, role = 'clinician', unit = 'demo-primary-care') => workforce.actor( - workforce - .forIdentity('https://local.eir.invalid', subject) - .find((r) => r.data.role === role && r.data.unitId === unit)!, + (await workforce.forIdentity('https://local.eir.invalid', subject)).find( + (r) => r.data.role === role && r.data.unitId === unit, + )!, ); - const doctor = find('emma'), - admin = find('emma', 'administrator'), - reviewer = find('reviewer', 'auditor'), - nurse = find('david'); - const patient = runtime.get('clinical').register(doctor, { + const doctor = await find('emma'), + admin = await find('emma', 'administrator'), + reviewer = await find('reviewer', 'auditor'), + nurse = await find('david'); + const patient = await runtime.get('clinical').register(doctor, { name: 'Anna Lindberg', birthDate: '1980-01-01', identifier: { type: 'local', value: 'STAFF-TEST-01' }, }); - const encounter = runtime + const encounter = await runtime .get('clinical') .create(doctor, patient.id, 'encounter', { reason: 'Uppföljning' }); return { runtime, workforce, store, doctor, admin, reviewer, nurse, patient, encounter, find }; diff --git a/tests/workforce.e2e.ts b/tests/workforce.e2e.ts index 0ba3c47..8ace6dc 100644 --- a/tests/workforce.e2e.ts +++ b/tests/workforce.e2e.ts @@ -61,19 +61,19 @@ test('public workspace switches between care, audit and administration without e test('reviewer records a durable assessment without receiving clinical access', async (t) => { const f = await staffFixture(); - f.store.audit(f.doctor, 'access.emergency-opened', f.patient.id); + await f.store.audit(f.doctor, 'access.emergency-opened', f.patient.id); const app = await createApp(f.runtime, root), address = await app.listen({ host: '127.0.0.1', port: 0 }); const browser = await chromium.launch({ headless: true }); t.after(async () => { await browser.close(); await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); const page = await browser.newPage({ viewport: { width: 1440, height: 950 } }); page.setDefaultTimeout(15000); await page.goto(address); - await page.locator('[name=token]').fill(f.runtime.get('identity').issue!(f.reviewer)); + await page.locator('[name=token]').fill(await f.runtime.get('identity').issue!(f.reviewer)); await page.getByRole('button', { name: 'Öppna arbetsyta' }).click(); await page.getByRole('heading', { name: 'Åtkomstlogg', exact: true }).waitFor(); assert.equal(await page.locator('.patient-option').count(), 0); @@ -85,7 +85,7 @@ test('reviewer records a durable assessment without receiving clinical access', await page.getByRole('button', { name: 'Registrera granskning' }).click(); await event.locator('summary').click(); await event.getByText('Utredning krävs', { exact: true }).waitFor(); - assert.equal(f.store.list(f.doctor.tenant, undefined, 'accessReview').length, 1); + assert.equal((await f.store.list(f.doctor.tenant, undefined, 'accessReview')).length, 1); await page.getByLabel('Utfall', { exact: true }).selectOption('denied'); await page.getByRole('button', { name: 'Filtrera', exact: true }).click(); await page.getByText('Inga händelser för valt filter.').waitFor(); diff --git a/tests/workforce.test.ts b/tests/workforce.test.ts index 8f257a4..b66660e 100644 --- a/tests/workforce.test.ts +++ b/tests/workforce.test.ts @@ -9,23 +9,24 @@ import { root } from './helpers.ts'; import { SqliteStore } from '../plugins/storage-sqlite.ts'; import { fromConfig } from '../packages/runtime.ts'; import { demoWorkforce } from '../apps/demo-workforce.ts'; +import { tokenHash } from '../packages/staff-sessions.ts'; test('strict authorization separates identity, unit, provider, care relationship and action', async (t) => { const f = await staffFixture(); t.after(() => f.runtime.stop()); const clinical = f.runtime.get('clinical'), access = f.runtime.get('access'); - assert.equal(clinical.chart(f.doctor, f.patient.id).length, 2); + assert.equal((await clinical.chart(f.doctor, f.patient.id)).length, 2); for (const actor of [ f.nurse, f.admin, f.reviewer, - f.find('emma', 'clinician', 'other-unit'), - f.find('emma', 'clinician', 'other-provider'), + await f.find('emma', 'clinician', 'other-unit'), + await f.find('emma', 'clinician', 'other-provider'), { id: f.doctor.id, tenant: f.doctor.tenant, role: 'clinician' as const }, ]) - assert.throws(() => clinical.chart(actor, f.patient.id)); - access.grant( + await assert.rejects(() => clinical.chart(actor, f.patient.id)); + await access.grant( f.doctor, f.patient.id, f.nurse.id, @@ -33,30 +34,36 @@ test('strict authorization separates identity, unit, provider, care relationship new Date(Date.now() + 86400000).toISOString(), 'Assigned care', ); - assert.equal(clinical.chart(f.nurse, f.patient.id).length, 2); - const row = f.workforce.current(f.nurse); - f.workforce.update(f.admin, row.id, row.version, { + assert.equal((await clinical.chart(f.nurse, f.patient.id)).length, 2); + const row = await f.workforce.current(f.nurse); + await f.workforce.update(f.admin, row.id, row.version, { permissions: ['chart.read', 'record.write'], enabled: true, validUntil: row.data.validUntil, reason: 'Restricted duties', }); - const note = clinical.create(f.nurse, f.patient.id, 'note', { + const note = await clinical.create(f.nurse, f.patient.id, 'note', { encounterId: f.encounter.id, text: 'Observation', }); - assert.throws( + await assert.rejects( () => clinical.transition(f.nurse, note.id, 'sign', note.version, {}), /Permission/, ); - assert.throws(() => f.runtime.get('fhir').bundle(f.nurse, f.patient.id), /Permission/); - assert.throws(() => f.runtime.get('medications').add(f.nurse, f.patient.id, {}), /Permission/); - assert.throws(() => f.runtime.get('laboratories').order(f.nurse, f.patient.id, {}), /Permission/); + await assert.rejects(() => f.runtime.get('fhir').bundle(f.nurse, f.patient.id), /Permission/); + await assert.rejects( + () => f.runtime.get('medications').add(f.nurse, f.patient.id, {}), + /Permission/, + ); + await assert.rejects( + () => f.runtime.get('laboratories').order(f.nurse, f.patient.id, {}), + /Permission/, + ); await assert.rejects( f.runtime.get('aiReview').propose(f.nurse, f.patient.id, f.encounter.id), /Permission/, ); - assert.throws( + await assert.rejects( () => access.grant( f.doctor, @@ -67,8 +74,11 @@ test('strict authorization separates identity, unit, provider, care relationship ), /self-grants/, ); - assert.throws(() => f.workforce.update(f.admin, f.doctor.assignmentId!, 1, {}), /yourself/); - assert.throws(() => + await assert.rejects( + () => f.workforce.update(f.admin, f.doctor.assignmentId!, 1, {}), + /yourself/, + ); + await assert.rejects(() => f.workforce.create(f.admin, { ...row.data, actorId: 'new', @@ -78,14 +88,12 @@ test('strict authorization separates identity, unit, provider, care relationship }), ); assert( - f.store - .auditEntries(f.doctor.tenant) - .some( - (r) => - r.action === 'permission.note.sign' && - r.outcome === 'denied' && - r.assignmentId === f.nurse.assignmentId, - ), + (await f.store.auditEntries(f.doctor.tenant)).some( + (r) => + r.action === 'permission.note.sign' && + r.outcome === 'denied' && + r.assignmentId === f.nurse.assignmentId, + ), ); }); @@ -93,25 +101,158 @@ test('session assignment switching, idle expiry, revocation and permission edits const f = await staffFixture(); t.after(() => f.runtime.stop()); const identity = f.runtime.get('identity'); - const token = identity.issue!(f.doctor); + const token = await identity.issue!(f.doctor); const a = await identity.select!(token, f.admin.assignmentId!); assert.equal(a.role, 'administrator'); await assert.rejects(identity.select!(token, f.nurse.assignmentId!), /unavailable/); const session = await identity.authenticate(token); - assert.throws(() => f.runtime.get('clinical').chart(session, f.patient.id)); + assert.equal(session.assignmentId, f.admin.assignmentId); + await assert.rejects(() => f.runtime.get('clinical').chart(session, f.patient.id)); await identity.select!(token, f.doctor.assignmentId!); - const nurseToken = identity.issue!(f.nurse), - row = f.workforce.current(f.nurse); - f.workforce.update(f.admin, row.id, row.version, { + const nurseToken = await identity.issue!(f.nurse), + row = await f.workforce.current(f.nurse); + await f.workforce.update(f.admin, row.id, row.version, { permissions: row.data.permissions, enabled: false, validUntil: row.data.validUntil, reason: 'Employment ended', }); await assert.rejects(identity.authenticate(nurseToken), /revoked/); - assert.throws(() => f.runtime.get('access').check(f.nurse, f.patient.id)); + assert.equal(await f.store.session(tokenHash(nurseToken)), undefined); + assert( + (await f.store.auditEntries(f.doctor.tenant)).some( + (entry) => + entry.action === 'session.assignment-revoked' && + entry.actor === f.nurse.id && + entry.outcome === 'denied', + ), + ); + await assert.rejects(() => f.runtime.get('access').check(f.nurse, f.patient.id)); f.store.db.exec("UPDATE sessions SET lastSeen='2000-01-01T00:00:00.000Z'"); await assert.rejects(identity.authenticate(token), /expired/); + assert.equal(await f.store.session(tokenHash(token)), undefined); +}); + +test('async permission context, team members and eligibility exclude unavailable staff and actions', async (t) => { + const f = await staffFixture(); + t.after(() => f.runtime.stop()); + const access = f.runtime.get('access'); + assert.deepEqual((await access.context!(f.nurse, f.patient.id)).permissions, []); + assert.equal(await access.eligible!(f.doctor, f.nurse.id, f.patient.id, 'chart.read'), false); + assert((await access.members!(f.doctor)).some((member) => member.id === f.nurse.id)); + await access.grant( + f.doctor, + f.patient.id, + f.nurse.id, + 'clinician', + new Date(Date.now() + 86400000).toISOString(), + 'Assigned care', + ); + const row = await f.workforce.current(f.nurse); + const restricted = await f.workforce.update(f.admin, row.id, row.version, { + enabled: true, + permissions: ['chart.read'], + validUntil: row.data.validUntil, + reason: 'Read-only duties', + }); + assert.deepEqual((await access.context!(f.nurse, f.patient.id)).permissions, ['chart.read']); + assert.equal(await access.eligible!(f.doctor, f.nurse.id, f.patient.id, 'chart.read'), true); + assert.equal(await access.eligible!(f.doctor, f.nurse.id, f.patient.id, 'record.write'), false); + assert.equal(await access.allowed(f.nurse, f.patient.id, true), false); + await f.workforce.update(f.admin, row.id, restricted.version, { + enabled: false, + permissions: ['chart.read'], + validUntil: row.data.validUntil, + reason: 'Assignment revoked', + }); + assert.equal(await access.eligible!(f.doctor, f.nurse.id, f.patient.id, 'chart.read'), false); + assert(!(await access.members!(f.doctor)).some((member) => member.id === f.nurse.id)); + await assert.rejects(access.context!(f.nurse, f.patient.id), /No active/); + t.mock.method(f.store, 'get', async () => { + throw new Error('Storage unavailable'); + }); + assert.equal(await access.allowed(f.doctor, f.patient.id), false); + await assert.rejects(access.permit(f.doctor, 'chart.read', f.patient.id), /Permission/); +}); + +test('concurrent staff creation preserves unique assignments and identity mapping', async (t) => { + const f = await staffFixture(); + t.after(() => f.runtime.stop()); + const row = await f.workforce.current(f.nurse); + const input = { ...row.data, actorId: 'new-staff', subject: 'new-staff' }; + const results = await Promise.allSettled([ + f.workforce.create(f.admin, input), + f.workforce.create(f.admin, input), + ]); + assert.equal(results.filter((result) => result.status === 'fulfilled').length, 1); + const rejected = results.find((result) => result.status === 'rejected'); + assert(rejected?.status === 'rejected'); + assert.match(rejected.reason.message, /Assignment already exists/); + assert.equal((await f.workforce.forIdentity(row.data.issuer, 'new-staff')).length, 1); + await assert.rejects( + f.workforce.create(f.admin, { ...input, actorId: 'another-staff' }), + /different staff/, + ); +}); + +test('failed async access and workforce writes roll back their paired mutations', async (t) => { + const f = await staffFixture(); + t.after(() => f.runtime.stop()); + const access = f.runtime.get('access'); + const insert = f.store.insert.bind(f.store); + t.mock.method(f.store, 'insert', async (...args: Parameters) => { + if (['careRelationship', 'assignmentChange'].includes(args[1])) + throw new Error('Follow-up write failed'); + return insert(...args); + }); + await assert.rejects( + access.grant( + f.doctor, + f.patient.id, + f.nurse.id, + 'clinician', + new Date(Date.now() + 86400000).toISOString(), + 'Assigned care', + ), + /Follow-up write failed/, + ); + assert.equal(await f.store.getGrant(f.doctor.tenant, f.patient.id, f.nurse.id), undefined); + assert( + !(await f.store.auditEntries(f.doctor.tenant)).some((entry) => entry.action === 'access.grant'), + ); + const row = await f.workforce.current(f.nurse); + await assert.rejects( + f.workforce.update(f.admin, row.id, row.version, { + enabled: false, + permissions: row.data.permissions, + validUntil: row.data.validUntil, + reason: 'Assignment revoked', + }), + /Follow-up write failed/, + ); + assert.deepEqual(await f.store.get(row.tenant, row.id), row); + assert.equal((await f.store.history(row.tenant, row.id)).length, 1); + assert((await f.store.verifyAudit()).ok); +}); + +test('failed assignment selection still persists expiry and revocation', async (t) => { + const f = await staffFixture(); + t.after(() => f.runtime.stop()); + const identity = f.runtime.get('identity'); + const token = await identity.issue!(f.nurse); + const row = await f.workforce.current(f.nurse); + await f.workforce.update(f.admin, row.id, row.version, { + enabled: false, + permissions: row.data.permissions, + validUntil: row.data.validUntil, + reason: 'Assignment revoked', + }); + await assert.rejects(identity.select!(token, f.doctor.assignmentId!), /revoked/); + assert.equal(await f.store.session(tokenHash(token)), undefined); + const expired = await identity.issue!(f.doctor); + f.store.db.exec("UPDATE sessions SET lastSeen='2000-01-01T00:00:00.000Z'"); + await assert.rejects(identity.select!(expired, f.admin.assignmentId!), /expired/); + assert.equal(await f.store.session(tokenHash(expired)), undefined); }); test('protected identity is excluded from every chart surface and emergency access is constrained and reviewed', async (t) => { @@ -119,11 +260,11 @@ test('protected identity is excluded from every chart surface and emergency acce const app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); const access = f.runtime.get('access'), review = f.runtime.get('accessReview'); - access.grant( + await access.grant( f.doctor, f.patient.id, f.nurse.id, @@ -131,12 +272,12 @@ test('protected identity is excluded from every chart surface and emergency acce new Date(Date.now() + 86400000).toISOString(), 'Assigned care', ); - review.protect(f.doctor, f.patient.id, f.patient.version, { + await review.protect(f.doctor, f.patient.id, f.patient.version, { protected: true, reason: 'Protected identity verified', }); - assert.deepEqual(f.runtime.get('clinical').patients(f.nurse), []); - const headers = { authorization: `Bearer ${f.runtime.get('identity').issue!(f.nurse)}` }; + assert.deepEqual(await f.runtime.get('clinical').patients(f.nurse), []); + const headers = { authorization: `Bearer ${await f.runtime.get('identity').issue!(f.nurse)}` }; for (const url of [ `/api/patients/${f.patient.id}/chart`, `/api/patients/${f.patient.id}/changes`, @@ -144,49 +285,48 @@ test('protected identity is excluded from every chart surface and emergency acce `/api/records/${f.encounter.id}/history`, ]) assert.equal((await app.inject({ url, headers })).statusCode, 403); - assert.throws(() => review.emergency(f.nurse, f.patient.id, { reason: 'Urgent' })); - f.store.grant( + await assert.rejects(() => review.emergency(f.nurse, f.patient.id, { reason: 'Urgent' })); + await f.store.grant( f.doctor.tenant, f.patient.id, f.doctor.id, 'clinician', '2000-01-01T00:00:00.000Z', ); - const grant = review.emergency(f.doctor, f.patient.id, { + const grant = await review.emergency(f.doctor, f.patient.id, { reason: 'Immediate assessment requested', }); - assert(access.allowed(f.doctor, f.patient.id)); - assert.throws(() => access.permit(f.doctor, 'record.write', f.patient.id)); - assert.throws(() => access.permit(f.doctor, 'chart.export', f.patient.id)); + assert(await access.allowed(f.doctor, f.patient.id)); + await assert.rejects(() => access.permit(f.doctor, 'record.write', f.patient.id)); + await assert.rejects(() => access.permit(f.doctor, 'chart.export', f.patient.id)); assert( - !f.runtime - .get('clinical') - .chart(f.doctor, f.patient.id) - .some((r) => r.kind === 'emergencyAccess'), + !(await f.runtime.get('clinical').chart(f.doctor, f.patient.id)).some( + (r) => r.kind === 'emergencyAccess', + ), ); - const page = review.list(f.reviewer, { limit: 100 }); + const page = await review.list(f.reviewer, { limit: 100 }); const event = page.entries.find((r) => r.action === 'access.emergency-opened')!; assert(event); assert.equal(event.entityId, grant.id); - review.review(f.reviewer, { + await review.review(f.reviewer, { seq: event.seq, hash: event.hash, decision: 'follow-up', note: 'Verify the clinical reason with the unit manager', }); assert.equal( - review.list(f.reviewer, { limit: 100 }).entries.find((r) => r.seq === event.seq)?.reviews - .length, + (await review.list(f.reviewer, { limit: 100 })).entries.find((r) => r.seq === event.seq) + ?.reviews.length, 1, ); - const own = review.list(f.reviewer, {}).entries.find((r) => r.actor === f.reviewer.id)!; - assert.throws(() => + const own = (await review.list(f.reviewer, {})).entries.find((r) => r.actor === f.reviewer.id)!; + await assert.rejects(() => review.review(f.reviewer, { seq: own.seq, hash: own.hash, decision: 'justified', note: 'Own' }), ); - assert.throws(() => review.list(f.doctor, {})); - f.store.restrict(f.doctor.tenant, f.patient.id, true); - assert(!access.allowed(f.doctor, f.patient.id)); - assert.throws(() => + await assert.rejects(() => review.list(f.doctor, {})); + await f.store.restrict(f.doctor.tenant, f.patient.id, true); + assert(!(await access.allowed(f.doctor, f.patient.id))); + await assert.rejects(() => review.emergency(f.doctor, f.patient.id, { reason: 'Cannot bypass restriction' }), ); }); @@ -196,19 +336,19 @@ test('audit pagination remains unit-scoped and cannot use the legacy audit bypas app = await createApp(f.runtime, root); t.after(async () => { await app.close(); - f.runtime.stop(); + await f.runtime.stop(); }); - const other = f.find('emma', 'clinician', 'other-unit'); - f.store.audit(other, 'outside-unit'); - for (let i = 0; i < 110; i++) f.store.audit(f.doctor, 'chart.test', f.patient.id); + const other = await f.find('emma', 'clinician', 'other-unit'); + await f.store.audit(other, 'outside-unit'); + for (let i = 0; i < 110; i++) await f.store.audit(f.doctor, 'chart.test', f.patient.id); const review = f.runtime.get('accessReview'); - const first = review.list(f.reviewer, { limit: 40 }), - second = review.list(f.reviewer, { limit: 40, before: first.nextBefore }); + const first = await review.list(f.reviewer, { limit: 40 }), + second = await review.list(f.reviewer, { limit: 40, before: first.nextBefore }); assert(first.nextBefore); assert(second.nextBefore); assert(!second.entries.some((e) => first.entries.some((p) => p.seq === e.seq))); assert(![...first.entries, ...second.entries].some((e) => e.action === 'outside-unit')); - const token = f.runtime.get('identity').issue!(f.reviewer); + const token = await f.runtime.get('identity').issue!(f.reviewer); assert.equal( (await app.inject({ url: '/api/audit', headers: { authorization: `Bearer ${token}` } })) .statusCode, @@ -219,8 +359,8 @@ test('audit pagination remains unit-scoped and cannot use the legacy audit bypas test('AI rechecks current assignment after inference and revoked work is not stored', async (t) => { const f = await staffFixture(); t.after(() => f.runtime.stop()); - const row = f.workforce.current(f.nurse); - f.runtime + const row = await f.workforce.current(f.nurse); + await f.runtime .get('access') .grant( f.doctor, @@ -231,7 +371,7 @@ test('AI rechecks current assignment after inference and revoked work is not sto 'Assigned care', ); f.runtime.get('aiProvider').generate = async (evidence) => { - f.workforce.update(f.admin, row.id, row.version, { + await f.workforce.update(f.admin, row.id, row.version, { permissions: row.data.permissions, enabled: false, validUntil: row.data.validUntil, @@ -243,7 +383,7 @@ test('AI rechecks current assignment after inference and revoked work is not sto f.runtime.get('aiReview').propose(f.nurse, f.patient.id, f.encounter.id), /Permission/, ); - assert.equal(f.store.list(f.doctor.tenant, f.patient.id, 'proposal').length, 0); + assert.equal((await f.store.list(f.doctor.tenant, f.patient.id, 'proposal')).length, 0); }); test('revoked assignments survive restart; v2 sessions and single-use login storage persist safely', async () => { @@ -251,50 +391,53 @@ test('revoked assignments survive restart; v2 sessions and single-use login stor try { const path = join(dir, 'clinic.sqlite'); const f = await staffFixture(path); - const row = f.workforce.current(f.nurse); - f.workforce.update(f.admin, row.id, row.version, { + const row = await f.workforce.current(f.nurse); + await f.workforce.update(f.admin, row.id, row.version, { permissions: row.data.permissions, enabled: false, validUntil: row.data.validUntil, reason: 'Revoked', }); - f.store.saveLogin('flow', { state: 'test' }, new Date(Date.now() + 60000).toISOString()); - f.runtime.stop(); + await f.store.saveLogin('flow', { state: 'test' }, new Date(Date.now() + 60000).toISOString()); + await f.runtime.stop(); const reopened = new SqliteStore(path); - assert.equal(reopened.get(row.tenant, row.id)?.data.enabled, false); - assert.deepEqual(reopened.consumeLogin('flow'), { state: 'test' }); - assert.equal(reopened.consumeLogin('flow'), undefined); - assert(reopened.verifyAudit().ok); - reopened.db.close(); + assert.equal((await reopened.get(row.tenant, row.id))?.data.enabled, false); + assert.deepEqual(await reopened.consumeLogin('flow'), { state: 'test' }); + assert.equal(await reopened.consumeLogin('flow'), undefined); + assert((await reopened.verifyAudit()).ok); + await reopened.close(); const restarted = await fromConfig(root + 'eir.demo.config.json', { 'eir.storage.sqlite': { path }, 'eir.workforce': demoWorkforce('clinic-a'), }); - assert.equal(restarted.runtime.get('store').get(row.tenant, row.id)?.data.enabled, false); - restarted.runtime.stop(); + assert.equal( + (await restarted.runtime.get('store').get(row.tenant, row.id))?.data.enabled, + false, + ); + await restarted.runtime.stop(); } finally { rmSync(dir, { recursive: true, force: true }); } }); -test('v1 migration invalidates old sessions, preserves records and audit, and rejects future schema versions', () => { +test('v1 migration invalidates old sessions, preserves records and audit, and rejects future schema versions', async () => { const dir = mkdtempSync(join(tmpdir(), 'eir-migration-')); try { const path = join(dir, 'old.sqlite'); const old = new SqliteStore(path); const actor = { id: 'legacy', tenant: 'clinic-a', role: 'clinician' as const }; - old.insert(actor, 'patient', null, { name: 'Synthetic legacy record' }); - old.saveSession('old-session', actor, '2099-01-01T00:00:00.000Z'); + await old.insert(actor, 'patient', null, { name: 'Synthetic legacy record' }); + await old.saveSession('old-session', actor, '2099-01-01T00:00:00.000Z'); old.db.exec( 'ALTER TABLE sessions DROP COLUMN lastSeen; DROP TABLE login_transactions; PRAGMA user_version=1;', ); - old.db.close(); + await old.close(); const migrated = new SqliteStore(path); - assert.equal(migrated.session('old-session'), undefined); - assert.equal(migrated.list(actor.tenant).length, 1); - assert(migrated.verifyAudit().ok); + assert.equal(await migrated.session('old-session'), undefined); + assert.equal((await migrated.list(actor.tenant)).length, 1); + assert((await migrated.verifyAudit()).ok); migrated.db.exec('PRAGMA user_version=3;'); - migrated.db.close(); + await migrated.close(); assert.throws(() => new SqliteStore(path), /newer/); } finally { rmSync(dir, { recursive: true, force: true }); From 684d8067dcfd02a19bfe6bad0bb06a8429a2d2ee Mon Sep 17 00:00:00 2001 From: Birger Date: Sat, 19 Sep 2026 08:35:41 +0200 Subject: [PATCH 2/2] Fix PostgreSQL client path in GitHub job environment --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f7a1a3f..85d2703 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,7 +19,7 @@ jobs: --health-interval 5s --health-timeout 3s --health-retries 10 env: EIR_TEST_POSTGRES_URL: postgresql://postgres:eir_disposable_ci_only@127.0.0.1:5432/eir_test - PG_BIN: ${{ runner.temp }}/eir-pg-bin + PG_BIN: /tmp/eir-pg-bin steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4