Package 'dicomtk.server'

Title: Multi-User Server, Honest Broker Custody, and Event Routing for 'DICOM'
Description: Multi-user research server and honest-broker custody satellite for 'dicomtk'. Provides eight-role OpenID Connect ('OIDC') and 'Keycloak' role-based access control ('RBAC'), a tamper-evident SHA-256 hash-chained JSONL audit trail, a walled-off honest-broker key and crosswalk custody enclave with two-person ('honest_broker' and 'dpo') re-identification approval, 'mirai' asynchronous job queues, 3D segmentation quality assurance ('Dice', 'HD95', and surface 'Dice'), 'MONAI Label' active learning, event-driven routing, and 'plumber' REST and 'shiny' clinician portal interfaces.
Authors: Yee How Lau [aut, cre, cph]
Maintainer: Yee How Lau <[email protected]>
License: GPL (>= 2)
Version: 1.0.0
Built: 2026-11-14 15:53:59 UTC
Source: https://github.com/lauyeehow1986-hub/dicomtk.server

Help Index


Add an Unlabeled Study Candidate to the Active Learning Pool

Description

Add an Unlabeled Study Candidate to the Active Learning Pool

Usage

active_learning_add_candidate(
  pool,
  project_id,
  study_uid,
  uncertainty_score = 0.5,
  metadata = list()
)

Arguments

pool

A "dicom_active_learning_pool" object.

project_id

Project identifier.

study_uid

StudyInstanceUID string.

uncertainty_score

Model uncertainty score in ⁠[0, 1]⁠.

metadata

Optional named list of study metadata.

Value

Candidate record list.


Select Next Candidate(s) for Annotation

Description

Select Next Candidate(s) for Annotation

Usage

active_learning_next(pool, project_id = NULL, n = 1L)

Arguments

pool

A "dicom_active_learning_pool" object.

project_id

Optional project filter.

n

Maximum number of candidates to return (default 1L).

Value

A tibble::tibble of prioritized unlabeled candidates.


Initialize a MONAI Label / Active Learning Candidate Pool

Description

Initialize a MONAI Label / Active Learning Candidate Pool

Usage

active_learning_pool_init(
  strategy = c("uncertainty", "fifo", "random"),
  logger = NULL
)

Arguments

strategy

Selection strategy: "uncertainty", "fifo", or "random".

logger

Optional "dicom_audit_logger" for label submission auditing.

Value

An S3 "dicom_active_learning_pool" object.

Examples

pool <- active_learning_pool_init(strategy = "uncertainty")
pool$strategy

Submit a Completed Annotation Label to the Active Learning Pool

Description

Requires "active_learning_submit" capability (annotator).

Usage

active_learning_submit(
  pool,
  principal,
  candidate_id,
  label_path = NULL,
  quality_score = NA_real_
)

Arguments

pool

A "dicom_active_learning_pool" object.

principal

Authenticated "dicom_server_principal".

candidate_id

Candidate identifier from active_learning_add_candidate().

label_path

Optional path to saved segmentation/label file.

quality_score

Optional numeric self-reported quality score.

Value

Updated candidate record list.


Append a Tamper-Evident Entry to the Hash-Chained Audit Log

Description

Append a Tamper-Evident Entry to the Hash-Chained Audit Log

Usage

audit_append(logger, actor, action, project_id = NULL, details = list())

Arguments

logger

A "dicom_audit_logger" object from audit_logger().

actor

Character user/principal identifier.

action

Character action name (e.g., "deid_ingest", "reid_disclose").

project_id

Optional project identifier string.

details

Optional named list of structured event metadata.

Value

The appended audit record list (including prev_hash and entry_hash).


Create or Open a Hash-Chained JSONL Audit Logger

Description

Initializes a tamper-evident JSON Lines (.jsonl) audit log where each appended entry commits to the cryptographic hash of the previous entry (prev_hash -> entry_hash).

