feat(fhir): read-only FHIR R4 REST search routes

GET /api/fhir/{metadata,Patient,Observation,MedicationStatement,
MedicationAdministration} and $everything, returning type:"searchset"
Bundles (total + self/next links, offset paging via _count clamped to 200)
as application/fhir+json, with an OperationOutcome on error. The per-resource
emitters are reused from src/lib/fhir/resources.ts so the document export and
the REST face share one coding source and can never drift. Auth is a narrow
fhir:read scope via requireAuth (cookie sessions also pass); userId is
narrowed from auth. Read-only — no write handlers. Rate-limited per user.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.8 committed 2026-06-04 01:05:06 +02:00
1 parent 6c3b8be099
commit 57b8fd8ad9
10 files changed
+809

No files matched your search

+190
View File
@@ -0,0 +1,190 @@
/**
* v1.11.0 — shared helpers for the read-only FHIR R4 REST face.
*
* The `GET /api/fhir/*` search routes are thin: each resolves the caller's own
* `DoctorReportData` (the SAME aggregator the PDF + document export consume),
* runs the matching shared emitter from `./resources`, then wraps the result
* in a `type: "searchset"` Bundle via the helpers here. Keeping the bundling,
* paging, content-type and `OperationOutcome` shaping in one place means every
* resource endpoint answers identically.
*
* Read-only: there are no write handlers anywhere under `/api/fhir`. Auth is a
* narrow `fhir:read` Bearer scope (cookie sessions also pass); `userId` is
* always narrowed from the auth context, never accepted from the wire.
*/
import { NextResponse } from "next/server";
import { decrypt } from "@/lib/crypto";
import { prisma } from "@/lib/db";
import {
collectDoctorReportData,
normaliseDateRange,
type DoctorReportData,
} from "@/lib/doctor-report-data";
import { GERMAN_ATC_DEFAULT_LOCALES } from "@/lib/fhir/resources";
import type {
FhirBundleEntry,
FhirBundleLink,
FhirOperationOutcome,
FhirResource,
FhirSearchsetBundle,
} from "@/lib/fhir/types";
/** The Bearer scope a narrow-scoped token must carry to read the FHIR face. */
export const FHIR_READ_SCOPE = "fhir:read";
/** Canonical FHIR media type for every response (success or outcome). */
export const FHIR_CONTENT_TYPE = "application/fhir+json; charset=utf-8";
/** Default page size; clamped to `[1, MAX_COUNT]`. */
export const DEFAULT_COUNT = 50;
/** Hard ceiling on `_count` so a single search can never page the whole store. */
export const MAX_COUNT = 200;
/**
* Parsed + clamped paging parameters. `count` is bounded to `[1, MAX_COUNT]`;
* `offset` floors at 0. A non-numeric / negative input collapses to the
* default rather than erroring — FHIR search is forgiving on paging params.
*/
export function parsePaging(searchParams: URLSearchParams): {
count: number;
offset: number;
} {
const rawCount = Number(searchParams.get("_count"));
const count =
Number.isFinite(rawCount) && rawCount > 0
? Math.min(Math.floor(rawCount), MAX_COUNT)
: DEFAULT_COUNT;
const rawOffset = Number(searchParams.get("_offset"));
const offset =
Number.isFinite(rawOffset) && rawOffset > 0 ? Math.floor(rawOffset) : 0;
return { count, offset };
}
/**
* Build the absolute self link, and a next link when more rows remain. The
* URL is rebuilt from the request URL with the paging params normalised, so
* the echoed link always carries the clamped `_count` and concrete `_offset`.
*/
function pagingLinks(
requestUrl: URL,
total: number,
count: number,
offset: number,
): FhirBundleLink[] {
const self = new URL(requestUrl.toString());
self.searchParams.set("_count", String(count));
self.searchParams.set("_offset", String(offset));
const links: FhirBundleLink[] = [{ relation: "self", url: self.toString() }];
const nextOffset = offset + count;
if (nextOffset < total) {
const next = new URL(requestUrl.toString());
next.searchParams.set("_count", String(count));
next.searchParams.set("_offset", String(nextOffset));
links.push({ relation: "next", url: next.toString() });
}
return links;
}
/**
* Wrap a page of resources in a `searchset` Bundle and return it as a FHIR
* JSON response. `total` is the FULL unpaged match count; `page` is the
* already-sliced window. Each entry is tagged `search.mode: "match"`.
*/
export function searchsetResponse(
requestUrl: URL,
page: FhirResource[],
total: number,
count: number,
offset: number,
): NextResponse {
const entry: FhirBundleEntry[] = page.map((resource) => ({
fullUrl: `${requestUrl.origin}/api/fhir/${resource.resourceType}/${resource.id}`,
resource,
search: { mode: "match" },
}));
const bundle: FhirSearchsetBundle = {
resourceType: "Bundle",
type: "searchset",
timestamp: new Date().toISOString(),
total,
link: pagingLinks(requestUrl, total, count, offset),
entry,
};
return new NextResponse(JSON.stringify(bundle), {
status: 200,
headers: { "Content-Type": FHIR_CONTENT_TYPE, "Cache-Control": "no-store" },
});
}
/** Return a raw FHIR resource (e.g. CapabilityStatement) as a FHIR response. */
export function fhirJsonResponse(body: unknown): NextResponse {
return new NextResponse(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": FHIR_CONTENT_TYPE, "Cache-Control": "no-store" },
});
}
/**
* Build an `OperationOutcome` JSON response — the FHIR error envelope. Used
* for 404 (no such resource) and any other FHIR-shaped error the routes
* surface. (Auth 401/403 stay on the standard envelope via `requireAuth`.)
*/
export function operationOutcome(
status: number,
code: string,
diagnostics: string,
severity: FhirOperationOutcome["issue"][number]["severity"] = "error",
): NextResponse {
const outcome: FhirOperationOutcome = {
resourceType: "OperationOutcome",
issue: [{ severity, code, diagnostics }],
};
return new NextResponse(JSON.stringify(outcome), {
status,
headers: { "Content-Type": FHIR_CONTENT_TYPE, "Cache-Control": "no-store" },
});
}
/**
* Resolve everything an emitter needs for a caller: the aggregated report data
* over the default reporting window, plus the decrypted KVNR identity and the
* BfArM-ATC flag (derived from the user's locale). Centralised so each
* resource route is a one-liner over the shared emitters.
*
* The window matches the document export's default (`normaliseDateRange`
* with no override). KVNR decryption is fail-soft: a key-rotation gap on a
* single row omits the identifier rather than 500-ing the read.
*/
export async function loadFhirContext(userId: string): Promise<{
data: DoctorReportData;
identity: { insuranceNumber: string | null };
germanAtc: boolean;
}> {
const range = normaliseDateRange(undefined);
const [data, userRow] = await Promise.all([
collectDoctorReportData(userId, range, {}),
prisma.user.findUnique({
where: { id: userId },
select: { insuranceNumberEncrypted: true, locale: true },
}),
]);
let insuranceNumber: string | null = null;
if (userRow?.insuranceNumberEncrypted) {
try {
insuranceNumber = decrypt(userRow.insuranceNumberEncrypted);
} catch {
insuranceNumber = null;
}
}
const germanAtc = (GERMAN_ATC_DEFAULT_LOCALES as readonly string[]).includes(
userRow?.locale ?? "",
);
return { data, identity: { insuranceNumber }, germanAtc };
}
+35
View File
@@ -203,6 +203,8 @@ export type FhirResource =
export interface FhirBundleEntry {
fullUrl?: string;
resource: FhirResource;
/** v1.11.0 — `searchset` per-entry search metadata (`mode: "match"`). */
search?: { mode: "match" | "include" | "outcome" };
}
export interface FhirBundle {
@@ -211,3 +213,36 @@ export interface FhirBundle {
timestamp: string;
entry: FhirBundleEntry[];
}
/** v1.11.0 — `Bundle.link` relation (self / next paging). */
export interface FhirBundleLink {
relation: "self" | "next";
url: string;
}
/**
* v1.11.0 — a `searchset` Bundle, the wire shape the FHIR REST search routes
* return. `total` is the unpaged match count; `link` carries the self + next
* relations for offset paging; each `entry.search.mode` is `"match"`.
*/
export interface FhirSearchsetBundle {
resourceType: "Bundle";
type: "searchset";
timestamp: string;
total: number;
link?: FhirBundleLink[];
entry: FhirBundleEntry[];
}
/** v1.11.0 — `OperationOutcome.issue` element. */
export interface FhirOperationOutcomeIssue {
severity: "fatal" | "error" | "warning" | "information";
code: string;
diagnostics?: string;
}
/** v1.11.0 — `OperationOutcome`, the FHIR error envelope. */
export interface FhirOperationOutcome {
resourceType: "OperationOutcome";
issue: FhirOperationOutcomeIssue[];
}
+144
View File
@@ -2102,6 +2102,150 @@ export const openApiPaths: NonNullable<ZodOpenApiObject["paths"]> = {
},
},
},
"/api/fhir/metadata": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 CapabilityStatement (v1.11.0)",
description:
"Read-only FHIR R4 capability statement for the REST face. Declares the served resource types (Patient, Observation, MedicationStatement, MedicationAdministration), the `$everything` operation, and the `application/fhir+json` format. Auth: `fhir:read` scope (cookie sessions also pass).",
responses: {
"200": {
description: "CapabilityStatement (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/fhir/Patient": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 Patient search (v1.11.0)",
description:
"Read-only `searchset` Bundle of the caller's own Patient resource. Auth: `fhir:read` scope. Offset paging via `_count` (clamped ≤200) / `_offset`. `userId` is narrowed from auth.",
requestParams: {
query: z.object({
_count: z.coerce.number().optional(),
_offset: z.coerce.number().optional(),
}),
},
responses: {
"200": {
description: "searchset Bundle (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/fhir/Observation": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 Observation search (v1.11.0)",
description:
"Read-only `searchset` Bundle of the caller's own Observations (vitals / activity / lab / survey). Auth: `fhir:read` scope. Offset paging via `_count` (clamped ≤200) / `_offset`.",
requestParams: {
query: z.object({
_count: z.coerce.number().optional(),
_offset: z.coerce.number().optional(),
}),
},
responses: {
"200": {
description: "searchset Bundle (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/fhir/MedicationStatement": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 MedicationStatement search (v1.11.0)",
description:
"Read-only `searchset` Bundle of the caller's own active-medication statements. Auth: `fhir:read` scope. Offset paging via `_count` (≤200) / `_offset`.",
requestParams: {
query: z.object({
_count: z.coerce.number().optional(),
_offset: z.coerce.number().optional(),
}),
},
responses: {
"200": {
description: "searchset Bundle (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/fhir/MedicationAdministration": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 MedicationAdministration search (v1.11.0)",
description:
"Read-only `searchset` Bundle of the caller's own acted intakes (completed / not-done). Auth: `fhir:read` scope. Offset paging via `_count` (≤200) / `_offset`.",
requestParams: {
query: z.object({
_count: z.coerce.number().optional(),
_offset: z.coerce.number().optional(),
}),
},
responses: {
"200": {
description: "searchset Bundle (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/fhir/$everything": {
get: {
tags: ["FHIR"],
summary: "FHIR R4 $everything (v1.11.0)",
description:
"Read-only `$everything` operation: every resource in the caller's own record (Patient, Coverage, Observations, MedicationStatements, MedicationAdministrations) in one `searchset` Bundle. Auth: `fhir:read` scope. Offset paging via `_count` (≤200) / `_offset`.",
requestParams: {
query: z.object({
_count: z.coerce.number().optional(),
_offset: z.coerce.number().optional(),
}),
},
responses: {
"200": {
description: "searchset Bundle (application/fhir+json).",
content: {
"application/fhir+json": {
schema: z.string().meta({ format: "binary" }),
},
},
},
...stdResponses,
},
},
},
"/api/auth/login": {
post: {
tags: ["Auth"],