Skip to content
Engine API

Authentication

Authentication endpoints of the MedHook engine API: 7 operations with parameters, schemas and a curl example for each.

On this page

Token issuance. Tokens are valid for 2 hours.

Obtain a JWT access token

post/api/auth/token

Exchange a named API client key (apiKey, from Settings > API clients or create-engine-api-client) or the engine auth secret (secret) for a short-lived JWT. Send one of the two. An API client token carries the client's role and lasts 2 hours, or until the client expires. Root-secret tokens are anonymous admin tokens; with NODE_ENV=production they are refused (403) unless ENGINE_ROOT_TOKEN_ENABLED=true. Supply the token as a Bearer token on all subsequent authenticated requests. Rate limited (429 RATE_LIMITED with Retry-After): 5 exchanges per minute for each API key (or secret), from any IP; 30 per minute per IP, so several keys can be exchanged from behind one NAT; and after 5 failed exchanges (an unknown, revoked or expired key, or a wrong secret) in a minute, the IP gets 429 for every exchange until a minute after the last failure.

Refresh tokens. An API-key exchange also answers refresh_token (mhr_ and 43 base64url characters) and refreshTokenExpiresAt. Send {"grant_type": "refresh_token", "refresh_token": "<token>"} before or after the access token expires to get a new access token and a new refresh token, so a CI job or scheduled task keeps access without storing the API key. Each refresh token works once: keep the new one from every answer. Presenting a used refresh token revokes every refresh token from the same API-key exchange (401 REFRESH_TOKEN_REUSED); exchange the API key again. A refresh token lasts ENGINE_REFRESH_TOKEN_TTL (default 30d; 12h or 90d style, at most 365 days), never longer than its API client, and each refresh starts a new lifetime. Revoking or rotating the API client revokes its refresh tokens. The engine stores only each refresh token's SHA-256 hash. Every issue, use, refusal and revocation is audited (refresh_token.issued, refresh_token.used, refresh_token.rejected, refresh_token.reuse_detected, refresh_token.revoked). A refresh counts against the same limits as a key exchange, by the refresh token's hash, and a refused refresh is a failed exchange. A root-secret exchange gets no refresh token. Answers that carry a token are sent with Cache-Control: no-store.

Auth: None, public route · Operation: createToken

Request body (required)

application/json · object

  • grant_typestring

    refresh_token to trade refresh_token for new tokens. Leave it out with apiKey or secret; any other value is 400.

    One of: "refresh_token"

  • refresh_tokenstring

    With grant_type refresh_token: the refresh token from the last API-key exchange or refresh. Works once.

  • apiKeystring

    Key of a named API client, shown once by Settings > API clients or printed once by create-engine-api-client <name>. Takes precedence over secret.

  • secretstring

    Value of the ENGINE_AUTH_SECRET environment variable (root-secret token).

Responses

  • 200Token issued.
    Response fields

    application/json · object

    • tokenstringrequired

      Signed JWT.

    • expiresAtstring (date-time)required

      Token expiry (UTC ISO 8601).

    • refresh_tokenstring

      API-key exchanges and refreshes only: the next refresh token. Shown only now; it works once.

    • refreshTokenExpiresAtstring (date-time)

      When refresh_token expires (UTC ISO 8601), never after the API client.

  • 400The body is not a JSON object, `grant_type` is not `refresh_token`, or `refresh_token` is missing.

    application/json · ApiError

  • 401Invalid secret, or an invalid, revoked or expired API key (`UNAUTHORIZED`). A refused refresh: `REFRESH_TOKEN_INVALID` (unknown), `REFRESH_TOKEN_REUSED` (already used: every refresh token from the same exchange is now revoked), `REFRESH_TOKEN_REVOKED` (revoked, or its API client was revoked, rotated or expired) or `REFRESH_TOKEN_EXPIRED`. Exchange the API key again.

    application/json · ApiError

  • 403Root-secret tokens are disabled (production without ENGINE_ROOT_TOKEN_ENABLED=true). Use an API client.

    application/json · ApiError

  • 429Rate limit exceeded.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl -X POST "$ENGINE_URL/api/auth/token" \
  -H "Content-Type: application/json" \
  -d '{
  "grant_type": "refresh_token",
  "refresh_token": "mhr_example_not_a_real_token",
  "apiKey": "mhk_example_not_a_real_key",
  "secret": "string"
}'

Start a SMART on FHIR launch

get/api/auth/smart/launch

