# 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(/