Usage

audit_logger(log_path = tempfile("dicomtk_audit_", fileext = ".jsonl"))

Arguments

log_path

Path to the .jsonl audit log file.

Value

An S3 "dicom_audit_logger" object.

Examples

lp <- tempfile(fileext = ".jsonl")
on.exit(unlink(lp), add = TRUE)
lg <- audit_logger(lp)
audit_append(lg, actor = "coord_1", action = "deid_ingest", project_id = "p1")
audit_verify(lg)$passed

Verify Cryptographic Continuity of a Hash-Chained Audit Log

Description

Verify Cryptographic Continuity of a Hash-Chained Audit Log

Usage

audit_verify(logger)

Arguments

logger

A "dicom_audit_logger" object from audit_logger().

Value

A list with passed (logical), n_entries (integer), and corrupted_line (NA_integer_ if valid, or 1-based line index of first failure).


De-Identify a Study Inside the Walled Honest-Broker Workspace

Description

Requires "deid_ingest" capability (coordinator, honest_broker, or admin). Executes dicomtk::dicom_deid() using the enclave's sealed key provider, records the reversible pseudonym_id -> original_patient_id mapping inside the enclave crosswalk, and writes clean de-identified files to out_dir.

Usage

broker_deid_study(
  enclave,
  principal,
  project_id,
  input_dir,
  out_dir,
  profile = "ps3.15"
)

Arguments

enclave

A "dicom_broker_enclave" from broker_enclave_init().

principal

Authenticated "dicom_server_principal".

project_id

Target project identifier.

input_dir

Source directory containing identified DICOM files.

out_dir

Output directory in the research project workspace.

profile

Baseline PS3.15 profile name (default "ps3.15").

Value

A list with project_id, pseudonym_id, out_dir, and n_files.


Initialize a Walled-Off Honest-Broker Key & Crosswalk Custody Enclave

Description

Creates a "dicom_broker_enclave" whose cryptographic master keys, HashiCorp Vault / KMS credentials, and patient-identity crosswalks live inside an isolated internal closure inaccessible to pi, coordinator, annotator, auditor, admin, and site_admin principals.

Usage

broker_enclave_init(
  work_dir = tempfile("broker_enclave_"),
  backend = c("local_vault", "hashicorp_vault", "kms"),
  passphrase = NULL,
  vault_url = NULL,
  vault_token = NULL,
  logger = NULL
)

Arguments

work_dir

Walled broker workspace directory.

backend

Key custody backend: "local_vault", "hashicorp_vault", or "kms".

passphrase

Optional passphrase for "local_vault" key derivation.

vault_url

Optional HashiCorp Vault / KMS endpoint URL.

vault_token

Optional Vault token (never exposed by print/str).

logger

Optional "dicom_audit_logger" from audit_logger().

Value

An opaque S3 "dicom_broker_enclave" handle.


Guarded Crosswalk Lookup (Rejects All Unapproved or Non-Broker Access)

Description

Guarded Crosswalk Lookup (Rejects All Unapproved or Non-Broker Access)

Usage

broker_lookup_crosswalk(enclave, principal, pseudonym_id)

Arguments

enclave

A "dicom_broker_enclave" object.

principal

Authenticated "dicom_server_principal".

pseudonym_id

Pseudonym identifier string.

Value

Never returns for unapproved access; aborts with permission error.


Check Role-Based Access Permission for a Principal

Description

Check Role-Based Access Permission for a Principal

Usage

check_permission(principal, action, project_id = NULL, throw = TRUE)

Arguments

principal

A "dicom_server_principal" from server_principal().

action

Action capability string (e.g., "reid_approve_broker").

project_id

Optional project ID to check project-level scope.

throw

Logical. Abort with permission error if unauthorized (TRUE).

Value

Logical TRUE if authorized, FALSE otherwise (when throw = FALSE).


Check Whether SaMD Clinical Chart Write-Back Is Explicitly Enabled