Starts a standalone or EHR-initiated SMART on FHIR launch. The engine checks iss against its SSRF rules, discovers the authorization endpoints, makes a PKCE verifier (S256), keeps the launch state in Redis for 10 minutes, and redirects the browser to the EHR's authorization server. Rate limits apply.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: startSmartLaunch

Parameters

NameInTypeDescription
issrequiredquerystring

The FHIR base URL of the EHR.

launchquerystring

The EHR's launch token, for an EHR launch. Leave out for a standalone launch.

scopequerystring

Space-separated SMART scopes. Defaults to a patient-level set.

redirect_uriquerystring

Override the default redirect URI.

Responses

  • 302Redirect to the EHR authorization server.
  • 400The request is malformed or fails validation.

    application/json · ApiError

  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl "$ENGINE_URL/api/auth/smart/launch?iss=https%3A%2F%2Ffhir.example.test%2Fr4" \
  -H "Authorization: Bearer $TOKEN"

SMART on FHIR callback

get/api/auth/smart/callback

The redirect target after the person approves the launch. The one-time state must match the launch; it is deleted on use. The engine exchanges the code with the stored PKCE verifier and keeps the token in Redis for at most 8 hours. The response never contains the access token: it gives a tokenKey for server-to-server use. Rate limited to 10 requests per minute.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: completeSmartLaunch

Parameters

NameInTypeDescription
coderequiredquerystring

The authorization code.

staterequiredquerystring

The state from the launch.

issquerystring

The issuer (SMART 2.0). Checked against the launch.

errorquerystring

Set by the EHR when access was denied.

error_descriptionquerystring

Set by the EHR with error.

Responses

  • 200A summary of the token.
    Response fields

    application/json · object

    • statestring
    • patientIdstring | null
    • encounterIdstring | null
    • scopestring
    • expiresIninteger
    • hasRefreshTokenboolean
    • hasIdTokenboolean
    • issstring
    • tokenStoredAtstring (date-time)
    • tokenKeystring
  • 400The request is malformed or fails validation.

    application/json · ApiError

  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

  • 502Error.

    application/json · ApiError

Example request

curl
curl "$ENGINE_URL/api/auth/smart/callback?code=string&state=string" \
  -H "Authorization: Bearer $TOKEN"

List API clients

get/api/api-clients

The named API clients the caller may see (integrations, CI jobs, scripts): every one for an admin; for an operator, the operator and viewer clients scoped to the workspaces where they are an operator. Name, role, status, workspace scope, created, expires, last used and the key's first characters. Never a key or its hash. Signed-in admins and operators only: a viewer gets 403 FORBIDDEN, and an API client gets 403 API_CLIENT_FORBIDDEN, even an admin one, so a leaked key can't mint more. Rate limited to 30 requests per minute.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: listApiClients

Responses

  • 200The clients, by name.
    Response fields

    application/json · object

    • clientsarray of object
      12 fields
      • idstring
      • namestring

        Shown in the audit log as api-client:<name>.

      • rolestring

        One of: "admin", "operator", "viewer"

      • statusstring

        One of: "active", "expired", "revoked"

      • workspaceIdstring | null

        The one workspace it may act in; null: every one.

      • workspaceSlugstring | null
      • inboundPerMinuteinteger | null

        Inbound trigger requests per minute; null: none.

      • keyPrefixstring | null

        The key's first 12 characters ("mhk_" and 8 more); null for keys made before it was kept. Never enough to use.

      • createdAtstring (date-time)
      • expiresAtstring (date-time)
      • lastUsedAtstring (date-time) | null

        When its key was last exchanged for a token.

      • revokedAtstring (date-time) | null
  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 403The caller's role, license or network address does not allow this. A signed-in person who is not a member of the requested workspace gets code `WORKSPACE_FORBIDDEN`; a viewer asking for message content gets `PHI_FORBIDDEN` (or `PHI_SEARCH_FORBIDDEN` for a search on message content).

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl "$ENGINE_URL/api/api-clients" \
  -H "Authorization: Bearer $TOKEN"

Create an API client

post/api/api-clients

Makes a named API client, as the create-engine-api-client CLI does, and answers its key once: only the key's SHA-256 hash and prefix are stored, and the key is never logged or audited. Exchange it at POST /api/auth/token with {"apiKey": "<key>"} for a 2-hour bearer token. workspace current scopes the client to the workspace this request is in (other workspaces get 403 WORKSPACE_FORBIDDEN); all lets it act in every workspace at its role. An operator may only create operator or viewer clients (403 ROLE_ABOVE_CALLER for admin) scoped to the current workspace (403 WORKSPACE_REQUIRED for all). A taken name is 409 EXISTS. Audited as api_client.created, with the signed-in admin or operator as the actor. Signed-in admins and operators only: a viewer gets 403 FORBIDDEN, and an API client gets 403 API_CLIENT_FORBIDDEN, even an admin one, so a leaked key can't mint more. Rate limited to 10 requests per minute.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: createApiClient

