# SMART Imaging Proxy > A working, public sandbox of SMART Imaging Access: one sign-in that gives an app a patient's clinical data and their DICOM images. Every sandbox is a private, stateful copy of the whole system, driven by real protocols and a small management API. Sample data only. ## Start here Create a sandbox, and use it for everything below: ```sh SANDBOX=https://imaging.argo.run$(curl -sX POST https://imaging.argo.run/api/sandboxes | jq -r .base) ``` Or open the site in a browser and choose Create a sandbox. Each sandbox has its own copy of this file at `$SANDBOX/llms.txt`, which names it. ## Who this is for A sandbox has both sides of SMART Imaging: the health system's servers, and a viewer app. Most people need one side. - **Building an app?** Read the shared background, then "Building an app": its rules first, then how. The page for people is `https://imaging.argo.run/build-an-app`, a wizard that ends at this sandbox's endpoints (`https://imaging.argo.run/build`). - **Testing your own server?** Read the shared background, then "Testing your server". The page for people is `https://imaging.argo.run/build-a-server`, a wizard that ends at the server check. - **Driving a sandbox** (its policy, faults and clock)? "The management API". Both of the above use it too, for its admin token. Each part stands on its own, so read only the ones you need. Any one comes on its own, with this opening, from the same file: `llms.txt?part=shared`, `?part=app`, `?part=server`, `?part=management` or `?part=references`. The site's pages are a single-page app: fetched without JavaScript, a page is an empty shell. Everything a page does is also a JSON API described here, so an agent never needs a browser: prefer the API. The exceptions are your own browser app, whose code has to run in one, and showing a person a page: "Links to a view" and "Driving the site in a browser" cover both. # Shared background ## The parts A real deployment has separate systems, and here they share one origin. | Role | URL | What it does | |---|---|---| | Clinical FHIR server | `$SANDBOX/fhir` | SMART discovery, `Patient`, `AllergyIntolerance`, `Condition`, `MedicationRequest`, `DiagnosticReport`, `Binary` | | Authorization server | `$SANDBOX/authorize`, `/token`, `/revoke`, `/register` | Sign-in, consent, tokens, registering apps | | Imaging FHIR server | `$SANDBOX/imaging/fhir` | `ImagingStudy` search, with each study's `Endpoint`. Applies policy | | DICOMweb proxy | `$SANDBOX/wado/{signed-context}/studies/...` | WADO-RS retrieval. Enforces the decision signed into the address | An app starts at the clinical FHIR base. `GET $SANDBOX/fhir/.well-known/smart-configuration` gives the endpoints. By default `associated_endpoints` names the separate imaging server by its `smart-imaging-access` capability. A sandbox can instead act as one server, with that capability at the top level and `ImagingStudy` at `$SANDBOX/fhir`. ## The sandbox model - A sandbox holds its own policy, approvals, tokens, registered apps, demo clock, and choice of image storage. Images and patients are shared and read-only. - It's saved to disk, and lasts until its owner deletes it (`DELETE /api/sandbox`). Only the throwaway sandboxes checks make for themselves idle out, after 30 minutes. - **Its URL is the access.** Anyone with it can read and change the sandbox, so treat it as a secret. The name is only a label. - Access is a union of grants. There are no deny rules: every grant only adds access. - The site root is read-only on public deployments. Work in a sandbox. ## Sample accounts Sign-in has no passwords. | Username | Name at sign-in | Patient id | Notes | |---|---|---|---| | `josh` | Josh Example | `josh-example` | Six real, de-identified studies | | `sam-caregiver` | Sam Example | `sam-example` | Two synthetic studies, and guardian of Riley | | `robin` | Robin Example | `robin-example` | No studies: a real empty result | What a correct app sees, signed in with a public client and approving everything offered, as this sandbox's policy stands (a new sandbox's is the default): | Sign in as | Choose | `ImagingStudy?patient=` | `DiagnosticReport?patient=` | Why | |---|---|---|---|---| | `josh` | `josh-example` | 6 | 6 | The patient's own | | `robin` | `robin-example` | None: `total` 0, no entries | None | No studies on file. Exit cleanly, not with an error | | `sam-caregiver` | `sam-example` | 2 | 2 | The patient's own | | `sam-caregiver` | `riley-example` | 1 of Riley's 2 | 1 | Left out: Synthetic skin biopsy, slide photo, labeled confidential-adolescent. Its report reads as 404 too | The same, as data, with study ids, UIDs and titles, the people and the kinds of client: `GET $SANDBOX/contract.json`, no token. Assert against it rather than this table. Its `state` says whether the sandbox answers as a new one: `clean` is true when `differences` is empty, and `differences` names, in words, each way it doesn't: a fault set, an app check running, the demo clock moved, unified topology, or policy changed (relationships, the imaging network's rules, shares). App approvals aren't counted, since every sign-in makes one. Approving less at sign-in leaves those studies and their reports out. `GET /api/sandbox/policy/explain` says why each study is or isn't released. `riley-example` is Sam's 15-year-old child. One of Riley's studies is confidential adolescent care, which Sam can't see. Clinical entries are invented. ## Links to a view Every state worth showing someone is in the page's address, and survives a reload, so you can hand a person the exact view: a wizard's step, a filtered log, a person's studies. A link holds nothing secret beyond the sandbox's own URL. Explore, the logs and the live trace have a Link to this view button that copies it. A saved server is named by `{iss}|{client id}`, URL-encoded, and opens only in the browser that saved it. | Page | Address | What it opens | |---|---|---| | Build an App | `https://imaging.argo.run/build-an-app?step=try&app={client id}` | The wizard at a step (`sandbox`, `app`, `connect`, `try`), with an app chosen | | Build a Server | `https://imaging.argo.run/build-a-server?step=server&how=confidential` | The wizard at a step (`register`, `server`, `check`), with a way of connecting; `&server={iss}\|{client id}` names the server described | | Build a Server | `https://imaging.argo.run/build-a-server?how=backend` | Registering the viewer as a `public`, `confidential` or `backend` client | | Build a Server | `https://imaging.argo.run/build-a-server?step=check&server={iss}\|{client id}` | A server you described, at the step that checks it | | Server check | `https://imaging.argo.run/check?sandbox=/s/{id}` | The server check, run on a sandbox; `?server={iss}\|{client id}` runs it on a saved server | | Server check | `https://imaging.argo.run/check?run={run id}` | A server check an agent started | | Viewer | `$SANDBOX/viewer?connect` | The viewer, a page of the sandbox's own, signing in at once in the same tab; `?server={iss}\|{client id}` chooses a server of your own, and `?sandbox=/s/{id}` another sandbox | | App check | `$SANDBOX/app-check?app={client id}` | An app check set up for an app; `?run={run id}` opens a run | | Explore | `$SANDBOX/explore?user=sam-caregiver&patient=riley-example` | A person looking at someone's studies; `&study={study id}` opens one | | Explore | `$SANDBOX/explore?client={service id}&referral={referral id}` | A service working from a referral | | Register an app | `$SANDBOX/connect?type=backend` | The form with a kind of app chosen; `?app={client id}` shows a registered app | | Logs | `$SANDBOX/activity?session={session}&type=searches&study={study id}` | The log filtered by session, `type`, `study`, `link` and `sandbox`; `&event={seq}` opens one event | | Live trace | `$SANDBOX/trace/?session={session}&span={span id}` | The live trace held on one session, with a span's preview open | | HTTP exchange | `$SANDBOX/trace/span?session={session}&span={span id}` | One HTTP exchange in full | | HTTP log | `$SANDBOX/trace/log?session={session}&trace={trace id}&filter={text}` | A trace's HTTP log, filtered | | Sandbox Config | `$SANDBOX/config?panel=clock` | The settings, scrolled to one panel: `storage`, `topology`, `clock`, `reset` or `end` | ## Driving the site in a browser When a browser is the point, as for your own app or a page to show someone: **Wait for `html[data-ready]`** after opening a page and after each change of view. It's set once the page has drawn its first real content, its data loaded or its error shown, and removed while a new page, or a new view named in the address, is loading. In Playwright: `await page.locator("html[data-ready]").waitFor()`. **Find controls by role and accessible name**, as `getByRole(role, { name, exact: true })` does, never by layout or CSS class. These names are kept stable, and a test finds each one: | Page | Control | Role | Name | |---|---|---|---| | My Sandboxes | Make a sandbox | `button` | `Create a sandbox` | | Build an App | A step, once it can be reached | `link` | `Your app` | | Build an App | The next step | `button` | `Next: Your app` | | Build a Server | A step, once it can be reached | `link` | `Your server` | | Build a Server | The viewer is registered at the server, so go on | `button` | `I've registered it` | | Register an app | Its name | `textbox` | `App name` | | Register an app | Its kind | `radio` | `Confidential app` | | Register an app | Its redirect URIs | `textbox` | `Redirect URIs` | | Register an app | Skip redirect check | `checkbox` | `Allow any redirect URI (don't check at sign-in, for testing)` | | Register an app | Register it | `button` | `Register` | | Register an app | Its client ID, to copy | `button` | `Copy {app}'s client ID` | | Register an app | Remove it | `button` | `Remove {app}` | | Build a Server | The server's FHIR base | `textbox` | `FHIR base URL` | | Build a Server | Read its discovery | `button` | `Check discovery` | | Build a Server | The viewer's client ID there | `textbox` | `Client ID` | | Build a Server | Save it, then check it | `button` | `Save and check` | | Server check | Sign in, when the check stops for it | `button` | `Sign in to continue` | | Server check | Run it again | `button` | `Run again` | | App check | The app to grade | `radio` | `{app}` | | App check | Start grading | `button` | `Start the run` | | App check | Stop and grade | `button` | `End the run and grade` | | Viewer | The server to connect to, such as a sandbox | `radio` | `{sandbox}` | | Viewer | Connect | `button` | `Connect` | | Sign-in (Authorization Server) | The account | `radio` | `{person}` | | Sign-in (Authorization Server) | Sign in | `button` | `Continue` | | Consent (Authorization Server) | Whose records | `radio` | `{person}` | | Consent (Authorization Server) | Allow the app | `button` | `Approve` | | Consent (Authorization Server) | Refuse it | `button` | `Deny` | | Explore | A sample person, or a service | `button` | `{first}` | | Explore, Logs, Live trace | Copy the address of the view shown | `button` | `Link to this view` | In a name, `{app}` is the app's name; `{sandbox}` is the sandbox's name; `{person}` is the person's name, as under Sample accounts; `{first}` is a person's first name, or a service's name. **Sign-in and consent are plain forms** from the Authorization Server, served without JavaScript. The viewer opens them in a tab of its own; with `connect` in its address it signs in in the same tab instead. Explore never shows them. # Building an app ## Rules an app must follow The binding part, for an app or a client library. Each rule is explained, with examples, in the section it names. 1. **Find imaging by capability, never by address.** Read `$SANDBOX/fhir/.well-known/smart-configuration`. If its top-level `capabilities` include `smart-imaging-access`, imaging is on that FHIR server itself; otherwise it's the `associated_endpoints` entry whose `capabilities` do. Which ways in work is SMART's own metadata: `authorization_code` in `grant_types_supported` for app launch, `client_credentials` for Backend Services. A sandbox can be switched between the two ("The parts"). 2. **Sign in with PKCE S256**, `aud=$SANDBOX/fhir`, and `scope=launch/patient patient/*.rs`. The token response's `patient` is a bare FHIR id, such as `josh-example`, and its `scope` is what you asked for: what's released is decided by policy, not by scope ("Connect an app"). 3. **Sign client assertions by real time**, `exp` at most five minutes ahead. Tokens, though, expire by the sandbox's demo clock: after the clock is moved, a cached token can be expired, so get a new one on a 401 ("Manage a sandbox"). 4. **Follow `next` links** to the end of a search. A server may return fewer results than asked for. A search with no results has no `entry` at all, only `total: 0` ("Read data"). 5. **Resolve each study's Endpoint in all three forms**, by FHIR's Bundle rules: `#id` in the study's `contained`, an absolute or `urn:` reference by exact `fullUrl`, and a relative `Endpoint/{id}` against the study's own `fullUrl` ("Read data"). 6. **Retrieve only under `Endpoint.address`**, as given, with the same token as the search, and an `Accept` header. A study's UID is its `urn:dicom:uid` identifier, less `urn:oid:` ("Read data"). 7. **Wait out a 503 with `Retry-After`**, then repeat the identical request: searches and retrievals may both answer it ("Read data"). 8. **Fetch images on demand.** A first instance can be several MB, and a whole study far more: josh's six first instances come to about 46 MB. 9. **Learn what you may see only from search.** Access to images can be narrowed in ways the token doesn't show: the person's choices of sites and studies at sign-in, the health system's policy, a guardian's limits. The `scope` reads the same either way. (The scope does show the types granted: see "Approving less at sign-in".) A study can be withheld, with its report, and a small or empty result is correct for some people ("Sample accounts", and `contract.json`). The App check ("App check: run one for someone") grades an app against the rules that are spec requirements, from the sandbox's side. ## Connect an app Public clients with PKCE (S256) are supported. Every endpoint an app uses (discovery, `/token`, FHIR, imaging and DICOMweb) answers CORS for any origin, so a browser app works as is. Register one in the sandbox, or use the page at `$SANDBOX/connect`. Every sandbox also has the demo's own apps, without anyone registering them: the public clients `portal-app`, `separate-viewer` and `demo-client`, and the Backend Services `hand-referral-service`, `outside-release-service` and `research-donation`. `GET /api/sandbox/clients` lists them under `builtIn`, with the apps registered here under `clients`; they can't be removed, and a service among them reaches what the sandbox's policy releases. Apps register by RFC 7591 dynamic registration, at discovery's `registration_endpoint` (`$SANDBOX/register`). The sandbox's admin token is the initial access token, sent as a bearer token: three calls, under "Manage a sandbox" in "The management API", with a key the sandbox gives out on purpose. An app or library that already registers itself this way needs nothing else. ```sh curl -X POST "$SANDBOX/register" -H "authorization: Bearer $ADMIN" -H 'content-type: application/json' \ -d '{"client_name":"My app","redirect_uris":["https://example.org/callback"],"token_endpoint_auth_method":"none","grant_types":["authorization_code"]}' ``` The answer is `201` with the client metadata as registered, its `client_id` and `client_id_issued_at`. Give one or more `redirect_uris` (matched exactly at sign-in; https, or http on loopback: `localhost`, `127.0.0.1` or `[::1]`), or `["*"]` to skip redirect URI matching for testing (accepting any http, https or custom-scheme URI without a fragment; `/token` still checks that `redirect_uri` matches the authorization request). Authorize with `aud=$SANDBOX/fhir` and `scope=launch/patient patient/*.rs`. A refusal is RFC 7591's: `400` with `error` (`invalid_redirect_uri` or `invalid_client_metadata`) and `error_description`; with no admin token, `401` and `invalid_token`. `/register` answers CORS, so a browser app can register itself from its own origin with the admin token. The kind of client follows from how it authenticates and its grant. Both signing kinds sign a `private_key_jwt` assertion with ES256, ES384 or RS384, and register the public half as `jwks`, or publish keys at a public https address and register it as `jwks_uri`, which also lets them rotate. Internal addresses are refused. | Kind | `token_endpoint_auth_method` | `grant_types` | Also needs | Flow | |---|---|---|---|---| | Public (default) | `none` | `["authorization_code"]`, optionally with `"refresh_token"` | `redirect_uris` | Authorization code with PKCE | | Confidential | `private_key_jwt` | `["authorization_code"]`, optionally with `"refresh_token"` | `redirect_uris`, and `jwks` or `jwks_uri` | The same, plus `client_assertion_type` and `client_assertion` at `/token` | | Backend service | `private_key_jwt` | `["client_credentials"]` | `jwks` or `jwks_uri`, and `patients`: `any` or one patient id | `client_credentials` with scope `system/ImagingStudy.rs`. No one signs in | `patients` is this sandbox's one extension to RFC 7591's metadata: a backend service has no one to approve it, so registering it names whose studies it may reach. It's required: leaving it out is `invalid_client_metadata`, never "any". An app that signs in is registered with both `authorization_code` and `refresh_token`: asking for `online_access` or `offline_access` at sign-in gets a refresh token (see "Refresh tokens"). ```sh curl -X POST "$SANDBOX/register" -H "authorization: Bearer $ADMIN" -H 'content-type: application/json' \ -d '{"client_name":"Referral service","token_endpoint_auth_method":"private_key_jwt","grant_types":["client_credentials"],"patients":"josh-example","jwks":{"keys":[{"kty":"EC","crv":"P-256","x":"...","y":"...","kid":"key-1"}]}}' ``` The assertion is a JWT with `iss` and `sub` set to the client id, `aud` set to `$SANDBOX/token` (or a list that holds it), a unique `jti`, and `exp` at most five minutes ahead, by real time: assertions are checked by real time, whatever the sandbox's demo clock says. A backend service names the patient in each search, and asking about a patient outside its grant returns 403. ## Sign in without a browser An agent can walk the forms a person would: 1. `GET $SANDBOX/authorize?response_type=code&client_id=...&redirect_uri=...&scope=...&aud=...&state=...&code_challenge=...&code_challenge_method=S256`. The response is a form. Take its `action`. 2. `POST` that action with the form field `username=josh`. Follow the 303 to the consent page, and take its form `action`. 3. `POST` that action with `decision=approve` and `patient=josh-example`, approving everything offered. The 302 `Location` has the `code`. 4. `POST $SANDBOX/token` with `grant_type=authorization_code`, `code`, `redirect_uri`, `client_id` and `code_verifier`. The response has `access_token`, `patient` (a bare FHIR id, such as `josh-example`), `scope` (what was granted: see below), and `expires_in` in seconds of the demo clock. A person can approve less on the consent page, and so can an agent driving it: see "Approving less at sign-in" under "The management API". An app can't tell from its token which sites or studies it got. The token's `scope` is what was granted, not an echo of the request: patient-level reads and searches of `ImagingStudy`, `DiagnosticReport`, `Patient`, `Condition`, `MedicationRequest` and `AllergyIntolerance` (by name or `*`), with `launch/patient`, `online_access` and `offline_access`. Write permissions narrow to reads (`patient/*.cruds` is granted as `patient/*.rs`), and anything else is left out, `openid` and `fhirUser` too, since no `id_token` is issued. Each read is checked against it: reading `Patient` takes a scope that covers `Patient`. ## Refresh tokens Ask for `online_access` or `offline_access` in `scope` at sign-in, and the token response also has a `refresh_token` (the two mean the same here). `POST $SANDBOX/token` with `grant_type=refresh_token`, `refresh_token` and `client_id` gets a new access token and a new refresh token, with the same patient, scope and approval; a confidential app also sends its `client_assertion`, as at the code exchange. Each refresh token works once. Presenting one that was already used is `invalid_grant`, and revokes every token in its chain, as a leaked token would need. A refresh token lasts 30 days of the demo clock unless the sandbox's settings say otherwise, and only the app it was issued to can use it. `POST $SANDBOX/revoke` with the form field `token` (RFC 7009) revokes an access or refresh token, and answers `200` whatever it was. A revoked access token stops at once everywhere: search, reports, and image retrieval through the signed `Endpoint.address` it was given. ## Read data To look at real answers before your app can sign in, the sandbox's admin key can get a token as a person for an app, with no forms: see "The same assertion, … gets a token as that person" under "Manage a sandbox". Your app should still sign in as below; the App check grades only its own tokens. ```sh curl "$SANDBOX/fhir/Patient/josh-example" -H "authorization: Bearer $TOKEN" curl "$SANDBOX/fhir/Condition?patient=Patient/josh-example&clinical-status=active" -H "authorization: Bearer $TOKEN" curl "$SANDBOX/imaging/fhir/ImagingStudy?patient=Patient/josh-example&_include=ImagingStudy:endpoint" -H "authorization: Bearer $TOKEN" ``` The clinical FHIR server is read-only: anything but `GET` is `405` with `Allow: GET`. Each FHIR server has a CapabilityStatement: `$SANDBOX/fhir/metadata` and `$SANDBOX/imaging/fhir/metadata`. Reports link to their images by accession number (`identifier`, with the same `system` as the study's accession) and by the study's DICOM UID (`imagingStudy[].identifier`, system `urn:dicom:uid`). Either goes in an ImagingStudy search's `identifier`; ImagingStudy isn't read by id. Each has a PDF and a text attachment at the URLs in `presentedForm`. A report is available only when the study it describes is released to the token. ```sh curl "$SANDBOX/fhir/DiagnosticReport?patient=Patient/josh-example" -H "authorization: Bearer $TOKEN" ``` Each study names its `Endpoint` in `endpoint`, in any of three forms the guide allows, and an app must resolve all three by FHIR's Bundle rules: `#wado` is in the study's own `contained`; `urn:uuid:…` is the entry with that exact `fullUrl`; and a relative `Endpoint/{id}` resolves against the base of the study's own `fullUrl` (`{imaging}/fhir/`), to the entry whose `fullUrl` is `{imaging}/fhir/Endpoint/{id}`. The smoke test below does exactly this. Its `address` is that study's own DICOMweb base: retrieve under it, never under an address you build. A search with no results has no `entry` at all, only `total: 0`, so read `entry ?? []`. A search parameter the server doesn't support is ignored, as FHIR allows: it's left out of the `self` and `next` links, and named in an entry with `search.mode: "outcome"` holding a warning OperationOutcome. With `Prefer: handling=strict`, it's a `400` instead. Supported: `patient`, `identifier`, `based-on:identifier`, `_lastUpdated`, `_count`, `_include=ImagingStudy:endpoint`, and `_cursor` from a `next` link. `$STUDY_UID` is the study's `identifier` with system `urn:dicom:uid`, less its `urn:oid:` prefix (not `ImagingStudy.id`); series and instance UIDs are `series[].uid` and `series[].instance[].uid`. Still send the token: ```sh curl "$ADDRESS/studies/$STUDY_UID/series/$SERIES_UID/instances/$INSTANCE_UID" \ -H "authorization: Bearer $TOKEN" \ -H 'accept: multipart/related; type="application/dicom"; transfer-syntax=*' ``` The answer is `multipart/related`: each part is one DICOM file, starting after the part's headers, with `DICM` at byte 128. `/studies/{uid}` and `/metadata` (`accept: application/dicom+json`) also work. `/frames`, `/rendered` and `/thumbnail` return 501. A study not yet ready answers 503 with `Retry-After`: wait that long and ask again. An address that isn't an `Endpoint.address` the search gave (such as `/wado/studies/{uid}`) is a 404, not a 503: there is nothing to wait for. Every refusal says why. FHIR endpoints answer an `OperationOutcome` whose `issue[0].diagnostics` gives the reason; everything else answers JSON `{error, hint?}`. An authorization error sent back to the app's redirect URI carries `error_description`. `$SANDBOX/wado/-/studies/{uid}/…` is retrieval with no signed context: the proxy asks the Imaging Server's decision API for each request (and caches the answer briefly), instead of reading the decision from the address. It's how a viewer handed only a token and a UID would ask, and what `decisionOutage` stops. An app given an `Endpoint.address` uses that. ## Smoke test One script, Node 20+ with no packages, that does what an app does, end to end, and prints `OK`: the admin token, registering a public app, signing in as `josh` through the forms, searching every page with the endpoints included, retrieving one image from each study (about 46 MB for josh's six), and reading a report. It removes its app at the end, pass or fail, and the app's approval and tokens go with it. It's a test of this sandbox, not authorization code to copy: it walks the sign-in forms itself, which only the sandbox's passwordless sample accounts allow. Download it from `$SANDBOX/smoke.mjs` and run it with `SANDBOX=https://…/s/{id} node smoke.mjs`. It's the same file shown here, and this site's tests run it as served, both in a new sandbox and with every condition an app check stages (small pages, 503s with Retry-After, and Endpoints in all three forms). ```js // smoke.mjs: what an app does, end to end. SANDBOX=https://…/s/{id} node smoke.mjs // A test of this sandbox, with its sample accounts: not authorization code to copy. It walks the sign-in forms // itself, which only a sandbox's passwordless accounts allow; a real app sends the person to sign in, in a // browser, and checks the state it gets back, as this does. import { createHash, createPrivateKey, randomBytes, randomUUID, sign } from "node:crypto"; const SANDBOX = process.env.SANDBOX, b64 = b => Buffer.from(b).toString("base64url"); const must = async (r, what) => { if (!r.ok && r.status !== 302 && r.status !== 303) throw new Error(`${what}: HTTP ${r.status} ${await r.text()}`); return r; }; // 1. The admin token, from the keys this sandbox shares on purpose. const k = await (await must(await fetch(`${SANDBOX}/api/sandbox/keys-shared-on-purpose`), "keys")).json(); const head = `${b64(JSON.stringify({ alg: "ES256", kid: k.admin.jwk.kid }))}.${b64(JSON.stringify({ iss: k.admin.client_id, sub: k.admin.client_id, aud: k.tokenEndpoint, jti: randomUUID(), exp: Math.floor(Date.now() / 1000) + 240 }))}`; const assertion = `${head}.${b64(sign("sha256", Buffer.from(head), { key: createPrivateKey({ key: k.admin.jwk, format: "jwk" }), dsaEncoding: "ieee-p1363" }))}`; const admin = (await (await must(await fetch(k.tokenEndpoint, { method: "POST", body: new URLSearchParams({ grant_type: "client_credentials", scope: "sandbox/admin", client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: assertion }) }), "admin token")).json()).access_token; // 2. A public app, with a redirect URI nothing needs to serve: the code is read from the redirect itself. const redirect = "http://localhost:8123/callback"; // Registered by RFC 7591 dynamic registration, at discovery's registration_endpoint, with the admin token as its // initial access token. An app that already registers itself this way needs nothing else. const conf = await (await must(await fetch(`${SANDBOX}/fhir/.well-known/smart-configuration`), "discovery")).json(); const registered = await (await must(await fetch(conf.registration_endpoint, { method: "POST", headers: { authorization: `Bearer ${admin}`, "content-type": "application/json" }, body: JSON.stringify({ client_name: "Smoke test", redirect_uris: [redirect], token_endpoint_auth_method: "none", grant_types: ["authorization_code"], response_types: ["code"], scope: "launch/patient patient/*.rs" }) }), "register")).json(); const app = { id: registered.client_id }; // The app is removed at the end, pass or fail, and its approval and tokens with it. try { // 3. Sign in as josh, through the forms, with PKCE. const state = b64(randomBytes(16)), verifier = b64(randomBytes(32)), challenge = b64(createHash("sha256").update(verifier).digest()); const auth = new URL(conf.authorization_endpoint); for (const [n, v] of Object.entries({ response_type: "code", client_id: app.id, redirect_uri: redirect, scope: "launch/patient patient/*.rs", aud: `${SANDBOX}/fhir`, state, code_challenge: challenge, code_challenge_method: "S256" })) auth.searchParams.set(n, v); const action = async (r, what) => new URL((await (await must(r, what)).text()).match(/]*action="([^"]+)"/)[1].replaceAll("&", "&"), r.url); const signIn = await action(await fetch(auth), "authorize"); const consent = new URL((await must(await fetch(signIn, { method: "POST", body: new URLSearchParams({ username: "josh" }), redirect: "manual" }), "sign in")).headers.get("location"), signIn); const decide = await action(await fetch(consent), "consent page"); const back = new URL((await must(await fetch(decide, { method: "POST", body: new URLSearchParams({ decision: "approve", patient: "josh-example" }), redirect: "manual" }), "approve")).headers.get("location")); if (back.searchParams.get("state") !== state) throw new Error("the redirect's state isn't the one sent"); const token = await (await must(await fetch(conf.token_endpoint, { method: "POST", body: new URLSearchParams({ grant_type: "authorization_code", code: back.searchParams.get("code"), redirect_uri: redirect, client_id: app.id, code_verifier: verifier }) }), "token")).json(); const bearer = { authorization: `Bearer ${token.access_token}` }; // Every GET waits out a 503 with Retry-After, as the guide asks of an app, for searches and retrievals alike. const get = async (url, headers) => { for (let tries = 0; ; tries++) { const r = await fetch(url, { headers }); if (r.status !== 503 || tries === 10) return must(r, `GET ${url}`); await new Promise(done => setTimeout(done, 1000 * Number(r.headers.get("retry-after") ?? 1))); } }; // 4. Every page of the search, with each study's Endpoint. // The FHIR server itself, if it advertises imaging at the top level (a unified sandbox), or else the associated // endpoint that does. Never a hardcoded address: a sandbox can be switched between the two. // App launch is there when grant_types_supported has authorization_code: SMART's own metadata says which ways in work. if (!conf.grant_types_supported?.includes("authorization_code")) throw new Error("discovery doesn't offer authorization_code"); const offers = caps => caps?.includes("smart-imaging-access"); const imaging = offers(conf.capabilities) ? `${SANDBOX}/fhir` : conf.associated_endpoints?.find(e => offers(e.capabilities))?.url; if (!imaging) throw new Error("discovery advertises no SMART Imaging server for app launch"); const entries = []; for (let next = `${imaging}/ImagingStudy?patient=Patient/${token.patient}&_include=ImagingStudy:endpoint`; next;) { const page = await (await get(next, bearer)).json(); entries.push(...(page.entry ?? [])); // a search with no results has no entry at all next = page.link?.find(l => l.relation === "next")?.url; } const studies = entries.filter(e => e.resource.resourceType === "ImagingStudy").map(e => e.resource); if (studies.length !== 6) throw new Error(`expected josh's 6 studies, got ${studies.length}`); // 5. Each study's Endpoint, in any of the three forms the guide allows, resolved by FHIR's Bundle rules: a // "#id" in the study's contained resources, an absolute or urn: reference by fullUrl, and a relative one // ("Endpoint/{id}") against the base of the study's own fullUrl. const studyEntry = study => entries.find(e => e.resource === study); function endpointOf(study) { for (const { reference: ref = "" } of study.endpoint ?? []) { const target = ref.startsWith("#") ? study.contained?.find(c => c.id === ref.slice(1)) : entries.find(e => e.fullUrl === ref || e.fullUrl === new URL(ref, studyEntry(study).fullUrl.replace(/ImagingStudy\/[^/]+$/, "")).href)?.resource; if (target?.resourceType === "Endpoint" && target.connectionType?.code === "dicom-wado-rs") return target; } throw new Error(`no WADO-RS Endpoint for ${study.id}`); } // 6. One image from each study, from its own Endpoint.address, waiting out a 503 with Retry-After. let bytes = 0; for (const study of studies) { const uid = study.identifier.find(i => i.system === "urn:dicom:uid").value.replace(/^urn:oid:/, ""); const series = study.series[0], url = `${endpointOf(study).address}/studies/${uid}/series/${series.uid}/instances/${series.instance[0].uid}`; const image = Buffer.from(await (await get(url, { ...bearer, accept: 'multipart/related; type="application/dicom"; transfer-syntax=*' })).arrayBuffer()); const part = image.subarray(image.indexOf("\r\n\r\n") + 4); if (part.subarray(128, 132).toString() !== "DICM") throw new Error(`${study.id}'s image isn't DICOM`); bytes += image.length; } // 7. A report, as text. const reports = await (await must(await fetch(`${SANDBOX}/fhir/DiagnosticReport?patient=Patient/${token.patient}`, { headers: bearer }), "reports")).json(); const text = reports.entry[0].resource.presentedForm.find(f => f.contentType.startsWith("text/plain")); await must(await fetch(text.url, { headers: bearer }), "report text"); console.log(`OK: ${studies.length} studies, an image from each (${bytes} bytes), ${reports.entry.length} reports`); } finally { await fetch(`${SANDBOX}/api/sandbox/clients/${app.id}`, { method: "DELETE", headers: { authorization: `Bearer ${admin}` } }); } ``` ## App check: run one for someone The App check (`$SANDBOX/app-check`) grades an app from the server side. A run puts the person's own sandbox, where their app is registered, into a staged mode: until the run ends, the sandbox does things the guide or FHIR lets any server do. The person follows a script with their app, then ends the run, and every request that client made in the meantime is graded from the sandbox's log. One run at a time per sandbox; a banner on every page of the sandbox says it's on. Ending it, abandoning it, or its two hours running out puts the sandbox back exactly as it was. ```sh curl -sX POST https://imaging.argo.run/api/checks -H 'content-type: application/json' \ -d '{"app":{"sandbox":"/s/{id}","clientId":"app-…","script":"josh"}}' # 201 {"id":"…","url":"https://imaging.argo.run/s/{id}/app-check?run=…","status":"waiting","expiresAt":"…"} curl -sX POST https://imaging.argo.run/api/checks/$ID/start # the staged mode goes on: an AppCheckRun, status running curl -sX POST https://imaging.argo.run/api/checks/$ID/end # graded: status done, with steps and notes curl -sX POST https://imaging.argo.run/api/checks/$ID/abandon # put back, not graded curl -s https://imaging.argo.run/api/checks/$ID # an AppCheckRun; while it runs, progress counts the app's requests so far ``` `app` is a `CheckApp`. `sandbox` is the sandbox's base or URL; `clientId` an app registered there. `script` is one of these, `josh` by default, and `service` for a backend service: | `script` | The person | A correct app | |---|---|---| | `josh` | Signs in as `josh`, approves everything offered, opens every study | Finds and opens all 6 | | `riley` | Signs in as `sam-caregiver` and chooses Riley | Finds 1 of Riley's 2, and opens it | | `robin` | Signs in as `robin` | Finds none, with no error | | `service` | Runs the backend service for `josh-example` | Finds and retrieves all 6 | `conditions` are what's staged, all four by default: `small-pages` (`pageSize: 2`), `search-503` and `retrieval-503` (`Retry-After: 1`), and `endpoint-forms`, as in the faults table under "Manage a sandbox". Give the person the `url`, or start the run and tell them: "Point your app at `$SANDBOX/fhir` with client ID `…`, sign in as josh, approve everything offered, open every study, then press End the run and grade on the page." It grades the sandbox's log, not a screen, so a headless app is graded exactly as a browser app is. Only that client's requests while the run is on count: its tokens from `token.issued`, its searches by `client`, and its retrievals by `tokenHash`, or with no token, by the address a search issued to one of its tokens. The result has three parts. `steps` with `group: "script"` say whether the app did what the script asked, against what the server itself released, so an app that stopped early fails where one that correctly found 1 or none passes. `steps` with `group: "requirement"` are clear requirements on apps, each with its `sources`, quoted: `pass`, `fail` with the requests behind it, or `note` when the app made no request it covers. `notes` are where the app relied on something the spec doesn't promise, such as one page of results or `/rendered`: not failures, each with why. The requirements and their sources are in [docs/app-check.md](https://github.com/jmandel/smart-imaging-proxy/blob/main/docs/app-check.md). `notChecked` lists what the run didn't look at, so a pass isn't read as more than it is: signing in (the sign-in server enforces it), token renewal, approving less, reports and clinical data, discovery, what the app shows, and any requirement the app made no request for. Holding the id is the only access to the run, as with a server check, and runs live in this server's memory for 24 hours. # Testing your server ## Test your server with the viewer The viewer can connect to any SMART server, in the browser, exactly as it connects to a sandbox. It's at `https://imaging.argo.run/viewer` for a server of your own, and at `$SANDBOX/viewer` in a sandbox, where the sandbox's bar stays around it. A sandbox is one more server in its list, signed in to with the sandbox's built-in public client, `demo-client`. What your server needs: 1. **CORS** for the origin `https://imaging.argo.run`, on discovery, the token endpoint, FHIR searches and image retrieval. The browser makes every request. 2. **Discovery** at `{FHIR base}/.well-known/smart-configuration`, with `authorization_endpoint` and `token_endpoint`. SMART Imaging is found by capability: `smart-imaging-access`, either in top-level `capabilities` or on an entry in `associated_endpoints`, whose `url` is the imaging FHIR server. The mode comes from `grant_types_supported`: `authorization_code` for app launch, `client_credentials` for Backend Services. 3. **A client for the viewer.** For sign-in, register the redirect URI `https://imaging.argo.run/viewer` exactly, the same for every server, with PKCE S256, and scope `launch/patient patient/*.rs`. A confidential client uses `private_key_jwt` with ES256. A backend service uses `client_credentials` with `system/ImagingStudy.rs`. The client metadata, in RFC 7591 names, is on Build a Server's first step, ready to copy. A signing client's public key can be registered as `jwks` or by `jwks_uri`: this site serves any ES256 public key at `https://imaging.argo.run/jwks/{key}`, where `{key}` is the base64url of `{"crv":"P-256","x":…,"y":…,"kid":…}`, with nothing stored. The page gives the address; a new key is a new address. 4. **Searches the viewer makes:** `Patient/{id}`, `AllergyIntolerance`, `Condition`, `MedicationRequest` and `DiagnosticReport` by `patient`, then `{imaging}/ImagingStudy?patient={id}&_include=ImagingStudy:endpoint`, following `next` links. It retrieves instances from each study's `dicom-wado-rs` `Endpoint.address`, sending the token only there, and honours `503` with `Retry-After`. Build a Server has a form for these settings, a button that checks discovery as the viewer reads it, and generates a key pair in the browser for clients that sign. The servers you describe are kept in the browser's storage, which an agent can't write, so give the person the values for the form, or a JSON entry to paste under "Import or export as JSON": ```json [{ "label": "My server", "iss": "https://example.org/fhir", "clientId": "my-client", "scope": "launch/patient patient/*.rs", "imaging": "https://example.org/imaging/fhir" }] ``` `scope` and `imaging` are optional. `imaging` is needed only if discovery doesn't name the imaging server. A confidential app adds `"auth":"private_key_jwt"` and `"jwk"`, a private ES256 JWK with a `kid`. A backend service adds `"mode":"backend"`, `"jwk"` and `"patient"`, the FHIR id it searches for. Keys are easier to make on the page: it shows the public half to register. If discovery can't be read from the page, it's usually CORS or a wrong base: check `curl -i "$ISS/.well-known/smart-configuration" -H "origin: https://imaging.argo.run"` for a 200 with `access-control-allow-origin`. ## Server check: run one for someone The Server check (`https://imaging.argo.run/check`) runs every step of SMART Imaging Access against one server, in a person's browser: discovery and CORS, the sign-in endpoints, SMART Imaging advertised, a token, the imaging search and its paging, refusals with no token and for another patient, every study's Endpoint, an image retrieved with the token and refused without it, and 503 with Retry-After. It needs a person for the sign-in, so an agent starts the run and hands its person a link: ```sh curl -sX POST https://imaging.argo.run/api/checks -H 'content-type: application/json' \ -d '{"server":{"label":"Acme","iss":"https://fhir.acme.example/r4","clientId":"acme-check"}}' # 201 {"id":"…","url":"https://imaging.argo.run/check?run=…","status":"waiting","expiresAt":"…"} ``` `server` is a `CheckServer` (see "API types"), checked as Build a Server's form checks one: `iss` and `imaging` use https. A confidential app adds `"auth":"private_key_jwt"` and `"jwk"`, a private ES256 JWK with a `kid`; a backend service adds `"mode":"backend"`, `"jwk"` and `"patient"`. A private key stays with the run on this site's server, which signs each assertion the page needs; no answer ever contains it. Send only a test client's key. Give your person the `url`, saying what it does: "This opens a check of your server in your browser. It stops once for you to sign in; the page shows what to register first: the redirect URI `https://imaging.argo.run/viewer`, the client ID, and the scope." A backend service runs to the end with no sign-in, but still runs in their browser, so they still open the link. Then poll: ```sh curl -s https://imaging.argo.run/api/checks/$ID # a CheckRun: status, summary, and each step's result, diagnosis and requests ``` `status` is `waiting` until they open the link, `paused` while it waits for their sign-in, `running`, then `done`. Each step's `state` is `pass`, `fail`, `skip`, `note` (nothing to check on this server, such as paging when everything fits one page), or `unreached` (an earlier step it depends on failed). A failed step's `diagnosis` says what it most likely means and how to check from a terminal. Requests are recorded masked, with no token in them. Poll every few seconds; the page reports after every step. The `id` is long and random, and holding it is the only access to the run: anyone with the link can open it, read it, and report to it. Runs live in this server's memory for 24 hours, a few hundred at a time, and are gone on a restart. # The management API ## Manage a sandbox Everything under `$SANDBOX/api/sandbox` is the management API, and it takes the sandbox's admin token as a bearer token. The admin is a SMART Backend Services client, `sandbox-admin`, whose key the sandbox gives out on purpose, at an address that says so: its URL is already its access, so the key grants nothing more. A call without the token is still refused. 1. `GET $SANDBOX/api/sandbox/keys-shared-on-purpose`, the one call that needs no token. It returns `why` (why giving these keys out is safe), `tokenEndpoint`, `now` (real time, in seconds), `admin` and `services`, each with `client_id` and a private ES256 `jwk`. 2. Sign a client assertion with `admin.jwk`: a JWT with header `{"alg":"ES256","kid":...}`, and `iss` and `sub` set to `sandbox-admin`, `aud` set to `tokenEndpoint`, a unique `jti`, and `exp` at most five minutes ahead. Assertions are checked by real time, never the demo clock, so your own clock works. 3. `POST` to `tokenEndpoint` with `grant_type=client_credentials`, `scope=sandbox/admin`, `client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer` and `client_assertion`. 4. Send `authorization: Bearer $ADMIN` on every management call. The token is checked before the path, so a mistyped path also answers 401 until you send one; with the token, it answers 404. A token revoked, or expired by the demo clock, gets 401: get another. ```js // Node 20+: an admin token for $SANDBOX. import { createPrivateKey, randomUUID, sign } from "node:crypto"; const k = await (await fetch(`${SANDBOX}/api/sandbox/keys-shared-on-purpose`)).json(); const part = o => Buffer.from(JSON.stringify(o)).toString("base64url"); const head = `${part({ alg: "ES256", kid: k.admin.jwk.kid })}.${part({ iss: k.admin.client_id, sub: k.admin.client_id, aud: k.tokenEndpoint, jti: randomUUID(), exp: k.now + 240 })}`; const jwt = `${head}.${sign("sha256", Buffer.from(head), { key: createPrivateKey({ key: k.admin.jwk, format: "jwk" }), dsaEncoding: "ieee-p1363" }).toString("base64url")}`; const t = await (await fetch(k.tokenEndpoint, { method: "POST", body: new URLSearchParams({ grant_type: "client_credentials", scope: "sandbox/admin", client_assertion_type: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", client_assertion: jwt }) })).json(); const ADMIN = t.access_token; ``` The same assertion, signed with `admin.jwk`, with `user`, `patient` and optionally `app` (default `portal-app`) sent in place of `scope` (send no `scope` at all), gets a token as that person for that app, as the app would get one at sign-in. It's a sandbox-only extension, for exploring what a person's app can reach without walking the sign-in. It makes sign-in's test: the person has to hold the patient's record (as the patient, a guardian, or by a share), or the answer is `invalid_grant`. Unlike sign-in, it records no approval, so it reads what the app's existing approval allows: a new app has none, and finds nothing until someone signs in to it once. What it reads is decided by policy, like any token's. The three services in `services` are ordinary Backend Services clients. Sign as one of them the same way, with `scope=system/ImagingStudy.rs`. All paths below are under `$SANDBOX`. Bodies are JSON. | Method and path | Does | |---|---| | `GET /api/sandbox` | Name, topology, image storage, demo clock, and the allowed clock moves | | `PATCH /api/sandbox` `{"name":"..."}` | Renames it | | `PATCH /api/sandbox` `{"topology":"unified"}` | Where imaging is advertised: `separate` or `unified` | | `PATCH /api/sandbox` `{"storage":"s3"}` | Image storage: `static-files`, `s3` or `orthanc` | | `DELETE /api/sandbox` | Deletes it permanently | | `GET /api/sandbox/storage` | Health of each image store | | `GET /api/sandbox/clients` | The apps registered here, and `builtIn`: the demo's own, which work in every sandbox without being registered, and can't be removed. Apps register by RFC 7591, at `$SANDBOX/register`: see "Connect an app" | | `DELETE /api/sandbox/clients/{id}` | Removes an app | | `DELETE /api/sandbox/clients?name-prefix=` | Removes every app whose name starts with the prefix, which can't be empty, and answers `{"removed":[ids]}`. For clearing up after test apps: give yours a common prefix | | `GET /api/sandbox/policy` | Relationships, policies, shares and approvals | | `GET /api/sandbox/policy/relationships`, `PUT` with a relationship, `DELETE ?subject=&relation=&object=` | Facts on file: who is guardian of whom. `relation` is `guardian_of`, the one policy reads, and `subject` one of the sample accounts | | `GET /api/sandbox/policy/policies`, `PUT /api/sandbox/policy/policies/{id}`, `DELETE /api/sandbox/policy/policies/{id}` | The imaging network's rules: sharing, guardian access, service access | | `GET /api/sandbox/policy/shares`, `POST` `{"from":"user:josh","with":"user:sam-caregiver","patient":"patient:josh-example","sites":[...],"label":"caregiver"}`, `DELETE ?from=&with=&patient=` | People's shares. `with` is another sample account; a name in `sites` that isn't a site is a 400, and a real site the sharer can't see is dropped, as the account page would | | `GET /api/sandbox/policy/app-approvals`, `POST` `{"by":"user:josh","app":"app:portal-app","patient":"patient:josh-example","sites":[...]}`, `DELETE ?by=&app=&patient=` | Which sites a person lets an app see. `"sites": null` is every site, including later ones; leaving `sites` out keeps the last choice | | `GET /api/sandbox/policy/explain?client=&user=&fhirUser=&patient=` | Each of a patient's studies, whether it's released to that app or service, and why. A `user` needs its `fhirUser`, e.g. `user=josh&fhirUser=Patient/josh-example` | | `GET /api/sandbox/explore/cast` | The people and services, whose records each holds, and each person's `fhirUser` | | `GET /api/sandbox/explore/referrals` | The referrals the services work from: the report each cites, its patient reference, accession number and system | | `GET /api/sandbox/explore/view?session=&user=&patient=` or `?session=&client=&referral=` | A view explained from policy: headline, the studies its viewer may know of with why each is or isn't released, the layer chain, and what could change it. `session` names the trace session your requests carry | | `GET /api/sandbox/explore/happened?session=&study=` | One line for what a session did with a study, from the activity log | | `GET /api/sandbox/explore/rule-sets?service=` | The imaging network's named rule sets for a service (its client id or Ref), with their rules to `PUT`. An unknown service is a 404. A service with no rule set of its own answers `{"ruleSets":[]}` | | `GET /api/sandbox/catalog?patient=` | A patient's studies as the catalog holds them, with UIDs, sites, dates and image counts, in the order search returns them | | `GET /api/sandbox/faults` | The faults on now, and the app check running here, if any: `{faults, appCheck}` | | `POST /api/sandbox/faults` with any of the fields below | Sets those faults and leaves the rest, answering with what's on now. `false` and `null` clear them. Refused with 409 while an app check runs here | | `POST /api/sandbox/clock` `{"advanceSeconds":N}` or `{"reset":true}` | Moves the demo clock. `N` must be one of the choices in `GET /api/sandbox`. Tokens, study links and ages follow it; client assertions are checked by real time | | `POST /api/sandbox/reset` `{"confirm":true}` | Puts policy back to what's on file | | `POST /api/sandbox/tokens/revoke-all` | Revokes every token. As with `/revoke`, a revoked token's retrievals stop at once, through signed addresses too | | `POST /api/sandbox/proxy/flush` | Forgets cached access decisions. A policy change otherwise reaches a cached decision, or a signed address, only when it expires (at most `contextLifetimeSeconds`, 300 by default) | | `POST /api/sandbox/signing-key/rotate` | Replaces the key that signs retrieval addresses | What each fault affects: | Field | Affects | Doesn't affect | |---|---|---| | `decisionOutage: true` | Image retrieval the proxy can't decide from the signed address alone, so asks the Imaging Server's decision API: an address with no signed context, or an expired or restricted one, with no cached decision. These answer `503` with `Retry-After` | `ImagingStudy` search, which decides access itself and still answers `200`; retrievals whose signed context the proxy verifies on its own | | `truncateAfter: N` | Image retrieval: the image store stops after `N` instances, so a multipart response is cut off with no closing boundary | Search, and metadata | | `pageSize: N` (1 to 100) | `ImagingStudy` search: at most `N` studies a page, with the rest behind `next` links that repeat the `_count` asked for | Retrieval | | `searchRetryAfter: N` (1 to 30) | `ImagingStudy` search: each token's first search after it's set, once access is checked, answers `503` with `Retry-After: N`, once; later ones answer normally. Each token has its own, so another app's search doesn't use up yours | Retrieval, and refusals: a search that would be 401 or 403 still is | | `retrievalRetryAfter: N` (1 to 30) | Image retrieval, including metadata: each token's first allowed request after it's set answers `503` with `Retry-After: N`, once | Search, and refused requests | | `endpointForms: true` | `ImagingStudy` search: Endpoints rotate, study by study, through the three forms the guide allows: a response-local `urn:uuid` entry, a contained `#wado`, and an entry with fullUrl `{imaging}/fhir/Endpoint/{id}` referenced as `Endpoint/{id}`. That address isn't served: the Endpoint is only in the Bundle | Retrieval: every form holds the same address | The last four are what the guide or FHIR lets any server do, and are what an app check stages. Create a new sandbox with `POST https://imaging.argo.run/api/sandboxes`. The response has `base`, a path to add to the origin. ### The activity log Every request any part of the sandbox answers is recorded as events, which the Activity page shows. Read them with no token; the sandbox's URL is the access. | Route | What it does | |---|---| | `GET $SANDBOX/api/activity` | One page of events, oldest first, up to `limit` (100 by default, at most 500). `more` says whether there are earlier ones; pass the answer's `before` as `before` for the page before it. `after=N` gives only events after sequence `N`, for polling | | `GET $SANDBOX/api/activity/summary` | Rollups of the same events: counts by type, a timeline, sessions and studies | | `GET $SANDBOX/api/activity/span?session=&span=` | The request and response behind one event | Filters, on the first two: `session`, `study` (an `ImagingStudy.id`), `type`, `kind`, `outcome`, `who`, `trace` and `link`. An Explore view has its own `session`; an app's own requests are in `unattributed@{sandbox id}`, or in the session named by the `baggage: demo.session=…` header they send. An event names the check that failed when something is refused, so `outcome=denied` with your session is the quickest answer to "why". The activity log keeps a limited amount across the whole deployment, oldest first out, so read what you need soon after. ### The account page `$SANDBOX/account` is the Authorization Server's own page for a signed-in person: what they hold, sharing with a related person, stopping a share, and stopping an app. Its forms write the same policy as `/api/sandbox/policy/shares` and `/app-approvals`. It's there for a person driving the sandbox in a browser; an agent uses the management API. ## Approving less at sign-in To approve less than everything at sign-in, as a person can on the consent page: this sandbox models that choice by site, a stand-in for whatever a real health system lets a person choose, and not part of SMART Imaging. To limit the approval to some sites, add `sites_shown=1` and a `sites` field per site, with the site's name exactly: `Northside Pathology`, `Lakeside Imaging` or `Riverside Hospital`. Sites left out aren't approved. A name that isn't a site at all is refused: the redirect carries `error=invalid_request` and an `error_description` listing the sites. A real site the person doesn't hold for that patient is dropped. To approve only some studies at a site, as the consent page's study boxes do: add `study_listed` with the site's name, and a `study` field with the id of each study to approve there. A site with `study_listed` approves just the studies named; one without it approves the whole site, including studies that arrive later. A study id is `ImagingStudy.id`, and `contract.json` lists them. When the person can act for more than one patient, the page names each field for its patient instead: `sites@{patient}`, `study@{patient}`, `study@{patient}_listed` and `sites_shown@{patient}`. When the request asks for any of the clinical record (`Condition`, `MedicationRequest`, `AllergyIntolerance`, or `patient/*`), the consent page also asks whether to share it: a checkbox, ticked to start with. Unticked, the form posts `clinical_shown=1` with no `share_clinical`, and the granted scope leaves those types out (`patient/*.rs` becomes `patient/ImagingStudy.rs patient/DiagnosticReport.rs patient/Patient.rs`), so their searches are `403`. A form posted without `clinical_shown` shares it, as approving everything offered does. Each sign-in's choice replaces that app's approval for that patient, so a later sign-in that approves fewer sites narrows what earlier tokens' searches return. A consent form posted with no site fields approves every site, as a form that showed none would. ## API types The shapes the management API takes and gives, as TypeScript. A `Ref` is a kind and an id: `user:josh`, `patient:josh-example`, `app:portal-app`, `service:hand-referral-service`. ```ts type Ref = string; // GET $SANDBOX/contract.json, no token: the sandbox's ground truth, worked out from its policy now. interface Contract { about: string; users: { username: string; name: string; fhirUser: string; patient?: string }[]; patients: { id: string; name: string; studies: number }[]; clientTypes: { type: "public" | "confidential" | "backend"; auth: string; grant: string; scope: string }[]; state: { clean: boolean; differences: string[]; faults: Faults; clockOffsetSeconds: number; appCheck: { script: string; staged: string[]; endsAt: string } | null }; expected: { user: string; patient: string; via: "self" | "related"; studies: { id: string; uid: string; title: string }[]; // what an app approving everything offered finds reports: number; withheld: { id: string; title: string; labels: string[] }[] }[]; } // GET /api/sandbox/keys-shared-on-purpose: the one call with no token. interface SampleKey { client_id: string; jwk: JsonWebKey & { kid: string; alg: "ES256" }; scope: string } interface Keys { why: string; tokenEndpoint: string; now: number; admin: SampleKey; services: SampleKey[] } // GET /api/sandbox, and what each settings call answers with. interface SandboxStatus { sandbox: { id: string; base: string } | null; name: string | null; clock: { offsetSeconds: number; now: number }; clockChoices: { value: number; label: string }[]; storage: { current: "static-files" | "s3" | "orthanc"; names: string[] }; topology: { current: "separate" | "unified"; names: string[] }; catalog: { source: string; studies: number; series: number; [count: string]: unknown }; signing: { kid: string }; proxy: { cachedDecisions: number }; faults: Faults; appCheck: AppCheckOn | null; } // GET /api/sandbox/faults gives { faults, appCheck }, and POST /api/sandbox/faults answers the same. POST takes any of these fields. interface Faults { decisionOutage: boolean; truncateAfter: number | null; pageSize: number | null; searchRetryAfter: number | null; retrievalRetryAfter: number | null; endpointForms: boolean } interface AppCheckOn { run: string; client: string; script: string; staged: string[]; startedAt: string; endsAt: string } // The policy API, /api/sandbox/policy/*. interface Relationship { id?: string; subject: Ref; relation: "guardian_of"; object: Ref; recordedBy?: string } type OrgPolicy = | { id: string; type: "guardian-access"; description?: string; when: { age: { min?: number; max?: number } }; allow: "all"; except?: string[] } | { id: string; type: "sharing"; description?: string; allowedFrom: ("patient" | "guardian")[] } | { id: string; type: "service-access"; description?: string; service: Ref; patients: "any" | Ref; allow: { all?: boolean; sites?: string[]; modalities?: string[]; studies?: string[]; since?: string }; withholdSeries?: string[]; contextForm?: "auto" | "restricted" }; interface Share { id?: string; from: Ref; with: Ref; patient: Ref; sites: string[]; label: string } // POST /shares takes it without id interface AppApproval { id?: string; by: Ref; app: Ref; patient: Ref; sites?: string[]; fhirUser?: string } // POST /app-approvals: fhirUser is needed for one's own records type Release = "none" | "study" | { series: string[] }; interface Explained { // GET /explain?client=&user=&fhirUser=&patient= searchAllowed: boolean; studies: { id: string; title?: string; site?: string; date?: string; modalities: string[]; release: Release; why: string; withheldSeries: { uid: string }[] }[]; } // Explore, /api/sandbox/explore/*. interface Cast { people: { id: string; name: string; fhirUser: string; role: string; records: { patient: string; name: string; via: "self" | "guardian" | "share"; relationship?: string }[]; others: { patient: string; name: string }[] }[]; services: { id: string; name: string; role: string }[]; relationships: string[]; app: string; names: Record; } interface Referral { id: string; report: string; reason?: string; patient: string; patientRef: string; accession: string; system: string } interface ExploreRow { id: string; title: string; site?: string; date?: string; modalities: string[]; released: boolean; reason?: string; partial?: string } type ExploreAction = | { kind: "approve"; label: string; sites: string[]; ticked?: string[]; patient?: string } | { kind: "share"; label: string; from: string; with?: string; patient: string; sites: string[] } | { kind: "unshare" | "revoke-app"; label: string; with?: string; patient: string } | { kind: "apply-policy"; label: string; ruleSet: string; text: string } | { kind: "person"; label: string; user: string } | { kind: "referral"; label: string; referral: string }; interface ExploreView { // GET /view: the studies a viewer may know of, and why each is or isn't released status: "results" | "no-access" | "forbidden" | "failed"; patient?: string; headline: string; detail?: string; rows: ExploreRow[]; actions: ExploreAction[]; empty?: { text: string; actions: ExploreAction[] }; whyTitle: string; chain?: { columns: { id: string; site?: string; title: string }[]; rows: { level: "fact" | "policy" | "choice" | "outcome"; name: string; has: string[] }[] }; activityUrl: string; } // GET /api/sandbox/catalog?patient= interface CatalogStudy { id: string; uid: string; site?: string; date?: string; instances: number; series: { uid: string; modality: string; instances: number }[] } // Server checks, at the site's root: POST /api/checks, then GET /api/checks/{id}. See "Server check: run one for someone". interface CheckServer { label: string; iss: string; clientId: string; mode?: "launch" | "backend"; auth?: "public" | "private_key_jwt"; jwk?: JsonWebKey & { kid: string }; patient?: string; scope?: string; imaging?: string } interface CheckCreated { id: string; url: string; status: "waiting"; expiresAt: string } type CheckStepState = "todo" | "running" | "paused" | "pass" | "fail" | "skip" | "note" | "unreached"; interface CheckStep { n: number; title: string; state: CheckStepState; result: string; diagnosis?: { cause: string; check?: string }; requests: { request: string; response: string }[] } interface CheckRun { id: string; server: Omit & { hasKey?: boolean; kid?: string }; // never the private key status: "waiting" | "running" | "paused" | "done"; // paused: waiting for the person to sign in summary: string | null; // "Stopped at step 5 of 12: …", "All 12 steps passed.", … steps: CheckStep[]; updatedAt: string; expiresAt: string; } // App checks, at the site's root too: POST /api/checks with an app, then start, end and GET. See "App check: run one for someone". interface CheckApp { sandbox: string; clientId: string; script?: "josh" | "riley" | "robin" | "service"; conditions?: ("small-pages" | "search-503" | "retrieval-503" | "endpoint-forms")[] } interface Source { doc: string; section: string; url: string; text: string } interface AppCheckStep { n: number; group: "script" | "requirement"; title: string; state: "pass" | "fail" | "note" | "unreached"; result: string; sources?: Source[]; requests: { request: string; response: string; log?: string }[] } interface AppCheckRun { id: string; app: Required & { name: string; type: string }; status: "waiting" | "running" | "done"; summary: string | null; script: { id: string; title: string; steps: string[] }; staged: { id: string; text: string }[]; fhirBase: string; startedAt?: string; endsAt?: string; endedAt?: string; ended?: "graded" | "abandoned" | "expired"; progress?: { tokens: number; searches: number; retrievals: number }; // while it runs steps: AppCheckStep[]; notes: { title: string; detail: string; sources: Source[]; requests: AppCheckStep["requests"] }[]; notChecked: string[]; // what this run didn't look at: a pass covers only the requirements graded updatedAt: string; expiresAt: string; } // POST $SANDBOX/register: RFC 7591 client metadata, and the same, with client_id and client_id_issued_at, in answer. interface ClientMetadata { client_name?: string; redirect_uris?: string[]; // one or more redirect URIs, or ["*"] to skip redirect checking grant_types?: ["authorization_code"] | ["authorization_code", "refresh_token"] | ["client_credentials"]; response_types?: ["code"]; token_endpoint_auth_method?: "none" | "private_key_jwt"; jwks?: { keys: (JsonWebKey & { kid: string })[] }; jwks_uri?: string; scope?: string; patients?: "any" | string; // this sandbox's extension, for a backend service } ``` ## Pages The menu is a guide for each audience, at the site's root. Each lists what matters, most important first. - [Build an App](https://imaging.argo.run/build-an-app): Connect your SMART app to a sandbox health system with sample patients and studies. - [Build a Server](https://imaging.argo.run/build-a-server): Register our known-good viewer with your server, describe it, and check every step of the guide against it. - [Why SMART Imaging](https://imaging.argo.run/about): What imaging interoperability makes possible, how it works, and what it takes. - [My Sandboxes](https://imaging.argo.run/sandboxes): The sandboxes this browser has made or joined, and a new one. The site's own tools, for a server of your own. A sandbox's viewer is the same app, at its own address: - [Server check](https://imaging.argo.run/check): Every step of the guide, run against your server, saying how far it got and why it stopped. - [Viewer](https://imaging.argo.run/viewer): Our SMART app, signed in to this sandbox, or to a server of your own. A sandbox's own pages, by what they're for: - [Home](https://imaging.argo.run/): This sandbox: its name, sharing, and its pages. - **Try it:** [Viewer](https://imaging.argo.run/viewer) (our SMART app, signed in to this sandbox, or to a server of your own), [Explore](https://imaging.argo.run/explore) (what each sample person and service can reach, and why), [Server check](https://imaging.argo.run/check) (every step of the guide, run against your server, saying how far it got and why it stopped), [App check](https://imaging.argo.run/app-check) (your app, run against this sandbox while it stages what servers may do, graded on each requirement of the guide). - **Your app:** [Endpoints](https://imaging.argo.run/build) (this sandbox's addresses, scopes, and sample people to sign in as), [Register an app](https://imaging.argo.run/connect) (a public app, a confidential app, or a backend service), [Logs](https://imaging.argo.run/activity) (every request, and why each was allowed or refused), [Live trace](https://imaging.argo.run/trace/) (every request between the services, as it happens). - **Under the hood:** [Sandbox Config](https://imaging.argo.run/config) (the demo clock, image storage, topology, resets, and ending access). # References ## Specifications IGs built on build.fhir.org publish their pages as Markdown for agents at `{ig}/ai.zip`: the narrative, each profile and example, and an `llms.txt` index. SMART Imaging Access's is at https://build.fhir.org/ig/argonautproject/smart-imaging/ai.zip. Read that rather than scraping the HTML. - [SMART Imaging Access](https://build.fhir.org/ig/argonautproject/smart-imaging/) - [SMART App Launch](https://build.fhir.org/ig/HL7/smart-app-launch/) - [FHIR ImagingStudy](https://build.fhir.org/imagingstudy.html) - [FHIR Endpoint](https://build.fhir.org/endpoint.html) - [DICOMweb WADO-RS](https://www.dicomstandard.org/using/dicomweb/retrieve-wado-rs-and-wado-uri) ## Source - [github.com/jmandel/smart-imaging-proxy](https://github.com/jmandel/smart-imaging-proxy)