Description

Clinical write-back (STOW-RS SEG/SR + FHIR DiagnosticReport + Provenance) is disabled by default as a Software as a Medical Device (SaMD) regulatory safeguard. Enable explicitly via options(dicomtk.server.enable_clinical_writeback = TRUE) or environment variable DICOMTK_ENABLE_CLINICAL_WRITEBACK=true.

Usage

clinical_writeback_enabled()

Value

Logical scalar (TRUE if enabled, FALSE otherwise).

Examples

clinical_writeback_enabled()

Execute Dual-Gated SaMD Clinical Chart Write-Back

Description

Enforces both the server-wide SaMD feature flag (clinical_writeback_enabled()) and RBAC "clinical_writeback" permission (pi or admin) before dispatching or simulating STOW-RS and FHIR DiagnosticReport + Provenance write-back, logging every event to the SHA-256 hash-chained audit trail.

Usage

clinical_writeback_execute(
  ctx,
  principal,
  project_id,
  air_bundle,
  dicomweb_stow_url = NULL,
  fhir_base_url = NULL,
  dry_run = FALSE
)

Arguments

ctx

A "dicom_server_context" from server_create_context().

principal

Authenticated "dicom_server_principal".

project_id

Project identifier.

air_bundle

A "dicom_ihe_air_bundle" from ihe_air_bundle().

dicomweb_stow_url

Optional DICOMweb STOW-RS endpoint URL.

fhir_base_url

Optional FHIR R4/R5 base URL for DiagnosticReport and Provenance write-back.

dry_run

Logical; if TRUE, validates gates and logs audit entry without performing external HTTP calls.

Value

A list with status, study_uid, dicom_sop_uid, and audit_seq.


Compute 3D Segmentation QA Metrics (Dice, HD95, Surface Dice)

Description

Compute 3D Segmentation QA Metrics (Dice, HD95, Surface Dice)

Usage

compute_seg_qa(pred_mask, ref_mask, spacing_mm = c(1, 1, 1), tolerance_mm = 1)

Arguments

pred_mask

3D binary/logical predicted mask array.

ref_mask

3D binary/logical reference mask array of identical dims.

spacing_mm

Numeric vector of length 3 giving voxel spacing in mm.

tolerance_mm

Surface Dice tolerance in mm (default 1.0).

Value

A list with dice, hd95_mm, and surface_dice.

Examples

m <- array(0L, dim = c(6L, 6L, 6L))
m[2:4, 2:4, 2:4] <- 1L
compute_seg_qa(m, m)

Construct and Validate an IHE AIR (AI Results) Conformance Bundle

Description

Packages a generated DICOM AI artifact (SEG or SR_TID1500) alongside a FHIR DiagnosticReport and W3C/FHIR Provenance record with model version and uncertainty metadata.

Usage

ihe_air_bundle(
  study_uid,
  model_name,
  model_version,
  dicom_artifact_type = c("SEG", "SR_TID1500"),
  dicom_sop_uid,
  fhir_report = list(),
  uncertainty_summary = list()
)

Arguments

study_uid

StudyInstanceUID string.

model_name

AI model name.

model_version

AI model semantic version string.

dicom_artifact_type

Either "SEG" or "SR_TID1500".

dicom_sop_uid

SOPInstanceUID of the generated DICOM AI object.

fhir_report

Named list of FHIR DiagnosticReport fields.

uncertainty_summary

Named list of model uncertainty metrics.

Value

An S3 "dicom_ihe_air_bundle" object.

Examples

air <- ihe_air_bundle(
  study_uid = "1.2.3.4",
  model_name = "TotalSegmentator",
  model_version = "2.4.0",
  dicom_artifact_type = "SEG",
  dicom_sop_uid = "1.2.3.99"
)
air$provenance$resourceType

Transition an IHE AIW-I Workitem State

Description