Request body (required)

application/json · object

  • namestringrequired

    2-63 characters: lowercase letters, digits, '.', '_' or '-' (lowercased).

  • rolestring

    Default operator. viewer is read-only. Operators may only pick operator or viewer.

    One of: "admin", "operator", "viewer"

  • workspacestring

    Default current. Operators must use current: their clients work in this workspace only.

    One of: "current", "all"

  • expiresInDaysinteger

    Lifetime in days.

Responses

  • 201The client and its key; the key is shown only now.
    Response fields

    application/json · object

    • clientobject
      12 fields
      • idstring
      • namestring

        Shown in the audit log as api-client:<name>.

      • rolestring

        One of: "admin", "operator", "viewer"

      • statusstring

        One of: "active", "expired", "revoked"

      • workspaceIdstring | null

        The one workspace it may act in; null: every one.

      • workspaceSlugstring | null
      • inboundPerMinuteinteger | null

        Inbound trigger requests per minute; null: none.

      • keyPrefixstring | null

        The key's first 12 characters ("mhk_" and 8 more); null for keys made before it was kept. Never enough to use.

      • createdAtstring (date-time)
      • expiresAtstring (date-time)
      • lastUsedAtstring (date-time) | null

        When its key was last exchanged for a token.

      • revokedAtstring (date-time) | null
    • keystring

      mhk_ and 43 base64url characters.

  • 400The request is malformed or fails validation.

    application/json · ApiError

  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 403The caller's role, license or network address does not allow this. A signed-in person who is not a member of the requested workspace gets code `WORKSPACE_FORBIDDEN`; a viewer asking for message content gets `PHI_FORBIDDEN` (or `PHI_SEARCH_FORBIDDEN` for a search on message content).

    application/json · ApiError

  • 404Not found in the caller's workspace.

    application/json · ApiError

  • 409The request conflicts with the current state.

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl -X POST "$ENGINE_URL/api/api-clients" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "name": "string",
  "role": "operator",
  "workspace": "current",
  "expiresInDays": 30
}'

Rotate an API client's key or change its expiry

patch/api/api-clients/{id}

rotate: true issues a new key, answered once as key (valid expiresInDays, default 30): the old key, every token minted from it and its refresh tokens stop working, and a revoked or expired client works again with the same role and scope. expiresInDays alone moves the current key's expiry without a new key (409 REVOKED for a revoked client). Audited as api_client.rotated or api_client.expiry_changed. 404 for an unknown id. An operator acts only on operator and viewer clients scoped to a workspace where they are an operator: another workspace's client, or one for every workspace, answers 404 NOT_FOUND as if unknown, and an admin client answers 403 ROLE_ABOVE_CALLER. Admins act on every client. Signed-in admins and operators only: a viewer gets 403 FORBIDDEN, and an API client gets 403 API_CLIENT_FORBIDDEN, even an admin one, so a leaked key can't mint more. Rate limited to 10 requests per minute.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: updateApiClient

Parameters

NameInTypeDescription
idrequiredpathstring

The API client's id.

Request body (required)

application/json · object

  • rotateboolean

    true: issue a new key.

  • expiresInDaysinteger

    New lifetime in days, from now.

Responses

  • 200The client; `key` only after a rotate.
    Response fields

    application/json · object

    • clientobject
      12 fields
      • idstring
      • namestring

        Shown in the audit log as api-client:<name>.

      • rolestring

        One of: "admin", "operator", "viewer"

      • statusstring

        One of: "active", "expired", "revoked"

      • workspaceIdstring | null

        The one workspace it may act in; null: every one.

      • workspaceSlugstring | null
      • inboundPerMinuteinteger | null

        Inbound trigger requests per minute; null: none.

      • keyPrefixstring | null

        The key's first 12 characters ("mhk_" and 8 more); null for keys made before it was kept. Never enough to use.

      • createdAtstring (date-time)
      • expiresAtstring (date-time)
      • lastUsedAtstring (date-time) | null

        When its key was last exchanged for a token.

      • revokedAtstring (date-time) | null
    • keystring

      The new key, shown only now.

  • 400The request is malformed or fails validation.

    application/json · ApiError

  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 403The caller's role, license or network address does not allow this. A signed-in person who is not a member of the requested workspace gets code `WORKSPACE_FORBIDDEN`; a viewer asking for message content gets `PHI_FORBIDDEN` (or `PHI_SEARCH_FORBIDDEN` for a search on message content).

    application/json · ApiError

  • 404Not found in the caller's workspace.

    application/json · ApiError

  • 409The request conflicts with the current state.

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl -X PATCH "$ENGINE_URL/api/api-clients/<id>" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
  "rotate": true,
  "expiresInDays": 1
}'

