feat(epic): Hanzo AI for Epic (SMART on FHIR)
Read+assist clinical copilot embedded in the EHR via SMART on FHIR. Loads the launched patient's chart over FHIR R4 (problems, meds, allergies, labs/vitals, notes) and runs four actions — summarize patient, draft SOAP note, extract problems & meds, ask — through the api.hanzo.ai gateway via @hanzo/ai@^0.2.0. PHI posture: the FHIR/PHI access token is confined server-side (server.ts); the browser holds only an opaque HttpOnly session cookie and a Hanzo gateway key. No PHI is ever logged; SMART is auth-code + PKCE (S256) with the confidential secret read from the environment; the proxy is scoped to the six read resources and the session's own FHIR base (SSRF/cross-tenant guards). Read + assist only — no clinical write-back, no *.write scope. Tests: 109 vitest across config/smart-oauth/fhir-client/chart/hanzo/auth/server. Workspace-wired like every sibling: test/ dir, root pnpm-lock importer, no package-level lock.
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
// Build the Epic SMART-on-FHIR app into dist/: bundle the SPA (app.ts, browser)
|
||||
// and the OAuth + FHIR-proxy service (server.ts, node), copy the static
|
||||
// HTML/CSS/assets.
|
||||
//
|
||||
// node build.js → production (base https://epic.hanzo.ai)
|
||||
// HANZO_EPIC_BASE=http://localhost:8791 node build.js → local dev
|
||||
//
|
||||
// The SMART app's PUBLIC client_id + redirect + a default FHIR base (for
|
||||
// standalone launch) are stamped into the SPA via esbuild `define`. The
|
||||
// client_id is public; the SECRET (confidential apps) is read from the
|
||||
// environment by the running server, NEVER bundled — a bundled secret would ship
|
||||
// to every browser.
|
||||
|
||||
import esbuild from 'esbuild';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const BASE = (process.env.HANZO_EPIC_BASE || 'https://epic.hanzo.ai').replace(/\/+$/, '');
|
||||
const SMART_CLIENT_ID = process.env.SMART_CLIENT_ID || '';
|
||||
const SMART_REDIRECT_URI = process.env.SMART_REDIRECT_URI || `${BASE}/oauth/callback`;
|
||||
// Optional default FHIR base for STANDALONE launch (e.g. Epic's public sandbox).
|
||||
// In an EHR launch the real `iss` arrives in the URL and overrides this.
|
||||
const SMART_DEFAULT_ISS = process.env.SMART_DEFAULT_ISS || '';
|
||||
const watch = process.argv.includes('--watch');
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url));
|
||||
const src = path.join(root, 'src');
|
||||
const dist = path.join(root, 'dist');
|
||||
|
||||
async function build() {
|
||||
fs.rmSync(dist, { recursive: true, force: true });
|
||||
fs.mkdirSync(dist, { recursive: true });
|
||||
|
||||
// The browser SPA — public client_id/redirect/default-iss stamped via define.
|
||||
// Secrets are NOT define-able here; server.ts reads them from process.env.
|
||||
const spa = await esbuild.context({
|
||||
entryPoints: [path.join(src, 'app.ts')],
|
||||
outfile: path.join(dist, 'app.js'),
|
||||
bundle: true,
|
||||
format: 'iife',
|
||||
platform: 'browser',
|
||||
target: ['chrome90', 'edge90', 'safari14', 'firefox90'],
|
||||
sourcemap: true,
|
||||
minify: !watch,
|
||||
define: {
|
||||
SMART_CLIENT_ID: JSON.stringify(SMART_CLIENT_ID),
|
||||
SMART_REDIRECT_URI: JSON.stringify(SMART_REDIRECT_URI),
|
||||
SMART_DEFAULT_ISS: JSON.stringify(SMART_DEFAULT_ISS),
|
||||
},
|
||||
logLevel: 'info',
|
||||
});
|
||||
await spa.rebuild();
|
||||
|
||||
// The OAuth + FHIR-proxy service — a Node ESM bundle. No secrets baked in; it
|
||||
// reads SMART_CLIENT_SECRET etc. from the environment when it runs.
|
||||
const server = await esbuild.context({
|
||||
entryPoints: [path.join(src, 'server.ts')],
|
||||
outfile: path.join(dist, 'server.js'),
|
||||
bundle: true,
|
||||
format: 'esm',
|
||||
platform: 'node',
|
||||
target: ['node18'],
|
||||
sourcemap: true,
|
||||
minify: !watch,
|
||||
banner: { js: '// Hanzo Epic SMART-on-FHIR service — run: node server.js' },
|
||||
logLevel: 'info',
|
||||
});
|
||||
await server.rebuild();
|
||||
|
||||
// Static files.
|
||||
for (const f of ['index.html', 'styles.css']) {
|
||||
fs.copyFileSync(path.join(src, f), path.join(dist, f));
|
||||
}
|
||||
|
||||
// assets/ (icons) — create the dir even if empty.
|
||||
const assetsSrc = path.join(root, 'assets');
|
||||
const assetsDst = path.join(dist, 'assets');
|
||||
fs.mkdirSync(assetsDst, { recursive: true });
|
||||
if (fs.existsSync(assetsSrc)) {
|
||||
for (const f of fs.readdirSync(assetsSrc)) {
|
||||
fs.copyFileSync(path.join(assetsSrc, f), path.join(assetsDst, f));
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`✅ Epic SMART-on-FHIR app built → dist/ (base ${BASE})`);
|
||||
console.log(' Serve dist/{index.html,app.js,styles.css,assets} as static; run dist/server.js for /oauth/* + /fhir.');
|
||||
if (!SMART_CLIENT_ID) {
|
||||
console.log(' ⚠ SMART_CLIENT_ID not set — set it (and SMART_CLIENT_SECRET on the server for a confidential app) before deploy.');
|
||||
}
|
||||
|
||||
if (watch) {
|
||||
await spa.watch();
|
||||
await server.watch();
|
||||
console.log('👀 watching…');
|
||||
} else {
|
||||
await spa.dispose();
|
||||
await server.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
build().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"name": "@hanzo/epic",
|
||||
"version": "0.1.0",
|
||||
"description": "Hanzo AI for Epic (SMART on FHIR) — brings Hanzo AI into the clinician's EHR workflow. Reads the launched patient's chart over FHIR R4 (problems, meds, allergies, labs, notes) and assists: summarize the patient, draft a SOAP note, extract problems & meds, and ask about the patient. Read + assist only (no clinical write-back in v1). Model calls route through the api.hanzo.ai gateway via @hanzo/ai; SMART-on-FHIR OAuth2 (auth-code + PKCE) with server-side token exchange; PHI-bearing tokens stay server-side.",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "node build.js",
|
||||
"watch": "node build.js --watch",
|
||||
"serve": "node dist/server.js",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hanzo/ai": "^0.2.0",
|
||||
"@hanzo/iam": "0.13.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.14.0",
|
||||
"esbuild": "^0.25.8",
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^3.2.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"keywords": [
|
||||
"hanzo",
|
||||
"epic",
|
||||
"smart-on-fhir",
|
||||
"fhir",
|
||||
"ehr",
|
||||
"healthcare",
|
||||
"clinical",
|
||||
"ai",
|
||||
"hipaa"
|
||||
],
|
||||
"author": "Hanzo AI",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/hanzoai/extension.git",
|
||||
"directory": "packages/epic"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
// The SMART app panel glue: the browser page that launches from Epic with a
|
||||
// patient in context, loads that patient's chart through the server-side FHIR
|
||||
// proxy (so no PHI token touches the browser), and drives the four Hanzo AI
|
||||
// actions over the assembled chart. All the logic-heavy work — SMART/PKCE
|
||||
// shaping, FHIR request wrappers, chart assembly, action prompts — lives in its
|
||||
// own tested pure modules; this file is the one impure, browser-only entry point
|
||||
// that binds them to the DOM.
|
||||
//
|
||||
// The launch dance (see README for the full flow):
|
||||
// 1. EHR launch: Epic opens this page with `iss` + `launch`. Standalone: the
|
||||
// page is opened with an `iss` (or the sandbox default) and no `launch`.
|
||||
// 2. The page mints PKCE + state, asks the server (/oauth/prepare) to discover
|
||||
// Epic's authorize/token endpoints, then redirects the browser to authorize.
|
||||
// 3. Epic redirects back to /oauth/callback?code&state; the page posts them to
|
||||
// the server, which exchanges (secret + PKCE server-side) and sets an opaque
|
||||
// session cookie. The browser learns only the patient id + granted scope.
|
||||
// 4. The page loads the chart via /fhir?path=… (proxied), assembles the
|
||||
// context, and runs actions against api.hanzo.ai with the pasted Hanzo key.
|
||||
//
|
||||
// These build-time constants are stamped by build.js (the client id + redirect
|
||||
// are PUBLIC; the secret is server-only and never bundled).
|
||||
declare const SMART_CLIENT_ID: string;
|
||||
declare const SMART_REDIRECT_URI: string;
|
||||
declare const SMART_DEFAULT_ISS: string;
|
||||
|
||||
import {
|
||||
createPkce,
|
||||
authorizeUrl,
|
||||
parseLaunch,
|
||||
parseCallback,
|
||||
} from './smart-oauth.js';
|
||||
import {
|
||||
getPatient,
|
||||
searchConditions,
|
||||
searchMedicationRequests,
|
||||
searchAllergyIntolerances,
|
||||
searchObservations,
|
||||
searchDocumentReferences,
|
||||
bundleEntries,
|
||||
fetchAllPages,
|
||||
type FhirResource,
|
||||
type FhirRequest,
|
||||
} from './fhir-client.js';
|
||||
import { assembleChartContext, chartIsEmpty, emptyChart, type Chart } from './chart.js';
|
||||
import { ACTIONS, isActionId, runAction, listModels } from './hanzo.js';
|
||||
import { scopeString } from './config.js';
|
||||
import { getApiKey, setApiKey, bearer, validateKey } from './auth.js';
|
||||
|
||||
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
|
||||
const STATE_KEY = 'hanzo.epic.oauthState';
|
||||
const VERIFIER_KEY = 'hanzo.epic.pkceVerifier';
|
||||
|
||||
// The panel's live SMART context (non-PHI parts) once authenticated.
|
||||
interface Session {
|
||||
patient: string;
|
||||
scope: string;
|
||||
}
|
||||
|
||||
let controller: AbortController | null = null;
|
||||
let session: Session | null = null;
|
||||
let chartContext = '';
|
||||
|
||||
window.addEventListener('DOMContentLoaded', () => void boot());
|
||||
|
||||
// boot decides which phase of the launch we are in: a callback (we have a code),
|
||||
// a launch (we have iss/launch — start authorize), or a cold open (show the
|
||||
// standalone launcher). Then wires the UI.
|
||||
async function boot(): Promise<void> {
|
||||
wireApiKey();
|
||||
wireActions();
|
||||
void populateModels();
|
||||
|
||||
const search = window.location.search;
|
||||
const cb = parseCallback(search);
|
||||
const launch = parseLaunch(search);
|
||||
|
||||
if (cb.error) {
|
||||
status(`Launch declined: ${cb.errorDescription || cb.error}`, 'error');
|
||||
return;
|
||||
}
|
||||
if (cb.code) {
|
||||
await completeCallback(cb.code, cb.state);
|
||||
return;
|
||||
}
|
||||
if (launch.iss || SMART_DEFAULT_ISS) {
|
||||
await beginAuthorize(launch.iss || SMART_DEFAULT_ISS, launch.launch);
|
||||
return;
|
||||
}
|
||||
status('Open this app from Epic, or configure a FHIR server to launch standalone.', 'warn');
|
||||
}
|
||||
|
||||
// beginAuthorize mints PKCE + state, asks the server to discover Epic's
|
||||
// endpoints, stores the verifier/state, and redirects the browser to authorize.
|
||||
async function beginAuthorize(iss: string, launchToken: string): Promise<void> {
|
||||
status('Connecting to the EHR…');
|
||||
const pkce = await createPkce();
|
||||
const state = crypto.randomUUID();
|
||||
sessionStorage.setItem(STATE_KEY, state);
|
||||
sessionStorage.setItem(VERIFIER_KEY, pkce.verifier);
|
||||
|
||||
const prep = await postJson('/oauth/prepare', { iss, state, codeVerifier: pkce.verifier });
|
||||
if (!prep.authorizationEndpoint) {
|
||||
status('Could not discover the EHR OAuth endpoints.', 'error');
|
||||
return;
|
||||
}
|
||||
window.location.href = authorizeUrl({
|
||||
authorizationEndpoint: prep.authorizationEndpoint,
|
||||
clientId: SMART_CLIENT_ID,
|
||||
redirectUri: SMART_REDIRECT_URI,
|
||||
aud: iss,
|
||||
scope: scopeString(),
|
||||
state,
|
||||
codeChallenge: pkce.challenge,
|
||||
launch: launchToken || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
// completeCallback verifies state, posts code+state to the server (which does
|
||||
// the secret+PKCE exchange and sets the session cookie), then loads the chart.
|
||||
async function completeCallback(code: string, returnedState: string): Promise<void> {
|
||||
const expected = sessionStorage.getItem(STATE_KEY) || '';
|
||||
if (!expected || returnedState !== expected) {
|
||||
status('OAuth state mismatch — refusing to continue.', 'error');
|
||||
return;
|
||||
}
|
||||
sessionStorage.removeItem(STATE_KEY);
|
||||
sessionStorage.removeItem(VERIFIER_KEY);
|
||||
status('Completing sign-in…');
|
||||
const out = await postJson('/oauth/callback', { code, state: returnedState });
|
||||
if (out.error || !out.patient) {
|
||||
status(`Sign-in failed: ${out.error || 'no patient context'}`, 'error');
|
||||
return;
|
||||
}
|
||||
// Clean the code/state out of the URL bar (never leave an auth code in history).
|
||||
window.history.replaceState({}, document.title, window.location.pathname);
|
||||
session = { patient: out.patient, scope: out.scope || '' };
|
||||
await loadChart();
|
||||
}
|
||||
|
||||
// loadChart pulls the launched patient's chart through the proxy and assembles
|
||||
// the clinical context. Every FHIR read goes through /fhir — the browser never
|
||||
// holds the FHIR token. Reads run concurrently; each is independent.
|
||||
async function loadChart(): Promise<void> {
|
||||
if (!session) return;
|
||||
status('Loading patient chart…');
|
||||
const patientId = session.patient;
|
||||
// The FHIR base/token live server-side; the request wrappers here shape a
|
||||
// RELATIVE path the proxy resolves. token/base are placeholders the proxy
|
||||
// replaces, so we pass empty strings and send only the resolved path.
|
||||
const rel = (req: FhirRequest) => proxyPath(req.url);
|
||||
const chart: Chart = emptyChart();
|
||||
try {
|
||||
const [patient, conditions, meds, allergies, obs, docs] = await Promise.all([
|
||||
proxyGet(rel(getPatient('', '', patientId))),
|
||||
proxyGetAll(searchConditions(sp(patientId))),
|
||||
proxyGetAll(searchMedicationRequests(sp(patientId))),
|
||||
proxyGetAll(searchAllergyIntolerances(sp(patientId))),
|
||||
proxyGetAll(searchObservations(sp(patientId))),
|
||||
proxyGetAll(searchDocumentReferences(sp(patientId))),
|
||||
]);
|
||||
chart.patient = (patient as FhirResource)?.resourceType === 'Patient' ? (patient as FhirResource) : undefined;
|
||||
chart.conditions = conditions;
|
||||
chart.medications = meds;
|
||||
chart.allergies = allergies;
|
||||
chart.observations = obs;
|
||||
chart.documents = docs;
|
||||
} catch (e: unknown) {
|
||||
status(`Could not load the chart: ${(e as Error).message}`, 'error');
|
||||
return;
|
||||
}
|
||||
chartContext = assembleChartContext(chart);
|
||||
const label = chart.patient
|
||||
? summarizeHeader(chart.patient)
|
||||
: `Patient ${patientId}`;
|
||||
$('patient-title').textContent = label;
|
||||
status(chartIsEmpty(chart) ? 'Chart loaded (no clinical data recorded).' : 'Chart loaded.', 'ok');
|
||||
setActionsEnabled(true);
|
||||
}
|
||||
|
||||
// sp builds a patient-scoped SearchParams with empty base/token — the proxy
|
||||
// supplies both. Only the relative path matters here.
|
||||
function sp(patientId: string) {
|
||||
return { base: '', token: '', patientId };
|
||||
}
|
||||
|
||||
// proxyPath turns a FHIR request URL (which the wrappers built with an empty
|
||||
// base, so it is like `/Condition?patient=…`) into the proxy query. The wrappers
|
||||
// prepend the normalized base; with an empty base the URL is just the path.
|
||||
function proxyPath(fhirUrl: string): string {
|
||||
const path = fhirUrl.replace(/^\/+/, '');
|
||||
return `/fhir?path=${encodeURIComponent(path)}`;
|
||||
}
|
||||
|
||||
// proxyGet does one proxied FHIR read and returns the parsed resource/Bundle.
|
||||
async function proxyGet(path: string): Promise<unknown> {
|
||||
const resp = await fetch(path, { credentials: 'same-origin' });
|
||||
if (!resp.ok) throw new Error(`FHIR proxy ${resp.status}`);
|
||||
return resp.json();
|
||||
}
|
||||
|
||||
// proxyGetAll pages a search to completion through the proxy, following the
|
||||
// Bundle `next` links (rewritten as proxy paths). Returns the flattened
|
||||
// resources. Uses fetchAllPages' Bundle logic via a proxy-backed fetch.
|
||||
async function proxyGetAll(first: FhirRequest): Promise<FhirResource[]> {
|
||||
const doFetch: typeof fetch = async (input) => {
|
||||
const raw = typeof input === 'string' ? input : (input as Request).url;
|
||||
// `raw` is either our first relative path or an absolute FHIR `next` URL;
|
||||
// both go through the proxy by path.
|
||||
return fetch(proxyPath(raw), { credentials: 'same-origin' }) as Promise<Response>;
|
||||
};
|
||||
return fetchAllPages({ ...first, url: first.url.replace(/^\/+/, '') }, '', { doFetch });
|
||||
}
|
||||
|
||||
// summarizeHeader renders a short patient label for the panel header from a
|
||||
// Patient resource (name only — the sensitive detail stays in the chart body).
|
||||
function summarizeHeader(patient: FhirResource): string {
|
||||
const p = patient as { name?: Array<{ text?: string; given?: string[]; family?: string }> };
|
||||
const n = Array.isArray(p.name) ? p.name[0] : undefined;
|
||||
if (n?.text) return n.text;
|
||||
const given = Array.isArray(n?.given) ? n!.given!.join(' ') : '';
|
||||
return `${given} ${n?.family ?? ''}`.trim() || 'Patient';
|
||||
}
|
||||
|
||||
// ── Actions ────────────────────────────────────────────────────────────────
|
||||
|
||||
function wireActions(): void {
|
||||
const chipRow = $('chips');
|
||||
for (const a of ACTIONS) {
|
||||
const b = document.createElement('button');
|
||||
b.className = 'chip';
|
||||
b.textContent = a.label;
|
||||
b.dataset.action = a.id;
|
||||
b.disabled = true;
|
||||
b.onclick = () => void run(a.id);
|
||||
chipRow.appendChild(b);
|
||||
}
|
||||
$<HTMLButtonElement>('stop').onclick = () => controller?.abort();
|
||||
}
|
||||
|
||||
function setActionsEnabled(on: boolean): void {
|
||||
for (const el of document.querySelectorAll<HTMLButtonElement>('.chip')) el.disabled = !on;
|
||||
}
|
||||
|
||||
// run executes one action over the assembled chart context. Requires a loaded
|
||||
// chart; a prompt-taking action reads the detail box.
|
||||
async function run(id: string): Promise<void> {
|
||||
if (!isActionId(id)) return;
|
||||
if (!chartContext) {
|
||||
status('Load a patient chart first (launch from Epic).', 'warn');
|
||||
return;
|
||||
}
|
||||
const def = ACTIONS.find((a) => a.id === id)!;
|
||||
const detail = $<HTMLTextAreaElement>('prompt').value.trim();
|
||||
if (def.needsPrompt && id === 'ask' && !detail) {
|
||||
status('Type a question about this patient.', 'warn');
|
||||
return;
|
||||
}
|
||||
controller?.abort();
|
||||
controller = new AbortController();
|
||||
const outputEl = $<HTMLTextAreaElement>('output');
|
||||
outputEl.value = '';
|
||||
status(`Running “${def.label}”…`);
|
||||
$<HTMLButtonElement>('stop').disabled = false;
|
||||
setActionsEnabled(false);
|
||||
const model = $<HTMLSelectElement>('model').value || undefined;
|
||||
try {
|
||||
const text = await runAction({
|
||||
id,
|
||||
detail,
|
||||
chartContext,
|
||||
opts: { token: bearer(), model, signal: controller.signal },
|
||||
});
|
||||
outputEl.value = text;
|
||||
status('Done. Review before use — decision support, not a diagnosis.', 'ok');
|
||||
} catch (e: unknown) {
|
||||
if ((e as Error).name === 'AbortError') status('Stopped.', 'warn');
|
||||
else status(`Error: ${(e as Error).message}`, 'error');
|
||||
} finally {
|
||||
$<HTMLButtonElement>('stop').disabled = true;
|
||||
setActionsEnabled(true);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Hanzo key + models ─────────────────────────────────────────────────────
|
||||
|
||||
function wireApiKey(): void {
|
||||
const apiKeyEl = $<HTMLInputElement>('apikey');
|
||||
apiKeyEl.value = getApiKey();
|
||||
$<HTMLButtonElement>('savekey').onclick = async () => {
|
||||
const key = apiKeyEl.value.trim();
|
||||
try {
|
||||
const models = await validateKey(key);
|
||||
setApiKey(key);
|
||||
fillModels(models);
|
||||
status('Hanzo API key saved.', 'ok');
|
||||
} catch (e: unknown) {
|
||||
status(`Key rejected: ${(e as Error).message}`, 'error');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function populateModels(): Promise<void> {
|
||||
try {
|
||||
fillModels(await listModels({ token: bearer() }));
|
||||
} catch {
|
||||
/* anonymous / offline — the picker stays with its default option */
|
||||
}
|
||||
}
|
||||
|
||||
function fillModels(ids: string[]): void {
|
||||
const sel = $<HTMLSelectElement>('model');
|
||||
const current = sel.value;
|
||||
sel.innerHTML = '';
|
||||
for (const id of ids) {
|
||||
const o = document.createElement('option');
|
||||
o.value = id;
|
||||
o.textContent = id;
|
||||
sel.appendChild(o);
|
||||
}
|
||||
if (current && ids.includes(current)) sel.value = current;
|
||||
}
|
||||
|
||||
// ── Small helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
async function postJson(path: string, body: unknown): Promise<any> {
|
||||
const resp = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return resp.json().catch(() => ({ error: `HTTP ${resp.status}` }));
|
||||
}
|
||||
|
||||
function status(msg: string, kind: '' | 'ok' | 'warn' | 'error' = ''): void {
|
||||
const el = $('status');
|
||||
el.textContent = msg;
|
||||
el.className = `status${kind ? ` ${kind}` : ''}`;
|
||||
}
|
||||
|
||||
// Re-export a couple of pure helpers the panel uses so the module boundary is
|
||||
// explicit (and so a smoke test can import this file under a DOM shim if needed).
|
||||
export { bundleEntries };
|
||||
@@ -0,0 +1,51 @@
|
||||
// The HANZO-gateway credential for the web panel — the zero-setup pasted-key
|
||||
// path. This is ONLY the Hanzo model-gateway bearer (an `hk-…` key or an IAM
|
||||
// token); it is emphatically NOT the FHIR/PHI token. The FHIR access token lives
|
||||
// server-side (server.ts) and is never handled here — the panel holds only the
|
||||
// opaque server session cookie for FHIR reads. So a leaked localStorage key
|
||||
// exposes a Hanzo gateway key, never PHI.
|
||||
//
|
||||
// Mirrors @hanzo/docusign / @hanzo/pdf exactly (one way to hold a Hanzo key): a
|
||||
// key pasted into the panel, validated by a real /v1/models call so a bad key is
|
||||
// rejected at paste time.
|
||||
|
||||
import { APIKEY_STORAGE_KEY, pickBearer } from './config.js';
|
||||
import { listModels } from './hanzo.js';
|
||||
|
||||
export function getApiKey(): string {
|
||||
try {
|
||||
return localStorage.getItem(APIKEY_STORAGE_KEY) || '';
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export function setApiKey(key: string): void {
|
||||
try {
|
||||
const k = key.trim();
|
||||
if (k) localStorage.setItem(APIKEY_STORAGE_KEY, k);
|
||||
else localStorage.removeItem(APIKEY_STORAGE_KEY);
|
||||
} catch {
|
||||
/* private-mode / storage disabled — the in-memory key still works this session */
|
||||
}
|
||||
}
|
||||
|
||||
export function hasApiKey(): boolean {
|
||||
return !!getApiKey();
|
||||
}
|
||||
|
||||
// bearer is the credential the chat call sends to the HANZO gateway: the pasted
|
||||
// key, else empty (anonymous public models). When Hanzo IAM OAuth lands it slots
|
||||
// in as the second argument to pickBearer with no change to callers.
|
||||
export function bearer(): string {
|
||||
return pickBearer(getApiKey(), '');
|
||||
}
|
||||
|
||||
// validateKey confirms a pasted key works by listing models with it. Returns the
|
||||
// model ids on success so the caller populates the picker in one round-trip;
|
||||
// throws with the gateway's message on failure. Empty key → clear message.
|
||||
export async function validateKey(key: string): Promise<string[]> {
|
||||
const k = key.trim();
|
||||
if (!k) throw new Error('Enter a Hanzo API key (hk-…).');
|
||||
return listModels({ token: k });
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
// Turning raw FHIR R4 resources into the clinical-context TEXT handed to Hanzo —
|
||||
// PURE and fully unit-tested (no network, no DOM, no @hanzo/ai). This is the
|
||||
// clinical-reasoning core: it reads the messy, deeply-nested FHIR shapes
|
||||
// (CodeableConcepts, references, effective[x] polymorphism) and renders a
|
||||
// compact, honest, human-readable chart that a model can reason over and a
|
||||
// clinician can eyeball.
|
||||
//
|
||||
// Two responsibilities, kept separate:
|
||||
// 1. per-resource extraction — one small pure function per resource type that
|
||||
// pulls the clinically-relevant fields into a flat, display-ready row.
|
||||
// 2. assembly + windowing — compose the sections into a single string capped
|
||||
// at a character budget, truncating VISIBLY (never silently) and section by
|
||||
// section so the most important sections (problems, meds, allergies)
|
||||
// survive when a chart is huge.
|
||||
//
|
||||
// The model's context window is finite and a real chart can be enormous, so we
|
||||
// window honestly: cap each section's row count and the whole assembled text,
|
||||
// and mark every truncation so the model — and the reviewing clinician — know
|
||||
// what was elided.
|
||||
|
||||
import type { FhirResource } from './fhir-client.js';
|
||||
|
||||
// ── FHIR primitive extractors (pure) ───────────────────────────────────────
|
||||
|
||||
// codeableText renders a FHIR CodeableConcept to a display string: prefer its
|
||||
// `text`, else the first coding's `display`, else the first coding's `code`.
|
||||
// This is the single place the CodeableConcept shape is decoded, so every
|
||||
// section reads a code the same way. Pure.
|
||||
export function codeableText(concept: unknown): string {
|
||||
const c = concept as {
|
||||
text?: unknown;
|
||||
coding?: Array<{ display?: unknown; code?: unknown }>;
|
||||
};
|
||||
if (typeof c?.text === 'string' && c.text.trim()) return c.text.trim();
|
||||
const coding = Array.isArray(c?.coding) ? c.coding[0] : undefined;
|
||||
if (typeof coding?.display === 'string' && coding.display.trim()) return coding.display.trim();
|
||||
if (typeof coding?.code === 'string' && coding.code.trim()) return coding.code.trim();
|
||||
return '';
|
||||
}
|
||||
|
||||
// effectiveDate pulls the clinically-relevant date off a resource's polymorphic
|
||||
// effective[x]/onset[x]/authoredOn/recordedDate, tolerating the several field
|
||||
// names FHIR uses across resource types. Returns '' when none is present. Pure.
|
||||
export function effectiveDate(res: FhirResource): string {
|
||||
const r = res as Record<string, unknown>;
|
||||
const period = r.effectivePeriod as { start?: unknown } | undefined;
|
||||
const candidates = [
|
||||
r.effectiveDateTime,
|
||||
period?.start,
|
||||
r.onsetDateTime,
|
||||
r.authoredOn,
|
||||
r.recordedDate,
|
||||
r.issued,
|
||||
];
|
||||
for (const v of candidates) {
|
||||
if (typeof v === 'string' && v.trim()) return v.trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// ── Per-resource rows (pure) ───────────────────────────────────────────────
|
||||
|
||||
// summarizePatient renders a Patient into the demographic header lines. Reads
|
||||
// the R4 name/gender/birthDate. Uses the FIRST official/usual name. Pure.
|
||||
export function summarizePatient(patient: FhirResource | undefined): string[] {
|
||||
if (!patient) return [];
|
||||
const p = patient as {
|
||||
name?: Array<{ text?: string; given?: string[]; family?: string; use?: string }>;
|
||||
gender?: string;
|
||||
birthDate?: string;
|
||||
};
|
||||
const lines: string[] = [];
|
||||
const name = pickName(p.name);
|
||||
if (name) lines.push(`Name: ${name}`);
|
||||
if (typeof p.gender === 'string' && p.gender) lines.push(`Sex: ${p.gender}`);
|
||||
if (typeof p.birthDate === 'string' && p.birthDate) lines.push(`DOB: ${p.birthDate}`);
|
||||
return lines;
|
||||
}
|
||||
|
||||
// pickName renders a HumanName[]: prefer a `text`, else "Given Family" from the
|
||||
// first name that has parts. Pure.
|
||||
function pickName(names: Array<{ text?: string; given?: string[]; family?: string }> | undefined): string {
|
||||
if (!Array.isArray(names)) return '';
|
||||
for (const n of names) {
|
||||
if (typeof n.text === 'string' && n.text.trim()) return n.text.trim();
|
||||
const given = Array.isArray(n.given) ? n.given.join(' ') : '';
|
||||
const full = `${given} ${n.family ?? ''}`.trim();
|
||||
if (full) return full;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// conditionRow renders a Condition (problem) to one line: its name, clinical
|
||||
// status, and onset date. Pure.
|
||||
export function conditionRow(res: FhirResource): string {
|
||||
const r = res as { clinicalStatus?: unknown };
|
||||
const name = codeableText((res as { code?: unknown }).code) || 'Unnamed condition';
|
||||
const status = codeableText(r.clinicalStatus);
|
||||
const onset = effectiveDate(res);
|
||||
return joinRow([name, status && `(${status})`, onset && `onset ${onset}`]);
|
||||
}
|
||||
|
||||
// medicationRow renders a MedicationRequest to one line: the drug (from
|
||||
// medicationCodeableConcept, or the display of a contained/referenced
|
||||
// Medication), status, and dosage text when present. Pure.
|
||||
export function medicationRow(res: FhirResource): string {
|
||||
const r = res as {
|
||||
medicationCodeableConcept?: unknown;
|
||||
medicationReference?: { display?: string };
|
||||
status?: string;
|
||||
dosageInstruction?: Array<{ text?: string }>;
|
||||
};
|
||||
const drug =
|
||||
codeableText(r.medicationCodeableConcept) ||
|
||||
(typeof r.medicationReference?.display === 'string' ? r.medicationReference.display : '') ||
|
||||
'Unnamed medication';
|
||||
const status = typeof r.status === 'string' ? r.status : '';
|
||||
const dosage = Array.isArray(r.dosageInstruction)
|
||||
? (r.dosageInstruction.find((d) => typeof d.text === 'string' && d.text)?.text ?? '')
|
||||
: '';
|
||||
return joinRow([drug, dosage && `— ${dosage}`, status && `(${status})`]);
|
||||
}
|
||||
|
||||
// allergyRow renders an AllergyIntolerance to one line: the substance, clinical
|
||||
// status, criticality, and the first reaction's manifestation when present.
|
||||
// Pure.
|
||||
export function allergyRow(res: FhirResource): string {
|
||||
const r = res as {
|
||||
clinicalStatus?: unknown;
|
||||
criticality?: string;
|
||||
reaction?: Array<{ manifestation?: unknown[] }>;
|
||||
};
|
||||
const substance = codeableText((res as { code?: unknown }).code) || 'Unknown allergen';
|
||||
const status = codeableText(r.clinicalStatus);
|
||||
const criticality = typeof r.criticality === 'string' ? r.criticality : '';
|
||||
const manifestation =
|
||||
Array.isArray(r.reaction) && Array.isArray(r.reaction[0]?.manifestation)
|
||||
? codeableText(r.reaction[0]!.manifestation![0])
|
||||
: '';
|
||||
return joinRow([
|
||||
substance,
|
||||
manifestation && `→ ${manifestation}`,
|
||||
criticality && `[${criticality}]`,
|
||||
status && `(${status})`,
|
||||
]);
|
||||
}
|
||||
|
||||
// observationRow renders an Observation (lab/vital) to one line: the test name,
|
||||
// the value (valueQuantity with unit, or valueCodeableConcept / valueString),
|
||||
// and the date. Pure.
|
||||
export function observationRow(res: FhirResource): string {
|
||||
const name = codeableText((res as { code?: unknown }).code) || 'Observation';
|
||||
const value = observationValue(res);
|
||||
const date = effectiveDate(res);
|
||||
return joinRow([name, value && `= ${value}`, date && `(${date})`]);
|
||||
}
|
||||
|
||||
// observationValue decodes an Observation's polymorphic value[x]: a
|
||||
// valueQuantity ("7.2 mg/dL"), a valueCodeableConcept, or a valueString. Pure.
|
||||
export function observationValue(res: FhirResource): string {
|
||||
const r = res as {
|
||||
valueQuantity?: { value?: unknown; unit?: unknown };
|
||||
valueCodeableConcept?: unknown;
|
||||
valueString?: unknown;
|
||||
};
|
||||
if (r.valueQuantity && r.valueQuantity.value !== undefined) {
|
||||
const v = r.valueQuantity.value;
|
||||
const unit = typeof r.valueQuantity.unit === 'string' ? r.valueQuantity.unit : '';
|
||||
return unit ? `${v} ${unit}` : String(v);
|
||||
}
|
||||
const coded = codeableText(r.valueCodeableConcept);
|
||||
if (coded) return coded;
|
||||
if (typeof r.valueString === 'string' && r.valueString.trim()) return r.valueString.trim();
|
||||
return '';
|
||||
}
|
||||
|
||||
// documentRow renders a DocumentReference to one line: its type/description and
|
||||
// date. The note BYTES are not inlined here (they may be large binaries or
|
||||
// attachments requiring a separate fetch); the model gets the note's existence,
|
||||
// type, and date so it can reference it honestly. Pure.
|
||||
export function documentRow(res: FhirResource): string {
|
||||
const r = res as { type?: unknown; description?: string; date?: string };
|
||||
const type = codeableText(r.type) || (typeof r.description === 'string' ? r.description : '') || 'Clinical note';
|
||||
const date = typeof r.date === 'string' ? r.date : effectiveDate(res);
|
||||
return joinRow([type, date && `(${date})`]);
|
||||
}
|
||||
|
||||
// joinRow joins the non-empty cells of a row with single spaces. Pure — the
|
||||
// per-resource rows all funnel through it so falsy cells never leave gaps.
|
||||
function joinRow(cells: Array<string | false | undefined>): string {
|
||||
return cells.filter((c): c is string => typeof c === 'string' && c.length > 0).join(' ');
|
||||
}
|
||||
|
||||
// ── The assembled chart ────────────────────────────────────────────────────
|
||||
|
||||
// A patient's chart as this app consumes it — the Patient plus the four/five
|
||||
// resource lists pulled via the FHIR client. Any list may be empty.
|
||||
export interface Chart {
|
||||
patient?: FhirResource;
|
||||
conditions: FhirResource[];
|
||||
medications: FhirResource[];
|
||||
allergies: FhirResource[];
|
||||
observations: FhirResource[];
|
||||
documents: FhirResource[];
|
||||
}
|
||||
|
||||
// emptyChart — a zero-value Chart, so callers can build incrementally. Pure.
|
||||
export function emptyChart(): Chart {
|
||||
return { conditions: [], medications: [], allergies: [], observations: [], documents: [] };
|
||||
}
|
||||
|
||||
// Windowing budgets. Per-section row caps keep any one section (e.g. hundreds of
|
||||
// lab results) from crowding out the problem list; the total char cap fits the
|
||||
// assembled chart into a model window alongside the response. Chosen honest, not
|
||||
// optimal — we truncate VISIBLY.
|
||||
export const MAX_ROWS_PER_SECTION = 40;
|
||||
export const MAX_CONTEXT_CHARS = 48_000;
|
||||
|
||||
// A section: a heading, the resources, and the row renderer. Ordered most- to
|
||||
// least- clinically-critical so truncation drops the least important first.
|
||||
interface Section {
|
||||
heading: string;
|
||||
resources: FhirResource[];
|
||||
row: (r: FhirResource) => string;
|
||||
}
|
||||
|
||||
// renderSection renders one section's heading + capped rows. When the section has
|
||||
// more resources than the cap, it appends a visible "…N more" line so the model
|
||||
// knows the list was truncated. Empty sections render a single "none recorded"
|
||||
// line so their ABSENCE is explicit (a blank problem list is clinically
|
||||
// meaningful — don't let the model assume data was withheld). Pure.
|
||||
export function renderSection(s: Section, maxRows = MAX_ROWS_PER_SECTION): string {
|
||||
const lines: string[] = [`## ${s.heading}`];
|
||||
if (s.resources.length === 0) {
|
||||
lines.push('(none recorded)');
|
||||
return lines.join('\n');
|
||||
}
|
||||
const shown = s.resources.slice(0, maxRows);
|
||||
for (const r of shown) {
|
||||
const row = s.row(r);
|
||||
if (row) lines.push(`- ${row}`);
|
||||
}
|
||||
const extra = s.resources.length - shown.length;
|
||||
if (extra > 0) lines.push(`- …and ${extra} more not shown`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// assembleChartContext renders a Chart into the single clinical-context string
|
||||
// handed to Hanzo. Demographics first, then the sections in clinical priority
|
||||
// order; the whole thing is capped at `maxChars` with a VISIBLE truncation
|
||||
// marker. Pure and deterministic — the exact text a test asserts is the exact
|
||||
// text sent to the model. Contains PHI: it is assembled in memory and sent ONLY
|
||||
// to api.hanzo.ai (never logged).
|
||||
export function assembleChartContext(chart: Chart, maxChars = MAX_CONTEXT_CHARS): string {
|
||||
const blocks: string[] = [];
|
||||
|
||||
const demo = summarizePatient(chart.patient);
|
||||
blocks.push(['# Patient', ...(demo.length ? demo : ['(no demographics available)'])].join('\n'));
|
||||
|
||||
const sections: Section[] = [
|
||||
{ heading: 'Problems', resources: chart.conditions, row: conditionRow },
|
||||
{ heading: 'Medications', resources: chart.medications, row: medicationRow },
|
||||
{ heading: 'Allergies', resources: chart.allergies, row: allergyRow },
|
||||
{ heading: 'Recent labs & vitals', resources: chart.observations, row: observationRow },
|
||||
{ heading: 'Clinical notes', resources: chart.documents, row: documentRow },
|
||||
];
|
||||
for (const s of sections) blocks.push(renderSection(s));
|
||||
|
||||
return truncate(blocks.join('\n\n'), maxChars);
|
||||
}
|
||||
|
||||
// truncate cuts text to a max length, appending a visible marker so the model
|
||||
// (and a reviewing clinician) know content was elided. Pure.
|
||||
export function truncate(text: string, max: number): string {
|
||||
if (text.length <= max) return text;
|
||||
return text.slice(0, max) + `\n…[chart truncated: ${text.length - max} chars omitted]`;
|
||||
}
|
||||
|
||||
// chartIsEmpty reports whether a chart has NOTHING beyond possibly a Patient —
|
||||
// so the UI can say "no clinical data for this patient" instead of asking the
|
||||
// model to summarize a blank chart. Pure.
|
||||
export function chartIsEmpty(chart: Chart): boolean {
|
||||
return (
|
||||
chart.conditions.length === 0 &&
|
||||
chart.medications.length === 0 &&
|
||||
chart.allergies.length === 0 &&
|
||||
chart.observations.length === 0 &&
|
||||
chart.documents.length === 0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
// Epic / SMART-on-FHIR config — the two backends this app talks to and nothing
|
||||
// else. Hanzo (the model gateway, api.hanzo.ai/v1, via @hanzo/ai) and the FHIR
|
||||
// server (Epic or any SMART-on-FHIR EHR), whose OAuth + REST endpoints are
|
||||
// DISCOVERED at runtime from the launch `iss` — never hard-coded, because a
|
||||
// SMART app must run against whatever FHIR server launched it (an Epic org, the
|
||||
// fhir.epic.com sandbox, or a non-Epic EHR).
|
||||
//
|
||||
// Rule: no `/api/` prefix on Hanzo (it IS api.hanzo.ai); the FHIR base comes
|
||||
// from `iss`, appended with `/Patient`, `/Condition`, etc. Secrets never live
|
||||
// here — the SMART app's client_secret (confidential apps) is read from the
|
||||
// environment by server.ts, never bundled and never sent to the browser.
|
||||
|
||||
// ── Hanzo model gateway ───────────────────────────────────────────────────
|
||||
|
||||
// Where the Hanzo model gateway lives. `@hanzo/ai` defaults here too. /v1 only,
|
||||
// never an /api/ prefix (api.hanzo.ai IS the api host).
|
||||
export const HANZO_API_BASE_URL = 'https://api.hanzo.ai';
|
||||
|
||||
// Default model. A Zen model (qwen3+). Overridable per-request via the picker;
|
||||
// the gateway routes it.
|
||||
export const DEFAULT_MODEL = 'zen5';
|
||||
|
||||
// localStorage key for the pasted Hanzo API key (`hk-…`) in the web panel. The
|
||||
// SMART app launches as a static web page (iframe/browser), not an EHR host with
|
||||
// server-side storage, so the zero-setup Hanzo credential lives in localStorage —
|
||||
// same as @hanzo/pdf and @hanzo/docusign. NOTE: this is the HANZO gateway key,
|
||||
// NOT the FHIR/PHI token — the FHIR token stays server-side (see server.ts).
|
||||
export const APIKEY_STORAGE_KEY = 'hanzo.epic.apiKey';
|
||||
|
||||
// pickBearer chooses the credential to send to the Hanzo gateway: a pasted API
|
||||
// key wins over an IAM token (an explicit key is a deliberate override), else
|
||||
// the token, else empty (anonymous — the gateway still serves public models).
|
||||
// Pure — unit-tested.
|
||||
export function pickBearer(apiKey: string, iamToken: string): string {
|
||||
return (apiKey && apiKey.trim()) || (iamToken && iamToken.trim()) || '';
|
||||
}
|
||||
|
||||
// ── SMART on FHIR ──────────────────────────────────────────────────────────
|
||||
//
|
||||
// SMART scopes this app requests. It is READ + ASSIST ONLY in v1 — there is NO
|
||||
// `*.write` scope, so a bug can never mutate a patient's chart. `launch` is for
|
||||
// the EHR-launch flow (Epic passes a `launch` token that carries the patient
|
||||
// context); `launch/patient` is the standalone-launch equivalent that asks the
|
||||
// user to pick a patient. `openid`+`fhirUser` identify the launching clinician;
|
||||
// `patient/<Resource>.read` grants read of the launched patient's chart only.
|
||||
//
|
||||
// Kept as an ordered array so the scope string is deterministic (stable tests,
|
||||
// stable authorize URLs). `offline_access` requests a refresh_token so a long
|
||||
// review session survives the access token's ~1h lifetime.
|
||||
export const SMART_SCOPES = [
|
||||
'launch',
|
||||
'launch/patient',
|
||||
'openid',
|
||||
'fhirUser',
|
||||
'offline_access',
|
||||
'patient/Patient.read',
|
||||
'patient/Condition.read',
|
||||
'patient/MedicationRequest.read',
|
||||
'patient/Observation.read',
|
||||
'patient/AllergyIntolerance.read',
|
||||
'patient/DocumentReference.read',
|
||||
] as const;
|
||||
|
||||
// scopeString renders the requested scopes into the space-delimited form the
|
||||
// SMART authorize endpoint expects. Pure.
|
||||
export function scopeString(scopes: readonly string[] = SMART_SCOPES): string {
|
||||
return scopes.join(' ');
|
||||
}
|
||||
|
||||
// The SMART discovery document path. A conformant SMART-on-FHIR server publishes
|
||||
// its authorize/token endpoints (and capabilities) at
|
||||
// `<iss>/.well-known/smart-configuration`. We NEVER guess these; we read them.
|
||||
export const SMART_CONFIG_PATH = '.well-known/smart-configuration';
|
||||
|
||||
// smartConfigUrl derives the discovery URL from the FHIR base (`iss`). Trailing
|
||||
// slashes on `iss` are normalized so the join is exact. Pure.
|
||||
export function smartConfigUrl(iss: string): string {
|
||||
return `${normalizeBase(iss)}/${SMART_CONFIG_PATH}`;
|
||||
}
|
||||
|
||||
// normalizeBase strips trailing slashes from a base/iss so callers append
|
||||
// `/<Resource>` or `/.well-known/...` without doubling the separator. Pure.
|
||||
export function normalizeBase(base: string): string {
|
||||
return base.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
// The Epic App Orchard / sandbox FHIR bases, for documentation + a default in
|
||||
// standalone launch. In an EHR launch the real `iss` arrives in the URL and
|
||||
// overrides any default — this table is only a convenience for standalone
|
||||
// testing against Epic's public sandbox.
|
||||
export const EPIC_SANDBOX_FHIR_BASE =
|
||||
'https://fhir.epic.com/interconnect-fhir-oauth/api/FHIR/R4';
|
||||
|
||||
// FHIR resource path segments this app reads. Named so the FHIR client and the
|
||||
// tests reference ONE set of names (no drift between the request builder and the
|
||||
// scope list above).
|
||||
export const FHIR_RESOURCES = {
|
||||
Patient: 'Patient',
|
||||
Condition: 'Condition',
|
||||
MedicationRequest: 'MedicationRequest',
|
||||
Observation: 'Observation',
|
||||
AllergyIntolerance: 'AllergyIntolerance',
|
||||
DocumentReference: 'DocumentReference',
|
||||
} as const;
|
||||
|
||||
export type FhirResourceType = keyof typeof FHIR_RESOURCES;
|
||||
@@ -0,0 +1,253 @@
|
||||
// FHIR R4 client. Every wrapper is PURE request-shaping — it returns the
|
||||
// { url, method, headers } a caller will fetch, so the wire contract (path,
|
||||
// `patient=` scoping, `_count`, category filters) is unit-testable without a
|
||||
// network. `fhirFetch` at the bottom is the one thin place that actually hits
|
||||
// the FHIR server; `bundleEntries` / `nextPageUrl` are the pure Bundle helpers
|
||||
// that drive pagination.
|
||||
//
|
||||
// FHIR R4 conventions this encodes:
|
||||
// - Bearer token auth; Accept: application/fhir+json.
|
||||
// - A patient-context read scopes EVERY search with `patient=<id>` so the app
|
||||
// can only ever see the launched patient (defence-in-depth over the
|
||||
// `patient/*.read` scope — the server enforces it too).
|
||||
// - A search returns a `Bundle`; its resources are `entry[].resource`, and the
|
||||
// NEXT page is the `link` whose `relation` is `next` (a full, absolute URL).
|
||||
// - `_count` caps page size; we never over-fetch.
|
||||
|
||||
import { FHIR_RESOURCES, normalizeBase, type FhirResourceType } from './config.js';
|
||||
|
||||
export interface FhirRequest {
|
||||
url: string;
|
||||
method: 'GET';
|
||||
headers: Record<string, string>;
|
||||
}
|
||||
|
||||
// baseHeaders — auth + the FHIR JSON accept on every read. Reads only, so no
|
||||
// content-type. Pure.
|
||||
function baseHeaders(token: string): Record<string, string> {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
Accept: 'application/fhir+json',
|
||||
};
|
||||
}
|
||||
|
||||
// buildQuery renders a query string from a params object, dropping undefined /
|
||||
// empty values and joining array-valued params with commas (the form FHIR wants
|
||||
// for multi-valued search params like `category`). Deterministic key order for
|
||||
// stable tests. Pure.
|
||||
function buildQuery(params: Record<string, string | number | string[] | undefined>): string {
|
||||
const q = new URLSearchParams();
|
||||
for (const key of Object.keys(params)) {
|
||||
const v = params[key];
|
||||
if (v === undefined || v === '') continue;
|
||||
q.set(key, Array.isArray(v) ? v.join(',') : String(v));
|
||||
}
|
||||
const s = q.toString();
|
||||
return s ? `?${s}` : '';
|
||||
}
|
||||
|
||||
// resourceUrl builds `<base>/<ResourceType>` (a search root) or, with an id,
|
||||
// `<base>/<ResourceType>/<id>` (a single-resource read). Pure.
|
||||
export function resourceUrl(base: string, type: FhirResourceType, id?: string): string {
|
||||
const root = `${normalizeBase(base)}/${FHIR_RESOURCES[type]}`;
|
||||
return id ? `${root}/${encodeURIComponent(id)}` : root;
|
||||
}
|
||||
|
||||
// A sensible default page size. The chart-review actions want breadth, not
|
||||
// depth; a page of 50 with pagination covers a real patient without a giant
|
||||
// single response.
|
||||
export const DEFAULT_COUNT = 50;
|
||||
|
||||
// ── Single-patient read ────────────────────────────────────────────────────
|
||||
|
||||
// getPatient reads the launched patient by id — `Patient/<id>`. The one FHIR
|
||||
// read that is NOT a search (it targets the resource directly). Pure.
|
||||
export function getPatient(base: string, token: string, patientId: string): FhirRequest {
|
||||
return {
|
||||
url: resourceUrl(base, 'Patient', patientId),
|
||||
method: 'GET',
|
||||
headers: baseHeaders(token),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Patient-scoped searches ────────────────────────────────────────────────
|
||||
|
||||
export interface SearchParams {
|
||||
base: string;
|
||||
token: string;
|
||||
patientId: string;
|
||||
count?: number;
|
||||
// A cursor: the full `next` URL from a previous Bundle. When present it is
|
||||
// used VERBATIM (it already carries the server's opaque paging state) and the
|
||||
// other params are ignored — that is how FHIR pagination works.
|
||||
pageUrl?: string;
|
||||
// Optional resource-specific filters (e.g. Observation category). Merged into
|
||||
// the query. Values are strings or string[] (comma-joined).
|
||||
extra?: Record<string, string | string[] | undefined>;
|
||||
}
|
||||
|
||||
// searchRequest is the shared shaper for every patient-scoped search: either the
|
||||
// verbatim `pageUrl` (pagination) or `<base>/<Type>?patient=<id>&_count=…&…`.
|
||||
// Every search is scoped by `patient=` — the app cannot search across patients.
|
||||
// Pure.
|
||||
function searchRequest(type: FhirResourceType, p: SearchParams): FhirRequest {
|
||||
if (p.pageUrl) {
|
||||
return { url: p.pageUrl, method: 'GET', headers: baseHeaders(p.token) };
|
||||
}
|
||||
const query = buildQuery({
|
||||
patient: p.patientId,
|
||||
_count: p.count ?? DEFAULT_COUNT,
|
||||
...(p.extra ?? {}),
|
||||
});
|
||||
return {
|
||||
url: `${resourceUrl(p.base, type)}${query}`,
|
||||
method: 'GET',
|
||||
headers: baseHeaders(p.token),
|
||||
};
|
||||
}
|
||||
|
||||
// searchConditions reads the patient's problem list (Condition). Pure.
|
||||
export function searchConditions(p: SearchParams): FhirRequest {
|
||||
return searchRequest('Condition', p);
|
||||
}
|
||||
|
||||
// searchMedicationRequests reads the patient's medications (MedicationRequest).
|
||||
// Pure.
|
||||
export function searchMedicationRequests(p: SearchParams): FhirRequest {
|
||||
return searchRequest('MedicationRequest', p);
|
||||
}
|
||||
|
||||
// searchAllergyIntolerances reads the patient's allergies (AllergyIntolerance).
|
||||
// Pure.
|
||||
export function searchAllergyIntolerances(p: SearchParams): FhirRequest {
|
||||
return searchRequest('AllergyIntolerance', p);
|
||||
}
|
||||
|
||||
// searchObservations reads the patient's Observations (labs/vitals). `category`
|
||||
// (e.g. 'laboratory', 'vital-signs') narrows the set — Epic wants a category on
|
||||
// an Observation search, so it defaults to laboratory+vital-signs unless the
|
||||
// caller overrides. Pure.
|
||||
export function searchObservations(
|
||||
p: SearchParams & { category?: string | string[] },
|
||||
): FhirRequest {
|
||||
const category = p.category ?? ['laboratory', 'vital-signs'];
|
||||
return searchRequest('Observation', {
|
||||
...p,
|
||||
extra: { ...(p.extra ?? {}), category },
|
||||
});
|
||||
}
|
||||
|
||||
// searchDocumentReferences reads the patient's clinical notes (DocumentReference).
|
||||
// Pure.
|
||||
export function searchDocumentReferences(p: SearchParams): FhirRequest {
|
||||
return searchRequest('DocumentReference', p);
|
||||
}
|
||||
|
||||
// ── Bundle helpers (pure) ──────────────────────────────────────────────────
|
||||
|
||||
// A minimal FHIR R4 resource — everything carries `resourceType`; the rest is
|
||||
// resource-specific and read by chart.ts.
|
||||
export interface FhirResource {
|
||||
resourceType: string;
|
||||
id?: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// A FHIR searchset Bundle (only the fields we read).
|
||||
export interface FhirBundle {
|
||||
resourceType: 'Bundle';
|
||||
type?: string;
|
||||
total?: number;
|
||||
entry?: Array<{ resource?: FhirResource; fullUrl?: string }>;
|
||||
link?: Array<{ relation?: string; url?: string }>;
|
||||
}
|
||||
|
||||
// isOperationOutcome reports whether a payload is a FHIR error (OperationOutcome)
|
||||
// rather than the expected resource/Bundle. Used to surface the server's real
|
||||
// diagnostics. Pure.
|
||||
export function isOperationOutcome(payload: unknown): boolean {
|
||||
return (payload as { resourceType?: string })?.resourceType === 'OperationOutcome';
|
||||
}
|
||||
|
||||
// operationOutcomeMessage renders an OperationOutcome's issues into one line so a
|
||||
// failure is diagnosable. Pure.
|
||||
export function operationOutcomeMessage(payload: unknown): string {
|
||||
const issues = (payload as { issue?: Array<{ diagnostics?: string; details?: { text?: string }; code?: string }> })
|
||||
?.issue;
|
||||
if (!Array.isArray(issues) || issues.length === 0) return 'FHIR OperationOutcome';
|
||||
return issues
|
||||
.map((i) => i.diagnostics || i.details?.text || i.code || 'issue')
|
||||
.join('; ');
|
||||
}
|
||||
|
||||
// bundleEntries pulls the resources out of a searchset Bundle's `entry[]`,
|
||||
// dropping entries without a resource. Returns [] for a non-Bundle (e.g. a
|
||||
// single-resource read passes through unchanged via readResource, not here).
|
||||
// Pure.
|
||||
export function bundleEntries(bundle: unknown): FhirResource[] {
|
||||
const b = bundle as FhirBundle;
|
||||
if (!Array.isArray(b?.entry)) return [];
|
||||
return b.entry
|
||||
.map((e) => e.resource)
|
||||
.filter((r): r is FhirResource => !!r && typeof r.resourceType === 'string');
|
||||
}
|
||||
|
||||
// nextPageUrl returns the absolute URL of the Bundle's next page — the `link`
|
||||
// whose relation is `next` — or '' when this is the last page. This is the ONLY
|
||||
// correct pagination cursor in FHIR (never construct it by hand). Pure.
|
||||
export function nextPageUrl(bundle: unknown): string {
|
||||
const links = (bundle as FhirBundle)?.link;
|
||||
if (!Array.isArray(links)) return '';
|
||||
const next = links.find((l) => l?.relation === 'next');
|
||||
return typeof next?.url === 'string' ? next.url : '';
|
||||
}
|
||||
|
||||
// ── The one thin network place ─────────────────────────────────────────────
|
||||
|
||||
// fhirFetch executes a shaped FhirRequest and returns the parsed JSON (a Bundle
|
||||
// or a resource). Throws on an OperationOutcome or a non-2xx with the server's
|
||||
// diagnostics, so failures are diagnosable — WITHOUT logging the body (it is
|
||||
// PHI). `doFetch` is injectable (tests / non-global-fetch runtimes). NEVER logs
|
||||
// the response.
|
||||
export async function fhirFetch(req: FhirRequest, doFetch: typeof fetch = fetch): Promise<unknown> {
|
||||
const resp = await doFetch(req.url, { method: req.method, headers: req.headers });
|
||||
const text = await resp.text();
|
||||
let data: unknown;
|
||||
try {
|
||||
data = text ? JSON.parse(text) : {};
|
||||
} catch {
|
||||
// Do NOT echo the body — it may be PHI. Status + a length hint only.
|
||||
throw new Error(`FHIR ${resp.status}: non-JSON response (${text.length} bytes)`);
|
||||
}
|
||||
if (isOperationOutcome(data)) {
|
||||
throw new Error(`FHIR ${resp.status}: ${operationOutcomeMessage(data)}`);
|
||||
}
|
||||
if (!resp.ok) {
|
||||
throw new Error(`FHIR ${resp.status}: request failed`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
// fetchAllPages walks a patient-scoped search to completion, following the
|
||||
// Bundle `next` links, and returns the flattened resources. `firstRequest` is
|
||||
// the initial FhirRequest (from a search* wrapper); each subsequent page reuses
|
||||
// the same bearer via `token`. A `maxPages` guard (default 20) bounds a runaway
|
||||
// or hostile server. `doFetch` is injectable. Returns resources only — the
|
||||
// caller never touches Bundle plumbing.
|
||||
export async function fetchAllPages(
|
||||
firstRequest: FhirRequest,
|
||||
token: string,
|
||||
opts: { maxPages?: number; doFetch?: typeof fetch } = {},
|
||||
): Promise<FhirResource[]> {
|
||||
const maxPages = opts.maxPages ?? 20;
|
||||
const doFetch = opts.doFetch ?? fetch;
|
||||
const out: FhirResource[] = [];
|
||||
let req: FhirRequest | null = firstRequest;
|
||||
for (let page = 0; page < maxPages && req; page++) {
|
||||
const bundle = await fhirFetch(req, doFetch);
|
||||
for (const r of bundleEntries(bundle)) out.push(r);
|
||||
const next = nextPageUrl(bundle);
|
||||
req = next ? { url: next, method: 'GET', headers: baseHeaders(token) } : null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// The Hanzo call over a patient's CHART, and the four clinical AI actions — pure
|
||||
// prompt/response shaping plus one thin async edge (the @hanzo/ai client). No
|
||||
// DOM, no FHIR SDK, so the prompt builders and the response extraction are fully
|
||||
// unit-testable without a network.
|
||||
//
|
||||
// This layers on the published headless SDK: `@hanzo/ai`'s `createAiClient`
|
||||
// gives ONE call shape across every Hanzo surface —
|
||||
// const ai = createAiClient({ token });
|
||||
// const res = await ai.chat.completions.create({ model, messages });
|
||||
// We import it directly (do NOT reimplement); the SDK defaults to
|
||||
// https://api.hanzo.ai and `/v1/...`. `ai` is injectable so the four actions and
|
||||
// their prompt builders are tested against a fake client with zero network.
|
||||
//
|
||||
// PHI posture: the assembled chart context (chart.ts) is PHI. It is sent ONLY to
|
||||
// api.hanzo.ai as the model input and is NEVER logged here. There is no
|
||||
// write-back to the EHR — these actions read the chart and return assistant text
|
||||
// for the clinician to review.
|
||||
|
||||
import {
|
||||
createAiClient,
|
||||
type AiClient,
|
||||
type ChatCompletion,
|
||||
type ChatCompletionMessage,
|
||||
} from '@hanzo/ai';
|
||||
import { DEFAULT_MODEL, HANZO_API_BASE_URL } from './config.js';
|
||||
|
||||
// ── System prompt ──────────────────────────────────────────────────────────
|
||||
|
||||
// CLINICAL_SYSTEM_PROMPT frames Hanzo as a clinician's assistant working over a
|
||||
// FHIR-derived chart. It FORBIDS inventing findings the chart doesn't support
|
||||
// (the failure mode that makes a clinical assistant dangerous), demands honesty
|
||||
// about a truncated chart, and states plainly that the output is decision
|
||||
// SUPPORT the clinician reviews — not a diagnosis or an order.
|
||||
export const CLINICAL_SYSTEM_PROMPT =
|
||||
'You are Hanzo AI, a clinical assistant embedded in the clinician\'s EHR via ' +
|
||||
'SMART on FHIR. You are given the launched patient\'s chart (problems, ' +
|
||||
'medications, allergies, recent labs/vitals, and notes) as structured data. ' +
|
||||
'Work ONLY from the chart provided — never invent diagnoses, medications, ' +
|
||||
'allergies, lab values, or history that the chart does not support. When the ' +
|
||||
'chart is marked truncated and a complete answer needs the omitted part, say ' +
|
||||
'so plainly rather than guessing. Be precise, concise, and neutral, and use ' +
|
||||
'standard clinical terminology. This is decision SUPPORT that the clinician ' +
|
||||
'reviews and is responsible for — it is not a diagnosis, a treatment ' +
|
||||
'recommendation to act on unreviewed, or a substitute for clinical judgment.';
|
||||
|
||||
// ── The four actions ───────────────────────────────────────────────────────
|
||||
|
||||
export type ActionId = 'summarize' | 'note' | 'extract' | 'ask';
|
||||
|
||||
// The action catalog — the single source of truth the UI chips and the prompt
|
||||
// builder both read, so they never drift. `needsPrompt` flags the actions that
|
||||
// take clinician-supplied detail (the note's reason-for-visit / the question).
|
||||
export interface ActionDef {
|
||||
id: ActionId;
|
||||
label: string;
|
||||
needsPrompt: boolean;
|
||||
}
|
||||
|
||||
export const ACTIONS: readonly ActionDef[] = [
|
||||
{ id: 'summarize', label: 'Summarize patient', needsPrompt: false },
|
||||
{ id: 'note', label: 'Draft clinical note', needsPrompt: true },
|
||||
{ id: 'extract', label: 'Extract problems & meds', needsPrompt: false },
|
||||
{ id: 'ask', label: 'Ask about this patient', needsPrompt: true },
|
||||
] as const;
|
||||
|
||||
// isActionId narrows an arbitrary string to an ActionId. Boundary guard. Pure.
|
||||
export function isActionId(v: string): v is ActionId {
|
||||
return ACTIONS.some((a) => a.id === v);
|
||||
}
|
||||
|
||||
// actionTask renders an action's task instruction. `detail` is the
|
||||
// clinician-supplied text for the two actions that need it (the note's
|
||||
// reason-for-visit, the free-text question); the other two are fixed. Pure — the
|
||||
// exact instruction a test asserts is the exact instruction sent to the model.
|
||||
export function actionTask(id: ActionId, detail = ''): string {
|
||||
const d = detail.trim();
|
||||
switch (id) {
|
||||
case 'summarize':
|
||||
return (
|
||||
'Write a concise clinical summary of this patient for a clinician ' +
|
||||
'picking up their care. Cover the active problems, current medications, ' +
|
||||
'allergies, and the most relevant recent labs/vitals, and flag anything ' +
|
||||
'that stands out (e.g. an abnormal value, a high-risk allergy, a ' +
|
||||
'medication–problem mismatch). Do not invent anything not in the chart.'
|
||||
);
|
||||
case 'note':
|
||||
return (
|
||||
`Draft a clinical note in SOAP format (Subjective, Objective, ` +
|
||||
`Assessment, Plan) for this encounter${
|
||||
d ? `. Reason for visit / clinician input: ${d}` : ''
|
||||
}. Populate Objective from the chart's labs, vitals, and active ` +
|
||||
'problems; base the Assessment and Plan on the charted problems and ' +
|
||||
'medications. Where the chart lacks information a real note needs (e.g. ' +
|
||||
'the subjective history), write a clear placeholder for the clinician to ' +
|
||||
'complete rather than fabricating it. The clinician reviews and signs ' +
|
||||
'this note.'
|
||||
);
|
||||
case 'extract':
|
||||
return (
|
||||
'Extract this patient\'s active problems and current medications as two ' +
|
||||
'structured lists. Problems: the condition and its status. Medications: ' +
|
||||
'the drug, dose/route/frequency if stated, and status. Include only what ' +
|
||||
'the chart contains; if a list is empty, say so plainly.'
|
||||
);
|
||||
case 'ask':
|
||||
return d || 'What is the most important thing to know about this patient right now?';
|
||||
}
|
||||
}
|
||||
|
||||
// ── Message assembly (pure) ────────────────────────────────────────────────
|
||||
|
||||
// buildMessages composes the clinical system frame, the fenced chart context,
|
||||
// and the task instruction into the OpenAI-compatible message list. The chart is
|
||||
// FENCED so the model treats a patient's data as data, never as instructions
|
||||
// (prompt-injection boundary — a note in the chart cannot redirect the model).
|
||||
// Pure.
|
||||
export function buildMessages(
|
||||
task: string,
|
||||
chartContext: string,
|
||||
systemPrompt = CLINICAL_SYSTEM_PROMPT,
|
||||
): ChatCompletionMessage[] {
|
||||
const context = chartContext.trim();
|
||||
const user: ChatCompletionMessage = {
|
||||
role: 'user',
|
||||
content: context
|
||||
? `---- patient chart ----\n${context}\n---- end patient chart ----\n\n---- task ----\n${task}`
|
||||
: task,
|
||||
};
|
||||
return [{ role: 'system', content: systemPrompt }, user];
|
||||
}
|
||||
|
||||
// extractContent pulls the assistant text out of a ChatCompletion, tolerating an
|
||||
// empty/odd shape. Throws on empty content so the caller surfaces a real failure
|
||||
// rather than rendering a blank result. Pure.
|
||||
export function extractContent(res: ChatCompletion): string {
|
||||
const content = res?.choices?.[0]?.message?.content;
|
||||
const text = typeof content === 'string' ? content : '';
|
||||
if (!text) throw new Error('Hanzo API returned no content');
|
||||
return text;
|
||||
}
|
||||
|
||||
// ── The single call path ───────────────────────────────────────────────────
|
||||
|
||||
export interface AskOptions {
|
||||
model?: string;
|
||||
temperature?: number;
|
||||
token?: string; // hk- key or IAM token; empty → anonymous/public models
|
||||
baseUrl?: string;
|
||||
/** Injected @hanzo/ai client (tests). Defaults to a real createAiClient. */
|
||||
client?: AiClient;
|
||||
signal?: AbortSignal;
|
||||
system?: string;
|
||||
}
|
||||
|
||||
// makeClient builds (or reuses an injected) @hanzo/ai client. One place decides
|
||||
// how the SDK is configured, so every call is consistent. Pure but for the SDK
|
||||
// construction.
|
||||
function makeClient(opts: AskOptions): AiClient {
|
||||
return (
|
||||
opts.client ??
|
||||
createAiClient({ token: opts.token, baseUrl: opts.baseUrl ?? HANZO_API_BASE_URL })
|
||||
);
|
||||
}
|
||||
|
||||
// ask runs ONE non-streaming completion over a chart and returns the assistant
|
||||
// text. This is the single path from every Epic surface to the model — all four
|
||||
// actions funnel through runAction → ask. Pure over the injected client.
|
||||
export async function ask(task: string, chartContext: string, opts: AskOptions = {}): Promise<string> {
|
||||
const client = makeClient(opts);
|
||||
const res = await client.chat.completions.create({
|
||||
model: opts.model ?? DEFAULT_MODEL,
|
||||
messages: buildMessages(task, chartContext, opts.system),
|
||||
stream: false,
|
||||
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
|
||||
}, { signal: opts.signal });
|
||||
return extractContent(res);
|
||||
}
|
||||
|
||||
export interface RunActionParams {
|
||||
id: ActionId;
|
||||
detail?: string; // note reason-for-visit / question
|
||||
chartContext: string; // assembled by chart.assembleChartContext
|
||||
opts?: AskOptions;
|
||||
}
|
||||
|
||||
// runAction forms the task for an action and asks Hanzo over the chart. Returns
|
||||
// the raw assistant text — there is NO write-back to the EHR (v1 is read +
|
||||
// assist only), so the clinician reviews the output before it is used.
|
||||
export async function runAction(p: RunActionParams): Promise<string> {
|
||||
const task = actionTask(p.id, p.detail);
|
||||
return ask(task, p.chartContext, p.opts);
|
||||
}
|
||||
|
||||
// listModels returns the model ids the caller may route to, via the SDK's
|
||||
// /v1/models. The catalog is org-scoped by the bearer; an empty token lists
|
||||
// public models. Thin over the injected client.
|
||||
export async function listModels(opts: AskOptions = {}): Promise<string[]> {
|
||||
const client = makeClient(opts);
|
||||
const models = await client.models.list({ signal: opts.signal });
|
||||
return models.map((m) => m.id).filter((id): id is string => typeof id === 'string' && id.length > 0);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Hanzo AI for Epic</title>
|
||||
<link rel="stylesheet" href="styles.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<span class="title">Hanzo AI</span>
|
||||
<select id="model" aria-label="Model"><option value="">default</option></select>
|
||||
<span class="host" id="patient-title">Patient</span>
|
||||
</header>
|
||||
|
||||
<!-- One-click clinical actions over the launched patient's chart. Chips are
|
||||
built from the action catalog and enabled once the chart loads. -->
|
||||
<div class="chips" id="chips"></div>
|
||||
|
||||
<label for="prompt">Ask about this patient · or add a reason-for-visit for the note</label>
|
||||
<textarea id="prompt" placeholder="e.g. What are the abnormal recent labs? · 72yo for HTN follow-up · Any drug interactions to watch?"></textarea>
|
||||
|
||||
<div class="row">
|
||||
<button id="stop" class="secondary" disabled>Stop</button>
|
||||
<span class="spacer"></span>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary>Hanzo API key</summary>
|
||||
<div class="row">
|
||||
<input id="apikey" type="password" placeholder="hk-…" autocomplete="off" />
|
||||
<button id="savekey" class="secondary">Save</button>
|
||||
</div>
|
||||
<div class="hint">The Hanzo model-gateway key. Not the FHIR token — patient data is read server-side and never leaves this app except to api.hanzo.ai.</div>
|
||||
</details>
|
||||
|
||||
<div class="status" id="status">Launch this app from Epic to load a patient.</div>
|
||||
|
||||
<label for="output">Result</label>
|
||||
<textarea id="output" placeholder="Hanzo's clinical assistance appears here." readonly></textarea>
|
||||
|
||||
<footer>Routed through api.hanzo.ai · grounded in the FHIR chart · decision support the clinician reviews — not a diagnosis. Read + assist only; no write-back to the EHR.</footer>
|
||||
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,368 @@
|
||||
// The SMART OAuth token-exchange + FHIR-proxy service. This is the ONLY place
|
||||
// the confidential-app client_secret exists — it is read from the environment
|
||||
// (never bundled, never sent to the browser). It is also where the PHI-bearing
|
||||
// FHIR access token lives: the browser NEVER receives the FHIR token, so a PHI
|
||||
// token can never leak into localStorage, a screenshot, or a browser log. The
|
||||
// SPA holds only an opaque server session id; every FHIR read goes through the
|
||||
// proxy here, which attaches the token server-side.
|
||||
//
|
||||
// A dependency-free Node http handler built on the pure modules (config,
|
||||
// smart-oauth, fhir-client) so it deploys behind hanzoai/ingress as a small
|
||||
// service at epic.hanzo.ai. Documented here; the PURE logic it wraps is what the
|
||||
// tests cover (an http server is an integration concern, not a unit).
|
||||
//
|
||||
// node dist/server.js (after build.js bundles it)
|
||||
//
|
||||
// Required environment:
|
||||
// SMART_CLIENT_ID — the SMART app's client id (public; also stamped into the SPA)
|
||||
// SMART_REDIRECT_URI — e.g. https://epic.hanzo.ai/oauth/callback
|
||||
// PORT — listen port (default 8791)
|
||||
// Optional:
|
||||
// SMART_CLIENT_SECRET — the confidential-app secret (SERVER ONLY). Omit for a
|
||||
// public app (PKCE-only). Never bundled.
|
||||
// SESSION_TTL_SECONDS — how long a server session lives (default 3600)
|
||||
//
|
||||
// PHI: this service NEVER logs a FHIR response body, an access token, a patient
|
||||
// id, or any resource. It logs only non-PHI operational facts (a session id, a
|
||||
// resource type, a status code).
|
||||
|
||||
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { normalizeBase, smartConfigUrl } from './config.js';
|
||||
import {
|
||||
parseSmartConfiguration,
|
||||
tokenExchange,
|
||||
tokenRefresh,
|
||||
parseTokenResponse,
|
||||
isExpired,
|
||||
type SmartContext,
|
||||
type SmartConfiguration,
|
||||
} from './smart-oauth.js';
|
||||
|
||||
// ── Environment ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ServerConfig {
|
||||
/** SMART app client id (public). */
|
||||
clientId: string;
|
||||
/** Confidential-app secret (SERVER ONLY). Empty → public app (PKCE-only). */
|
||||
clientSecret: string;
|
||||
/** OAuth redirect registered on the app. */
|
||||
redirectUri: string;
|
||||
/** Server-session lifetime (ms). */
|
||||
sessionTtlMs: number;
|
||||
/** Listen port. */
|
||||
port: number;
|
||||
}
|
||||
|
||||
// readServerConfig fails fast (throws) if a required value is missing — a server
|
||||
// that cannot exchange codes must not pretend to start. The client_secret is the
|
||||
// one OPTIONAL field (a public app has none). Pure given an env map, so it is
|
||||
// unit-tested without touching process.env.
|
||||
export function readServerConfig(env: Record<string, string | undefined>): ServerConfig {
|
||||
const clientId = env.SMART_CLIENT_ID;
|
||||
const redirectUri = env.SMART_REDIRECT_URI;
|
||||
const missing: string[] = [];
|
||||
if (!clientId) missing.push('SMART_CLIENT_ID');
|
||||
if (!redirectUri) missing.push('SMART_REDIRECT_URI');
|
||||
if (missing.length > 0) {
|
||||
throw new Error(`Missing required environment: ${missing.join(', ')}`);
|
||||
}
|
||||
return {
|
||||
clientId: clientId!,
|
||||
clientSecret: env.SMART_CLIENT_SECRET || '',
|
||||
redirectUri: redirectUri!,
|
||||
sessionTtlMs: (Number(env.SESSION_TTL_SECONDS) || 3600) * 1000,
|
||||
port: Number(env.PORT) || 8791,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Server sessions (PHI lives here, never in the browser) ────────────────
|
||||
//
|
||||
// A session binds the browser to a SMART context server-side. The browser holds
|
||||
// ONLY the opaque `sid`; the FHIR access token + patient id stay in this map.
|
||||
// In-memory is correct for a single-instance service; a multi-instance
|
||||
// deployment swaps this for hanzoai/kv (Valkey) with the SAME interface, no call
|
||||
// site changes. Kept behind a tiny interface so that swap is one file.
|
||||
|
||||
// A pending auth: the PKCE verifier + discovered token endpoint + FHIR base,
|
||||
// stashed under `state` between the authorize redirect and the callback.
|
||||
interface PendingAuth {
|
||||
state: string;
|
||||
codeVerifier: string;
|
||||
tokenEndpoint: string;
|
||||
fhirBase: string;
|
||||
}
|
||||
|
||||
export interface SessionStore {
|
||||
putPending(p: PendingAuth): void;
|
||||
takePending(state: string): PendingAuth | undefined;
|
||||
putSession(sid: string, ctx: SmartContext, fhirBase: string, tokenEndpoint: string): void;
|
||||
getSession(sid: string): ServerSession | undefined;
|
||||
updateSession(sid: string, ctx: SmartContext): void;
|
||||
}
|
||||
|
||||
export interface ServerSession {
|
||||
ctx: SmartContext;
|
||||
fhirBase: string;
|
||||
tokenEndpoint: string;
|
||||
}
|
||||
|
||||
// memoryStore is the default in-memory SessionStore. One place; swap for Valkey
|
||||
// in production by implementing the same interface.
|
||||
export function memoryStore(): SessionStore {
|
||||
const pending = new Map<string, PendingAuth>();
|
||||
const sessions = new Map<string, ServerSession>();
|
||||
return {
|
||||
putPending: (p) => void pending.set(p.state, p),
|
||||
takePending: (state) => {
|
||||
const p = pending.get(state);
|
||||
if (p) pending.delete(state);
|
||||
return p;
|
||||
},
|
||||
putSession: (sid, ctx, fhirBase, tokenEndpoint) =>
|
||||
void sessions.set(sid, { ctx, fhirBase, tokenEndpoint }),
|
||||
getSession: (sid) => sessions.get(sid),
|
||||
updateSession: (sid, ctx) => {
|
||||
const s = sessions.get(sid);
|
||||
if (s) sessions.set(sid, { ...s, ctx });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ── Discovery + token exchange (server-side) ──────────────────────────────
|
||||
|
||||
// discoverSmart fetches and parses `<iss>/.well-known/smart-configuration`.
|
||||
// `doFetch` is injectable for tests. The FHIR base is validated to be an http(s)
|
||||
// URL before we ever talk to it (SSRF boundary guard — a hostile `iss` cannot
|
||||
// point us at an internal host over a non-http scheme).
|
||||
export async function discoverSmart(iss: string, doFetch: typeof fetch = fetch): Promise<SmartConfiguration> {
|
||||
assertHttpUrl(iss, 'iss');
|
||||
const resp = await doFetch(smartConfigUrl(iss), { headers: { Accept: 'application/json' } });
|
||||
if (!resp.ok) throw new Error(`SMART discovery ${resp.status}`);
|
||||
return parseSmartConfiguration(await resp.json());
|
||||
}
|
||||
|
||||
// assertHttpUrl throws unless `u` is an absolute http(s) URL. Guards the two
|
||||
// externally-influenced URLs (the launch `iss` and a FHIR request path) against
|
||||
// scheme-based SSRF. Boundary guard.
|
||||
function assertHttpUrl(u: string, label: string): void {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(u);
|
||||
} catch {
|
||||
throw new Error(`${label} is not a valid URL`);
|
||||
}
|
||||
if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
|
||||
throw new Error(`${label} must be http(s)`);
|
||||
}
|
||||
}
|
||||
|
||||
// exchangeCode runs the server-side code→token exchange with the confidential
|
||||
// secret and the PKCE verifier, returning the parsed SmartContext. `doFetch` is
|
||||
// injectable. NEVER logs the code, the tokens, or the patient id.
|
||||
export async function exchangeCode(
|
||||
cfg: ServerConfig,
|
||||
pending: PendingAuth,
|
||||
code: string,
|
||||
doFetch: typeof fetch = fetch,
|
||||
): Promise<SmartContext> {
|
||||
const shape = tokenExchange({
|
||||
tokenEndpoint: pending.tokenEndpoint,
|
||||
clientId: cfg.clientId,
|
||||
redirectUri: cfg.redirectUri,
|
||||
code,
|
||||
codeVerifier: pending.codeVerifier,
|
||||
clientSecret: cfg.clientSecret || undefined,
|
||||
});
|
||||
const resp = await doFetch(shape.url, { method: 'POST', headers: shape.headers, body: shape.body });
|
||||
const data = await resp.json().catch(() => ({}));
|
||||
return parseTokenResponse(data);
|
||||
}
|
||||
|
||||
// ensureFreshToken refreshes a session's access token when it is at/near expiry
|
||||
// and a refresh_token is available, persisting the new context. Returns the live
|
||||
// access token. Never logs it.
|
||||
export async function ensureFreshToken(
|
||||
cfg: ServerConfig,
|
||||
store: SessionStore,
|
||||
sid: string,
|
||||
session: ServerSession,
|
||||
doFetch: typeof fetch = fetch,
|
||||
): Promise<string> {
|
||||
if (!isExpired(session.ctx) || !session.ctx.refreshToken) return session.ctx.accessToken;
|
||||
const shape = tokenRefresh({
|
||||
tokenEndpoint: session.tokenEndpoint,
|
||||
clientId: cfg.clientId,
|
||||
refreshToken: session.ctx.refreshToken,
|
||||
clientSecret: cfg.clientSecret || undefined,
|
||||
});
|
||||
const resp = await doFetch(shape.url, { method: 'POST', headers: shape.headers, body: shape.body });
|
||||
const data = await resp.json().catch(() => ({}));
|
||||
const refreshed = parseTokenResponse(data);
|
||||
// A refresh may omit a new refresh_token — keep the old one.
|
||||
const merged: SmartContext = {
|
||||
...refreshed,
|
||||
refreshToken: refreshed.refreshToken || session.ctx.refreshToken,
|
||||
patient: refreshed.patient || session.ctx.patient,
|
||||
};
|
||||
store.updateSession(sid, merged);
|
||||
return merged.accessToken;
|
||||
}
|
||||
|
||||
// ── FHIR proxy path guard (pure) ──────────────────────────────────────────
|
||||
|
||||
// The resource types the proxy will forward — exactly the read scopes this app
|
||||
// holds. A request for anything else is refused BEFORE a token is attached, so
|
||||
// the proxy can never be turned into a general-purpose FHIR gateway.
|
||||
const PROXY_ALLOWED = new Set([
|
||||
'Patient',
|
||||
'Condition',
|
||||
'MedicationRequest',
|
||||
'Observation',
|
||||
'AllergyIntolerance',
|
||||
'DocumentReference',
|
||||
]);
|
||||
|
||||
// resolveProxyTarget validates a proxied FHIR path and returns the absolute URL
|
||||
// to call, or throws. The SPA sends a RELATIVE FHIR path (e.g.
|
||||
// `Condition?patient=123&_count=50`) OR a full same-origin `next` page URL; both
|
||||
// must resolve under the session's FHIR base and hit an allowed resource type.
|
||||
// This is the defence that a session can only ever read its own patient's
|
||||
// allowed resources. Pure.
|
||||
export function resolveProxyTarget(fhirBase: string, requestedPath: string): string {
|
||||
const base = normalizeBase(fhirBase);
|
||||
// Absolute URL (a pagination `next` link) must be under the same FHIR base.
|
||||
const absolute = /^https?:\/\//i.test(requestedPath);
|
||||
const url = absolute ? requestedPath : `${base}/${requestedPath.replace(/^\/+/, '')}`;
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
throw new Error('invalid FHIR path');
|
||||
}
|
||||
if (!url.startsWith(base)) throw new Error('FHIR path escapes the session base');
|
||||
const segment = parsed.pathname.slice(base.length ? new URL(base).pathname.length : 0);
|
||||
const resourceType = segment.replace(/^\/+/, '').split(/[/?]/)[0];
|
||||
if (!PROXY_ALLOWED.has(resourceType)) {
|
||||
throw new Error(`resource ${resourceType || '(none)'} not permitted`);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
// ── HTTP glue ──────────────────────────────────────────────────────────────
|
||||
|
||||
async function readBody(req: IncomingMessage): Promise<string> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const c of req) chunks.push(c as Buffer);
|
||||
return Buffer.concat(chunks).toString('utf8');
|
||||
}
|
||||
|
||||
function json(res: ServerResponse, status: number, body: unknown): void {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
}
|
||||
|
||||
// sessionCookie / readSid — the browser holds ONLY the opaque session id, in an
|
||||
// HttpOnly, Secure, SameSite=Lax cookie so client JS (and any injected script)
|
||||
// cannot read it and it is not exposed to localStorage.
|
||||
function sessionCookie(sid: string, ttlMs: number): string {
|
||||
const maxAge = Math.floor(ttlMs / 1000);
|
||||
return `epic_sid=${sid}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAge}`;
|
||||
}
|
||||
export function readSid(cookieHeader: string | undefined): string {
|
||||
if (!cookieHeader) return '';
|
||||
for (const part of cookieHeader.split(';')) {
|
||||
const [k, v] = part.split('=');
|
||||
if (k?.trim() === 'epic_sid') return (v ?? '').trim();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
// The request router. Each handler is a thin wrapper over the pure modules; the
|
||||
// service state is the session store. NO PHI is ever logged.
|
||||
export function createHandler(cfg: ServerConfig, store: SessionStore = memoryStore()) {
|
||||
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
||||
const url = new URL(req.url || '/', `http://localhost:${cfg.port}`);
|
||||
try {
|
||||
// POST /oauth/prepare { iss, state, codeVerifier } → discover endpoints,
|
||||
// stash the pending auth, return { authorizationEndpoint, tokenEndpoint }.
|
||||
if (req.method === 'POST' && url.pathname === '/oauth/prepare') {
|
||||
const { iss, state, codeVerifier } = JSON.parse((await readBody(req)) || '{}');
|
||||
if (!iss || !state || !codeVerifier) return json(res, 400, { error: 'missing iss/state/codeVerifier' });
|
||||
const smart = await discoverSmart(iss);
|
||||
store.putPending({ state, codeVerifier, tokenEndpoint: smart.tokenEndpoint, fhirBase: normalizeBase(iss) });
|
||||
return json(res, 200, { authorizationEndpoint: smart.authorizationEndpoint, tokenEndpoint: smart.tokenEndpoint });
|
||||
}
|
||||
|
||||
// POST /oauth/callback { code, state } → exchange (secret + PKCE server-
|
||||
// side), mint a server session, set the opaque cookie. The browser gets
|
||||
// back ONLY the non-PHI context it needs to render (patient id + scope),
|
||||
// never the FHIR token.
|
||||
if (req.method === 'POST' && url.pathname === '/oauth/callback') {
|
||||
const { code, state } = JSON.parse((await readBody(req)) || '{}');
|
||||
if (!code || !state) return json(res, 400, { error: 'missing code/state' });
|
||||
const pending = store.takePending(state);
|
||||
if (!pending) return json(res, 400, { error: 'unknown or replayed state' });
|
||||
const ctx = await exchangeCode(cfg, pending, code);
|
||||
const sid = randomUUID();
|
||||
const fhirBase = ctx.fhirBase || pending.fhirBase;
|
||||
store.putSession(sid, ctx, fhirBase, pending.tokenEndpoint);
|
||||
res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': sessionCookie(sid, cfg.sessionTtlMs) });
|
||||
res.end(JSON.stringify({ patient: ctx.patient, scope: ctx.scope }));
|
||||
return;
|
||||
}
|
||||
|
||||
// GET /fhir?path=<relative-or-next-url> → the PHI proxy. Reads the session
|
||||
// from the cookie, refreshes the token if needed, attaches it server-side,
|
||||
// and streams the FHIR JSON back. The token never touches the browser.
|
||||
if (req.method === 'GET' && url.pathname === '/fhir') {
|
||||
const sid = readSid(req.headers.cookie);
|
||||
const session = sid ? store.getSession(sid) : undefined;
|
||||
if (!session) return json(res, 401, { error: 'no session' });
|
||||
const path = url.searchParams.get('path') || '';
|
||||
let target: string;
|
||||
try {
|
||||
target = resolveProxyTarget(session.fhirBase, path);
|
||||
} catch (e: unknown) {
|
||||
return json(res, 400, { error: (e as Error).message });
|
||||
}
|
||||
const token = await ensureFreshToken(cfg, store, sid, session);
|
||||
const upstream = await fetch(target, {
|
||||
headers: { Authorization: `Bearer ${token}`, Accept: 'application/fhir+json' },
|
||||
});
|
||||
const text = await upstream.text();
|
||||
// Pass through the FHIR JSON verbatim; do NOT log it (PHI).
|
||||
res.writeHead(upstream.status, { 'Content-Type': 'application/fhir+json' });
|
||||
res.end(text);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method === 'GET' && url.pathname === '/healthz') return json(res, 200, { ok: true });
|
||||
return json(res, 404, { error: 'not found' });
|
||||
} catch (e: unknown) {
|
||||
// Operational error only — never include a response body (may be PHI).
|
||||
return json(res, 500, { error: (e as Error)?.message || 'internal error' });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// main boots the http server when run directly. Import-safe: only the direct
|
||||
// entry starts listening, so tests import the pure handlers without a port.
|
||||
export function main(): void {
|
||||
const cfg = readServerConfig(process.env);
|
||||
const server = createServer(createHandler(cfg));
|
||||
server.listen(cfg.port, () => {
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
msg: 'epic smart-on-fhir service up',
|
||||
port: cfg.port,
|
||||
confidential: !!cfg.clientSecret,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// ESM entry check: run main() only when this file is the process entry.
|
||||
if (process.argv[1] && process.argv[1].endsWith('server.js')) {
|
||||
main();
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
// SMART-on-FHIR launch: discovery, PKCE, the authorize URL, the code→token
|
||||
// exchange/refresh shaping, and pulling the patient context out of the token
|
||||
// response. PURE request-shaping only — this module never does a network call
|
||||
// and never sources the client_secret (server.ts holds it, from the
|
||||
// environment), so it is trivially unit-testable and free of secrets.
|
||||
//
|
||||
// SMART App Launch (http://hl7.org/fhir/smart-app-launch): the app is launched
|
||||
// EITHER by the EHR (Epic) with `iss` (the FHIR base) + `launch` (an opaque
|
||||
// launch token carrying the patient/encounter context) in the URL, OR
|
||||
// standalone (the app supplies its own `iss` and asks the user to pick a
|
||||
// patient via the `launch/patient` scope). Both paths then:
|
||||
// 1. discover authorize/token endpoints from `<iss>/.well-known/smart-configuration`
|
||||
// 2. redirect the browser to `authorize` with auth-code + PKCE (+ the `launch`
|
||||
// token and `aud=<iss>` — Epic REQUIRES `aud`)
|
||||
// 3. exchange the returned `code` for tokens, which for a patient-context
|
||||
// launch carry a `patient` id (the launched patient) alongside the tokens.
|
||||
// Confidential apps (server-side secret) also send client_secret at step 3;
|
||||
// public apps rely on PKCE alone. This module shapes 1–3; server.ts runs them.
|
||||
|
||||
// ── SMART discovery ────────────────────────────────────────────────────────
|
||||
|
||||
// The subset of `.well-known/smart-configuration` this app needs: the two OAuth
|
||||
// endpoints and (informational) the capabilities/scopes the server advertises.
|
||||
// Epic publishes the full document; we read only what we use.
|
||||
export interface SmartConfiguration {
|
||||
authorizationEndpoint: string;
|
||||
tokenEndpoint: string;
|
||||
// Optional, informational: what the server says it supports.
|
||||
capabilities?: string[];
|
||||
scopesSupported?: string[];
|
||||
}
|
||||
|
||||
// parseSmartConfiguration validates the discovery document and extracts the two
|
||||
// endpoints. Throws when either endpoint is missing — a SMART app that cannot
|
||||
// find the authorize/token URLs must fail loudly, not guess Epic-specific paths.
|
||||
// Pure — the fetch is server.ts's job. Boundary guard on an external response.
|
||||
export function parseSmartConfiguration(data: unknown): SmartConfiguration {
|
||||
const d = data as {
|
||||
authorization_endpoint?: unknown;
|
||||
token_endpoint?: unknown;
|
||||
capabilities?: unknown;
|
||||
scopes_supported?: unknown;
|
||||
};
|
||||
const authorizationEndpoint = d?.authorization_endpoint;
|
||||
const tokenEndpoint = d?.token_endpoint;
|
||||
if (typeof authorizationEndpoint !== 'string' || !authorizationEndpoint) {
|
||||
throw new Error('SMART discovery: no authorization_endpoint');
|
||||
}
|
||||
if (typeof tokenEndpoint !== 'string' || !tokenEndpoint) {
|
||||
throw new Error('SMART discovery: no token_endpoint');
|
||||
}
|
||||
return {
|
||||
authorizationEndpoint,
|
||||
tokenEndpoint,
|
||||
capabilities: Array.isArray(d?.capabilities)
|
||||
? (d.capabilities.filter((c) => typeof c === 'string') as string[])
|
||||
: undefined,
|
||||
scopesSupported: Array.isArray(d?.scopes_supported)
|
||||
? (d.scopes_supported.filter((s) => typeof s === 'string') as string[])
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// ── PKCE ───────────────────────────────────────────────────────────────────
|
||||
//
|
||||
// PKCE (RFC 7636) protects the auth-code exchange: the app sends a random
|
||||
// `code_verifier`'s SHA-256 hash (`code_challenge`) at authorize time, then the
|
||||
// raw verifier at token time — an intercepted code is useless without it. Epic
|
||||
// requires PKCE (S256) for public apps and supports it for confidential ones.
|
||||
|
||||
// base64url encodes bytes without padding, per RFC 7636. Pure.
|
||||
export function base64urlEncode(bytes: Uint8Array): string {
|
||||
let bin = '';
|
||||
for (const b of bytes) bin += String.fromCharCode(b);
|
||||
// btoa in the browser; Buffer in node — both reachable here, prefer btoa.
|
||||
const b64 =
|
||||
typeof btoa === 'function'
|
||||
? btoa(bin)
|
||||
: Buffer.from(bytes).toString('base64');
|
||||
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
// A PKCE pair: the secret verifier (kept by the app across the redirect) and the
|
||||
// challenge (sent to authorize). `method` is always S256 — the only method Epic
|
||||
// and the SMART spec want; `plain` is never used.
|
||||
export interface PkcePair {
|
||||
verifier: string;
|
||||
challenge: string;
|
||||
method: 'S256';
|
||||
}
|
||||
|
||||
// randomVerifier makes a high-entropy code_verifier: 32 random bytes → 43-char
|
||||
// base64url (within the RFC's 43–128 range). `random` is injectable so a test
|
||||
// gets a deterministic verifier; it defaults to Web Crypto's CSPRNG.
|
||||
export function randomVerifier(
|
||||
random: (n: number) => Uint8Array = cryptoRandom,
|
||||
): string {
|
||||
return base64urlEncode(random(32));
|
||||
}
|
||||
|
||||
// cryptoRandom fills n bytes from the platform CSPRNG (Web Crypto in the browser
|
||||
// and in node ≥18). Never Math.random — this is security material.
|
||||
function cryptoRandom(n: number): Uint8Array {
|
||||
const out = new Uint8Array(n);
|
||||
crypto.getRandomValues(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// challengeFromVerifier derives the S256 code_challenge = base64url(sha256(
|
||||
// verifier)). `sha256` is injectable for tests; defaults to Web Crypto's
|
||||
// subtle.digest (async). Returns the challenge string.
|
||||
export async function challengeFromVerifier(
|
||||
verifier: string,
|
||||
sha256: (input: string) => Promise<Uint8Array> = subtleSha256,
|
||||
): Promise<string> {
|
||||
return base64urlEncode(await sha256(verifier));
|
||||
}
|
||||
|
||||
async function subtleSha256(input: string): Promise<Uint8Array> {
|
||||
const data = new TextEncoder().encode(input);
|
||||
const digest = await crypto.subtle.digest('SHA-256', data);
|
||||
return new Uint8Array(digest);
|
||||
}
|
||||
|
||||
// createPkce mints a full PKCE pair (verifier + S256 challenge). The app stores
|
||||
// `verifier` alongside the CSRF `state` before the redirect and replays it at
|
||||
// token exchange. `random`/`sha256` are injectable for deterministic tests.
|
||||
export async function createPkce(
|
||||
random: (n: number) => Uint8Array = cryptoRandom,
|
||||
sha256: (input: string) => Promise<Uint8Array> = subtleSha256,
|
||||
): Promise<PkcePair> {
|
||||
const verifier = randomVerifier(random);
|
||||
const challenge = await challengeFromVerifier(verifier, sha256);
|
||||
return { verifier, challenge, method: 'S256' };
|
||||
}
|
||||
|
||||
// ── The authorize redirect ───────────────────────────────────────────────
|
||||
|
||||
export interface AuthorizeParams {
|
||||
authorizationEndpoint: string; // discovered from smart-configuration
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
// The FHIR base (`iss`) — SMART/Epic REQUIRE it as `aud` so the token is
|
||||
// audienced to the FHIR server the app will call.
|
||||
aud: string;
|
||||
scope: string;
|
||||
state: string; // CSRF state the caller mints and verifies on the callback
|
||||
codeChallenge: string; // PKCE S256 challenge
|
||||
// The opaque `launch` token from an EHR launch. Present for EHR launch,
|
||||
// absent (and omitted) for standalone launch.
|
||||
launch?: string;
|
||||
}
|
||||
|
||||
// authorizeUrl builds the exact URL to redirect the browser to. SMART's
|
||||
// authorization request: response_type=code, client_id, redirect_uri, scope,
|
||||
// state, aud, code_challenge(+method=S256), and `launch` when present. Pure.
|
||||
export function authorizeUrl(p: AuthorizeParams): string {
|
||||
const params = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: p.clientId,
|
||||
redirect_uri: p.redirectUri,
|
||||
scope: p.scope,
|
||||
state: p.state,
|
||||
aud: p.aud,
|
||||
code_challenge: p.codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
});
|
||||
if (p.launch) params.set('launch', p.launch);
|
||||
return `${p.authorizationEndpoint}?${params.toString()}`;
|
||||
}
|
||||
|
||||
// ── Token exchange / refresh shaping ──────────────────────────────────────
|
||||
|
||||
// The shape of the POST server.ts will make — separated from fetch so a test
|
||||
// asserts URL, headers, and form body without a network call. Confidential apps
|
||||
// authenticate with client_secret (in the body here — Epic accepts
|
||||
// client_secret_post); public apps omit it and rely on PKCE.
|
||||
export interface TokenRequest {
|
||||
url: string;
|
||||
headers: Record<string, string>;
|
||||
body: string; // urlencoded form
|
||||
}
|
||||
|
||||
export interface ExchangeParams {
|
||||
tokenEndpoint: string; // discovered
|
||||
clientId: string;
|
||||
redirectUri: string;
|
||||
code: string; // the authorization code from the callback
|
||||
codeVerifier: string; // the PKCE verifier stored before the redirect
|
||||
// Confidential-app secret (server-only). Omit for a public app.
|
||||
clientSecret?: string;
|
||||
}
|
||||
|
||||
// tokenExchange shapes the code→token POST. SMART/OAuth2:
|
||||
// grant_type=authorization_code with code, redirect_uri, client_id,
|
||||
// code_verifier, and client_secret for confidential apps. Pure.
|
||||
export function tokenExchange(p: ExchangeParams): TokenRequest {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'authorization_code',
|
||||
code: p.code,
|
||||
redirect_uri: p.redirectUri,
|
||||
client_id: p.clientId,
|
||||
code_verifier: p.codeVerifier,
|
||||
});
|
||||
if (p.clientSecret) body.set('client_secret', p.clientSecret);
|
||||
return {
|
||||
url: p.tokenEndpoint,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: body.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
export interface RefreshParams {
|
||||
tokenEndpoint: string;
|
||||
clientId: string;
|
||||
refreshToken: string;
|
||||
clientSecret?: string;
|
||||
// A refresh MAY narrow scope; omit to keep the granted scopes.
|
||||
scope?: string;
|
||||
}
|
||||
|
||||
// tokenRefresh shapes the refresh POST. grant_type=refresh_token with the stored
|
||||
// refresh_token (+ client_secret for confidential apps). Same endpoint/content
|
||||
// type as exchange. Pure.
|
||||
export function tokenRefresh(p: RefreshParams): TokenRequest {
|
||||
const body = new URLSearchParams({
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: p.refreshToken,
|
||||
client_id: p.clientId,
|
||||
});
|
||||
if (p.clientSecret) body.set('client_secret', p.clientSecret);
|
||||
if (p.scope) body.set('scope', p.scope);
|
||||
return {
|
||||
url: p.tokenEndpoint,
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: body.toString(),
|
||||
};
|
||||
}
|
||||
|
||||
// ── The token response → SMART context ────────────────────────────────────
|
||||
|
||||
// A parsed SMART token response: the OAuth tokens PLUS the SMART launch context
|
||||
// that rides in the token payload (`patient`, `encounter`, `id_token`, the
|
||||
// granted `scope`, and the FHIR base to call). The `patient` id is what every
|
||||
// subsequent FHIR read scopes to.
|
||||
export interface SmartContext {
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
tokenType: string;
|
||||
// Absolute expiry (epoch ms) computed from expires_in at parse time, so
|
||||
// callers compare against Date.now() without re-deriving.
|
||||
expiresAt: number;
|
||||
// The launched patient's FHIR id — present for a patient-context launch.
|
||||
patient: string;
|
||||
// The encounter id when the launch carries one (optional).
|
||||
encounter: string;
|
||||
// The granted scopes (may be narrower than requested).
|
||||
scope: string;
|
||||
// OpenID id_token identifying the clinician (`fhirUser`), when present.
|
||||
idToken: string;
|
||||
// Some servers echo the FHIR base in the token response; kept when present so
|
||||
// the caller can prefer it over the launch `iss`.
|
||||
fhirBase: string;
|
||||
}
|
||||
|
||||
// parseTokenResponse turns a SMART token payload into a SmartContext, computing
|
||||
// the absolute expiry. `now` is injectable so the derivation is unit-testable.
|
||||
// Throws on an OAuth error payload so the caller surfaces the server's real
|
||||
// reason. Boundary guard on an external response.
|
||||
export function parseTokenResponse(data: unknown, now: number = Date.now()): SmartContext {
|
||||
const d = data as Record<string, unknown>;
|
||||
if (d && d.error) {
|
||||
const desc = (d.error_description as string) || (d.error as string);
|
||||
throw new Error(`SMART OAuth error: ${desc}`);
|
||||
}
|
||||
const accessToken = d?.access_token;
|
||||
if (typeof accessToken !== 'string' || !accessToken) {
|
||||
throw new Error('SMART OAuth: no access_token in response');
|
||||
}
|
||||
const expiresIn = Number(d?.expires_in ?? 0);
|
||||
const str = (v: unknown): string => (typeof v === 'string' ? v : '');
|
||||
return {
|
||||
accessToken,
|
||||
refreshToken: str(d?.refresh_token),
|
||||
tokenType: str(d?.token_type) || 'Bearer',
|
||||
expiresAt: now + expiresIn * 1000,
|
||||
patient: str(d?.patient),
|
||||
encounter: str(d?.encounter),
|
||||
scope: str(d?.scope),
|
||||
idToken: str(d?.id_token),
|
||||
fhirBase: str(d?.fhirBase) || str((d as { serverUrl?: unknown })?.serverUrl),
|
||||
};
|
||||
}
|
||||
|
||||
// isExpired reports whether a context's access token is at/near expiry. A skew
|
||||
// (default 60s) refreshes slightly early so an in-flight FHIR read never races
|
||||
// the boundary. Pure.
|
||||
export function isExpired(ctx: Pick<SmartContext, 'expiresAt'>, now: number = Date.now(), skewMs = 60_000): boolean {
|
||||
return now >= ctx.expiresAt - skewMs;
|
||||
}
|
||||
|
||||
// ── Launch-URL parsing (pure) ─────────────────────────────────────────────
|
||||
|
||||
// The launch parameters SMART puts on the app's launch URL. EHR launch carries
|
||||
// `iss` (FHIR base) + `launch` (opaque token); standalone launch carries
|
||||
// neither (the app supplies its own `iss`). Both may be absent when the page is
|
||||
// opened cold.
|
||||
export interface LaunchParams {
|
||||
iss: string; // FHIR base from the EHR
|
||||
launch: string; // opaque launch token
|
||||
}
|
||||
|
||||
// parseLaunch reads the launch URL query into a LaunchParams. Pure — takes a
|
||||
// query string so it is unit-tested without a DOM. Values are trimmed; absence
|
||||
// is represented as ''.
|
||||
export function parseLaunch(search: string): LaunchParams {
|
||||
const q = new URLSearchParams(search);
|
||||
return {
|
||||
iss: (q.get('iss') || '').trim(),
|
||||
launch: (q.get('launch') || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
// The callback parameters SMART returns to redirect_uri: the auth `code` and the
|
||||
// `state` (to verify against the mint), or an `error`(+description) when the
|
||||
// user declines / the server rejects.
|
||||
export interface CallbackParams {
|
||||
code: string;
|
||||
state: string;
|
||||
error: string;
|
||||
errorDescription: string;
|
||||
}
|
||||
|
||||
// parseCallback reads the callback URL query. Pure. An `error` present means the
|
||||
// grant failed — the caller surfaces errorDescription and does NOT exchange.
|
||||
export function parseCallback(search: string): CallbackParams {
|
||||
const q = new URLSearchParams(search);
|
||||
return {
|
||||
code: (q.get('code') || '').trim(),
|
||||
state: (q.get('state') || '').trim(),
|
||||
error: (q.get('error') || '').trim(),
|
||||
errorDescription: (q.get('error_description') || '').trim(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
--fg: #1a1a1a; --muted: #666; --bg: #fff; --line: #e3e3e3; --accent: #111;
|
||||
--ok: #1a7f37; --warn: #9a6700; --error: #cf222e;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--fg: #eaeaea; --muted: #9a9a9a; --bg: #1e1e1e; --line: #333; --accent: #fff;
|
||||
--ok: #3fb950; --warn: #d29922; --error: #f85149;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
font: 14px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
color: var(--fg); background: var(--bg); margin: 0 auto; padding: 14px;
|
||||
max-width: 720px;
|
||||
}
|
||||
header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
|
||||
header .title { font-weight: 600; font-size: 15px; }
|
||||
header .host { color: var(--muted); font-size: 12px; margin-left: auto; max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
label { display: block; font-size: 12px; color: var(--muted); margin: 10px 0 4px; }
|
||||
textarea, select, input {
|
||||
width: 100%; font: inherit; color: var(--fg); background: var(--bg);
|
||||
border: 1px solid var(--line); border-radius: 6px; padding: 8px;
|
||||
}
|
||||
textarea#prompt { min-height: 56px; resize: vertical; }
|
||||
textarea#output { min-height: 260px; resize: vertical; }
|
||||
.row { display: flex; gap: 8px; align-items: center; margin-top: 8px; }
|
||||
button {
|
||||
font: inherit; border: 1px solid var(--line); background: var(--accent);
|
||||
color: var(--bg); border-radius: 6px; padding: 8px 14px; cursor: pointer;
|
||||
}
|
||||
button.secondary { background: transparent; color: var(--fg); }
|
||||
button:disabled { opacity: .5; cursor: default; }
|
||||
.spacer { flex: 1; }
|
||||
.status { min-height: 18px; font-size: 12px; margin-top: 10px; color: var(--muted); }
|
||||
.status.ok { color: var(--ok); } .status.warn { color: var(--warn); } .status.error { color: var(--error); }
|
||||
.hint { font-size: 11px; color: var(--muted); margin-top: 4px; }
|
||||
footer { margin-top: 12px; font-size: 11px; color: var(--muted); }
|
||||
select#model { width: auto; max-width: 150px; padding: 4px 8px; font-size: 12px; }
|
||||
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
|
||||
.chip {
|
||||
padding: 5px 10px; border-radius: 999px; font-size: 13px; cursor: pointer;
|
||||
background: transparent; color: var(--fg); border: 1px solid var(--line);
|
||||
}
|
||||
.chip:hover:not(:disabled) { border-color: var(--accent); }
|
||||
.chip:disabled { opacity: .5; cursor: default; }
|
||||
details summary { cursor: pointer; font-size: 12px; color: var(--muted); margin-top: 10px; }
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
// A minimal localStorage stub so the browser-only auth module is testable in
|
||||
// node. Installed before importing the module under test.
|
||||
class MemStorage {
|
||||
private m = new Map<string, string>();
|
||||
getItem(k: string) {
|
||||
return this.m.has(k) ? this.m.get(k)! : null;
|
||||
}
|
||||
setItem(k: string, v: string) {
|
||||
this.m.set(k, v);
|
||||
}
|
||||
removeItem(k: string) {
|
||||
this.m.delete(k);
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
(globalThis as { localStorage?: unknown }).localStorage = new MemStorage();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
describe('auth: pasted Hanzo key (NOT the FHIR/PHI token)', () => {
|
||||
it('stores, reads, and clears the key', async () => {
|
||||
const { getApiKey, setApiKey, hasApiKey, bearer } = await import('../src/auth.js');
|
||||
expect(getApiKey()).toBe('');
|
||||
expect(hasApiKey()).toBe(false);
|
||||
setApiKey(' hk-abc ');
|
||||
expect(getApiKey()).toBe('hk-abc'); // trimmed
|
||||
expect(hasApiKey()).toBe(true);
|
||||
expect(bearer()).toBe('hk-abc');
|
||||
setApiKey('');
|
||||
expect(getApiKey()).toBe('');
|
||||
expect(hasApiKey()).toBe(false);
|
||||
});
|
||||
|
||||
it('validateKey rejects an empty key before any network call', async () => {
|
||||
const { validateKey } = await import('../src/auth.js');
|
||||
await expect(validateKey(' ')).rejects.toThrow(/Hanzo API key/);
|
||||
});
|
||||
|
||||
it('does not touch the FHIR/PHI storage — only the Hanzo gateway key', async () => {
|
||||
const { setApiKey } = await import('../src/auth.js');
|
||||
const { APIKEY_STORAGE_KEY } = await import('../src/config.js');
|
||||
setApiKey('hk-x');
|
||||
// The one and only key it writes is the Hanzo gateway key.
|
||||
expect(localStorage.getItem(APIKEY_STORAGE_KEY)).toBe('hk-x');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,241 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
codeableText,
|
||||
effectiveDate,
|
||||
summarizePatient,
|
||||
conditionRow,
|
||||
medicationRow,
|
||||
allergyRow,
|
||||
observationRow,
|
||||
observationValue,
|
||||
documentRow,
|
||||
renderSection,
|
||||
assembleChartContext,
|
||||
truncate,
|
||||
chartIsEmpty,
|
||||
emptyChart,
|
||||
MAX_ROWS_PER_SECTION,
|
||||
type Chart,
|
||||
} from '../src/chart.js';
|
||||
import type { FhirResource } from '../src/fhir-client.js';
|
||||
|
||||
// ── Realistic R4 fixtures ──────────────────────────────────────────────────
|
||||
|
||||
const patient: FhirResource = {
|
||||
resourceType: 'Patient',
|
||||
id: 'p1',
|
||||
name: [{ use: 'official', given: ['Jane', 'Q'], family: 'Doe' }],
|
||||
gender: 'female',
|
||||
birthDate: '1958-03-11',
|
||||
};
|
||||
|
||||
const hypertension: FhirResource = {
|
||||
resourceType: 'Condition',
|
||||
id: 'c1',
|
||||
clinicalStatus: { coding: [{ code: 'active', display: 'Active' }] },
|
||||
code: { text: 'Essential hypertension', coding: [{ system: 'http://snomed.info/sct', code: '59621000' }] },
|
||||
onsetDateTime: '2015-06-01',
|
||||
};
|
||||
|
||||
const diabetes: FhirResource = {
|
||||
resourceType: 'Condition',
|
||||
id: 'c2',
|
||||
clinicalStatus: { coding: [{ code: 'active' }] },
|
||||
code: { coding: [{ display: 'Type 2 diabetes mellitus' }] },
|
||||
};
|
||||
|
||||
const lisinopril: FhirResource = {
|
||||
resourceType: 'MedicationRequest',
|
||||
id: 'm1',
|
||||
status: 'active',
|
||||
medicationCodeableConcept: { text: 'Lisinopril 10 mg oral tablet' },
|
||||
dosageInstruction: [{ text: 'Take 1 tablet by mouth once daily' }],
|
||||
};
|
||||
|
||||
const metforminByRef: FhirResource = {
|
||||
resourceType: 'MedicationRequest',
|
||||
id: 'm2',
|
||||
status: 'active',
|
||||
medicationReference: { display: 'Metformin 500 mg' },
|
||||
};
|
||||
|
||||
const penicillinAllergy: FhirResource = {
|
||||
resourceType: 'AllergyIntolerance',
|
||||
id: 'a1',
|
||||
clinicalStatus: { coding: [{ code: 'active' }] },
|
||||
criticality: 'high',
|
||||
code: { text: 'Penicillin' },
|
||||
reaction: [{ manifestation: [{ text: 'Anaphylaxis' }] }],
|
||||
};
|
||||
|
||||
const a1c: FhirResource = {
|
||||
resourceType: 'Observation',
|
||||
id: 'o1',
|
||||
code: { text: 'Hemoglobin A1c' },
|
||||
valueQuantity: { value: 8.2, unit: '%' },
|
||||
effectiveDateTime: '2026-05-20',
|
||||
};
|
||||
|
||||
const bp: FhirResource = {
|
||||
resourceType: 'Observation',
|
||||
id: 'o2',
|
||||
code: { text: 'Systolic blood pressure' },
|
||||
valueQuantity: { value: 148, unit: 'mmHg' },
|
||||
effectivePeriod: { start: '2026-06-01' },
|
||||
};
|
||||
|
||||
const progressNote: FhirResource = {
|
||||
resourceType: 'DocumentReference',
|
||||
id: 'd1',
|
||||
type: { text: 'Progress note' },
|
||||
date: '2026-06-15',
|
||||
};
|
||||
|
||||
describe('CodeableConcept decoding', () => {
|
||||
it('prefers text, then coding.display, then coding.code', () => {
|
||||
expect(codeableText({ text: 'Foo' })).toBe('Foo');
|
||||
expect(codeableText({ coding: [{ display: 'Bar' }] })).toBe('Bar');
|
||||
expect(codeableText({ coding: [{ code: 'baz' }] })).toBe('baz');
|
||||
expect(codeableText({})).toBe('');
|
||||
expect(codeableText(undefined)).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('effectiveDate polymorphism', () => {
|
||||
it('reads effectiveDateTime, effectivePeriod.start, onset, authoredOn', () => {
|
||||
expect(effectiveDate({ resourceType: 'X', effectiveDateTime: '2026-01-01' })).toBe('2026-01-01');
|
||||
expect(effectiveDate({ resourceType: 'X', effectivePeriod: { start: '2026-02-02' } })).toBe('2026-02-02');
|
||||
expect(effectiveDate({ resourceType: 'X', onsetDateTime: '2026-03-03' })).toBe('2026-03-03');
|
||||
expect(effectiveDate({ resourceType: 'X', authoredOn: '2026-04-04' })).toBe('2026-04-04');
|
||||
expect(effectiveDate({ resourceType: 'X' })).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('patient demographics', () => {
|
||||
it('renders name, sex, DOB from a HumanName', () => {
|
||||
expect(summarizePatient(patient)).toEqual(['Name: Jane Q Doe', 'Sex: female', 'DOB: 1958-03-11']);
|
||||
});
|
||||
it('prefers name.text when present', () => {
|
||||
expect(summarizePatient({ resourceType: 'Patient', name: [{ text: 'John Smith' }] })).toEqual([
|
||||
'Name: John Smith',
|
||||
]);
|
||||
});
|
||||
it('is empty for no patient', () => {
|
||||
expect(summarizePatient(undefined)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('per-resource rows', () => {
|
||||
it('conditionRow — name, status, onset', () => {
|
||||
expect(conditionRow(hypertension)).toBe('Essential hypertension (Active) onset 2015-06-01');
|
||||
expect(conditionRow(diabetes)).toBe('Type 2 diabetes mellitus (active)');
|
||||
});
|
||||
|
||||
it('medicationRow — from codeableConcept with dosage, and from a reference', () => {
|
||||
expect(medicationRow(lisinopril)).toBe(
|
||||
'Lisinopril 10 mg oral tablet — Take 1 tablet by mouth once daily (active)',
|
||||
);
|
||||
expect(medicationRow(metforminByRef)).toBe('Metformin 500 mg (active)');
|
||||
});
|
||||
|
||||
it('allergyRow — substance, manifestation, criticality, status', () => {
|
||||
expect(allergyRow(penicillinAllergy)).toBe('Penicillin → Anaphylaxis [high] (active)');
|
||||
});
|
||||
|
||||
it('observationRow / observationValue — quantity with unit + date', () => {
|
||||
expect(observationValue(a1c)).toBe('8.2 %');
|
||||
expect(observationRow(a1c)).toBe('Hemoglobin A1c = 8.2 % (2026-05-20)');
|
||||
expect(observationRow(bp)).toBe('Systolic blood pressure = 148 mmHg (2026-06-01)');
|
||||
});
|
||||
|
||||
it('observationValue — codeable and string variants', () => {
|
||||
expect(observationValue({ resourceType: 'Observation', valueCodeableConcept: { text: 'Positive' } })).toBe(
|
||||
'Positive',
|
||||
);
|
||||
expect(observationValue({ resourceType: 'Observation', valueString: 'see report' })).toBe('see report');
|
||||
expect(observationValue({ resourceType: 'Observation' })).toBe('');
|
||||
});
|
||||
|
||||
it('documentRow — type and date, no bytes inlined', () => {
|
||||
expect(documentRow(progressNote)).toBe('Progress note (2026-06-15)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderSection', () => {
|
||||
it('renders a heading + bulleted rows', () => {
|
||||
const out = renderSection({ heading: 'Problems', resources: [hypertension, diabetes], row: conditionRow });
|
||||
expect(out).toContain('## Problems');
|
||||
expect(out).toContain('- Essential hypertension (Active) onset 2015-06-01');
|
||||
expect(out).toContain('- Type 2 diabetes mellitus (active)');
|
||||
});
|
||||
|
||||
it('marks an empty section explicitly (absence is meaningful)', () => {
|
||||
expect(renderSection({ heading: 'Allergies', resources: [], row: allergyRow })).toBe(
|
||||
'## Allergies\n(none recorded)',
|
||||
);
|
||||
});
|
||||
|
||||
it('caps rows and shows a visible "N more" marker', () => {
|
||||
const many = Array.from({ length: MAX_ROWS_PER_SECTION + 5 }, (_, i) => ({
|
||||
...diabetes,
|
||||
code: { text: `Condition ${i}` },
|
||||
}));
|
||||
const out = renderSection({ heading: 'Problems', resources: many, row: conditionRow });
|
||||
expect(out).toContain('- …and 5 more not shown');
|
||||
// exactly MAX_ROWS_PER_SECTION data rows + heading + the "more" line
|
||||
expect(out.split('\n').filter((l) => l.startsWith('- ')).length).toBe(MAX_ROWS_PER_SECTION + 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assembleChartContext', () => {
|
||||
const chart: Chart = {
|
||||
patient,
|
||||
conditions: [hypertension, diabetes],
|
||||
medications: [lisinopril, metforminByRef],
|
||||
allergies: [penicillinAllergy],
|
||||
observations: [a1c, bp],
|
||||
documents: [progressNote],
|
||||
};
|
||||
|
||||
it('assembles demographics + all five sections in clinical priority order', () => {
|
||||
const ctx = assembleChartContext(chart);
|
||||
expect(ctx.indexOf('# Patient')).toBeLessThan(ctx.indexOf('## Problems'));
|
||||
expect(ctx.indexOf('## Problems')).toBeLessThan(ctx.indexOf('## Medications'));
|
||||
expect(ctx.indexOf('## Medications')).toBeLessThan(ctx.indexOf('## Allergies'));
|
||||
expect(ctx.indexOf('## Allergies')).toBeLessThan(ctx.indexOf('## Recent labs & vitals'));
|
||||
expect(ctx.indexOf('## Recent labs & vitals')).toBeLessThan(ctx.indexOf('## Clinical notes'));
|
||||
expect(ctx).toContain('Jane Q Doe');
|
||||
expect(ctx).toContain('Penicillin → Anaphylaxis [high]');
|
||||
expect(ctx).toContain('Hemoglobin A1c = 8.2 %');
|
||||
});
|
||||
|
||||
it('renders a usable chart even with no demographics', () => {
|
||||
const ctx = assembleChartContext({ ...emptyChart(), conditions: [hypertension] });
|
||||
expect(ctx).toContain('(no demographics available)');
|
||||
expect(ctx).toContain('Essential hypertension');
|
||||
});
|
||||
|
||||
it('caps the whole context and marks truncation visibly', () => {
|
||||
const bigDoc: FhirResource = {
|
||||
resourceType: 'DocumentReference',
|
||||
type: { text: 'x'.repeat(2000) },
|
||||
date: '2026-01-01',
|
||||
};
|
||||
const chartBig: Chart = { ...emptyChart(), documents: Array.from({ length: 50 }, () => bigDoc) };
|
||||
const ctx = assembleChartContext(chartBig, 500);
|
||||
expect(ctx.length).toBeLessThanOrEqual(500 + 60);
|
||||
expect(ctx).toMatch(/chart truncated: \d+ chars omitted/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('truncate + chartIsEmpty', () => {
|
||||
it('truncate marks elision and passes short text through', () => {
|
||||
expect(truncate('short', 100)).toBe('short');
|
||||
expect(truncate('abcdef', 3)).toMatch(/^abc\n…\[chart truncated: 3 chars omitted\]$/);
|
||||
});
|
||||
it('chartIsEmpty is true only when all clinical lists are empty', () => {
|
||||
expect(chartIsEmpty(emptyChart())).toBe(true);
|
||||
expect(chartIsEmpty({ ...emptyChart(), patient })).toBe(true); // patient alone still empty
|
||||
expect(chartIsEmpty({ ...emptyChart(), conditions: [hypertension] })).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
HANZO_API_BASE_URL,
|
||||
DEFAULT_MODEL,
|
||||
pickBearer,
|
||||
SMART_SCOPES,
|
||||
scopeString,
|
||||
smartConfigUrl,
|
||||
normalizeBase,
|
||||
FHIR_RESOURCES,
|
||||
} from '../src/config.js';
|
||||
|
||||
describe('config: Hanzo gateway', () => {
|
||||
it('points at api.hanzo.ai with no /api/ prefix', () => {
|
||||
expect(HANZO_API_BASE_URL).toBe('https://api.hanzo.ai');
|
||||
expect(HANZO_API_BASE_URL).not.toContain('/api/');
|
||||
});
|
||||
|
||||
it('default model is a zen model', () => {
|
||||
expect(DEFAULT_MODEL).toMatch(/^zen/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config: pickBearer', () => {
|
||||
it('prefers the pasted key over the IAM token', () => {
|
||||
expect(pickBearer('hk-key', 'iam-token')).toBe('hk-key');
|
||||
});
|
||||
it('falls back to the IAM token when no key', () => {
|
||||
expect(pickBearer('', 'iam-token')).toBe('iam-token');
|
||||
expect(pickBearer(' ', 'iam-token')).toBe('iam-token');
|
||||
});
|
||||
it('is empty (anonymous) when neither is present', () => {
|
||||
expect(pickBearer('', '')).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('config: SMART scopes', () => {
|
||||
it('requests launch + patient read scopes and NO write scope', () => {
|
||||
const s = scopeString();
|
||||
expect(s).toContain('launch');
|
||||
expect(s).toContain('openid');
|
||||
expect(s).toContain('fhirUser');
|
||||
expect(s).toContain('patient/Patient.read');
|
||||
expect(s).toContain('patient/Condition.read');
|
||||
expect(s).toContain('patient/MedicationRequest.read');
|
||||
expect(s).toContain('patient/Observation.read');
|
||||
expect(s).toContain('patient/AllergyIntolerance.read');
|
||||
expect(s).toContain('patient/DocumentReference.read');
|
||||
// Read + assist only — a write scope must never be requested in v1.
|
||||
expect(s).not.toMatch(/\.write/);
|
||||
expect(s).not.toMatch(/\*\/\*/);
|
||||
});
|
||||
|
||||
it('scopeString is space-delimited and deterministic', () => {
|
||||
expect(scopeString(['a', 'b', 'c'])).toBe('a b c');
|
||||
expect(scopeString()).toBe(SMART_SCOPES.join(' '));
|
||||
});
|
||||
});
|
||||
|
||||
describe('config: discovery URL', () => {
|
||||
it('derives the well-known discovery URL from iss', () => {
|
||||
expect(smartConfigUrl('https://fhir.example.org/r4')).toBe(
|
||||
'https://fhir.example.org/r4/.well-known/smart-configuration',
|
||||
);
|
||||
});
|
||||
it('normalizes a trailing slash on iss', () => {
|
||||
expect(smartConfigUrl('https://fhir.example.org/r4/')).toBe(
|
||||
'https://fhir.example.org/r4/.well-known/smart-configuration',
|
||||
);
|
||||
expect(normalizeBase('https://x/')).toBe('https://x');
|
||||
expect(normalizeBase('https://x///')).toBe('https://x');
|
||||
});
|
||||
});
|
||||
|
||||
describe('config: FHIR resource names', () => {
|
||||
it('names the six read resources', () => {
|
||||
expect(Object.keys(FHIR_RESOURCES).sort()).toEqual([
|
||||
'AllergyIntolerance',
|
||||
'Condition',
|
||||
'DocumentReference',
|
||||
'MedicationRequest',
|
||||
'Observation',
|
||||
'Patient',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
resourceUrl,
|
||||
getPatient,
|
||||
searchConditions,
|
||||
searchMedicationRequests,
|
||||
searchAllergyIntolerances,
|
||||
searchObservations,
|
||||
searchDocumentReferences,
|
||||
bundleEntries,
|
||||
nextPageUrl,
|
||||
isOperationOutcome,
|
||||
operationOutcomeMessage,
|
||||
fhirFetch,
|
||||
fetchAllPages,
|
||||
DEFAULT_COUNT,
|
||||
type FhirRequest,
|
||||
} from '../src/fhir-client.js';
|
||||
|
||||
const BASE = 'https://fhir.example.org/r4';
|
||||
const TOKEN = 'AT-secret';
|
||||
const PID = 'Patient-123';
|
||||
|
||||
function res(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/fhir+json' } });
|
||||
}
|
||||
|
||||
describe('resourceUrl', () => {
|
||||
it('builds a search root and a single-resource URL', () => {
|
||||
expect(resourceUrl(BASE, 'Condition')).toBe(`${BASE}/Condition`);
|
||||
expect(resourceUrl(BASE, 'Patient', PID)).toBe(`${BASE}/Patient/Patient-123`);
|
||||
});
|
||||
it('normalizes a trailing slash and encodes the id', () => {
|
||||
expect(resourceUrl(`${BASE}/`, 'Patient', 'a/b')).toBe(`${BASE}/Patient/a%2Fb`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('single-patient read', () => {
|
||||
it('getPatient targets Patient/<id> with a bearer + fhir accept', () => {
|
||||
const r = getPatient(BASE, TOKEN, PID);
|
||||
expect(r.method).toBe('GET');
|
||||
expect(r.url).toBe(`${BASE}/Patient/Patient-123`);
|
||||
expect(r.headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
expect(r.headers.Accept).toBe('application/fhir+json');
|
||||
});
|
||||
});
|
||||
|
||||
describe('patient-scoped searches', () => {
|
||||
const sp = { base: BASE, token: TOKEN, patientId: PID };
|
||||
|
||||
it('scopes every search with patient=<id> and a default _count', () => {
|
||||
for (const req of [
|
||||
searchConditions(sp),
|
||||
searchMedicationRequests(sp),
|
||||
searchAllergyIntolerances(sp),
|
||||
searchDocumentReferences(sp),
|
||||
]) {
|
||||
const u = new URL(req.url);
|
||||
expect(u.searchParams.get('patient')).toBe(PID);
|
||||
expect(u.searchParams.get('_count')).toBe(String(DEFAULT_COUNT));
|
||||
}
|
||||
});
|
||||
|
||||
it('hits the right resource path for each search', () => {
|
||||
expect(new URL(searchConditions(sp).url).pathname).toMatch(/\/Condition$/);
|
||||
expect(new URL(searchMedicationRequests(sp).url).pathname).toMatch(/\/MedicationRequest$/);
|
||||
expect(new URL(searchAllergyIntolerances(sp).url).pathname).toMatch(/\/AllergyIntolerance$/);
|
||||
expect(new URL(searchDocumentReferences(sp).url).pathname).toMatch(/\/DocumentReference$/);
|
||||
});
|
||||
|
||||
it('observation search defaults to laboratory + vital-signs categories', () => {
|
||||
const u = new URL(searchObservations(sp).url);
|
||||
expect(u.pathname).toMatch(/\/Observation$/);
|
||||
expect(u.searchParams.get('category')).toBe('laboratory,vital-signs');
|
||||
});
|
||||
|
||||
it('observation category is overridable', () => {
|
||||
const u = new URL(searchObservations({ ...sp, category: 'laboratory' }).url);
|
||||
expect(u.searchParams.get('category')).toBe('laboratory');
|
||||
});
|
||||
|
||||
it('a custom _count is honored', () => {
|
||||
expect(new URL(searchConditions({ ...sp, count: 10 }).url).searchParams.get('_count')).toBe('10');
|
||||
});
|
||||
|
||||
it('a pageUrl cursor is used verbatim (pagination), ignoring other params', () => {
|
||||
const next = `${BASE}/Condition?patient=${PID}&_count=50&_getpages=abc&_getpagesoffset=50`;
|
||||
const r = searchConditions({ ...sp, pageUrl: next, count: 999 });
|
||||
expect(r.url).toBe(next);
|
||||
expect(r.headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Bundle helpers', () => {
|
||||
const bundle = {
|
||||
resourceType: 'Bundle',
|
||||
type: 'searchset',
|
||||
entry: [
|
||||
{ resource: { resourceType: 'Condition', id: 'c1' } },
|
||||
{ resource: { resourceType: 'Condition', id: 'c2' } },
|
||||
{ fullUrl: 'no-resource-here' }, // dropped
|
||||
],
|
||||
link: [
|
||||
{ relation: 'self', url: `${BASE}/Condition?patient=${PID}` },
|
||||
{ relation: 'next', url: `${BASE}/Condition?_getpages=abc` },
|
||||
],
|
||||
};
|
||||
|
||||
it('bundleEntries returns only entries with a resource', () => {
|
||||
const rs = bundleEntries(bundle);
|
||||
expect(rs.map((r) => r.id)).toEqual(['c1', 'c2']);
|
||||
});
|
||||
it('bundleEntries returns [] for a non-Bundle', () => {
|
||||
expect(bundleEntries({ resourceType: 'Condition' })).toEqual([]);
|
||||
expect(bundleEntries(null)).toEqual([]);
|
||||
});
|
||||
it('nextPageUrl returns the next link, or empty on the last page', () => {
|
||||
expect(nextPageUrl(bundle)).toBe(`${BASE}/Condition?_getpages=abc`);
|
||||
expect(nextPageUrl({ resourceType: 'Bundle', link: [{ relation: 'self', url: 'x' }] })).toBe('');
|
||||
expect(nextPageUrl({ resourceType: 'Bundle' })).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('OperationOutcome handling', () => {
|
||||
const oo = {
|
||||
resourceType: 'OperationOutcome',
|
||||
issue: [{ severity: 'error', code: 'forbidden', diagnostics: 'not authorized for this patient' }],
|
||||
};
|
||||
it('detects an OperationOutcome and renders its message', () => {
|
||||
expect(isOperationOutcome(oo)).toBe(true);
|
||||
expect(isOperationOutcome({ resourceType: 'Bundle' })).toBe(false);
|
||||
expect(operationOutcomeMessage(oo)).toBe('not authorized for this patient');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fhirFetch', () => {
|
||||
it('returns the parsed Bundle on success', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(res(200, { resourceType: 'Bundle', entry: [] }));
|
||||
const out = (await fhirFetch(getPatient(BASE, TOKEN, PID) as FhirRequest, doFetch)) as {
|
||||
resourceType: string;
|
||||
};
|
||||
expect(out.resourceType).toBe('Bundle');
|
||||
expect(doFetch).toHaveBeenCalledWith(`${BASE}/Patient/Patient-123`, {
|
||||
method: 'GET',
|
||||
headers: { Authorization: `Bearer ${TOKEN}`, Accept: 'application/fhir+json' },
|
||||
});
|
||||
});
|
||||
|
||||
it('throws the OperationOutcome diagnostics (not the raw body)', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(
|
||||
res(403, { resourceType: 'OperationOutcome', issue: [{ diagnostics: 'access denied' }] }),
|
||||
);
|
||||
await expect(fhirFetch(getPatient(BASE, TOKEN, PID), doFetch)).rejects.toThrow(/access denied/);
|
||||
});
|
||||
|
||||
it('throws on a non-2xx without echoing a PHI body', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(res(500, { resourceType: 'Bundle' }));
|
||||
await expect(fhirFetch(getPatient(BASE, TOKEN, PID), doFetch)).rejects.toThrow(/FHIR 500/);
|
||||
});
|
||||
|
||||
it('throws a length-only hint on non-JSON', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(new Response('<html>PHI leak</html>', { status: 502 }));
|
||||
const err = await fhirFetch(getPatient(BASE, TOKEN, PID), doFetch).then(
|
||||
() => new Error('expected a throw'),
|
||||
(e: unknown) => e as Error,
|
||||
);
|
||||
expect(err.message).toMatch(/non-JSON/);
|
||||
expect(err.message).not.toContain('PHI leak');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchAllPages', () => {
|
||||
it('walks Bundle next links and flattens resources', async () => {
|
||||
const page1 = {
|
||||
resourceType: 'Bundle',
|
||||
entry: [{ resource: { resourceType: 'Condition', id: 'c1' } }],
|
||||
link: [{ relation: 'next', url: `${BASE}/Condition?page=2` }],
|
||||
};
|
||||
const page2 = {
|
||||
resourceType: 'Bundle',
|
||||
entry: [{ resource: { resourceType: 'Condition', id: 'c2' } }],
|
||||
link: [{ relation: 'self', url: `${BASE}/Condition?page=2` }],
|
||||
};
|
||||
const doFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(res(200, page1))
|
||||
.mockResolvedValueOnce(res(200, page2));
|
||||
const first = searchConditions({ base: BASE, token: TOKEN, patientId: PID });
|
||||
const all = await fetchAllPages(first, TOKEN, { doFetch });
|
||||
expect(all.map((r) => r.id)).toEqual(['c1', 'c2']);
|
||||
expect(doFetch).toHaveBeenCalledTimes(2);
|
||||
// The second call used the exact `next` URL, with the bearer re-attached.
|
||||
expect(doFetch.mock.calls[1][0]).toBe(`${BASE}/Condition?page=2`);
|
||||
expect(doFetch.mock.calls[1][1].headers.Authorization).toBe(`Bearer ${TOKEN}`);
|
||||
});
|
||||
|
||||
it('stops at maxPages against an infinite pager', async () => {
|
||||
const loop = {
|
||||
resourceType: 'Bundle',
|
||||
entry: [{ resource: { resourceType: 'Condition', id: 'c' } }],
|
||||
link: [{ relation: 'next', url: `${BASE}/Condition?loop` }],
|
||||
};
|
||||
// A fresh Response per call — a Response body is single-use, so the same
|
||||
// object cannot be returned twice (fhirFetch consumes it with .text()).
|
||||
const doFetch = vi.fn().mockImplementation(async () => res(200, loop));
|
||||
const first = searchConditions({ base: BASE, token: TOKEN, patientId: PID });
|
||||
const all = await fetchAllPages(first, TOKEN, { doFetch, maxPages: 3 });
|
||||
expect(doFetch).toHaveBeenCalledTimes(3);
|
||||
expect(all).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('returns a single page when there is no next link', async () => {
|
||||
const only = {
|
||||
resourceType: 'Bundle',
|
||||
entry: [{ resource: { resourceType: 'Condition', id: 'x' } }],
|
||||
link: [{ relation: 'self', url: 'self' }],
|
||||
};
|
||||
const doFetch = vi.fn().mockResolvedValue(res(200, only));
|
||||
const all = await fetchAllPages(searchConditions({ base: BASE, token: TOKEN, patientId: PID }), TOKEN, {
|
||||
doFetch,
|
||||
});
|
||||
expect(all).toHaveLength(1);
|
||||
expect(doFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,195 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { AiClient, ChatCompletion, ChatCompletionCreateParams } from '@hanzo/ai';
|
||||
import {
|
||||
CLINICAL_SYSTEM_PROMPT,
|
||||
ACTIONS,
|
||||
isActionId,
|
||||
actionTask,
|
||||
buildMessages,
|
||||
extractContent,
|
||||
ask,
|
||||
runAction,
|
||||
listModels,
|
||||
} from '../src/hanzo.js';
|
||||
import { DEFAULT_MODEL } from '../src/config.js';
|
||||
|
||||
// A fake @hanzo/ai client that records the create() params and returns a canned
|
||||
// completion, so we assert request shaping with zero network.
|
||||
function fakeClient(text = 'AI OUTPUT') {
|
||||
const create = vi.fn(
|
||||
async (
|
||||
_params: ChatCompletionCreateParams,
|
||||
_options?: { signal?: AbortSignal },
|
||||
): Promise<ChatCompletion> => ({
|
||||
id: 'x',
|
||||
object: 'chat.completion',
|
||||
created: 0,
|
||||
model: 'zen5',
|
||||
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
|
||||
}),
|
||||
);
|
||||
const list = vi.fn(async (_options?: { signal?: AbortSignal }) => [
|
||||
{ id: 'zen5', object: 'model' as const },
|
||||
{ id: 'zen-eco', object: 'model' as const },
|
||||
]);
|
||||
const client = {
|
||||
chat: { completions: { create } },
|
||||
models: { list },
|
||||
} as unknown as AiClient;
|
||||
return { client, create, list };
|
||||
}
|
||||
|
||||
describe('system prompt', () => {
|
||||
it('grounds in the chart, forbids fabrication, and disclaims diagnosis', () => {
|
||||
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/SMART on FHIR/);
|
||||
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/never invent/i);
|
||||
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/not a diagnosis/i);
|
||||
expect(CLINICAL_SYSTEM_PROMPT).toMatch(/clinician reviews/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('action catalog', () => {
|
||||
it('exposes the four actions with prompt flags', () => {
|
||||
expect(ACTIONS.map((a) => a.id)).toEqual(['summarize', 'note', 'extract', 'ask']);
|
||||
expect(ACTIONS.find((a) => a.id === 'note')!.needsPrompt).toBe(true);
|
||||
expect(ACTIONS.find((a) => a.id === 'ask')!.needsPrompt).toBe(true);
|
||||
expect(ACTIONS.find((a) => a.id === 'summarize')!.needsPrompt).toBe(false);
|
||||
expect(ACTIONS.find((a) => a.id === 'extract')!.needsPrompt).toBe(false);
|
||||
});
|
||||
it('isActionId is a strict boundary guard', () => {
|
||||
expect(isActionId('summarize')).toBe(true);
|
||||
expect(isActionId('delete')).toBe(false);
|
||||
expect(isActionId('')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('action prompt builders', () => {
|
||||
it('summarize covers problems/meds/allergies/labs and forbids invention', () => {
|
||||
const t = actionTask('summarize');
|
||||
expect(t).toMatch(/active problems/i);
|
||||
expect(t).toMatch(/medications/i);
|
||||
expect(t).toMatch(/allergies/i);
|
||||
expect(t).toMatch(/labs\/vitals/i);
|
||||
expect(t).toMatch(/not in the chart/i);
|
||||
});
|
||||
|
||||
it('note asks for SOAP and folds in the reason-for-visit', () => {
|
||||
const t = actionTask('note', '72yo HTN follow-up');
|
||||
expect(t).toMatch(/SOAP/);
|
||||
expect(t).toMatch(/Subjective, Objective, Assessment, Plan/);
|
||||
expect(t).toContain('72yo HTN follow-up');
|
||||
// Without detail it still asks for SOAP but omits the input clause.
|
||||
const bare = actionTask('note');
|
||||
expect(bare).toMatch(/SOAP/);
|
||||
expect(bare).not.toMatch(/clinician input:/);
|
||||
});
|
||||
|
||||
it('extract asks for two structured lists (problems + meds)', () => {
|
||||
const t = actionTask('extract');
|
||||
expect(t).toMatch(/active problems/i);
|
||||
expect(t).toMatch(/current medications/i);
|
||||
expect(t).toMatch(/structured lists/i);
|
||||
});
|
||||
|
||||
it('ask uses the question, or a sensible default', () => {
|
||||
expect(actionTask('ask', 'Any drug interactions?')).toBe('Any drug interactions?');
|
||||
expect(actionTask('ask')).toMatch(/most important thing/i);
|
||||
});
|
||||
});
|
||||
|
||||
describe('message assembly', () => {
|
||||
it('fences the chart as data with a system + user turn', () => {
|
||||
const msgs = buildMessages('SUMMARIZE', 'CHART TEXT');
|
||||
expect(msgs).toHaveLength(2);
|
||||
expect(msgs[0]).toEqual({ role: 'system', content: CLINICAL_SYSTEM_PROMPT });
|
||||
expect(msgs[1].role).toBe('user');
|
||||
const content = msgs[1].content as string;
|
||||
expect(content).toContain('---- patient chart ----');
|
||||
expect(content).toContain('CHART TEXT');
|
||||
expect(content).toContain('---- end patient chart ----');
|
||||
expect(content).toContain('---- task ----');
|
||||
expect(content).toContain('SUMMARIZE');
|
||||
});
|
||||
|
||||
it('with no chart, sends just the task', () => {
|
||||
const content = buildMessages('ASK', '')[1].content as string;
|
||||
expect(content).toBe('ASK');
|
||||
});
|
||||
|
||||
it('honors a custom system prompt', () => {
|
||||
expect(buildMessages('t', 'c', 'SYS')[0].content).toBe('SYS');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractContent', () => {
|
||||
it('pulls the assistant message text', () => {
|
||||
expect(
|
||||
extractContent({
|
||||
id: 'x',
|
||||
object: 'chat.completion',
|
||||
created: 0,
|
||||
model: 'm',
|
||||
choices: [{ index: 0, message: { role: 'assistant', content: 'hi' }, finish_reason: 'stop' }],
|
||||
}),
|
||||
).toBe('hi');
|
||||
});
|
||||
it('throws on empty content', () => {
|
||||
expect(() =>
|
||||
extractContent({
|
||||
id: 'x',
|
||||
object: 'chat.completion',
|
||||
created: 0,
|
||||
model: 'm',
|
||||
choices: [{ index: 0, message: { role: 'assistant', content: '' }, finish_reason: 'stop' }],
|
||||
}),
|
||||
).toThrow(/no content/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ask over the SDK client', () => {
|
||||
it('sends model + fenced messages, non-streaming, and returns the text', async () => {
|
||||
const { client, create } = fakeClient('SUMMARY');
|
||||
const out = await ask('SUMMARIZE', 'CHART', { client });
|
||||
expect(out).toBe('SUMMARY');
|
||||
const params = create.mock.calls[0][0];
|
||||
expect(params.model).toBe(DEFAULT_MODEL);
|
||||
expect(params.stream).toBe(false);
|
||||
expect(params.messages[0].role).toBe('system');
|
||||
expect((params.messages[1].content as string)).toContain('CHART');
|
||||
});
|
||||
|
||||
it('passes a model override + temperature + abort signal', async () => {
|
||||
const { client, create } = fakeClient();
|
||||
const signal = new AbortController().signal;
|
||||
await ask('t', 'c', { client, model: 'zen-eco', temperature: 0.2, signal });
|
||||
expect(create.mock.calls[0][0].model).toBe('zen-eco');
|
||||
expect(create.mock.calls[0][0].temperature).toBe(0.2);
|
||||
expect(create.mock.calls[0][1]).toEqual({ signal });
|
||||
});
|
||||
|
||||
it('omits temperature from the wire when unset', async () => {
|
||||
const { client, create } = fakeClient();
|
||||
await ask('t', 'c', { client });
|
||||
expect('temperature' in create.mock.calls[0][0]).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runAction', () => {
|
||||
it('forms the action task and asks over the chart', async () => {
|
||||
const { client, create } = fakeClient('NOTE');
|
||||
const out = await runAction({ id: 'note', detail: 'HTN f/u', chartContext: 'CHART', opts: { client } });
|
||||
expect(out).toBe('NOTE');
|
||||
const userMsg = create.mock.calls[0][0].messages[1].content as string;
|
||||
expect(userMsg).toContain('SOAP');
|
||||
expect(userMsg).toContain('HTN f/u');
|
||||
expect(userMsg).toContain('CHART');
|
||||
});
|
||||
});
|
||||
|
||||
describe('listModels', () => {
|
||||
it('returns model ids from the SDK', async () => {
|
||||
const { client, list } = fakeClient();
|
||||
expect(await listModels({ client })).toEqual(['zen5', 'zen-eco']);
|
||||
expect(list).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import {
|
||||
readServerConfig,
|
||||
memoryStore,
|
||||
discoverSmart,
|
||||
exchangeCode,
|
||||
ensureFreshToken,
|
||||
resolveProxyTarget,
|
||||
readSid,
|
||||
type ServerConfig,
|
||||
} from '../src/server.js';
|
||||
import type { SmartContext } from '../src/smart-oauth.js';
|
||||
|
||||
function res(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
||||
}
|
||||
|
||||
const CFG: ServerConfig = {
|
||||
clientId: 'my-client',
|
||||
clientSecret: 'shh',
|
||||
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
|
||||
sessionTtlMs: 3_600_000,
|
||||
port: 8791,
|
||||
};
|
||||
|
||||
const BASE = 'https://fhir.example.org/r4';
|
||||
|
||||
describe('readServerConfig', () => {
|
||||
it('requires client id + redirect, secret optional', () => {
|
||||
const cfg = readServerConfig({
|
||||
SMART_CLIENT_ID: 'id',
|
||||
SMART_REDIRECT_URI: 'https://x/cb',
|
||||
});
|
||||
expect(cfg.clientId).toBe('id');
|
||||
expect(cfg.clientSecret).toBe(''); // public app
|
||||
expect(cfg.port).toBe(8791);
|
||||
});
|
||||
it('reads the confidential secret when present', () => {
|
||||
const cfg = readServerConfig({
|
||||
SMART_CLIENT_ID: 'id',
|
||||
SMART_REDIRECT_URI: 'https://x/cb',
|
||||
SMART_CLIENT_SECRET: 's',
|
||||
PORT: '9000',
|
||||
SESSION_TTL_SECONDS: '600',
|
||||
});
|
||||
expect(cfg.clientSecret).toBe('s');
|
||||
expect(cfg.port).toBe(9000);
|
||||
expect(cfg.sessionTtlMs).toBe(600_000);
|
||||
});
|
||||
it('throws listing every missing required var', () => {
|
||||
expect(() => readServerConfig({})).toThrow(/SMART_CLIENT_ID.*SMART_REDIRECT_URI/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discoverSmart', () => {
|
||||
it('fetches the well-known and returns the endpoints', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(
|
||||
res(200, { authorization_endpoint: `${BASE}/auth`, token_endpoint: `${BASE}/token` }),
|
||||
);
|
||||
const cfg = await discoverSmart(BASE, doFetch);
|
||||
expect(cfg.authorizationEndpoint).toBe(`${BASE}/auth`);
|
||||
expect(doFetch.mock.calls[0][0]).toBe(`${BASE}/.well-known/smart-configuration`);
|
||||
});
|
||||
|
||||
it('rejects a non-http(s) iss (SSRF guard)', async () => {
|
||||
await expect(discoverSmart('file:///etc/passwd')).rejects.toThrow(/http/);
|
||||
await expect(discoverSmart('not-a-url')).rejects.toThrow(/valid URL/);
|
||||
});
|
||||
|
||||
it('surfaces a discovery failure', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(res(404, {}));
|
||||
await expect(discoverSmart(BASE, doFetch)).rejects.toThrow(/discovery 404/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exchangeCode (server-side secret + PKCE)', () => {
|
||||
it('POSTs the exchange and parses the SMART context', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(
|
||||
res(200, { access_token: 'AT', refresh_token: 'RT', expires_in: 3600, patient: 'P-1', scope: 's' }),
|
||||
);
|
||||
const pending = { state: 'st', codeVerifier: 'ver', tokenEndpoint: `${BASE}/token`, fhirBase: BASE };
|
||||
const ctx = await exchangeCode(CFG, pending, 'the-code', doFetch);
|
||||
expect(ctx.accessToken).toBe('AT');
|
||||
expect(ctx.patient).toBe('P-1');
|
||||
const [url, init] = doFetch.mock.calls[0];
|
||||
expect(url).toBe(`${BASE}/token`);
|
||||
const body = new URLSearchParams(init.body);
|
||||
expect(body.get('code')).toBe('the-code');
|
||||
expect(body.get('code_verifier')).toBe('ver');
|
||||
expect(body.get('client_secret')).toBe('shh'); // confidential
|
||||
});
|
||||
|
||||
it('surfaces an OAuth error from the token endpoint', async () => {
|
||||
const doFetch = vi.fn().mockResolvedValue(res(400, { error: 'invalid_grant', error_description: 'bad code' }));
|
||||
const pending = { state: 'st', codeVerifier: 'ver', tokenEndpoint: `${BASE}/token`, fhirBase: BASE };
|
||||
await expect(exchangeCode(CFG, pending, 'x', doFetch)).rejects.toThrow(/bad code/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensureFreshToken', () => {
|
||||
const base = (expiresAt: number, refresh = 'RT'): SmartContext => ({
|
||||
accessToken: 'OLD',
|
||||
refreshToken: refresh,
|
||||
tokenType: 'Bearer',
|
||||
expiresAt,
|
||||
patient: 'P-1',
|
||||
encounter: '',
|
||||
scope: 's',
|
||||
idToken: '',
|
||||
fhirBase: '',
|
||||
});
|
||||
|
||||
it('returns the live token when not near expiry', async () => {
|
||||
const store = memoryStore();
|
||||
const sess = { ctx: base(Date.now() + 3_600_000), fhirBase: BASE, tokenEndpoint: `${BASE}/token` };
|
||||
const doFetch = vi.fn();
|
||||
expect(await ensureFreshToken(CFG, store, 'sid', sess, doFetch)).toBe('OLD');
|
||||
expect(doFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refreshes an expired token and keeps the old refresh_token/patient', async () => {
|
||||
const store = memoryStore();
|
||||
store.putSession('sid', base(0), BASE, `${BASE}/token`);
|
||||
const sess = store.getSession('sid')!;
|
||||
const doFetch = vi.fn().mockResolvedValue(res(200, { access_token: 'NEW', expires_in: 3600 }));
|
||||
const token = await ensureFreshToken(CFG, store, 'sid', sess, doFetch);
|
||||
expect(token).toBe('NEW');
|
||||
const updated = store.getSession('sid')!;
|
||||
expect(updated.ctx.accessToken).toBe('NEW');
|
||||
expect(updated.ctx.refreshToken).toBe('RT'); // preserved
|
||||
expect(updated.ctx.patient).toBe('P-1'); // preserved
|
||||
});
|
||||
|
||||
it('does not refresh when there is no refresh_token', async () => {
|
||||
const store = memoryStore();
|
||||
const sess = { ctx: base(0, ''), fhirBase: BASE, tokenEndpoint: `${BASE}/token` };
|
||||
const doFetch = vi.fn();
|
||||
expect(await ensureFreshToken(CFG, store, 'sid', sess, doFetch)).toBe('OLD');
|
||||
expect(doFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveProxyTarget (the PHI proxy guard)', () => {
|
||||
it('resolves a relative allowed resource under the session base', () => {
|
||||
expect(resolveProxyTarget(BASE, `Condition?patient=P-1&_count=50`)).toBe(
|
||||
`${BASE}/Condition?patient=P-1&_count=50`,
|
||||
);
|
||||
expect(resolveProxyTarget(BASE, 'Patient/P-1')).toBe(`${BASE}/Patient/P-1`);
|
||||
});
|
||||
|
||||
it('accepts an absolute next-page URL under the same base', () => {
|
||||
const next = `${BASE}/Observation?patient=P-1&_getpages=abc`;
|
||||
expect(resolveProxyTarget(BASE, next)).toBe(next);
|
||||
});
|
||||
|
||||
it('refuses a resource type outside the read scopes', () => {
|
||||
expect(() => resolveProxyTarget(BASE, 'Appointment?patient=P-1')).toThrow(/not permitted/);
|
||||
expect(() => resolveProxyTarget(BASE, 'metadata')).toThrow(/not permitted/);
|
||||
});
|
||||
|
||||
it('refuses a path that escapes the session FHIR base (SSRF / cross-tenant)', () => {
|
||||
expect(() => resolveProxyTarget(BASE, 'https://evil.example.com/Condition')).toThrow(/escapes/);
|
||||
expect(() => resolveProxyTarget(BASE, 'https://fhir.example.org/OTHER/Condition')).toThrow(/escapes/);
|
||||
});
|
||||
|
||||
it('refuses a malformed path', () => {
|
||||
expect(() => resolveProxyTarget(BASE, 'http://')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('session store + cookie', () => {
|
||||
it('takePending is single-use (defends against state replay)', () => {
|
||||
const store = memoryStore();
|
||||
store.putPending({ state: 'st', codeVerifier: 'v', tokenEndpoint: 't', fhirBase: BASE });
|
||||
expect(store.takePending('st')).toBeDefined();
|
||||
expect(store.takePending('st')).toBeUndefined(); // replay yields nothing
|
||||
});
|
||||
|
||||
it('readSid extracts the opaque session id from the cookie header', () => {
|
||||
expect(readSid('foo=bar; epic_sid=abc123; baz=qux')).toBe('abc123');
|
||||
expect(readSid('epic_sid=only')).toBe('only');
|
||||
expect(readSid(undefined)).toBe('');
|
||||
expect(readSid('no_session_here=1')).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createHash, createHmac } from 'node:crypto';
|
||||
import {
|
||||
parseSmartConfiguration,
|
||||
base64urlEncode,
|
||||
randomVerifier,
|
||||
challengeFromVerifier,
|
||||
createPkce,
|
||||
authorizeUrl,
|
||||
tokenExchange,
|
||||
tokenRefresh,
|
||||
parseTokenResponse,
|
||||
isExpired,
|
||||
parseLaunch,
|
||||
parseCallback,
|
||||
} from '../src/smart-oauth.js';
|
||||
|
||||
// A deterministic SHA-256 that matches the browser subtle.digest contract, so
|
||||
// the PKCE challenge is verifiable in a plain node test.
|
||||
const nodeSha256 = async (input: string): Promise<Uint8Array> =>
|
||||
new Uint8Array(createHash('sha256').update(input, 'utf8').digest());
|
||||
|
||||
describe('smart discovery', () => {
|
||||
it('extracts authorize + token endpoints', () => {
|
||||
const cfg = parseSmartConfiguration({
|
||||
authorization_endpoint: 'https://ehr/auth',
|
||||
token_endpoint: 'https://ehr/token',
|
||||
capabilities: ['launch-ehr', 'client-confidential-symmetric'],
|
||||
scopes_supported: ['openid', 'patient/Patient.read'],
|
||||
});
|
||||
expect(cfg.authorizationEndpoint).toBe('https://ehr/auth');
|
||||
expect(cfg.tokenEndpoint).toBe('https://ehr/token');
|
||||
expect(cfg.capabilities).toContain('launch-ehr');
|
||||
expect(cfg.scopesSupported).toContain('patient/Patient.read');
|
||||
});
|
||||
|
||||
it('throws when the authorize endpoint is missing', () => {
|
||||
expect(() => parseSmartConfiguration({ token_endpoint: 'https://ehr/token' })).toThrow(
|
||||
/authorization_endpoint/,
|
||||
);
|
||||
});
|
||||
it('throws when the token endpoint is missing', () => {
|
||||
expect(() => parseSmartConfiguration({ authorization_endpoint: 'https://ehr/auth' })).toThrow(
|
||||
/token_endpoint/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('PKCE', () => {
|
||||
it('base64url has no +/= characters', () => {
|
||||
const enc = base64urlEncode(new Uint8Array([251, 255, 191, 0, 62, 63]));
|
||||
expect(enc).not.toMatch(/[+/=]/);
|
||||
});
|
||||
|
||||
it('randomVerifier uses the injected randomness and is base64url', () => {
|
||||
const bytes = new Uint8Array(32).fill(7);
|
||||
const v = randomVerifier(() => bytes);
|
||||
expect(v).toBe(base64urlEncode(bytes));
|
||||
expect(v).not.toMatch(/[+/=]/);
|
||||
// 32 bytes → 43 base64url chars (within the RFC 7636 43..128 range).
|
||||
expect(v.length).toBe(43);
|
||||
});
|
||||
|
||||
it('challenge = base64url(sha256(verifier)) — S256', async () => {
|
||||
const verifier = 'test-verifier-value';
|
||||
const challenge = await challengeFromVerifier(verifier, nodeSha256);
|
||||
const expected = base64urlEncode(await nodeSha256(verifier));
|
||||
expect(challenge).toBe(expected);
|
||||
// Cross-check against the RFC 7636 canonical construction.
|
||||
const rfc = createHash('sha256')
|
||||
.update(verifier)
|
||||
.digest('base64')
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
expect(challenge).toBe(rfc);
|
||||
});
|
||||
|
||||
it('createPkce returns a verifier + matching S256 challenge', async () => {
|
||||
const bytes = new Uint8Array(32).fill(9);
|
||||
const pkce = await createPkce(() => bytes, nodeSha256);
|
||||
expect(pkce.method).toBe('S256');
|
||||
expect(pkce.verifier).toBe(base64urlEncode(bytes));
|
||||
expect(pkce.challenge).toBe(await challengeFromVerifier(pkce.verifier, nodeSha256));
|
||||
});
|
||||
});
|
||||
|
||||
describe('authorize URL', () => {
|
||||
const base = {
|
||||
authorizationEndpoint: 'https://ehr/auth',
|
||||
clientId: 'my-client',
|
||||
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
|
||||
aud: 'https://fhir/r4',
|
||||
scope: 'launch openid patient/Patient.read',
|
||||
state: 'st-123',
|
||||
codeChallenge: 'chal-abc',
|
||||
};
|
||||
|
||||
it('carries response_type, PKCE, aud and scope', () => {
|
||||
const u = new URL(authorizeUrl(base));
|
||||
expect(u.origin + u.pathname).toBe('https://ehr/auth');
|
||||
const p = u.searchParams;
|
||||
expect(p.get('response_type')).toBe('code');
|
||||
expect(p.get('client_id')).toBe('my-client');
|
||||
expect(p.get('redirect_uri')).toBe('https://epic.hanzo.ai/oauth/callback');
|
||||
expect(p.get('aud')).toBe('https://fhir/r4');
|
||||
expect(p.get('scope')).toBe('launch openid patient/Patient.read');
|
||||
expect(p.get('state')).toBe('st-123');
|
||||
expect(p.get('code_challenge')).toBe('chal-abc');
|
||||
expect(p.get('code_challenge_method')).toBe('S256');
|
||||
});
|
||||
|
||||
it('includes launch for an EHR launch and omits it standalone', () => {
|
||||
expect(new URL(authorizeUrl({ ...base, launch: 'lt-9' })).searchParams.get('launch')).toBe('lt-9');
|
||||
expect(new URL(authorizeUrl(base)).searchParams.has('launch')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('token exchange shaping', () => {
|
||||
it('shapes a confidential auth-code exchange with PKCE verifier + secret', () => {
|
||||
const req = tokenExchange({
|
||||
tokenEndpoint: 'https://ehr/token',
|
||||
clientId: 'my-client',
|
||||
redirectUri: 'https://epic.hanzo.ai/oauth/callback',
|
||||
code: 'auth-code',
|
||||
codeVerifier: 'the-verifier',
|
||||
clientSecret: 'shh',
|
||||
});
|
||||
expect(req.url).toBe('https://ehr/token');
|
||||
expect(req.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
|
||||
const body = new URLSearchParams(req.body);
|
||||
expect(body.get('grant_type')).toBe('authorization_code');
|
||||
expect(body.get('code')).toBe('auth-code');
|
||||
expect(body.get('redirect_uri')).toBe('https://epic.hanzo.ai/oauth/callback');
|
||||
expect(body.get('client_id')).toBe('my-client');
|
||||
expect(body.get('code_verifier')).toBe('the-verifier');
|
||||
expect(body.get('client_secret')).toBe('shh');
|
||||
});
|
||||
|
||||
it('omits client_secret for a public (PKCE-only) app', () => {
|
||||
const req = tokenExchange({
|
||||
tokenEndpoint: 'https://ehr/token',
|
||||
clientId: 'pub',
|
||||
redirectUri: 'https://x/cb',
|
||||
code: 'c',
|
||||
codeVerifier: 'v',
|
||||
});
|
||||
expect(new URLSearchParams(req.body).has('client_secret')).toBe(false);
|
||||
// PKCE verifier is ALWAYS present — a public app depends on it.
|
||||
expect(new URLSearchParams(req.body).get('code_verifier')).toBe('v');
|
||||
});
|
||||
|
||||
it('shapes a refresh with the stored refresh_token', () => {
|
||||
const req = tokenRefresh({
|
||||
tokenEndpoint: 'https://ehr/token',
|
||||
clientId: 'my-client',
|
||||
refreshToken: 'rt-1',
|
||||
clientSecret: 'shh',
|
||||
});
|
||||
const body = new URLSearchParams(req.body);
|
||||
expect(body.get('grant_type')).toBe('refresh_token');
|
||||
expect(body.get('refresh_token')).toBe('rt-1');
|
||||
expect(body.get('client_id')).toBe('my-client');
|
||||
expect(body.get('client_secret')).toBe('shh');
|
||||
});
|
||||
});
|
||||
|
||||
describe('token response → SMART context', () => {
|
||||
it('parses tokens + patient context and computes absolute expiry', () => {
|
||||
const now = 1_000_000;
|
||||
const ctx = parseTokenResponse(
|
||||
{
|
||||
access_token: 'AT',
|
||||
refresh_token: 'RT',
|
||||
token_type: 'Bearer',
|
||||
expires_in: 3600,
|
||||
scope: 'launch patient/Patient.read',
|
||||
patient: 'Patient-42',
|
||||
encounter: 'Enc-7',
|
||||
id_token: 'IDT',
|
||||
},
|
||||
now,
|
||||
);
|
||||
expect(ctx.accessToken).toBe('AT');
|
||||
expect(ctx.refreshToken).toBe('RT');
|
||||
expect(ctx.tokenType).toBe('Bearer');
|
||||
expect(ctx.expiresAt).toBe(now + 3600 * 1000);
|
||||
expect(ctx.patient).toBe('Patient-42');
|
||||
expect(ctx.encounter).toBe('Enc-7');
|
||||
expect(ctx.scope).toBe('launch patient/Patient.read');
|
||||
expect(ctx.idToken).toBe('IDT');
|
||||
});
|
||||
|
||||
it('defaults missing optionals to empty strings', () => {
|
||||
const ctx = parseTokenResponse({ access_token: 'AT', expires_in: 300 }, 0);
|
||||
expect(ctx.refreshToken).toBe('');
|
||||
expect(ctx.patient).toBe('');
|
||||
expect(ctx.encounter).toBe('');
|
||||
expect(ctx.tokenType).toBe('Bearer');
|
||||
});
|
||||
|
||||
it('throws on an OAuth error payload with the real reason', () => {
|
||||
expect(() =>
|
||||
parseTokenResponse({ error: 'invalid_grant', error_description: 'code expired' }),
|
||||
).toThrow(/code expired/);
|
||||
});
|
||||
|
||||
it('throws when there is no access_token', () => {
|
||||
expect(() => parseTokenResponse({ token_type: 'Bearer' })).toThrow(/no access_token/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isExpired', () => {
|
||||
it('is true at/after expiry (minus skew) and false before', () => {
|
||||
expect(isExpired({ expiresAt: 100_000 }, 0, 60_000)).toBe(false); // well before
|
||||
expect(isExpired({ expiresAt: 100_000 }, 50_000, 60_000)).toBe(true); // within skew window
|
||||
expect(isExpired({ expiresAt: 100_000 }, 100_001, 60_000)).toBe(true); // past expiry
|
||||
expect(isExpired({ expiresAt: 100_000 }, 39_999, 60_000)).toBe(false); // just before the skew window
|
||||
});
|
||||
});
|
||||
|
||||
describe('launch + callback parsing', () => {
|
||||
it('parses an EHR launch (iss + launch)', () => {
|
||||
const l = parseLaunch('?iss=https%3A%2F%2Ffhir%2Fr4&launch=xyz');
|
||||
expect(l.iss).toBe('https://fhir/r4');
|
||||
expect(l.launch).toBe('xyz');
|
||||
});
|
||||
it('tolerates a cold open (no params)', () => {
|
||||
const l = parseLaunch('');
|
||||
expect(l.iss).toBe('');
|
||||
expect(l.launch).toBe('');
|
||||
});
|
||||
it('parses a success callback', () => {
|
||||
const c = parseCallback('?code=abc&state=st');
|
||||
expect(c.code).toBe('abc');
|
||||
expect(c.state).toBe('st');
|
||||
expect(c.error).toBe('');
|
||||
});
|
||||
it('parses a declined callback with a reason', () => {
|
||||
const c = parseCallback('?error=access_denied&error_description=user%20declined');
|
||||
expect(c.error).toBe('access_denied');
|
||||
expect(c.errorDescription).toBe('user declined');
|
||||
expect(c.code).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
// Guard: the module must not accidentally depend on hmac/secret material for
|
||||
// PKCE (a common wrong turn). PKCE is a plain hash — this asserts the intent.
|
||||
describe('PKCE is a plain SHA-256, not an HMAC', () => {
|
||||
it('challenge does not match an HMAC construction', async () => {
|
||||
const verifier = 'v';
|
||||
const challenge = await challengeFromVerifier(verifier, nodeSha256);
|
||||
const hmac = createHmac('sha256', 'anykey').update(verifier).digest('base64url');
|
||||
expect(challenge).not.toBe(hmac);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"types": ["node"],
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "test/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['test/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
Generated
+22
@@ -338,6 +338,28 @@ importers:
|
||||
specifier: ^7.0.1
|
||||
version: 7.0.1
|
||||
|
||||
packages/epic:
|
||||
dependencies:
|
||||
'@hanzo/ai':
|
||||
specifier: ^0.2.0
|
||||
version: 0.2.0
|
||||
'@hanzo/iam':
|
||||
specifier: 0.13.2
|
||||
version: 0.13.2(react@19.2.7)
|
||||
devDependencies:
|
||||
'@types/node':
|
||||
specifier: ^20.14.0
|
||||
version: 20.19.9
|
||||
esbuild:
|
||||
specifier: ^0.25.8
|
||||
version: 0.25.8
|
||||
typescript:
|
||||
specifier: ^5.8.3
|
||||
version: 5.8.3
|
||||
vitest:
|
||||
specifier: ^3.2.6
|
||||
version: 3.2.6(@types/node@20.19.9)(jsdom@26.1.0)(sass@1.60.0)(terser@5.43.1)
|
||||
|
||||
packages/figma:
|
||||
dependencies:
|
||||
'@hanzo/ai':
|
||||
|
||||
@@ -7,6 +7,7 @@ packages:
|
||||
- 'packages/clio'
|
||||
- 'packages/desktop'
|
||||
- 'packages/docusign'
|
||||
- 'packages/epic'
|
||||
- 'packages/dxt'
|
||||
- 'packages/figma'
|
||||
- 'packages/github'
|
||||
|
||||
Reference in New Issue
Block a user