Enforces valid UPS-RS state transitions: "SCHEDULED" -> "IN PROGRESS" or "CANCELED"; "IN PROGRESS" -> "COMPLETED" or "CANCELED".

Usage

ihe_aiw_transition(
  workitem,
  to_state = c("IN PROGRESS", "COMPLETED", "CANCELED"),
  performer = NULL,
  output_refs = list()
)

Arguments

workitem

A "dicom_ihe_workitem" from ihe_aiw_workitem().

to_state

Target state: "IN PROGRESS", "COMPLETED", or "CANCELED".

performer

Optional AI worker/performer identifier.

output_refs

Optional named list of generated DICOM SOP UIDs.

Value

Updated "dicom_ihe_workitem" object.


Create an IHE AIW-I (AI Workflow for Imaging) UPS-RS Workitem

Description

Initializes a workitem in the "SCHEDULED" state following the IHE AIW-I Unified Procedure Step (UPS-RS) state machine.

Usage

ihe_aiw_workitem(workitem_id, study_uid, model_name, input_series_uid = NULL)

Arguments

workitem_id

Unique workitem identifier string.

study_uid

StudyInstanceUID string.

model_name

AI model identifier string.

input_series_uid

Optional SeriesInstanceUID string.

Value

An S3 "dicom_ihe_workitem" object.

Examples

wi <- ihe_aiw_workitem("wi-001", study_uid = "1.2.3.4", model_name = "TotalSegmentator")
wi$state

Initialize an Asynchronous or Synchronous Job Queue

Description

Creates a job queue supporting synchronous in-process execution ("sync") or non-blocking parallel worker execution via mirai ("mirai").

Usage

job_queue_init(backend = c("sync", "mirai"), workers = 2L, logger = NULL)

Arguments

backend

Execution backend: "sync" or "mirai".

workers

Number of mirai daemon workers when backend = "mirai".

logger

Optional "dicom_audit_logger" for job submission auditing.

Value

An S3 "dicom_job_queue" object.

Examples

q <- job_queue_init(backend = "sync")
q$backend

Retrieve Job Result

Description

Retrieve Job Result

Usage

job_result(queue, job_id, wait = TRUE)

Arguments

queue

A "dicom_job_queue" object.

job_id

Job identifier returned by job_submit().

wait

Logical; if TRUE and backend is "mirai", blocks until completion.

Value

The return value of the submitted job function.


Query Job Status

Description

Query Job Status

Usage

job_status(queue, job_id)

Arguments

queue

A "dicom_job_queue" object.

job_id

Job identifier returned by job_submit().

Value

A list with job_id, project_id, job_type, and status.


Submit a Job to the Server Job Queue

Description

Requires "job_submit" permission on project_id.

Usage

job_submit(
  queue,
  principal,
  project_id,
  fn,
  args = list(),
  job_type = "generic"
)

Arguments

queue

A "dicom_job_queue" from job_queue_init().

principal

Authenticated "dicom_server_principal".

project_id

Target project identifier.

fn

Function to execute.

args

Named list of arguments passed to fn.

job_type

Short job category string (default "generic").

Value

A list with job_id, project_id, job_type, and status.


Mint a Signed Local Test OIDC JWT Token

Description

Mint a Signed Local Test OIDC JWT Token

Usage

mint_test_jwt(
  user_id,
  roles,
  project_ids = "*",
  secret = "dicomtk-test-secret",
  expires_in = 3600
)

Arguments

user_id

Subject user ID (sub claim).

roles

Character vector of Keycloak realm_access$roles.

project_ids

Character vector of authorized project IDs.

secret

HMAC signing secret.

expires_in

Expiration offset in seconds (default 3600).

Value

A signed compact JWT string (header.payload.signature).


Create or Register a Research Imaging Project

Description

Create or Register a Research Imaging Project

Usage

project_create(
  registry,
  project_id,
  title = project_id,
  deid_profile = "ps3.15",
  custody_mode = c("broker", "ttp", "local")
)