Revoke an API client

delete/api/api-clients/{id}

Revokes the client: its key, tokens and refresh tokens stop working within seconds, and POST /api/auth/token answers 401 for its key. Revoking a revoked client changes nothing. Rotate it to use it again. Audited as api_client.revoked. 404 for an unknown id. An operator acts only on operator and viewer clients scoped to a workspace where they are an operator: another workspace's client, or one for every workspace, answers 404 NOT_FOUND as if unknown, and an admin client answers 403 ROLE_ABOVE_CALLER. Admins act on every client. Signed-in admins and operators only: a viewer gets 403 FORBIDDEN, and an API client gets 403 API_CLIENT_FORBIDDEN, even an admin one, so a leaked key can't mint more. Rate limited to 10 requests per minute.

Minimum role: operator.

Auth: Bearer token (how to get one) · Operation: revokeApiClient

Parameters

NameInTypeDescription
idrequiredpathstring

The API client's id.

Responses

  • 200Revoked.
    Response fields

    application/json · object

    • clientobject
      12 fields
      • idstring
      • namestring

        Shown in the audit log as api-client:<name>.

      • rolestring

        One of: "admin", "operator", "viewer"

      • statusstring

        One of: "active", "expired", "revoked"

      • workspaceIdstring | null

        The one workspace it may act in; null: every one.

      • workspaceSlugstring | null
      • inboundPerMinuteinteger | null

        Inbound trigger requests per minute; null: none.

      • keyPrefixstring | null

        The key's first 12 characters ("mhk_" and 8 more); null for keys made before it was kept. Never enough to use.

      • createdAtstring (date-time)
      • expiresAtstring (date-time)
      • lastUsedAtstring (date-time) | null

        When its key was last exchanged for a token.

      • revokedAtstring (date-time) | null
    • revokedboolean
  • 401No credential, or the token is invalid or expired.

    application/json · ApiError

  • 403The caller's role, license or network address does not allow this. A signed-in person who is not a member of the requested workspace gets code `WORKSPACE_FORBIDDEN`; a viewer asking for message content gets `PHI_FORBIDDEN` (or `PHI_SEARCH_FORBIDDEN` for a search on message content).

    application/json · ApiError

  • 404Not found in the caller's workspace.

    application/json · ApiError

  • 429Rate limit exceeded (see the `Retry-After` header), or on the AI routes the daily AI budget is used up.

    application/json · ApiError

  • 500Unexpected server error.

    application/json · ApiError

Example request

curl
curl -X DELETE "$ENGINE_URL/api/api-clients/<id>" \
  -H "Authorization: Bearer $TOKEN"

Schemas

Named objects the operations above link to.

ApiError

The error body. error is always present. code is present on most errors and is the field to branch on; a few routes and the sign-in and role checks return only error (and sometimes detail).

  • errorstringrequired

    Human-readable error message.

  • codestring

    Machine-readable error code.

    One of: "BAD_REQUEST", "INVALID_REQUEST", "UNAUTHORIZED", "UNAUTHENTICATED", "FORBIDDEN", "NOT_FOUND", "CONFLICT", "UNPROCESSABLE_ENTITY", "RATE_LIMITED", "INTERNAL_ERROR", "SERVICE_UNAVAILABLE", "NOT_CONFIGURED", "SIGNATURE_REQUIRED", "INVALID_SIGNATURE", "TIMESTAMP_REQUIRED", "TIMESTAMP_INVALID", "TIMESTAMP_OUT_OF_TOLERANCE", "INVALID_CREDENTIALS", "INVALID_TOKEN", "PAYLOAD_TOO_LARGE", "INVALID_NDJSON", "PHI_NOT_AUTHORIZED", "PHI_IN_SANDBOX", "IN_PROGRESS", "RETRY_SCHEDULED", "WORKFLOW_DISABLED", "CONFLICTING_SCOPE", "ALREADY_DELIVERED", "CHAIN_TOO_DEEP", "NO_FAILED_DESTINATION", "STALE_SCOPE", "UNKNOWN_DESTINATION", "NO_DESTINATIONS", "NOT_A_MESSAGE", "AI_FEATURES_DISABLED"

  • detailsany

    Optional structured context about the error.