Imladris is the patient portal and consent layer of a three-part healthcare IT demo. Live at
https://portal.adrianbernhard.ch. All patients are fictional.
1. Overview#
Imladris is a patient-facing web portal that unifies one patient's record across two deliberately separate institutions: Erebor, a hospital running a FHIR R4 server, and Orthanc, a radiology institute running a DICOMweb archive with a small FHIR R5 RIS. Erebor and Orthanc know nothing about each other or about Imladris, and they never share patient ids. Imladris is the only place the fragmented record gets joined, and only for institutions the patient has linked with a single-use code that the institution's own front desk verifies and redeems. Imladris stores identity and link state only; every clinical item is read live from the institution at view time and never persisted.
2. Architecture#
flowchart LR
subgraph Browser
Picker["Account picker<br/>(index.html, login.js)"]
Dash["Dashboard<br/>(dashboard.html, dashboard.js)"]
Viewer["Inline DICOM viewer<br/>(Cornerstone3D bundle, lazy-loaded)"]
Desk["Institution front desk<br/>(popup window, other origin)"]
end
subgraph Imladris["Imladris (Node/Express)"]
API["Patient API<br/>/api/accounts, /api/session,<br/>/api/dashboard, /api/link-codes, /api/links"]
InstAPI["Institution API<br/>/api/institution/link-codes/*<br/>(server-to-server only)"]
Clients["Clients<br/>fhir.js (R4) / dicom.js (DICOMweb + R5)"]
MD["Markdown to sanitized HTML"]
end
DB[("PostgreSQL 16<br/>accounts, institutions,<br/>links, link_codes")]
subgraph Erebor["Erebor (hospital)"]
FHIR["FHIR R4 API"]
EDesk["Front desk backend"]
end
subgraph Orthanc["Orthanc (radiology)"]
DW["DICOMweb<br/>QIDO-RS / WADO-RS"]
RIS["RIS, FHIR R5"]
ODesk["Front desk backend"]
end
Picker --> API
Dash --> API
API --> DB
API --> Clients
Clients --> FHIR
Clients --> DW
Clients --> RIS
API --> MD
Viewer -- "WADO-RS, cross-origin" --> DW
Dash -- "window.open" --> Desk
Desk -. "postMessage nudge" .-> Dash
Desk --> EDesk
Desk --> ODesk
EDesk -- "X-Institution-Key" --> InstAPI
ODesk -- "X-Institution-Key" --> InstAPI
InstAPI --> DB
Walkthrough.
- The visitor picks a demo account. That sets a signed session cookie; there is no password.
/api/dashboard/summaryreturns the account's own details and the institutions it is linked to, from the database only.- For each linked institution the browser opens a Server-Sent Events stream. The server-side
client for that institution's
typereads the record live (FHIR R4 searches for Erebor; QIDO-RS plus the R5 RIS for Orthanc) and streams normalized timeline events. Institutions load concurrently and fail independently. An institution that answers503is starting up (see "Institution starting up" below), which its card shows as a neutral notice with a retry. - Opening a letter or report fetches that one document live, renders its Markdown to sanitized
HTML, and returns it with
Cache-Control: no-store. - "Images" lazy-loads the viewer bundle, which reads pixel data straight from Orthanc's DICOMweb endpoint in the browser.
- Linking a new institution issues a code, opens that institution's front desk in a popup, and the desk's backend looks up and redeems the code against Imladris's institution API. The dashboard learns about the result by polling its own server.
The front desks themselves are part of Erebor and Orthanc, not Imladris. This document covers only the Imladris side of the contract.
3. Stack#
| Layer | Choice | Version (as pinned) |
|---|---|---|
| Runtime | Node.js | node:22.23-alpine base image (Node 22 LTS) |
| Web framework | Express | ^4.19.2 |
| Session | cookie-session (signed cookie, no server store) | ^2.1.0 |
| Database | PostgreSQL | postgres:16.15 image; driver pg ^8.12.0 |
| Document rendering | markdown-it + sanitize-html | ^14.3.2, ^2.18.0 |
| Front end | Static HTML, CSS, vanilla JS, no framework, no build step | n/a |
| DICOM viewer | @cornerstonejs/core, /tools, /dicom-image-loader |
5.8.2 exactly, bumped together |
| Viewer bundler | esbuild (ESM, es2022, minified) | ^0.24.0 |
| WASM codecs | OpenJPEG (JPEG 2000), CharLS (JPEG-LS), libjpeg-turbo 8-bit, OpenJPH (HTJ2K) | from the dicom-image-loader package |
| Tests | Node's built-in node --test |
n/a |
| Infrastructure | Docker Compose (two services), deployed on Coolify | n/a |
| Styling | skeleton.css copied from Erebor's explorer, plus own styles.css (teal #0F6E56) |
n/a |
Server-side fetching uses Node 22's built-in fetch; there is no HTTP client dependency.
4. Data model#
erDiagram
accounts ||--o{ links : "has"
institutions ||--o{ links : "has"
accounts ||--o{ link_codes : "issued for"
institutions ||--o{ link_codes : "redeemable at"
accounts {
serial id PK
text name
date date_of_birth
text sex "male | female | other"
text ahv "999.xxxx.xxxx.xx demo format"
timestamptz created_at
}
institutions {
text id PK "slug: erebor, orthanc"
text name
text type "fhir | dicom"
text base_url
text color_primary
text color_dark
text color_tint
text description
text desk_url
boolean desk_enabled
}
links {
int account_id PK,FK
text institution_id PK,FK
text external_patient_id "non-empty"
text match_level "match | differences | mismatch | unknown"
text_array match_fields
timestamptz updated_at
}
link_codes {
uuid id PK
int account_id FK
text institution_id FK
text code_hash UK "HMAC-SHA256, never the code"
timestamptz created_at
timestamptz expires_at
timestamptz used_at
int failed_attempts
}
| Table | What it is | Notable rules |
|---|---|---|
accounts |
Imladris's own identity for a patient | Not a copy of any institution's record. ahv is constrained by a CHECK to the 999. demo prefix, so a real 756. number cannot be stored. |
institutions |
Institutions as data | Adding a third institution is an INSERT (plus a client if its type is new). No per-institution columns, routes or front-end code. |
links |
One row per linked (account, institution) | The row's existence is the linked state; there is no boolean. Holds the institution's own patient id (Erebor EB + 8 digits, Orthanc OR- + 5 digits). match_level / match_fields have DB CHECKs; only field names are stored, never values. |
link_codes |
Single-use linking codes | Only a keyed hash is stored. "Expired" covers every way a code stops working, because early invalidation pulls expires_at to now(). |
No table holds anything clinical: no conditions, encounters, documents, studies or cached responses.
5. Interfaces#
Pages#
| Path | What |
|---|---|
/ |
Account picker (index.html): the 8 demo accounts, their link tags, "Reset this demo account" where an account differs from its seed. |
/dashboard |
Dashboard (dashboard.html): patient card, Upcoming, institution cards, unified timeline, discovery/link dialog, document reader, viewer. Redirects to the picker without a session. |
/viewer/* |
Generated viewer bundle, decode worker and WASM codecs (static). |
Public, no session#
GET /api/accounts: demo accounts, sorted by number of links, plus every institution's public
fields (never base_url). Each account carries only a modified flag, never its external ids.
curl -s https://portal.adrianbernhard.ch/api/accounts
{
"institutions": [
{ "id": "erebor", "name": "Erebor", "type": "fhir",
"description": "A hospital's FHIR clinical record system",
"colors": { "primary": "#4B3F8C", "dark": "#332B61", "tint": "#ECEAF6" } }
],
"accounts": [
{ "id": 2, "name": "Léa Morand", "date_of_birth": "1992-11-11",
"sex": "female", "linked_institution_ids": ["erebor", "orthanc"], "modified": false }
]
}
(Truncated to one entry each. Birth dates are plain calendar dates, so no visitor time zone can shift them.)
GET /api/session/me: who is signed in, or null.
curl -s https://portal.adrianbernhard.ch/api/session/me
{ "account": null }
Write endpoints, described only:
| Endpoint | Behavior |
|---|---|
POST /api/session/login |
Body names an account id; stamps it into the signed cookie (imladris_session, 24 h, HttpOnly, SameSite=Lax, Secure in production). This is the picker's "sign in". |
POST /api/session/logout |
Clears the cookie. |
POST /api/accounts/:id/reset |
Restores one demo account's identity and links to the seed and deletes its link codes. Open to anyone, like the picker, because it can only ever restore the seed. Rate limited to 5 per minute per client IP. |
Session-scoped (patient)#
All return 401 without a session. The examples assume the cookie set by the picker in a browser.
GET /api/dashboard/summary: DB only, no external calls. Only linked institutions are named.
curl -s -b "imladris_session=<set by the picker>" https://portal.adrianbernhard.ch/api/dashboard/summary
{
"account": { "id": 2, "name": "Léa Morand", "dateOfBirth": "1992-11-11", "sex": "female" },
"institutions": [
{ "id": "orthanc", "name": "Orthanc", "type": "dicom",
"description": "A radiology institute's DICOM imaging archive",
"colors": { "primary": "#2C5F8A", "dark": "#1F4361", "tint": "#E4EEF6" },
"units": [ { "key": "study", "singular": "study", "plural": "studies" },
{ "key": "report", "singular": "report", "plural": "reports" } ],
"match": { "level": "match", "fields": [] } }
]
}
GET /api/dashboard/institutions/:id/events: Server-Sent Events. 404 if not linked. Event
types: page (repeated), then done; or institution-starting ({ "retryAfter": 30 }, the
institution answered 503, see below); or stream-error (deliberately not error, which
EventSource reserves for its own connection failures).
curl -sN -b "imladris_session=<set by the picker>" https://portal.adrianbernhard.ch/api/dashboard/institutions/orthanc/events
event: page
data: {"newEvents":[{"kind":"study","tally":["study","report"],"date":"2024-02-26",
"title":"MRI breast bilateral with contrast","detail":"MR · 6 series · 146 images · Dr. Aline Favre",
"viewer":{"studyInstanceUID":"1.3.6.1.4.1.14519.5.2.1.7695.1700.1152...","dicomWebRoot":"https://dicom.adrianbernhard.ch/dicom-web"},
"document":{"resourceType":"DiagnosticReport","id":"dr-ORT-2024-916693"}}, ...],
"loaded":7,"total":7,"registration":{"name":"Lea Morand","birthDate":"1992-11-11"}}
event: done
data: {}
(Line-wrapped and shortened. Erebor's stream sends one page event per FHIR Bundle page across
five concurrent searches, plus one for the registration. total only feeds the "Loading… x/y"
progress text: it is null until every search has a total, which is Bundle.total when the server
sends one unasked, else the search's own count once its last page is in.)
Paging. Erebor's searches ask for _count=200, the page cap of Erebor's gateway (HAPI's
max_page_size), so a typical patient needs one page per search: five Bundles per load. A second
page cost ~550 ms each on a warm local HAPI. Larger results still follow link[relation=next]
(capped at 200 pages per search). There is no _total=accurate: it costs HAPI an extra count query
per search, and the progress total is derived as above instead. Orthanc's RIS searches send no
_count, so the RIS returns every match in one Bundle (it has no page cap and pages only when
asked); QIDO-RS /studies is one response.
GET /api/dashboard/institutions/:id/documents/:resourceType/:docId: one document, fetched on
open, Cache-Control: no-store. Always the same 404 unless the account is linked, the type is
readable by that client (DocumentReference, DiagnosticReport for FHIR; DiagnosticReport for
DICOM), the id matches ^[A-Za-z0-9.-]{1,64}$, and the document's subject is this account's
patient at that institution. If the institution answers 503 (starting up), this returns 503
{ "error": "starting", "retryAfter": 30 } with the same Retry-After.
curl -s -b "imladris_session=<set by the picker>" \
https://portal.adrianbernhard.ch/api/dashboard/institutions/orthanc/documents/DiagnosticReport/dr-ORT-2024-916693
{ "title": "MRI breast bilateral with contrast", "date": "2024-02-26", "author": "Dr. Aline Favre",
"typeLabel": "Radiology report",
"html": "<p><strong>Orthanc Radiology Institute</strong><br />...</p><hr /><h2>Clinical question</h2>...",
"viewer": { "studyInstanceUID": "1.3.6.1.4.1.14519.5.2.1.7695.1700.1152...",
"dicomWebRoot": "https://dicom.adrianbernhard.ch/dicom-web" } }
GET /api/institutions/:id/status: whether an institution is ready, from its own
GET <origin>/health: { "status": "ready" | "starting" | "unknown", "retryAfter": 30 | null }.
A 503 or {"status":"starting"} is starting; no such endpoint, another answer, a timeout
(4 s) or a connection error is unknown, which the front end treats as ready. 404 unless the
institution's desk is enabled or the account is linked to it. The answer is cached per
institution for 5 s, and concurrent checks share one request, so an institution's /health sees
at most one request every 5 s from Imladris, however many visitors ask. Cache-Control: no-store
towards the browser, and 30 calls per minute per account on top.
GET /api/institutions/discover?q=: institutions not yet linked whose desk is
desk_enabled, filtered by name or description (case-insensitive, q capped at 100 characters,
% and _ escaped). Fetched only when the discovery dialog opens.
curl -s -b "imladris_session=<set by the picker>" "https://portal.adrianbernhard.ch/api/institutions/discover?q=radio"
{ "institutions": [ { "id": "orthanc", "name": "Orthanc", "type": "dicom",
"description": "A radiology institute's DICOM imaging archive",
"colors": { "primary": "#2C5F8A", "dark": "#1F4361", "tint": "#E4EEF6" } } ] }
(For an account not linked to Orthanc. An account linked to both gets [].)
Write endpoints, described only:
| Endpoint | Behavior |
|---|---|
POST /api/link-codes |
Issues a code for one institution: 201 with the code id, the formatted code, expires_at, the desk URL with the code as a query parameter, and the identity the desk will see (name, birth date, AHV). 409 if already linked, 404 if unknown or desk not enabled. 10 per minute per account. |
GET /api/link-codes/:id/status |
pending, redeemed or expired; 404 for a code belonging to another account. |
DELETE /api/links/:institution_id |
Withdraws consent; 204, or 404 if not linked. |
Institution API (server-to-server)#
Called only by the Erebor and Orthanc front-desk backends. Described here, not demonstrated.
| Endpoint | Behavior |
|---|---|
POST /api/institution/link-codes/lookup |
For a live code issued for the calling institution: { status: "valid", claimed_identity }. For every other case (malformed, unknown, expired, used, another institution's) the identical 200 { status: "invalid" }. |
POST /api/institution/link-codes/redeem |
With the code, the institution's own patient id, and an optional match report. In one transaction: verifies, marks used, upserts the link. 200 { status: "redeemed" } or 400 { status: "invalid" }. |
Authentication, browser refusal and rate limits are covered in section 7.
6. Standards#
| Standard | Where | How faithfully |
|---|---|---|
| HL7 FHIR R4 (RESTful search) | Erebor client (server/clients/fhir.js) |
Standard search parameters (patient, _id, date=ge, status), _include, _elements, _count (200), and Bundle paging via link[relation=next] (no _total). search.mode = include entries are used for name lookup and never counted. Encounter class is a v3 ActCode, mapped to plain labels; DiagnosticReport titles come from the v2-0074 category (SP, GE, and others). Attachment text is decoded only for text/markdown or text/plain. |
| HL7 FHIR R5 | Orthanc's RIS (server/clients/dicom.js) |
Reads DiagnosticReport, Patient, Practitioner. Uses R5's DiagnosticReport.study (R4's imagingStudy). The two clients deliberately share no FHIR code, so R4 and R5 assumptions cannot leak into each other. The RIS supports plain searches only, so full reports are fetched and only metadata is streamed. |
| DICOM / DICOMweb | Orthanc client (server) and viewer (browser) | QIDO-RS study search (/studies?PatientID=, with includefield=00081030 for StudyDescription) and series search; WADO-RS series metadata and frame retrieval. Responses in the DICOM JSON model (application/dicom+json), read by tag (0020000D, 00080061, 00201206, ...). PN values parsed from Family^Given^Middle. Non-image modalities (SR, SEG, KO, PR, RT*, REG, DOC) are listed but never opened by default. |
| Swiss AHV number format | accounts.ahv |
Format only, 999. prefix enforced by CHECK. The checksum is not validated by Imladris. |
Mapping to real-world healthcare IT. These are analogies, not implementations:
- Patient identity cross-referencing. Imladris holding
(account, institution, external id)rows is functionally what an IHE PIX cross-reference manager does, except that the cross-reference is created by the patient's own consented action, not by an MPI matching algorithm. The desk'smatchreport loosely resembles the confidence a PDQ demographics query gives a human to decide on. - Consent. The link code plus in-person ID check mirrors the Swiss EPD practice of opening
a record at a registration point after identity verification. Imladris does not use IHE
BPPC/APPC or a FHIR
Consentresource; consent is implicit in the existence of alinksrow, and withdrawal is deleting it. - Document and image access. In a real EPD community, documents flow through IHE XDS.b / MHD and images through XDS-I.b / WIA, behind a registry and with audit logging (ATNA). Imladris instead reads each institution's own open API directly.
- Identifiers. The Swiss EPD identifies a record by the EPR-SPID, issued by the Central Compensation Office (ZAS), not by the AHV number. Using a (demo) AHV number as part of the identity claim the desk matches against is a deliberate simplification of this demo, not how the EPD works.
Simplified on purpose: no SMART on FHIR or OAuth (institution reads are open), no audit trail,
no FHIR Consent, no document registry, no real identity proofing (the desk is a demo), and the
account picker is not authentication at all.
7. Security and privacy#
Access model.
| Surface | Who | Protection |
|---|---|---|
| Account picker, login | Anyone | None by design: any visitor can "become" any demo account. |
| Patient API | Signed-in session | Signed cookie with the account id. Every query is scoped to req.session.accountId; another account's code ids return 404. |
| Document reads | Session + link | Linked check, type allowlist, id regex, and a subject check against the stored external id, all answered with one indistinguishable 404. |
| Institution API | Front-desk backends | Per-institution shared key (X-Institution-Key), see below. |
| Institution data reads | Anyone | Erebor's and Orthanc's read APIs are open in the demo; Imladris adds no secrecy there. |
Client keys. Erebor and Orthanc rate-limit their APIs per IP, and every visitor's reads reach
them from Imladris's one IP. When EREBOR_CLIENT_KEY is set, the FHIR client sends it as
X-Client-Key on every request to Erebor: the timeline stream (all searches and followed next
pages, the registration read) and the single-document read. The DICOM client does the same with
ORTHANC_CLIENT_KEY on every request to Orthanc: the QIDO-RS study search, the RIS searches and
the single-report read. Each key goes to its own institution only, never on Imladris's own routes,
never reaches the browser (these reads are server-side) and never appears in a log or error
message. The in-app viewer's WADO-RS image requests come from the browser and carry no key;
Orthanc's per-IP limit for viewer traffic is sized for one person scrolling a large series. Unset
or empty, no header goes out and the normal limits apply. Keys are looked up as <ID>_CLIENT_KEY
for the institution, so the clients stay generic. test/client-key.test.js checks each case with a
stubbed fetch.
Link codes.
- 8 characters from a 31-symbol alphabet without look-alikes (
0 O 1 I L), viacrypto.randomInt, about 40 bits. Shown asXXXX-XXXX; input is normalized for case, dashes and spaces. - Stored only as HMAC-SHA256 with a key derived from
SESSION_SECRET, so a database dump cannot be brute-forced offline. Rotating the secret only invalidates codes in their 10-minute life. - 10-minute TTL. A newer code for the same pair invalidates the older one; issuing runs under
SELECT ... FOR UPDATEon the account row so two concurrent issues cannot both leave an active code. - Redeem locks the code row, so two concurrent redeems cannot both succeed (covered by a test).
- Failed redeems of a live code (wrong institution, unusable patient id, malformed
match) are counted; the fifth invalidates the code. Guesses that match nothing are bounded by the rate limit. - Lookup answers are uniform, so the API never reveals whether a code exists, expired, was used or belongs to someone else.
Institution API hardening.
- Keys come from
INSTITUTION_KEY_<ID>env vars; keys under 32 characters are ignored. Both sides are SHA-256'd and compared withcrypto.timingSafeEqualagainst every configured key on every call. The key alone determines the institution. - Browser-proof: no CORS headers, the custom header forces a preflight that fails, and any request
carrying
OriginorSec-Fetch-Sitegets403. - Mounted before the app-wide JSON parser; the body (limit 2 kB) is parsed only after auth, and the router has its own error handler that logs only an error class and Postgres code. Codes, identities, keys and raw bodies never reach a log.
- 30 requests per minute per key, per route.
Identity match levels. The desk reports match: { level, fields }, validated strictly:
| Level | Fields | Card badge |
|---|---|---|
match |
none allowed | none |
differences |
at least one | amber "Linked with differences" |
mismatch |
at least one | red "Identity mismatch", plus "If these aren't your records, remove the link." |
unknown |
none (stored when no report was sent; a desk cannot send it) | grey "Identity not checked" |
Fields are drawn from given_name, family_name, birth_date, ahv_missing, ahv_different,
no duplicates, no extra keys. A malformed report counts as a failed attempt.
Popup, postMessage, COOP.
- The desk opens with
window.open(url, "imladris-desk-<id>", "popup,width=520,height=720,..."), placed beside the current window. A blocked popup falls back to a link with the same target name andrel="opener". - The desk posts
{ type: "imladris-link", status: "redeemed" }to its opener. Imladris accepts it only from the pending code's desk origin, and treats it purely as a nudge to ask its own server. A forged message cannot link anything. - The browser polls status every 3 s (polling survives closing the dialog), checks on
visibilitychange, and watchespopup.closedevery second. - Imladris sends
Cross-Origin-Opener-Policy: same-origin-allow-popups. Plainsame-originwould sever the popup reference (closed,openerandpostMessageall lost). The desks must not send a restrictive COOP either.
Rendering untrusted documents. Document text comes from external servers, so it passes two
independent layers: markdown-it with raw HTML disabled and links, images and autolinks off; then
sanitize-html with a structural tag allowlist, no attributes and no URL schemes, discarding
script, style, iframe, svg and similar along with their content. A test feeds it a hostile
document.
What is never stored or logged.
- No clinical data in the database, ever; no server-side cache of institution responses.
- Document responses are
no-store; document-fetch errors log only the institution's HTTP status message, never the content. - Link codes are stored only as HMACs; match reports only as field names.
- All patient data is synthetic. AHV numbers use the non-assigned
999prefix.
Deliberately open in the demo: the account picker and per-account reset (so any visitor can try any scenario), and the institutions' read APIs (so the demo works without credentials).
Response headers (server/securityHeaders.js, on every response, pages and API alike):
| Header | Value and reason |
|---|---|
Content-Security-Policy |
default-src 'self'; script-src 'self' 'wasm-unsafe-eval' (no inline script anywhere; WASM compilation for the viewer's codecs, but not eval); worker-src 'self' (the decode worker); style-src 'self' plus Google Fonts' stylesheet host, font-src Google's font host; img-src 'self' data: blob:; connect-src 'self' plus the origin of every DICOM institution's base_url, read from the database at startup; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'. |
X-Content-Type-Options |
nosniff |
Referrer-Policy |
strict-origin-when-cross-origin: other sites (the front desk, Google Fonts) see only Imladris's origin. |
Cross-Origin-Opener-Policy |
same-origin-allow-popups, for the desk popup (above). |
X-Powered-By is disabled. The policy was checked in Chrome against the picker, the dashboard,
the document reader, the viewer (slice scrolling, series switching, all four WASM codecs
compiling) and the desk popup, with no violations. Scripts set styles only through the CSSOM
(element.style), which CSP does not restrict, so styles need no 'unsafe-inline' either.
Session cookie. HttpOnly and SameSite=Lax always; Secure when NODE_ENV=production
(the compose default). In production Express trusts exactly one proxy hop, Coolify's
TLS-terminating reverse proxy, so it sees the visitor's HTTPS and IP address. The per-IP reset
limit depends on the latter.
8. Operations#
Build. A two-stage Dockerfile: stage one installs all dependencies and runs
npm run build:viewer (esbuild bundles Cornerstone3D, builds the decode worker separately, and
copies four decode-only WASM codecs into public/viewer/); stage two installs production
dependencies only and copies the generated viewer in. public/viewer/ is gitignored and
dockerignored, so a stale local build cannot leak into an image.
Compose. Two services: the app and postgres:16.15 (pinned to a patch release, like Erebor's
and Orthanc's databases) with a named volume. The app waits on a
pg_isready healthcheck (depends_on: service_healthy) and additionally retries its own first
connection (10 attempts, 2 s apart). The app exposes container port 3000 with no host binding.
Deploy. Coolify auto-deploys on every push to main: it builds the compose file and assigns
the public URL to the app service. Coolify's proxy terminates TLS in front of the app.
Startup migration. Every boot runs, in one transaction: legacy links conversion if the old
two-column shape is detected, schema.sql (idempotent IF NOT EXISTS), institutions.sql
(upsert; always owns desk_enabled, fills desk_url only if empty), the optional URL overrides,
then the demo-account sync. Migration failure exits the process non-zero instead of serving with
a broken schema. This replaced Postgres's docker-entrypoint-initdb.d, which once silently left
production with no tables.
Environment variables (names only):
| Name | Required | Purpose |
|---|---|---|
NODE_ENV |
no (compose defaults to production) |
production: secure cookie, trust one proxy hop. development for local plain-http runs. |
DATABASE_URL |
yes (set by compose) | Postgres connection |
POSTGRES_PASSWORD |
yes | Database password used by compose |
SESSION_SECRET |
yes | Signs the session cookie; also the root of the link-code HMAC key |
INSTITUTION_KEY_EREBOR, INSTITUTION_KEY_ORTHANC |
for linking | Front-desk shared keys (32+ characters) |
EREBOR_CLIENT_KEY |
no | Sent to Erebor as X-Client-Key (lifts its per-IP rate limit); unset: no header |
ORTHANC_CLIENT_KEY |
no | Sent to Orthanc as X-Client-Key on server-side calls (lifts its per-IP rate limits); unset: no header |
EREBOR_FHIR_BASE_URL, ORTHANC_BASE_URL |
no | Override institution base_url |
EREBOR_DESK_URL, ORTHANC_DESK_URL |
no | Override institution desk_url |
DEMO_ANCHOR_DATE |
no | Override the pinned birth-date anchor (2026-10-03) |
PORT |
no | Listen port, default 3000 |
TEST_DATABASE_URL, TEST_LIVE_EREBOR |
tests only | Enable DB tests / live birth-date check |
Scheduled jobs. npm run reset-demo restores every demo account's links to the seed and deletes
every link code, in one transaction. It runs as a host-level cron on the VPS at 03:15 UTC, after
Erebor's own 03:00 reset; the README gives the crontab line. Independently, every restart or redeploy also restores demo
links, because the sync runs on startup.
Demo accounts and rolling dates. Eight accounts, generated from a sibling curated-patients
workspace into db/demo-accounts.json (never edited by hand):
| ids | Seeded links |
|---|---|
| 1, 2 | Erebor and Orthanc |
| 3, 4 | Erebor only |
| 5, 6 | Orthanc only |
| 7, 8 | none |
All eight exist at both institutions; link state is only what the patient has linked in Imladris.
Erebor and Orthanc roll their dates forward in whole weeks, so Imladris shifts birth dates by the
same rule at sync time. The reference date is hard-pinned to 2026-10-03 (a 7-day shift), the
anchor Erebor and Orthanc were last built from, with no fallback to today: a birth date one week
off would show up as a birth_date mismatch at the desk. DEMO_ANCHOR_DATE overrides the pin,
and is only meant to be set when the institutions are rebuilt from another anchor; unset, the pin
stands. An opt-in live test compares every demo birth date with Erebor's Patient.birthDate.
A shared weekly rebuild, in which Erebor, Orthanc and Imladris move their dates together from one
shared anchor in the same step, is planned but not running. Until it exists, all three stay on
2026-10-03.
Monitoring and logging. Plain console output to the container log: startup sync summary,
reset counts, and errors (with the redactions described in section 7). Each institution load
(server/eventStream.js) logs one line with the institution id, outcome (done, starting,
error), total time and the number of search pages fetched, e.g. imladris: load erebor done in 412 ms, 5 pages (Orthanc's are QIDO plus RIS responses, the Erebor Patient read isn't counted). No
account, patient id or clinical data. Imladris has no app healthcheck, metrics endpoint or external
monitoring of its own. Rate-limit counters are in memory and reset on restart. Log lines never contain codes, keys, identities or document text.
Institution starting up. After a deploy and after its nightly reset, Erebor's gateway answers
/fhir with 503, Retry-After: 30 and a FHIR OperationOutcome while HAPI starts and warms
up, and reports {"status":"starting"} on GET /health. Imladris treats a 503 from any
institution that way (Orthanc does not send one yet):
- Both clients turn a
503into anInstitutionStartingError(server/clients/starting.js) carryingretryAfterin seconds (delta-seconds or an HTTP date;nullif absent). Timeouts, connection errors, other5xxand4xxstay ordinary errors. - Each institution has its own SSE stream (
server/eventStream.js), so one starting never affects another: the starting one ends withinstitution-starting, the others stream as usual. A page that arrives from a concurrent search after the stream has ended is dropped. - The card shows a neutral notice in the institution's own colors (never the red error style):
"<name> is starting up. Try again in a minute." with Try again, which reloads only that
institution. One automatic retry follows after
Retry-After(default 30 s, kept within 5 s to 2 min); it re-arms only after a load completes. - Opening a document while the institution is starting shows the same notice in the reader, with its own Try again.
- Linking: the code screen asks
/api/institutions/:id/statusonce the code is up, and again when the desk window closes unredeemed. While the institution is starting, the "Open front desk" button gives way to the same notice with Try again (plus one automatic re-check). Codes, polling and redemption are unchanged; the code stays valid meanwhile. - The in-app viewer shows the same notice, with Try again, when a DICOMweb request answers
503: the series list, a series' metadata, or a frame (also one scrolled to after the series loaded; the retry then resumes at that slice). See "Viewer on touchscreens" below. The browser can only read that status because Orthanc's gateway sends CORS headers on every answer; a503from a proxy in front of a stopped gateway, without them, still shows the viewer's generic error. - The viewer also retries once on its own, like the cards: after the failing response's
Retry-After(default 30 s, kept within 5 s to 2 min), resuming at the same slice. Orthanc's gateway exposesRetry-Aftervia CORS (Access-Control-Expose-Headers), so the viewer reads it from its ownfetch()calls and from the image loader's XHRs alike; a hidden or missing header means the default. Several frames failing at once arm one timer, which runs the latest retry. Try again, picking another series or closing the viewer cancels a pending automatic retry, and the automatic retry re-arms only after a series has loaded, so a retry that meets another503leaves just the button (createStartingRetryinviewer-src/dicomweb.js).
Viewer on touchscreens. The viewer (viewer-src/) works with mouse and touch alike, on
Cornerstone3D 5.8.2's own touch support:
- What 5.8.2 offers. Touch bindings are
{ numTouchPoints: n }beside the mouse ones. For a gesture it picks the first active tool, in the tool group's option order (the order of each tool's firstsetTool*()call, not ofaddTool()), whose binding has that many touch points, or, for one finger only, the mouse-primary binding.StackScrollTool,WindowLevelToolandPanToolhave touch-drag handlers;ZoomToolhas a pinch handler that zooms and pans at once (pinchToZoomandpan, both on by default), so two-finger pan needs noPanToolbinding (and a second two-finger binding would never be reached). Taps come asTOUCH_TAPwith atapscount (300 ms window);TOUCH_PRESS(700 ms) andTOUCH_SWIPEexist but are not used. Touch input is Touch Events (touchstart/touchmove), not Pointer Events. - Bindings (
viewer-src/touch.js). Mouse unchanged: left window/level, middle pan, right zoom, wheel slices. One finger: slices ("Scroll", the default) or window/level ("Contrast"). Stack scroll is set up first, so its one-finger binding wins; "Contrast" removes that binding and the mouse-primary fallback hands one finger to window/level. Two fingers: pinch zooms, dragging pans, in either mode. Double tap resets zoom, pan and window/level.test/viewer.test.mjsresolves gestures with Cornerstone's owngetActiveToolForTouchEventon a realToolGroup, so a change in its matching rules fails the tests. - Toolbar. "Scroll" / "Contrast" toggle buttons (
aria-pressed, at least 44 × 44 px) on any device with a touchscreen (any-pointer: coarse), touchscreen laptops included; the legend follows the primary pointer, so mouse users keep the mouse legend. Every open starts in "Scroll". No measurement or annotation tools. - Slice scrubber (
viewer-src/scrubber.js). A native vertical range input (keyboard and screen reader support for free,aria-valuetext"Slice 12 of 48") with "12 / 48" above it, synced both ways: the viewport'sSTACK_VIEWPORT_SCROLL/STACK_NEW_IMAGEmove the thumb (not while it is held), and dragging it seeks. Previous/next series buttons sit under it, or below the image on phones, where the series list is hidden and a caption on the image names the series. - Layout. One CSS grid with three arrangements (wide; phones in portrait; phones in landscape,
where everything but the image moves to the side rail). On phones the viewer modal is the whole
screen at
100dvh.touch-action: noneon the modal (the series list opts back into vertical scrolling), the viewport and the scrubber, so no gesture scrolls or zooms the page behind and the address bar never moves. The canvas follows the stage through aResizeObserver: a flip between portrait and landscape re-fits the image, any other resize keeps zoom and pan. The resize is debounced out of the render frame and re-fits (keepCamera: false) before putting zoom and pan back viagetViewPresentation/setViewPresentation: in 5.8.2,resize(…, keepCamera = true)left the image stretched after a width-only change (the scrubber rail appearing as the first image loads), and a resize while a render frame is pending only records the new size. - Requests. Unchanged caching and loading: no prefetch beyond what was there. Scrubber seeks are coalesced to one per animation frame and use Cornerstone's debounced loading (a frame not yet in the cache is only requested once the position rests for 40 ms), like finger and wheel scrolling. A frame is requested at most once per open, while the cache holds it. Measured in Chrome device emulation on a 19-slice series: six fast full-length scrubber drags caused 8 frame requests, four fast finger flicks 10; a full series costs at most one request per frame, far inside Orthanc's 3000/min viewer limit.
Tests. npm test runs: the Markdown sanitizer against a hostile document, parseMatch()
validation, the CSP directives, the starting-up handling (503 is "starting", every other failure
an error, one institution starting beside one that is fine, the health probe and its 5 s
cache), the viewer's touch
bindings and mode switching, slice scrubber sync, 503 detection and the automatic retry
(Retry-After parsing, the 5 s to 2 min window, one timer, cancel and re-arm; test/viewer.test.mjs), the
birth-date shift offline (live comparison opt-in), and, with
TEST_DATABASE_URL, a suite against real Postgres (25 cases: code format, invalidation,
concurrency, expiry, cross-institution rejection, the 5-failure lockout, uniform lookup answers,
key auth and browser refusal, rate limits including the per-IP reset limit, match storage,
discovery, unlink, per-account and nightly reset, plain-date birth dates, and the security
headers and cookie flags on real responses).
scripts/mock-institution.js stands in for a front desk for local testing.
9. Design decisions and trade-offs#
1. Never store clinical data; read live at view time.
- Why: the portal's job is to mediate access, not become a third copy of the record. If a link is removed, nothing lingers.
- Trade-off: every dashboard load hits both institutions; an institution outage blanks its card
(handled per card, never as a whole-page failure; a
503while it starts up shows as "starting up" with a retry rather than an error), and there is no offline view or search.
2. Institutions as rows, clients by type.
- Why: replaced an earlier
linkstable witherebor_patient_id/orthanc_patient_idcolumns. A third institution is now anINSERT, and the front end names no institution anywhere. - Trade-off: a one-time in-place migration (rename, convert, drop in one transaction), and per-institution colors and descriptions live in data rather than code.
3. The institution vouches; Imladris only records.
- Why: identity proofing belongs with whoever holds the record and sees the ID. Imladris issues a code and stores the redeemed link plus the desk's match verdict.
- Trade-off: Imladris has to trust the desk's
external_patient_idandmatchreport. It validates their shape strictly but cannot check them, and it showsunknownrather than assuming a match.
4. Popup to another origin for linking, inline modal for viewing.
- Why: the desk is visibly the institution's own site, which makes the institutional boundary tangible. Viewing already-granted images should feel seamless.
- Trade-off: popups get blocked and lose their opener under strict COOP, hence the
same-origin-allow-popupsheader, the blocked-popup link fallback, the closed-window watch, and polling as the source of truth.
5. Server is the only source of truth for link status.
- Why:
postMessagefrom another window can be forged; a nudge that only triggers a status check is harmless. - Trade-off: a 3-second polling loop per pending code, and a small delay if the message is lost.
6. Migrations and seed from the app on every boot, not Postgres init scripts.
- Why: the init-dir approach fired once per volume and once silently left production without tables. Idempotent SQL plus a sync makes every deploy self-healing.
- Trade-off: every restart also resets demo links, so a visitor's links last only until the next deploy or the nightly reset.
7. Hard-pinned birth-date anchor.
- Why: the institutions do not follow the calendar yet, so following today would move Imladris's birth dates a week further from theirs every week.
- Trade-off: the anchor must be moved by hand, together with the institutions, whenever they are rebuilt.
8. One build step, only for the viewer.
- Why: Cornerstone3D is ESM-only with a web worker and WASM codecs; everything else stays plain static files.
- Trade-off: a separate Docker stage, a generated directory to keep out of git, and three packages pinned to one exact version that must move together.
10. Known limits#
Each of these follows from the demo's scope: synthetic data, one small deployment, and a focus on the linking contract rather than on production hardening.
- No real authentication. Anyone can act as any demo account, and any visitor can reset one. Real use would need an identity provider (in Switzerland, a certified eID for the EPD).
- No standards-based consent or audit. No FHIR
Consent, no access log for the patient to see who read what. - Open institution reads. The security model covers the linking contract, not the institutions' data APIs, which are open in this demo.
- CSP origin list is read at startup. Adding a DICOM institution, or changing its
base_url, reaches the CSP on the next restart (which every deploy is anyway). - Single instance. Rate limits and the status cache are in memory, so they do not survive restarts or work across replicas.
- No resource limits. Imladris runs without CPU or memory limits on its container.
- Orthanc identity data. Orthanc has no AHV number on file for two demo patients (Werner
Aebischer and Marco Rüegg), which its desk reports as
ahv_missing. - Fixed date anchor. Dates stay on
2026-10-03until the planned shared weekly rebuild exists (section 8).
11. Try it#
The live demo is shared, so other visitors may have linked or unlinked accounts. Wherever the picker offers Reset this demo account, use it first to start from the seed state.
- Open
https://portal.adrianbernhard.ch, reset Léa Morand if offered, and pick her (linked to both). The two cards load independently, and the timeline merges hospital records with radiology exams, each row tagged with its source. Note "Registered as Lea Morand" under Orthanc's card: the radiology institute registered her without the accent, a deliberate example of the demographic drift Imladris bridges. - On an Orthanc row with images, press Images: the viewer opens inline and reads the study directly from Orthanc's DICOMweb endpoint (drag to window/level, scroll or use the slice scrubber to page through the stack; on a phone, one finger scrolls or adjusts contrast, pinch zooms, two fingers pan, double tap resets). Press Read on a report or letter to see a live-fetched, sanitized document.
- Switch account, reset Sandra Bernasconi if offered, and pick her (no links). The dashboard names no institution. Press + link a new institution, choose one, and watch a code with a 10-minute countdown appear and the institution's front desk open in a separate window on its own domain.
- Complete the desk flow. The new card appears on the dashboard without a reload, with an identity badge if the desk reported differences.
- Use Remove link on a card to withdraw consent, then go back to the picker and use Reset this demo account to restore the seed state for the next visitor.