Arguments

registry

A "dicom_project_registry" from project_registry_init().

project_id

Unique project identifier string.

title

Human-readable project title.

deid_profile

Baseline PS3.15 de-identification profile name (default "ps3.15").

custody_mode

Key custody mode: "broker" (default), "ttp", or "local".

Value

A list describing the created project.


Retrieve a Registered Project

Description

Retrieve a Registered Project

Usage

project_get(registry, project_id)

Arguments

registry

A "dicom_project_registry" object.

project_id

Project identifier string.

Value

The project metadata list.


List Registered Projects

Description

List Registered Projects

Usage

project_list(registry)

Arguments

registry

A "dicom_project_registry" object.

Value

A tibble::tibble summarizing registered projects.


Initialize a Multi-Project Server Registry

Description

Initialize a Multi-Project Server Registry

Usage

project_registry_init()

Value

An S3 "dicom_project_registry" object.

Examples

reg <- project_registry_init()
project_create(reg, "nsclc_01", title = "Lung AI")
project_list(reg)

Enqueue a Study or Segmentation into the QA Review Queue

Description

Enqueue a Study or Segmentation into the QA Review Queue

Usage

qa_enqueue(
  qa_queue,
  project_id,
  study_uid,
  pred_mask = NULL,
  ref_mask = NULL,
  spacing_mm = c(1, 1, 1),
  tolerance_mm = 1,
  metrics = NULL,
  priority = "normal"
)

Arguments

qa_queue

A "dicom_qa_queue" object from qa_queue_init().

project_id

Project identifier.

study_uid

StudyInstanceUID string.

pred_mask

Optional 3D predicted mask array.

ref_mask

Optional 3D reference mask array.

spacing_mm

Voxel spacing in mm (default c(1, 1, 1)).

tolerance_mm

Surface Dice tolerance in mm (default 1.0).

metrics

Optional pre-computed list of QA metrics.

priority

Priority label ("normal", "high", "urgent").

Value

Enqueued QA item list.


List QA Queue Items

Description

List QA Queue Items

Usage

qa_list(qa_queue, project_id = NULL, status = NULL)

Arguments

qa_queue

A "dicom_qa_queue" object.

project_id

Optional project filter.

status

Optional status filter ("pending", "approved", etc.).

Value

A tibble::tibble of QA items.


Initialize a QA Review Queue

Description

Initialize a QA Review Queue

Usage

qa_queue_init(logger = NULL)

Arguments

logger

Optional "dicom_audit_logger" for QA review actions.

Value

An S3 "dicom_qa_queue" object.


Submit a QA Review Decision

Description

Requires "qa_review" capability (pi, annotator, or admin).

Usage

qa_submit_review(
  qa_queue,
  principal,
  item_id,
  decision = c("approve", "reject", "revise"),
  notes = NULL
)

Arguments

qa_queue

A "dicom_qa_queue" object.

principal

Authenticated "dicom_server_principal".

item_id

QA item identifier returned by qa_enqueue().

decision

Review decision: "approve", "reject", or "revise".

notes

Optional reviewer notes.

Value

Updated QA item list.


Approve a Re-Identification Request (Two-Person Broker + DPO Rule)

Description

Requires both an honest_broker ("reid_approve_broker") and a distinct dpo ("reid_approve_dpo") principal to approve before disclosure is unlocked.

Usage

reid_approve(enclave, principal, request_id)

Arguments

enclave

A "dicom_broker_enclave" object.

principal

Authenticated "dicom_server_principal" with honest_broker or dpo role.

request_id

Request identifier returned by reid_request().

Value

Updated re-identification request list.


Disclose Original Patient Identity for an Approved Re-Identification Request

Description

Requires "reid_disclose" capability (honest_broker), completed two-person approval, and an unexpired TTL window.

Usage

reid_disclose(enclave, principal, request_id)

