# SMART Health Links API

Source: https://www.flexpa.com/docs/smart-health-links
Description: SMART Health Links (SHLs) are secure URLs using the shlink: scheme that provide access to encrypted health information, including SMART Health Cards.

## Overview

SMART Health Links (SHLs) are secure URLs using the `shlink:` scheme that provide access to encrypted health information, including [SMART Health Cards](https://www.flexpa.com/smart-health-cards).
Each link embeds a unique encryption key and manifest URL, enabling secure data sharing without confusing online portals or expensive network connection fees.

Flexpa's API fully implements the [SMART Health Cards and Links STU1](https://hl7.org/fhir/uv/smart-health-cards-and-links/STU1/links-specification.html) specification while leveraging Flexpa's proven healthcare data infrastructure.

**Perfect for healthcare applications needing to:**
- [Kill the clipboard](https://www.flexpa.com/kill-the-clipboard) and participate in CMS Aligned Networks
- Enable patient-controlled data portability and verifiable health records
- Share comprehensive records such as lab results, [digital insurance cards](https://hl7.org/fhir/us/insurance-card/STU1.1/), and visit summaries directly with patients without requiring online portals

### Why Use Flexpa?

Our SMART Health Links implementation combines full specification compliance with enterprise-grade reliability:

- **Full Spec Compliance**: Complete implementation of SMART Health Cards and Links STU1 specification with all required [flags](#flags), [status lifecycle](#status), and support for both [Manifest](#manifest) and [Direct Transfer](#direct-transfer) recipient access patterns
- **Enterprise-Grade Security**: JSON Web Encryption (JWE) with A256GCM algorithm, unique 32-byte keys per link, reliable cloud object storage (S3), automatic expiry (TTL), [passcodes](#passcodes) with brute-force protection, and [revocation](#revoke-shl)
- **Production-Ready Infrastructure**: Built on Flexpa's proven platform with automatic cleanup jobs, comprehensive error handling, rate limiting, and full audit logging

*Image: SHLs API*

## How Health Links work

When a patient receives a QR code containing their health records, that code is actually a SMART Health Link - a secure URL starting with `shlink:/` that contains everything needed to decrypt and access their encrypted health data. Here's how the entire flow works from creation to access.

### Lifecycle

Creating the QR Code

1

Data Encryption

Your application

sends health data

to Flexpa's API, which encrypts it using AES-256-GCM encryption

2

Unique Key Generation

A unique 32-byte encryption key is generated specifically for this link - this key is not persisted by
Flexpa

3

URL Creation

The encrypted data is stored securely in S3, and a shlink:/ URL is
created containing both the manifest location and the encryption key

4

QR Generation

This URL can be rendered as a QR code that patients can share or print

Scanning the QR Code

5

URL Decoding

The QR scanner reads the shlink:/ URL and extracts the embedded JSON
payload

6

Key Extraction

The recipient's app extracts both the manifest URL and the unique decryption key from the payload

7

Secure Retrieval

The app calls Flexpa's

manifest endpoint

(optionally with a passcode if required)

8

Local Decryption

Using the embedded key, the app decrypts the health data locally - Flexpa never sees the decryption key

### Security model

### Health Links vs Health Cards

While **SMART Health Cards** are tamper-proof digital credentials containing signed health data (like vaccination records), **SMART Health Links** provide a secure way to *share* those credentials and other health data through encrypted, shareable URLs. Think of SHCs as the digital certificates themselves, while SHLs are the secure delivery mechanism.

**SHCs** are digitally signed JWS tokens containing health data that can be verified offline. **SHLs** are encrypted URLs (`shlink:`) that can contain one or more SHCs plus additional FHIR resources. Use them together by creating SHCs for tamper-proof credentials, then packaging them into SHLs for secure sharing.

---

### Passcodes

SMART Health Links support optional passcode protection to add an extra layer of security for sensitive health data. When a link is created with passcode protection, recipients must provide the correct passcode to access the encrypted content.

Passcodes provide several security benefits:

- **Access Control**: Only recipients who know the passcode can decrypt and view the health data, even if the SHL is intercepted or shared unintentionally.
- **Brute-Force Protection**: The system automatically locks access after 3 failed passcode attempts, preventing unauthorized access through repeated guessing.
- **Flexible Distribution**: Passcodes can be shared through separate channels from the link itself (e.g., link via email, passcode via SMS), implementing a two-factor approach to data access.

Passcodes must be between 5-128 characters and cannot be used in combination with direct transfer mode (`U` flag), since direct file access bypasses the manifest endpoint where passcode validation occurs.

Passcode Processing Flow

1

Creation (5-128 chars)
Passcode hashed with SHA-256 before database storage

2

Validation Request
Database row locked to prevent race conditions

✓

Correct Passcode
Safe string comparison, access granted

!

Wrong Passcode
Attempt counter incremented, remaining attempts returned

✗

3rd Failed Attempt
Link automatically locked, access permanently denied

Security Features

• Serializable database isolation level
• Row-level locking prevents concurrent attacks
• Constant-time hash comparison
• Immediate lockout after 3 attempts

---

### Flags

SMART Health Links use single-character flags to control access behavior and link properties. Flags are concatenated alphabetically in the `flag` property of the JSON payload and determine how recipients can interact with the link.

---

### Manifests

The manifest is the central coordination point for accessing encrypted health data through SMART Health Links. It provides recipients with metadata about available health files and URLs to download them.

When recipients decode a SMART Health Link, they extract a manifest URL that serves as the API endpoint for accessing the encrypted content. The manifest endpoint handles two primary access patterns:

- **[Standard Manifest Flow (POST)](#manifest)**: Recipients POST to the manifest URL with their identifier and optional passcode. The server validates the request, enforces security policies, and returns a structured response containing encrypted file references, status information, and download locations.

- **[Direct Transfer Flow (GET)](#direct-transfer)**: For links with the `U` flag, recipients can bypass the manifest entirely and GET the encrypted files directly. This streamlined approach reduces round trips but sacrifices the ability to use passcode protection.

The manifest response includes critical metadata about each file's content type, encryption status, and availability. Files may be embedded directly in the response (for smaller content) or provided as temporary download URLs (for larger files), allowing efficient handling of varying data sizes while maintaining security.

```json
{
  "status": "finalized",
  "files": [
    {
      "contentType": "application/smart-health-card",
      "embedded": "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...",
      "location": null,
      "lastUpdated": "2024-01-01T10:30:00.000Z"
    },
    {
      "contentType": "application/fhir+json",
      "embedded": null,
      "location": "https://api.flexpa.com/smart/health-links/files/abc123?token=xyz789",
      "lastUpdated": "2024-01-01T10:30:00.000Z"
    }
  ]
}
```

### Status

SMART Health Links contain a status value used to communicate the current state of the link and its contents to recipients. The status is returned in the manifest response and helps applications understand whether the data is stable, may change, or is no longer accessible.

Together with the `L` (Long-term) flag, the status can be used to enable workflows such as generating a SHL prior to data being available - such as the results of a diagnostic tests - or providing continuously updated data - such as a personal health history.

---

### Recipient access

*End-to-end example*

```js
import { compactDecrypt } from "jose";

// Step 1: Decode the payload
const b64 = shlUri.replace("shlink:/", "");
const payload = JSON.parse(
  Buffer.from(b64, "base64url").toString(),
);

// Step 2: Check expiration
if (payload.exp && payload.exp < Date.now() / 1000) {
  throw new Error("Link expired");
}

// Step 3: POST to the manifest URL
const res = await fetch(payload.url, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    recipient: "your-app-id",
    // Include passcode if P flag is set
    // passcode: "12345",
  }),
});
const manifest = await res.json();

// Step 4: Check status, then extract JWEs
if (manifest.status === "no-longer-valid") {
  throw new Error("Link is no longer valid");
}
const jweTokens = [];
for (const file of manifest.files) {
  if (file.embedded) {
    jweTokens.push(file.embedded);
  } else if (file.location) {
    const fileRes = await fetch(file.location);
    jweTokens.push(await fileRes.text());
  }
}

// Step 5: Decrypt each file
const key = Buffer.from(payload.key, "base64url");
const decrypted = [];
for (const jwe of jweTokens) {
  const { plaintext } = await compactDecrypt(jwe.trim(), key);
  decrypted.push(JSON.parse(
    new TextDecoder().decode(plaintext),
  ));
}

// Step 6: decrypted[] contains your health data
```

```js
import { compactDecrypt } from "jose";

// Step 1: Decode the payload
const b64 = shlUri.replace("shlink:/", "");
const payload = JSON.parse(
  Buffer.from(b64, "base64url").toString(),
);

// Step 2: Check expiration
if (payload.exp && payload.exp < Date.now() / 1000) {
  throw new Error("Link expired");
}

// Step 3: GET the URL directly
const res = await fetch(payload.url, {
  headers: { Accept: "application/jose" },
});
const jwe = await res.text();

// Steps 4: N/A for direct transfer (no manifest)

// Step 5: Decrypt
const key = Buffer.from(payload.key, "base64url");
const { plaintext } = await compactDecrypt(jwe.trim(), key);
const content = JSON.parse(
  new TextDecoder().decode(plaintext),
);

// Step 6: content is your health data
```

## Authenticated API

The [Node SDK](https://www.flexpa.com/docs/records/node-sdk#smart-health-links) 2.1.0 provides typed methods for all four endpoints, including pagination and audit filters.

These endpoints authenticate with an [Application Access Token](https://www.flexpa.com/docs/records#application-access-token) in the `Authorization: Bearer` header. Application tokens are the primary credential for managing the SHLs created by your application. A [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) is also accepted when you need user-scoped behavior — list, revoke, and accesses are then limited to the links created by that token's Consent.

A patient access token manages exactly the links its own Consent created. A link created with an application token records a Consent only when you pass `user.consentId`; without it the link is managed by your application alone, and a patient access token will not see it.

All credentials are scoped by mode: test credentials can only manage test links, and live credentials can only manage live links.

---

### Create SHL

Create a new SHL containing encrypted health data files. Returns a shareable `shlink:` URL with embedded encryption keys and manifest endpoint.

**Note:**
**Integration Tip:** Combine SHLs with other Flexpa APIs for powerful workflows. Use [Patient/$health-cards-issue](https://www.flexpa.com/records#patient-health-cards-issue) to generate SMART Health Cards from FHIR data, then package them into shareable links.

**Request Headers**

- `Authorization` (string, required):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](https://www.flexpa.com/docs/records#application-access-token). A [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) is also accepted and creates the link for the authenticated patient.

**Request Parameters**

- `files` (array, required):
Array of files to include in the SHL.

  - `contentType` (string, required):
Content type: `application/smart-health-card`, `application/fhir+json`, or `application/smart-api-access`.

  - `content` (string | object, required):
File content - string for pre-built SHCs, object for FHIR resources or API access.

- `user` (object):
User information for tracking and association. Required when authenticating with an Application Access Token; optional when authenticating with a patient access token (externalId is then derived from the token).

  - `externalId` (string):
Your internal user identifier for tracking. Required for Application Access Token authentication, unless you supply `consentId`. With a patient access token it is optional and, if supplied, must match the token's user.

  - `consentId` (string):
The Consent the link belongs to, which decides whose patient access token may manage it. Only for Application Access Token authentication; the Consent must belong to the same application and mode. `externalId` is then derived from that Consent and may be omitted, but must match it when supplied. Without `consentId` the link records no Consent and only your application can manage it.

- `label` (string):
Optional label for the link (max 80 characters). Note: This label is embedded directly in the SHL URL and is accessible without a passcode.

- `passcode` (string):
Optional passcode protection (5-128 characters). Cannot be used with `directTransfer: true`.

- `ttl` (number):
Time-to-live in seconds (minimum 1). Required unless `longTerm: true` is set; omitting both `ttl` and `longTerm` returns a `400` error (`ttl is required unless longTerm is set to true`).

- `longTerm` (boolean):
Whether this is a long-term link. Adds `L` flag. Setting this to `true` makes `ttl` optional and creates a link with no expiration (`expiresAt` is `null`).

- `directTransfer` (boolean):
Enable direct file transfer. Adds `U` flag. Cannot be used with passcode. Requires exactly one file in `files`; supplying multiple files returns a `400` error (`Direct transfer (U flag) can only be used with a single file`).

**Note:**
**Request Size Limit:** Total request payload is limited to 10MB.

**Response Fields**

- `id` (string):
Unique identifier for the SHL (UUID format).

- `shl` (string):
The complete SHL URL starting with `shlink:/`.

- `viewerUrl` (string):
Direct URL to view the health data in Flexpa's viewer interface.

- `manifestUrl` (string):
API endpoint URL for programmatic access to the encrypted manifest.

- `expiresAt` (string | null):
ISO 8601 timestamp when the link expires, or `null` for long-term links.

*Request*

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
# First generate a SMART Health Card using Patient/$health-cards-issue
curl -X POST https://api.flexpa.com/smart/health-links \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "files": [
      {
        "contentType": "application/smart-health-card",
        "content": "eyJhbGciOiJFUzI1NiI..."
      }
    ],
    "user": {
      "externalId": "patient-123"
    },
    "label": "Vaccination Record",
    "ttl": 86400
  }'
```

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
# Create link from Patient/$everything Bundle
curl -X POST https://api.flexpa.com/smart/health-links \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "files": [
      {
        "contentType": "application/fhir+json",
        "content": {
          "resourceType": "Bundle",
          "type": "collection",
          "entry": [
            {
              "resource": {
                "resourceType": "Patient",
                "id": "123"
              }
            },
            {
              "resource": {
                "resourceType": "Condition",
                "id": "456"
              }
            }
          ]
        }
      }
    ],
    "user": {
      "externalId": "patient-456"
    },
    "passcode": "SecurePass123",
    "longTerm": true,
    "label": "Complete Medical Records"
  }'
```

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
curl -X POST https://api.flexpa.com/smart/health-links \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "files": [
      {
        "contentType": "application/smart-health-card",
        "content": "eyJhbGciOiJFUzI1NiI..."
      }
    ],
    "user": {
      "externalId": "patient-789"
    },
    "directTransfer": true,
    "ttl": 3600
  }'
```

*Response Examples*

```json
{
  "id": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "shl": "shlink:/eyJhbGciOiJFUzI1NiI...",
  "viewerUrl": "https://shc.flexpa.com/#shlink:/eyJhbGciOiJFUzI1NiI...",
  "manifestUrl": "https://api.flexpa.com/smart/health-links/manifests/7d4c9a5e3b2f1a8c6d9e4f7a8b5c2e1d",
  "expiresAt": "2024-02-01T00:00:00.000Z"
}
```

```json
{
  "id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8",
  "shl": "shlink:/eyJhbGciOiJFUzI1NiI...",
  "viewerUrl": "https://shc.flexpa.com/#shlink:/eyJhbGciOiJFUzI1NiI...",
  "manifestUrl": "https://api.flexpa.com/smart/health-links/manifests/2f8a1b3c4e5d6a7b8c9d0e1f2a3b4c5d",
  "expiresAt": null
}
```

```json
{
  "statusCode": 400,
  "error": "Bad Request",
  "message": "body/passcode must NOT have fewer than 5 characters"
}
```

---

### List SHLs

Retrieve a paginated list of all SHLs created by your application. With a [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token), only links belonging to the authenticated patient are returned.

**Request Headers**

- `Authorization` (string, required):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](https://www.flexpa.com/docs/records#application-access-token). A [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) is also accepted and returns only the links belonging to that patient.

**Request Parameters**

- `limit` (integer):
Number of results per page (1-1000, default: 20).

- `cursor` (string):
Use the `meta.nextCursor` value from the previous response unchanged. Omit this parameter for the first page. Malformed or empty cursors return `400` with an `Invalid cursor` error.

**Response Fields**

- `data` (array):
Array of SHL objects.

  - `id` (string):
Unique identifier for the SHL.

  - `manifestId` (string):
Unique identifier for the encrypted manifest.

  - `user` (object):
User information associated with the link.

    - `externalId` (string):
Your internal user identifier.

  - `label` (string | null):
Optional label for the link.

  - `flags` (string):
SHL flags (L, P, U combinations).

  - `expiresAt` (string | null):
ISO 8601 expiration timestamp, or `null` for long-term links.

  - `revokedAt` (string | null):
ISO 8601 timestamp when revoked, or `null` if active.

  - `createdAt` (string):
ISO 8601 timestamp when the link was created.

  - `updatedAt` (string):
ISO 8601 timestamp when the link was last updated.

  - `fileCount` (number):
Number of files contained in the link.

  - `totalSize` (number):
Total size of all files in bytes.

  - `accessCount` (number):
Number of successful accesses to the link.

  - `lastAccessedAt` (string | null):
ISO 8601 timestamp of the latest successful access, or `null` if the link has not been accessed successfully.

- `meta` (object):
Pagination metadata.

  - `hasMore` (boolean):
Whether more results are available.

  - `nextCursor` (string | null):
Cursor for the next page, or `null` if no more pages.

*Request*

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
curl https://api.flexpa.com/smart/health-links?limit=10 \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

*Response Example*

```json
{
  "data": [{
    "id": "a1b2c3d4-e5f6-4789-abc1-23def4567890",
    "manifestId": "9a8b7c6d5e4f3a2b1c0d9e8f7a6b5c4d",
    "user": {"externalId": "patient-123"},
    "label": "Lab Results",
    "flags": "LP",
    "expiresAt": "2024-02-01T00:00:00.000Z",
    "revokedAt": null,
    "createdAt": "2024-01-01T10:30:00.000Z",
    "updatedAt": "2024-01-01T10:30:00.000Z",
    "fileCount": 1,
    "totalSize": 2048,
    "accessCount": 3,
    "lastAccessedAt": "2024-01-01T11:00:00.000Z"
  }],
  "meta": {
    "hasMore": true,
    "nextCursor": "eyJjcmVhdGVkQXQi..."
  }
}
```

---

### SHL statistics

Count links created in the selected period and their successful accesses.
Links created before the period are excluded.

**Request headers**

- `Authorization` (string, required):
`Bearer` [Application Access Token](https://www.flexpa.com/docs/records#application-access-token),
scoped to its application and mode. A
[Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) returns only that
patient's statistics.

**Request parameters**

- `lookbackDays` (integer):
Days to include (1–365, default: 30). The rolling UTC window ends at the
time of the request.

**Response fields**

- `data` (object):
Totals for links created during `period`, including expired or revoked links.

  - `linksCreated` (integer):
Links created.

  - `linksAccessed` (integer):
Links with a recorded successful access by `period.end`.

  - `usersWithLinks` (integer):
Distinct owners of those links.

  - `usersWithAccesses` (integer):
Distinct owners of successfully accessed links.

  - `successfulAccesses` (integer):
Recorded successful accesses by `period.end`, including repeats.

- `timeSeries` (array):
Counts by UTC link creation date, oldest first, including dates with no
activity. Later accesses count toward the link's creation date. Daily user
counts cannot be summed; use `data` for distinct-user totals.

  - `date` (string):
Link creation date (`YYYY-MM-DD`).

  - `linksCreated` (integer):
Links created on this date.

  - `linksAccessed` (integer):
Those links with a recorded successful access by `period.end`.

  - `usersWithLinks` (integer):
Distinct owners of links created on this date.

  - `usersWithAccesses` (integer):
Distinct owners of successfully accessed links created on this date.

  - `successfulAccesses` (integer):
Recorded successful accesses to those links by `period.end`, including repeats.

- `period` (object):
Reporting window, inclusive.

  - `start` (string):
ISO 8601 UTC start timestamp.

  - `end` (string):
ISO 8601 UTC end timestamp.

**Note:**
Access counts do not confirm QR scans or file downloads. Activity before
access auditing was enabled is not backfilled.

*Request*

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
curl 'https://api.flexpa.com/smart/health-links/stats?lookbackDays=1' \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

*Response example*

```json
{
  "data": {
    "linksCreated": 12,
    "linksAccessed": 8,
    "usersWithLinks": 10,
    "usersWithAccesses": 7,
    "successfulAccesses": 18
  },
  "timeSeries": [
    {
      "date": "2026-09-09",
      "linksCreated": 12,
      "linksAccessed": 8,
      "usersWithLinks": 10,
      "usersWithAccesses": 7,
      "successfulAccesses": 18
    },
    {
      "date": "2026-09-10",
      "linksCreated": 0,
      "linksAccessed": 0,
      "usersWithLinks": 0,
      "usersWithAccesses": 0,
      "successfulAccesses": 0
    }
  ],
  "period": {
    "start": "2026-09-09T12:00:00.000Z",
    "end": "2026-09-10T12:00:00.000Z"
  }
}
```

---

### Revoke SHL

Permanently revoke a SHL, making it inaccessible and scheduling file deletion.

**Note:**
**Permanent Action:** Revocation cannot be undone. All associated files will be deleted from storage.

**Request Headers**

- `Authorization` (string, required):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](https://www.flexpa.com/docs/records#application-access-token). A [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) is also accepted but can only revoke the authenticated patient's own links.

**Request Parameters**

- `id` (string, required):
The UUID of the SHL to revoke (path parameter).

*Request*

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
curl -X DELETE https://api.flexpa.com/smart/health-links/f47ac10b-58cc-4372-a567-0e02b2c3d479 \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

*Response Examples*

```http
HTTP/1.1 204 No Content
(empty body)
```

```json
{
  "error": "SMART Health Link not found"
}
```

---

### Audit trail

Retrieve the audit trail of access events for a SHL — who attempted to access the link, when, and with what outcome. Application tokens can read the trail for any link belonging to their application; patient access tokens see only events for their own links.

**Request Headers**

- `Authorization` (string, required):
An `Authorization: Bearer` header value must be presented with an [Application Access Token](https://www.flexpa.com/docs/records#application-access-token). A [Patient Access Token](https://www.flexpa.com/docs/records#patient-access-token) is also accepted but can only read access events for the authenticated patient's own links.

**Request Parameters**

- `id` (string, required):
The UUID of the SHL to inspect (path parameter).

- `limit` (integer):
Number of results per page (1-100, default: 20).

- `cursor` (string):
Use the cursor from the Bundle's `next` link unchanged, or follow that link directly. Omit this parameter for the first page. Malformed or empty cursors return `400` with an `Invalid cursor` error.

- `status` (string):
Filter by access status: `SUCCEEDED`, `PASSCODE_REQUIRED`, `INVALID_PASSCODE`, `LOCKED`, `EXPIRED`, or `REVOKED`.

- `type` (string):
Filter by access type: `MANIFEST` or `DIRECT`.

**Response Fields**

- `resourceType` (string):
Always `Bundle`.

- `type` (string):
Always `searchset`.

- `link` (array):
Bundle links: a `self` link to the request URL and, when more results exist, a `next` link with the next cursor.

- `entry` (array):
Array of access events, newest first. Omitted when no events match. Each entry has a stable `fullUrl` (`urn:uuid:{event-id}`) and a `resource` containing the following [FHIR AuditEvent](https://hl7.org/fhir/R4/auditevent.html) fields:

  - `resourceType` (string):
Always `AuditEvent`.

  - `id` (string):
Unique identifier for the access event.

  - `type` (object):
The `rest` code from the FHIR audit event type code system, identifying a RESTful operation.

  - `subtype` (array):
The `read` code from the FHIR RESTful interaction code system.

  - `action` (string):
Always `R` (read).

  - `outcome` (string):
FHIR outcome code: `0` success, `4` minor failure (incorrect or missing passcode), `8` serious failure (locked, expired, or revoked links).

  - `outcomeDesc` (string):
The access status: `SUCCEEDED`, `PASSCODE_REQUIRED`, `INVALID_PASSCODE`, `LOCKED`, `EXPIRED`, or `REVOKED`.

  - `recorded` (string):
ISO 8601 timestamp when the access occurred.

  - `agent` (array):
Who performed the access.

    - `who` (object):

      - `display` (string):
The recipient identifier supplied to the manifest or direct transfer request, or `Unknown`.

    - `requestor` (boolean):
Always `true`.

  - `source` (object):
Identifies the observer as `Flexpa SMART Health Links`.

  - `entity` (array):
The accessed SHL.

    - `what` (object):

      - `identifier` (object):

        - `value` (string):
The id of the SHL.

    - `name` (string):
The SHL label, when set.

  - `extension` (array):
Flexpa extension at `https://flexpa.com/docs/shl#access-event` with an `accessType` code (`MANIFEST` or `DIRECT`) and the access `status` code.

*Request*

```bash
ACCESS_TOKEN=eyJhbGciOiJFUzI1NiI...
# Obtain an application token via the client credentials grant: https://www.flexpa.com/docs/consent#token
curl "https://api.flexpa.com/smart/health-links/f47ac10b-58cc-4372-a567-0e02b2c3d479/accesses?limit=20" \
  -H "Authorization: Bearer $ACCESS_TOKEN"
```

*Response Examples*

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "link": [
    {
      "relation": "self",
      "url": "https://api.flexpa.com/smart/health-links/f47ac10b-58cc-4372-a567-0e02b2c3d479/accesses?limit=20"
    }
  ],
  "entry": [
    {
      "fullUrl": "urn:uuid:55c2f4a1-9d83-4b2c-9876-543210abcdef",
      "resource": {
        "resourceType": "AuditEvent",
        "id": "55c2f4a1-9d83-4b2c-9876-543210abcdef",
        "type": {
          "system": "http://terminology.hl7.org/CodeSystem/audit-event-type",
          "code": "rest",
          "display": "RESTful Operation"
        },
        "subtype": [
          {
            "system": "http://hl7.org/fhir/restful-interaction",
            "code": "read",
            "display": "read"
          }
        ],
        "action": "R",
        "recorded": "2024-01-01T10:30:00.000Z",
        "outcome": "0",
        "outcomeDesc": "SUCCEEDED",
        "agent": [
          {
            "who": { "display": "patient-123" },
            "requestor": true
          }
        ],
        "source": { "observer": { "display": "Flexpa SMART Health Links" } },
        "entity": [
          {
            "what": {
              "identifier": {
                "system": "https://api.flexpa.com/smart/health-links",
                "value": "f47ac10b-58cc-4372-a567-0e02b2c3d479"
              }
            },
            "name": "Vaccination Record"
          }
        ],
        "extension": [
          {
            "url": "https://flexpa.com/docs/shl#access-event",
            "extension": [
              { "url": "accessType", "valueCode": "MANIFEST" },
              { "url": "status", "valueCode": "SUCCEEDED" }
            ]
          }
        ]
      }
    }
  ]
}
```

```json
{
  "resourceType": "Bundle",
  "type": "searchset",
  "link": [
    {
      "relation": "self",
      "url": "https://api.flexpa.com/smart/health-links/f47ac10b-58cc-4372-a567-0e02b2c3d479/accesses?limit=20"
    }
  ]
}
```

```json
{
  "error": "Missing or invalid authorization header"
}
```

```json
{
  "error": "Invalid cursor"
}
```

```json
{
  "error": "Patient authorization does not have an associated user identity"
}
```

```json
{
  "error": "SMART Health Link not found"
}
```

## Manifest and Direct Transfer

These endpoints are accessible to end recipients of SHLs and require no Flexpa credential. A manifest request is authorized by the manifest URL carried in the SHL and, when the link was created with one, a passcode the recipient sends in the request body. The encryption key the SHL carries decrypts the files the manifest returns and is never sent to Flexpa.

---

### Direct Transfer

Direct download of encrypted health data files. Only available for links with the `U` flag enabled.

**Warning:**
**Flag Restriction:** This endpoint only works with links that have the `U` (Direct Transfer) flag. Links with both `U` and `P` flags are invalid.

**Parameters**

- `manifestId` (string, required):
The manifest ID from the SHL (path parameter).

- `recipient` (string):
Optional recipient identifier (query parameter).

**Response Fields**

- `Content-Type` (header):
Set to `application/jose` for JWE-encrypted content.

- `Response Body` (string):
JWE (JSON Web Encryption) string using A256GCM algorithm. Decrypt using the 32-byte key embedded in the original SHL URL payload.

*Request*

```bash
curl https://api.flexpa.com/smart/health-links/manifests/7d4c9a5e3b2f1a8c6d9e4f7a8b5c2e1d
```

*Response Examples*

```bash
HTTP/1.1 200 OK
Content-Type: application/jose

eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..iv8E9W3flKTiZhYeAW3Se.4hU4gz
mSH5K6E5WCekMtV8u9-g_bCh5lUhcmAJI9EqTvJZLKqttqHpLJiyqk0jRl-BqRDjNiU2r
IeqZVb0k2JPj7IuR8qVzN8kpmw0K8fvPhKMmjmC41ydPG1sqVvgPYN0nz8sT5x5Z2MpYV
8N6iNwAjhSNnqYk3jJGmCLNMOKpEhHz7kN-d4fWqR3X9iG7Lh2xuEOLed7_27dxcpvnS2
ScbvhzPqhYqiVF7KQ3mTbWcKdxNM5KkrCw.Bx8xiafv0c-uVEXy_6q-jg
```

```json
{
  "error": "Direct file access not allowed for this SMART Health Link"
}
```

```json
{
  "error": "Invalid flag combination"
}
```

```json
{
  "error": "SMART Health Link not found"
}
```

```json
{
  "error": "SMART Health Link has expired"
}
```

```json
{
  "error": "SMART Health Link has been revoked"
}
```

---

### Manifest

Recipients use this endpoint to retrieve the encrypted health data from a SHL.

**Request Parameters**

- `recipient` (string, required):
Identifier for the requesting party.

- `passcode` (string):
Required if the link has passcode protection (max 128 characters).

- `embeddedLengthMax` (number):
Maximum byte length for embedded content (minimum 0). When omitted, all files are embedded; set to `0` to force every file to be returned as a `location` URL; set to N to embed only files `<=` N bytes.

**Response Fields**

- `status` (string):
Indicates file changeability: `finalized` (stable), `can-change` (may evolve), or `no-longer-valid` (expired/revoked).

- `files` (array):
Array of encrypted health data files following the SHLs manifest structure.

  - `contentType` (string):
MIME type: `application/smart-health-card`, `application/fhir+json`, or `application/smart-api-access`.

  - `embedded` (string | null):
JWE-encrypted file content (base64url encoded) if within size limits, otherwise `null`.

  - `location` (string | null):
Short-lived URL for downloading large encrypted files, or `null` if embedded.

- `remainingAttempts` (number | null):
Number of passcode attempts remaining (only included for incorrect passcode errors).

*Request*

```bash
curl -X POST https://api.flexpa.com/smart/health-links/manifests/7d4c9a5e3b2f1a8c6d9e4f7a8b5c2e1d \
  -H "Content-Type: application/json" \
  -d '{
    "recipient": "healthcare-provider-id",
    "passcode": "12345"
  }'
```

*Response Examples*

```json
{
  "status": "finalized",
  "files": [{
    "contentType": "application/smart-health-card",
    "embedded": "eyJhbGciOiJFUzI1NiI...",
    "lastUpdated": "2024-01-01T10:30:00.000Z"
  }]
}
```

```json
{
  "error": "Invalid passcode",
  "remainingAttempts": 2
}
```

```json
{
  "error": "Passcode required"
}
```

```json
{
  "error": "SMART Health Link has been locked due to too many failed attempts",
  "remainingAttempts": 0
}
```

```json
{
  "error": "Manifest not found"
}
```

```json
{
  "status": "no-longer-valid"
}
```