Arguments

enclave

A "dicom_broker_enclave" object.

principal

Authenticated "dicom_server_principal" with honest_broker role.

request_id

Request identifier returned by reid_request().

Value

A list containing original_patient_id, pseudonym_id, study_uid, and expires_at.


Request Two-Person Re-Identification of a Pseudonymized Study

Description

Requires "reid_request" capability (pi, coordinator, or honest_broker). Records a pending re-identification request inside the walled honest-broker enclave.

Usage

reid_request(
  enclave,
  principal,
  project_id,
  pseudonym_id,
  reason,
  ttl_seconds = 3600L
)

Arguments

enclave

A "dicom_broker_enclave" object.

principal

Authenticated "dicom_server_principal".

project_id

Project identifier matching the pseudonymized study.

pseudonym_id

Pseudonym identifier recorded in the enclave crosswalk.

reason

Clinical or regulatory justification string.

ttl_seconds

Time-to-live in seconds once both approvals complete (default 3600L).

Value

A list describing the pending re-identification request.


Execute Matching Event-Driven Routing Rules

Description

Requires "routing_run" capability (coordinator, honest_broker, or admin).

Usage

routing_execute(rules, principal, event, logger = NULL)

Arguments

rules

List of "dicom_routing_rule" objects.

principal

Authenticated "dicom_server_principal".

event

Named list with event_type, project_id, modality, and study_uid.

logger

Optional "dicom_audit_logger".

Value

A tibble::tibble summarizing matched and dispatched rules.


Define an Event-Driven Study Routing Rule

Description

Define an Event-Driven Study Routing Rule

Usage

routing_rule(
  rule_id,
  when_modality = NULL,
  when_event = "study_ingested",
  action = c("enqueue_qa", "deid_forward", "notify", "custom"),
  target = NULL,
  handler = NULL
)

Arguments

rule_id

Unique rule identifier string.

when_modality

Optional modality filter (e.g. "CT", "MR").

when_event

Event type filter (default "study_ingested").

action

Action to execute: "enqueue_qa", "deid_forward", "notify", or "custom".

target

Optional target queue/endpoint name.

handler

Optional callback ⁠function(event)⁠ used when action = "custom".

Value

An S3 "dicom_routing_rule" object.

Examples

r <- routing_rule("ct_qa", when_modality = "CT", action = "enqueue_qa", target = "qa_default")
r$rule_id

Create a Multi-User dicomtk.server Runtime Context

Description

Bundles the project registry, SHA-256 hash-chained audit logger, walled-off honest-broker custody enclave, job queue, QA review queue, and active learning pool into a single server context.

Usage

server_create_context(
  work_dir = tempfile("dicomtk_srv_"),
  jwt_secret = "change-me-in-production",
  enclave_passphrase = NULL
)

Arguments

work_dir

Base directory for server state and audit logs.

jwt_secret

Secret key for HS256 JWT verification.

enclave_passphrase

Optional passphrase for the honest-broker enclave.

Value

An S3 "dicom_server_context" object.

Examples

tmp <- tempfile("srv_ctx_")
ctx <- server_create_context(work_dir = tmp, jwt_secret = "demo-secret")
server_handle_request(ctx, "GET", "/health")
unlink(tmp, recursive = TRUE)

Generate a CycloneDX 1.5 Software Bill of Materials (SBOM)

Description

Inspects the installed or source DESCRIPTION of pkg and its R package dependencies to emit a CycloneDX 1.5 JSON Software Bill of Materials with ⁠pkg:cran/⁠ Package URLs (purl).

Usage

server_generate_sbom(pkg = "dicomtk.server", out_path = NULL)

Arguments

pkg

Package name (default "dicomtk.server").

out_path

Optional file path to write the CycloneDX JSON document.

Value

A list representing the CycloneDX 1.5 BOM.

Examples

sbom <- server_generate_sbom("dicomtk.server")
sbom$bomFormat

Dispatch an HTTP-Style Request Against a dicom_server_context

Description

Provides a pure-R, test-friendly REST dispatcher enforcing JWT authentication and RBAC permissions before delegating to server subsystems.

Usage

server_handle_request(
  ctx,
  method = "GET",
  path = "/health",
  headers = list(),
  body = list()
)

Arguments

ctx

A "dicom_server_context" from server_create_context().

method

HTTP method ("GET" or "POST").

path

Request path (e.g. "/health", "/projects", "/qa", "/audit/verify").

headers

Named list of HTTP headers (including Authorization).

body

Named list representing parsed JSON request body.

Value

A list with status (integer HTTP code) and body (response list).


Build a plumber REST Router for dicomtk.server

Description

Build a plumber REST Router for dicomtk.server

Usage

server_plumber_api(ctx)

Arguments

ctx

A "dicom_server_context" object.

Value

A plumber::Plumber router instance.


Construct an Authenticated Server Principal

Description

Construct an Authenticated Server Principal

Usage

server_principal(user_id, roles, project_ids = "*")

Arguments

user_id

Unique user identifier string.

roles

Character vector of roles from server_roles().

project_ids

Character vector of authorized project IDs (or "*" for all).

Value

An S3 "dicom_server_principal" object.


List Standard dicomtk.server RBAC Roles

Description

List Standard dicomtk.server RBAC Roles

Usage

server_roles()

Value

Character vector of the 8 standard server roles.

Examples

server_roles()

Build the shiny Server Function for dicomtk.server

Description

Build the shiny Server Function for dicomtk.server

Usage

server_shiny_server(ctx)

Arguments

ctx

A "dicom_server_context" object.

Value

A shiny server ⁠function(input, output, session)⁠.


Build the shiny Portal UI for dicomtk.server

Description

Build the shiny Portal UI for dicomtk.server

Usage

server_shiny_ui(ctx)

Arguments

ctx

A "dicom_server_context" object.

Value

A shiny UI tag list.


Return the dicomtk.server STRIDE Threat Model Matrix

Description

Documents security threats, architectural mitigations, and automated verification controls across all six STRIDE categories (Spoofing, Tampering, Repudiation, ⁠Information Disclosure⁠, ⁠Denial of Service⁠, and ⁠Elevation of Privilege⁠).

Usage

server_threat_model()

Value

A tibble::tibble describing the threat model.

Examples

tm <- server_threat_model()
tm$stride_category

Generate an HTML5 Zero-Footprint Medical Imaging Viewer Scaffold

Description

Produces a lightweight HTML5 container configured for Cornerstone3D (DICOMweb WADO-RS) or NiiVue (NIfTI / 3D overlay QA).

Usage

server_viewer_html(
  study_uid = "",
  viewer = c("cornerstone3d", "niivue"),
  dicomweb_url = "/dicomweb"
)

Arguments

study_uid

StudyInstanceUID to display.

viewer

Viewer engine: "cornerstone3d" or "niivue".

dicomweb_url

Base DICOMweb endpoint URL.

Value

Character string containing the HTML5 viewer fragment.

Examples

html <- server_viewer_html("1.2.840.113619.2.55", viewer = "cornerstone3d")
grepl("cornerstone3d", html)

Build a SMART on FHIR v2 EHR-Launch Authorization URL

Description

Build a SMART on FHIR v2 EHR-Launch Authorization URL

Usage

smart_build_auth_url(
  config,
  client_id,
  redirect_uri,
  launch = NULL,
  scopes = c("launch", "openid", "fhirUser", "patient/Patient.rs",
    "patient/ImagingStudy.rs", "patient/DiagnosticReport.rs"),
  state = NULL,
  pkce = smart_pkce_challenge()
)

Arguments

config

SMART configuration list from smart_discover_config().

client_id

Registered OAuth2 client identifier.

redirect_uri

Callback redirect URI.

launch

Optional EHR launch context token.

scopes

Character vector of SMART v2 scopes.

state

Optional CSRF state token (auto-generated if NULL).

pkce

PKCE challenge list from smart_pkce_challenge().

Value

A list with url, state, and pkce.


Discover SMART on FHIR v2 Configuration

Description

Queries ⁠<fhir_base_url>/.well-known/smart-configuration⁠ (or validates a supplied mock_config list) and verifies that "S256" PKCE is supported.

Usage

smart_discover_config(fhir_base_url, mock_config = NULL)

Arguments

fhir_base_url

Base URL of the FHIR R4/R5 server.

mock_config

Optional named list for offline/unit testing.

Value

A list with fhir_base_url, authorization_endpoint, token_endpoint, and code_challenge_methods_supported.

Examples

cfg <- smart_discover_config(
  "https://fhir.example.org/r4",
  mock_config = list(
    authorization_endpoint = "https://auth.example.org/authorize",
    token_endpoint = "https://auth.example.org/token",
    code_challenge_methods_supported = "S256"
  )
)
cfg$authorization_endpoint

Exchange a SMART Authorization Code for a Patient-Context Session

Description

Verifies CSRF state equality and RFC 7636 code_verifier length before exchanging the authorization code at config$token_endpoint.

Usage

smart_exchange_token(
  config,
  code,
  redirect_uri,
  client_id,
  code_verifier,
  expected_state = NULL,
  received_state = NULL,
  mock_response = NULL
)

Arguments

config

SMART configuration list from smart_discover_config().

code

Authorization code received at redirect_uri.

redirect_uri

Callback redirect URI.

client_id

Registered OAuth2 client identifier.

code_verifier

PKCE code_verifier matching the code_challenge.

expected_state

Expected CSRF state generated in smart_build_auth_url().

received_state

state query parameter returned by the auth server.

mock_response

Optional named list for offline/unit testing.

Value

An S3 "dicom_smart_session" object.


Generate an RFC 7636 S256 PKCE Verifier and Challenge Pair

Description

Generate an RFC 7636 S256 PKCE Verifier and Challenge Pair

Usage

smart_pkce_challenge(verifier = NULL)

Arguments

verifier

Optional PKCE code_verifier (43-128 URL-safe characters). If NULL, a high-entropy 64-character verifier is generated.

Value

A list with code_verifier, code_challenge, and code_challenge_method = "S256".

Examples

pkce <- smart_pkce_challenge()
pkce$code_challenge_method

Pull Patient-Context FHIR Resources into the Honest-Broker Enclave

Description

Requires "deid_ingest" permission (coordinator, honest_broker, or admin). Pseudonymizes the EHR patient_id inside the walled enclave crosswalk and returns only de-identified imaging/report counts and UIDs.

Usage

smart_pull_patient_context(
  session,
  enclave,
  principal,
  project_id,
  fhir_bundle = NULL
)

Arguments

session

A "dicom_smart_session" from smart_exchange_token().

enclave

A "dicom_broker_enclave" from broker_enclave_init().

principal

Authenticated "dicom_server_principal".

project_id

Target project identifier.

fhir_bundle

Optional parsed FHIR Bundle list for offline testing.

Value

A de-identified summary list containing project_id, pseudonym_id, n_imaging_studies, n_diagnostic_reports, and study_uids.


Verify an OIDC / Keycloak Bearer Token and Return a Server Principal

Description

Verify an OIDC / Keycloak Bearer Token and Return a Server Principal

Usage

verify_bearer_token(token, secret = NULL, oidc_userinfo_url = NULL)

Arguments

token

Bearer token string (with or without "Bearer " prefix).

secret

HMAC secret for verifying local test JWTs.

oidc_userinfo_url

Optional Keycloak OIDC ⁠/userinfo⁠ endpoint URL.

Value

A "dicom_server_principal" object.