# Trustlith Developer Center (`llms.txt`)

> Cryptographic authentication and high-trust transaction authorization built on Cloudflare Workers & D1.

## Current Capability Scope
- **LIVE (Public Runtime API v1):** Passwordless `login` step-up and `fund_transfer` transaction authorization (`TRUSTLITH-AUTH-V1\0`, ES256 P-256).
- **PROPOSED / NOT YET DEPLOYED (ADR 0022 V2):** Developer-defined Custom Auditable Transactions (`action: "custom"`, `/consume`, `/acknowledge-execution`) are specification-only and **not available on the live Runtime API**.
- **SDK Note:** `@trustlith/sdk-js` is a non-production local Phase 1 prototype. Integrate over standard backend HTTPS using `Authorization: Bearer <TRUSTLITH_API_KEY>`.

## Canonical Machine-Readable & Downloadable Docs
- Proposed public Developer Center distribution: `https://developers.trustlith.com`
- `TRUSTLITH-INTEGRATION.md` ([GitHub source](./TRUSTLITH-INTEGRATION.md)): Self-contained backend integration bundle (auth, `login`, `fund_transfer`, polling, cancel, error matrix, and AI coding guardrails).
- `llms-full.txt`: Complete single-file generated corpus combining `llms.txt`, `TRUSTLITH-INTEGRATION.md`, all Developer Center guides, changelog, and `docs/openapi.yaml`.
- [OpenAPI 3.1 Specification](./docs/openapi.yaml): Exact V1 Runtime REST contracts, schemas, scopes, and error codes.
- [Developer Center Index](./docs/developer-center/README.md): Dual-path manual + AI integration hub.
- [5-Step Quickstart](./docs/developer-center/quickstart.md): End-to-end Portal setup -> API key -> test user -> QR enrollment -> challenge flow.
- [API Reference](./docs/developer-center/api-reference.md): Verified V1 routes, Bearer scopes, origin matching, and status transitions.
- [Code Examples](./docs/developer-center/examples.md): Node.js (TypeScript/Fetch), Python, and cURL examples.
- [User Enrollment Guide](./docs/developer-center/user-enrollment.md): Mapping users, issuing QR handoffs (`/v1/enrollments` + `/v1/enrollment-handoffs`), and device completion.
- [AI Coding Agent Guide](./docs/developer-center/ai-agent-guide.md): Prompting and security guardrails for autonomous coding agents.
- [Developer Changelog](./docs/developer-center/changelog.md): Live V1 milestones separated from planned V2 roadmap.

## Non-Negotiable Integration Rules
1. Keep `TRUSTLITH_API_KEY` exclusively server-side; never bundle into browser/mobile code.
2. Never send `tenantId` or `applicationId` in `POST /v1/challenges` payloads (`400 SCOPE_NOT_ACCEPTED`).
3. Always match `context.origin` exactly against the registered application origin.
4. For `fund_transfer`, always include `transactionContext.type = "fund_transfer"`.
5. Fail closed: authorize sensitive actions only when server-side `GET /v1/challenges/:challengeId/status` confirms `status === "APPROVED"`.

================================================================================
# TRUSTLITH-INTEGRATION.md
================================================================================

# Trustlith Integration Guide (`TRUSTLITH-INTEGRATION.md`)

> **Capability Scope Notice (Important for Humans & AI Coding Agents)**
> - **LIVE / SUPPORTED NOW (Public Runtime API v1):** Passwordless step-up authentication (`action: "login"`) and fund transfer authorization (`action: "fund_transfer"` with `transactionContext.type = "fund_transfer"`), backed by device-bound ES256 P-256 keys (`TRUSTLITH-AUTH-V1\0`).
> - **PLANNED / NOT YET AVAILABLE (V2):** Developer-defined Custom Auditable Transactions (`action: "custom"`, `POST /v1/challenges/:id/consume`, `/acknowledge-execution`, Transaction Studio) are specified in proposed ADR 0022 and are **not implemented on the Runtime API yet**. Do not generate calls to V2 endpoints against V1 environments.
> - **SDK Status Notice:** `@trustlith/sdk-js` in the monorepo is a local Phase 1 prototype only and is **not for production use**. Integrate directly over HTTPS using your server runtime (`fetch`, `httpx`, etc.) with `Authorization: Bearer <TRUSTLITH_API_KEY>`.
> - **Pre-Production DEV Notice:** Controlled DEV deployments run with public signup disabled (`PORTAL_PUBLIC_SIGNUP_ENABLED="false"`). Unattested DEV device claims (`assurance: "HARDWARE_BACKED" | "SOFTWARE"`) remain `NOT_EVALUATED` under ADR 0010 until future platform attestation ships.

---

## 1. Security Rules (Non-Negotiable)

1. **Server-Side Only Secrets:** Store `TRUSTLITH_API_KEY` (`trl_pd1_...`) and `TRUSTLITH_API_BASE_URL` strictly on your backend server environment (`.env` / secrets manager). **Never** expose Trustlith API keys in frontend JS/TS, mobile apps, `NEXT_PUBLIC_*` vars, query strings, or git commits.
2. **Never Supply Tenant or App Overrides:** Never pass `tenantId` or `applicationId` in `POST /v1/challenges` bodies (`400 SCOPE_NOT_ACCEPTED`). Trustlith derives tenant and application ownership solely from your Bearer credential.
3. **Origin Matching Is Strict:** `context.origin` in `POST /v1/challenges` must **exact-match** the registered origin configured for your application in Trustlith Developer Portal (`404 USER_OR_ORIGIN_NOT_AVAILABLE` otherwise).
4. **Fail Closed on Non-`APPROVED` Challenges:** Only treat the challenge as authorized when `GET /v1/challenges/:challengeId/status` returns `status === "APPROVED"` (from your server, never trusted solely from browser state). Treat `PENDING`, `EXPIRED`, `REJECTED`, and `CANCELLED` as **denied / incomplete**.
5. **`fund_transfer` Requires `type: "fund_transfer"`:** When `action === "fund_transfer"`, `transactionContext` is mandatory and **must** include `type: "fund_transfer"`, `amount` matching `^\d{1,12}\.\d{2}$`, 3-letter uppercase ISO currency (`currency`), `recipientId`, `recipientDisplay`, and `transactionReference`.

---

## 2. Five-Step Pilot Onboarding Checklist

1. **Register Application (Portal → Applications):** Create an application with your exact backend/web origin (for example `https://app.example.com`).
2. **Issue & Activate API Credential (Portal → API Credentials):** Issue a key, complete the one-time reveal step, copy it into your backend secret store as `TRUSTLITH_API_KEY`, and **Activate** it in Portal. Issued/inactive keys fail `401`.
3. **Map Your Test User (Portal → Test Users):** Add the `externalUserId` string your backend uses (for example immutable user UUID `"usr_01J..."` or `"user_12345"`).
4. **Enroll Trustlith Authenticator (Portal → Enrollment or `POST /v1/enrollments`):** Generate a one-time QR handoff and scan it with Trustlith Authenticator on iOS/Android so the user's device binds an ES256 P-256 key.
5. **Trigger & Poll Challenges from Backend (`POST /v1/challenges` + `GET /v1/challenges/:challengeId/status`):** Issue a challenge (`login` or `fund_transfer`), prompt the user to approve in Trustlith Authenticator, and poll `GET /v1/challenges/:challengeId/status` until terminal status (`APPROVED`, `REJECTED`, `CANCELLED`, or `EXPIRED`).

---

## 3. Verified Public Runtime API v1 Endpoints (Application Bearer)

| Method & Path | Scope | Purpose |
| --- | --- | --- |
| `GET /health` | None | Verify Runtime availability (`{ status: "ok", ... }`). |
| `POST /v1/enrollments` | `enrollments:create` | Create a 10-minute one-time primary enrollment for an `ACTIVE` mapped `externalUserId`. |
| `POST /v1/enrollment-handoffs` | `enrollments:create` | Mint an opaque 5-minute single-use QR/deep-link handoff (`FIRST_DEVICE` / `ADDITIONAL_DEVICE`) returning `ref` once. |
| `POST /v1/challenges` | `challenges:create` | Create a `login` or `fund_transfer` challenge (`TTL 120s`, returns `{ challengeId, status: "PENDING", expiresAt }`). |
| `GET /v1/challenges/:challengeId/status` | `challenges:read` | Poll authoritative status (`PENDING`, `APPROVED`, `REJECTED`, `CANCELLED`, `EXPIRED`). |
| `POST /v1/challenges/:challengeId/cancel` | `challenges:cancel` | Atomically cancel an unexpired `PENDING` challenge (`CANCELLED`); fails `409 INVALID_STATE_TRANSITION` if overdue/terminal. |

---

## 4. Reference Server-Side Implementation (TypeScript / Node.js 20+)

```ts
const BASE_URL = process.env.TRUSTLITH_API_BASE_URL!; // e.g. https://provisioning-dev.trustlith.com
const API_KEY = process.env.TRUSTLITH_API_KEY!;        // Server-side secret only
const APP_ORIGIN = process.env.APP_PUBLIC_ORIGIN!;     // Must match registered Portal app origin

export type ChallengeStatus = "PENDING" | "APPROVED" | "REJECTED" | "CANCELLED" | "EXPIRED";

async function trustlithFetch<T>(path: string, init?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE_URL.replace(/\/+$/, "")}${path}`, {
    ...init,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${API_KEY}`,
      ...init?.headers,
    },
  });
  const data = (await res.json()) as T & { error?: { code: string; message: string } };
  if (!res.ok) {
    throw new Error(`Trustlith API error ${res.status}: ${data.error?.code ?? "UNKNOWN"} - ${data.error?.message ?? ""}`);
  }
  return data;
}

export async function startLoginChallenge(externalUserId: string, deviceLabel = "Web Browser") {
  return trustlithFetch<{ challengeId: string; status: "PENDING"; expiresAt: string }>("/v1/challenges", {
    method: "POST",
    body: JSON.stringify({
      externalUserId,
      action: "login",
      context: { origin: APP_ORIGIN, device: deviceLabel },
    }),
  });
}

export async function startFundTransferChallenge(input: {
  externalUserId: string;
  amount: string; // e.g. "250.00" (strict ^\d{1,12}\.\d{2}$)
  currency: string; // e.g. "USD" (^[A-Z]{3}$)
  recipientId: string;
  recipientDisplay: string;
  transactionReference: string;
  deviceLabel?: string;
}) {
  return trustlithFetch<{ challengeId: string; status: "PENDING"; expiresAt: string }>("/v1/challenges", {
    method: "POST",
    body: JSON.stringify({
      externalUserId: input.externalUserId,
      action: "fund_transfer",
      context: { origin: APP_ORIGIN, device: input.deviceLabel ?? "Web Checkout" },
      transactionContext: {
        type: "fund_transfer",
        amount: input.amount,
        currency: input.currency,
        recipientId: input.recipientId,
        recipientDisplay: input.recipientDisplay,
        transactionReference: input.transactionReference,
      },
    }),
  });
}

export async function checkChallengeStatus(challengeId: string) {
  return trustlithFetch<{ challengeId: string; status: ChallengeStatus; expiresAt: string; action: "login" | "fund_transfer" }>(
    `/v1/challenges/${encodeURIComponent(challengeId)}/status`,
  );
}

export async function cancelPendingChallenge(challengeId: string) {
  return trustlithFetch<{ challengeId: string; status: "CANCELLED" }>(
    `/v1/challenges/${encodeURIComponent(challengeId)}/cancel`,
    { method: "POST" },
  );
}
```

---

## 5. Error Codes & Handling Matrix

| HTTP | Error `code` | Cause & Recommended Action |
| --- | --- | --- |
| `400` | `SCOPE_NOT_ACCEPTED` | Remove `tenantId` / `applicationId` from request body. |
| `400` | `INVALID_ACTION` / `INVALID_TRANSACTION` | Ensure `action` is `"login"` or `"fund_transfer"`, and `fund_transfer` includes `transactionContext.type: "fund_transfer"` + formatted `amount` (`0.00`). |
| `401` | `UNAUTHORIZED` | Credential missing, revoked, expired, not yet activated, or tenant/app suspended. |
| `403` | `FORBIDDEN` / `ENTITLEMENT_INACTIVE` | Key lacks the required route scope or organization entitlement is inactive. |
| `404` | `USER_OR_ORIGIN_NOT_AVAILABLE` / `USER_NOT_AVAILABLE` / `CHALLENGE_NOT_FOUND` | Verify `externalUserId` is mapped as `ACTIVE` in this app and `context.origin` matches the registered Portal origin. |
| `409` | `INVALID_STATE_TRANSITION` | Challenge already approved, rejected, cancelled, or expired before `/cancel`. |
| `429` | `CHALLENGE_LIMIT_REACHED` / `AUTHENTICATION_LIMIT_REACHED` / `ENROLLMENT_LIMIT_REACHED` | Respect pending-challenge limits, cooldowns, and daily/monthly sandbox quotas; avoid tight polling loops. |

---

## 6. AI Coding Agent Guardrails

When an AI coding agent integrates Trustlith into a codebase:
- Wire all Trustlith HTTP calls inside backend API routes, server actions, or Edge/Worker middleware—**never** inside client components.
- Bind `externalUserId` from the caller's verified primary session (never accept raw `externalUserId` from untrusted client form fields).
- Enforce server-side authorization gates: after `POST /v1/challenges`, store `{ challengeId, externalUserId, purpose, targetAction }` in a pending server session/DB row and complete the sensitive action **only** when server-side `GET /v1/challenges/:challengeId/status` confirms `status === "APPROVED"` for that exact `challengeId` and user.
- Provide user-facing **Cancel** support calling `POST /v1/challenges/:challengeId/cancel` if the user abandons step-up.
- Handle timeouts cleanly (`120s` challenge TTL) and allow the user to start a fresh challenge if `EXPIRED`, `CANCELLED`, or `REJECTED`.

================================================================================
# docs/developer-center/README.md
================================================================================

# Trustlith Developer Center

Integrate hardware-backed cryptographic authentication and transaction authorization into your backend application in minutes. Choose either our **Manual Integration** path or our **AI Coding Agent** path.

> **Current Platform Capability Matrix**
> - **LIVE — Public Runtime API v1:** `login` step-up authentication, `fund_transfer` transaction authorization (`TRUSTLITH-AUTH-V1\0` ES256 P-256), challenge polling, atomic challenge cancellation, and programmatic device enrollment handoffs.
> - **PLANNED — Custom Auditable Transactions V2:** Developer-defined custom transaction schemas (`action: "custom"`, `/consume`, `/acknowledge-execution`, Transaction Studio) are specified in proposed **ADR 0022** (pending separate owner acceptance on PR #70) and are **not deployed yet**.
> - **Prototype SDK Notice:** `@trustlith/sdk-js` in `packages/sdk-js` is a local Phase 1 prototype only and must **not** be used in production. Integrate directly against the verified HTTPS REST endpoints below using server-side `fetch` / HTTP clients.

---

## Two Equally Supported Integration Paths

### Path A: Integrate Manually
1. [5-Step Quickstart](./quickstart.md) — Workspace setup, API key activation, test-user mapping, QR enrollment, and live challenge verification.
2. [User Enrollment Guide](./user-enrollment.md) — Programmatic `POST /v1/enrollments` + opaque QR/deep-link handoffs (`POST /v1/enrollment-handoffs`).
3. [API Reference](./api-reference.md) — All verified V1 routes, Bearer scopes, origin rules, and error codes (`docs/openapi.yaml`).
4. [Code Examples](./examples.md) — Copy-ready server-side examples in **Node.js (TypeScript/Fetch)**, **Python**, and **cURL**.
5. [Developer Changelog](./changelog.md) — V1 release notes clearly separated from planned V2 features.

### Path B: Integrate with an AI Coding Agent
1. [AI Coding Agent Guide](./ai-agent-guide.md) — Copy-ready prompt templates, architectural boundaries, and verification checklist for Claude Code, Cursor, Codex, and Antigravity.
2. Download the self-contained bundle [TRUSTLITH-INTEGRATION.md](../../TRUSTLITH-INTEGRATION.md) into your repository root.
3. Point your AI assistant at [`llms.txt`](../../llms.txt), `llms-full.txt` (generated distribution artifact), and [`openapi.yaml`](../openapi.yaml).

================================================================================
# docs/developer-center/quickstart.md
================================================================================

# 5-Step Quickstart (Public Runtime API v1)

Follow this sequence to connect an application to Trustlith using your Developer Portal workspace:

## Step 1 — Register Your Application & Origin
In Developer Portal → **Applications**, register your application name and exact canonical origin URL (for example `https://app.example.com`). Every `POST /v1/challenges` request must submit this exact `context.origin` string.

## Step 2 — Issue, Reveal & Activate a Backend API Credential
1. Open Developer Portal → **API Credentials** for your application.
2. Issue a new credential and complete the **one-time reveal** step.
3. Save the credential in your backend server's secret store as `TRUSTLITH_API_KEY`.
4. Click **Activate** in Portal. Keys that remain `ISSUED` or are `REVOKED` / `EXPIRED` fail closed with `401`.

> **Security Warning:** Never place `TRUSTLITH_API_KEY` inside browser JavaScript, mobile apps, or client-visible environment variables (`NEXT_PUBLIC_*`).

## Step 3 — Map an External User
Open Developer Portal → **Test Users** and register an immutable external user identifier (`externalUserId`, max 128 chars, for example a database user UUID or `"user_12345"`).

## Step 4 — Enroll Trustlith Authenticator
Open Developer Portal → **Enrollment** (or follow [User Enrollment Guide](./user-enrollment.md) programmatically), generate a one-time QR handoff for the mapped user, and scan it with **Trustlith Authenticator** on iOS or Android. Wait until the Portal shows an active hardware-bound P-256 device.

## Step 5 — Trigger & Verify a Challenge from Your Backend
1. Call `POST /v1/challenges` with `action: "login"` or `action: "fund_transfer"` (see [Code Examples](./examples.md)).
2. Instruct your frontend to display a waiting state ("Approve in Trustlith Authenticator within 2 minutes").
3. Poll `GET /v1/challenges/:challengeId/status` from your backend every `2`–`3` seconds (stopping immediately on terminal status or user cancel).
4. Grant access or execute the sensitive mutation **only** when your backend observes `status === "APPROVED"`. Reject cleanly on `REJECTED`, `CANCELLED`, or `EXPIRED`.

================================================================================
# docs/developer-center/user-enrollment.md
================================================================================

# User Enrollment Guide (V1)

Before a user can approve `login` or `fund_transfer` challenges, they must be mapped in your application and have at least one enrolled Trustlith Authenticator device holding a P-256 key.

## Option 1 — Developer Portal Test Workbench (Fastest for Pilot Setup)
1. Open Developer Portal → **Test Users** and register your user's immutable `externalUserId`.
2. Open Developer Portal → **Enrollment**, choose the user, and click **Start First-Device QR Enrollment**.
3. Scan the rendered QR code using **Trustlith Authenticator** on iOS or Android and confirm biometric prompt completion.

## Option 2 — Programmatic Backend Handoff (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`)
For an active mapped user in `tenant_users`:

1. **Create a 10-minute enrollment (`enrollments:create`):**
   ```http
   POST /v1/enrollments
   Authorization: Bearer <TRUSTLITH_API_KEY>
   Content-Type: application/json

   { "externalUserId": "user_12345" }
   ```
   Returns `{ enrollmentId, enrollmentToken, expiresAt, developmentOnly }`. Keep `enrollmentToken` server-side!

2. **Mint an opaque single-use QR/deep-link handoff (`enrollments:create`):**
   ```http
   POST /v1/enrollment-handoffs
   Authorization: Bearer <TRUSTLITH_API_KEY>
   Content-Type: application/json

   { "enrollmentId": "<enrollmentId>", "ceremonyType": "FIRST_DEVICE" }
   ```
   Returns `{ handoffId, ceremonyType, expiresAt, ref }` (`ref` expires within 5 minutes, returned **once** and never logged). Encode `ref` into your UI's one-time QR code or mobile deep link; Trustlith Authenticator redeems `ref` directly against `/v1/enrollment-handoffs/redeem` without ever seeing `enrollmentToken`.

================================================================================
# docs/developer-center/api-reference.md
================================================================================

# Public Runtime API v1 Reference

Machine-readable schema: [`docs/openapi.yaml`](../openapi.yaml).

## Authentication & Scoping Rules
- **Header:** `Authorization: Bearer <TRUSTLITH_API_KEY>` (Application Bearer routes) or `Authorization: Device <retrieval-token>` (Authenticator device routes).
- **Server-Derived Ownership:** Never include `tenantId` or `applicationId` in `POST /v1/challenges` payloads (`400 SCOPE_NOT_ACCEPTED`).
- **Strict Origin Binding:** `context.origin` must exact-match your application's registered origin (`404 USER_OR_ORIGIN_NOT_AVAILABLE` on mismatch).
- **Challenge TTL:** `120` seconds from creation (`expiresAt`).

## Application Bearer Endpoints

| Method & Path | Required Scope | Request Body | Success Response |
| --- | --- | --- | --- |
| `GET /health` | None | — | `200 { status: "ok", service: "trustlith-api", environment, phase }` |
| `POST /v1/enrollments` | `enrollments:create` | `{ externalUserId }` | `201 { enrollmentId, enrollmentToken, expiresAt, developmentOnly }` |
| `POST /v1/enrollment-handoffs` | `enrollments:create` | `{ enrollmentId, ceremonyType: "FIRST_DEVICE" \| "ADDITIONAL_DEVICE" }` | `201 { handoffId, ceremonyType, expiresAt, ref }` |
| `POST /v1/challenges` | `challenges:create` | `{ externalUserId, action: "login" \| "fund_transfer", context: { origin, device }, transactionContext? }` | `201 { challengeId, status: "PENDING", expiresAt }` |
| `GET /v1/challenges/:challengeId/status` | `challenges:read` | — | `200 { challengeId, status, expiresAt, action }` |
| `POST /v1/challenges/:challengeId/cancel` | `challenges:cancel` | — | `200 { challengeId, status: "CANCELLED" }` |

## Challenge `status` State Machine
- `PENDING`: Waiting for device approval/rejection prior to `expiresAt`.
- `APPROVED`: Device submitted a verified ES256 P-256 signature over `TRUSTLITH-AUTH-V1\0`.
- `REJECTED`: User explicitly declined the challenge on their Authenticator.
- `CANCELLED`: Your backend cancelled an unexpired `PENDING` challenge via `/cancel`.
- `EXPIRED`: Challenge passed `expiresAt` (`120s`) without signature verification.

## Common Error Codes
- `400 SCOPE_NOT_ACCEPTED` — `tenantId` or `applicationId` passed in request JSON.
- `400 INVALID_ACTION` / `400 INVALID_TRANSACTION` — Missing `transactionContext.type: "fund_transfer"`, malformed `amount` (`^\d{1,12}\.\d{2}$`), or non-ISO 3-letter `currency`.
- `401 UNAUTHORIZED` — Missing, unactivated, expired, or revoked Bearer credential, or suspended tenant/app.
- `403 FORBIDDEN` / `403 ENTITLEMENT_INACTIVE` — Credential lacks the route's required scope or plan entitlement is inactive.
- `404 USER_OR_ORIGIN_NOT_AVAILABLE` — `externalUserId` is not mapped/active for this app OR `context.origin` does not match the registered origin.
- `409 INVALID_STATE_TRANSITION` — Attempted `/cancel` on an already resolved or overdue/expired challenge.
- `429 CHALLENGE_LIMIT_REACHED` / `429 AUTHENTICATION_LIMIT_REACHED` / `429 ENROLLMENT_LIMIT_REACHED` — Pending ceiling, cooldown, or quota limit reached.

================================================================================
# docs/developer-center/examples.md
================================================================================

# Integration Code Examples (V1 Backend)

> Use these snippets **exclusively on your backend server**. Replace `TRUSTLITH_API_BASE_URL` (for DEV: `https://provisioning-dev.trustlith.com`, local: `http://localhost:8787`), `TRUSTLITH_API_KEY`, and `APP_PUBLIC_ORIGIN` with your server environment variables.

## 1. Node.js / TypeScript (Built-in `fetch`)

### Login Step-Up + Polling + Cancel
```ts
const baseUrl = process.env.TRUSTLITH_API_BASE_URL!.replace(/\/+$/, "");
const apiKey = process.env.TRUSTLITH_API_KEY!;
const appOrigin = process.env.APP_PUBLIC_ORIGIN!;

export async function createLoginChallenge(externalUserId: string, deviceLabel: string) {
  const res = await fetch(`${baseUrl}/v1/challenges`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      externalUserId,
      action: "login",
      context: { origin: appOrigin, device: deviceLabel },
    }),
  });
  if (!res.ok) throw new Error(`Challenge create failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as { challengeId: string; status: "PENDING"; expiresAt: string };
}

export async function getChallengeStatus(challengeId: string) {
  const res = await fetch(`${baseUrl}/v1/challenges/${encodeURIComponent(challengeId)}/status`, {
    headers: { Authorization: `Bearer ${apiKey}` },
  });
  if (!res.ok) throw new Error(`Status check failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as {
    challengeId: string;
    status: "PENDING" | "APPROVED" | "REJECTED" | "CANCELLED" | "EXPIRED";
    expiresAt: string;
    action: "login" | "fund_transfer";
  };
}

export async function cancelChallenge(challengeId: string) {
  const res = await fetch(`${baseUrl}/v1/challenges/${encodeURIComponent(challengeId)}/cancel`, {
    method: "POST",
    headers: { Authorization: `Bearer ${apiKey}` },
  });
  if (!res.ok) throw new Error(`Cancel failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as { challengeId: string; status: "CANCELLED" };
}
```

### Fund Transfer Authorization (`type: "fund_transfer"` Mandatory)
```ts
export async function createFundTransferChallenge(input: {
  externalUserId: string;
  amount: string;               // e.g. "250.00"
  currency: string;             // e.g. "USD"
  recipientId: string;          // e.g. "acct_vendor_01"
  recipientDisplay: string;     // e.g. "Acme Cloud Services"
  transactionReference: string; // e.g. "INV-2026-041"
}) {
  const res = await fetch(`${baseUrl}/v1/challenges`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: JSON.stringify({
      externalUserId: input.externalUserId,
      action: "fund_transfer",
      context: { origin: appOrigin, device: "Checkout Session" },
      transactionContext: {
        type: "fund_transfer",
        amount: input.amount,
        currency: input.currency,
        recipientId: input.recipientId,
        recipientDisplay: input.recipientDisplay,
        transactionReference: input.transactionReference,
      },
    }),
  });
  if (!res.ok) throw new Error(`Fund transfer create failed: ${res.status} ${await res.text()}`);
  return (await res.json()) as { challengeId: string; status: "PENDING"; expiresAt: string };
}
```

---

## 2. Python (`httpx` or standard library `urllib`)

```python
import os
import json
import urllib.request

BASE_URL = os.environ["TRUSTLITH_API_BASE_URL"].rstrip("/")
API_KEY = os.environ["TRUSTLITH_API_KEY"]
APP_ORIGIN = os.environ["APP_PUBLIC_ORIGIN"]


def create_fund_transfer_challenge(external_user_id: str, amount: str, currency: str, recipient_id: str, recipient_display: str, reference: str) -> dict:
    payload = {
        "externalUserId": external_user_id,
        "action": "fund_transfer",
        "context": {"origin": APP_ORIGIN, "device": "Python Backend"},
        "transactionContext": {
            "type": "fund_transfer",
            "amount": amount,
            "currency": currency,
            "recipientId": recipient_id,
            "recipientDisplay": recipient_display,
            "transactionReference": reference,
        },
    }
    req = urllib.request.Request(
        f"{BASE_URL}/v1/challenges",
        data=json.dumps(payload).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {API_KEY}",
        },
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=10) as resp:
        return json.loads(resp.read().decode("utf-8"))
```

---

## 3. cURL

```bash
# 1. Trigger a login challenge
curl -sS -X POST "$TRUSTLITH_API_BASE_URL/v1/challenges" \
  -H "Authorization: Bearer $TRUSTLITH_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "externalUserId": "user_12345",
    "action": "login",
    "context": {
      "origin": "https://app.example.com",
      "device": "CLI Verification"
    }
  }'

# 2. Poll challenge status
curl -sS "$TRUSTLITH_API_BASE_URL/v1/challenges/<challengeId>/status" \
  -H "Authorization: Bearer $TRUSTLITH_API_KEY"

# 3. Cancel an active pending challenge
curl -sS -X POST "$TRUSTLITH_API_BASE_URL/v1/challenges/<challengeId>/cancel" \
  -H "Authorization: Bearer $TRUSTLITH_API_KEY"
```

================================================================================
# docs/developer-center/ai-agent-guide.md
================================================================================

# AI Coding Agent Integration Guide

Trustlith supports AI-assisted integration out of the box using [`TRUSTLITH-INTEGRATION.md`](../../TRUSTLITH-INTEGRATION.md), [`llms.txt`](../../llms.txt), and [`docs/openapi.yaml`](../openapi.yaml).

## Quick Workflow for Developers Using Claude Code, Cursor, Codex, or Antigravity
1. Download [`TRUSTLITH-INTEGRATION.md`](../../TRUSTLITH-INTEGRATION.md) into the root of your application repository (or download directly from Developer Portal → **Documentation** → **Integrate with AI Agent**).
2. Store `TRUSTLITH_API_KEY`, `TRUSTLITH_API_BASE_URL`, and `APP_PUBLIC_ORIGIN` exclusively in your server `.env` / secret store (never pass live secrets in AI chat prompts).
3. Paste the prompt below into your AI coding agent.

## Recommended AI Agent Prompt
```text
Read TRUSTLITH-INTEGRATION.md at the repository root and integrate Trustlith Public Runtime API v1 into our backend for <step-up login / fund transfer verification>.

Strict requirements:
1. Place all Trustlith API calls strictly on the server using process.env.TRUSTLITH_API_BASE_URL and process.env.TRUSTLITH_API_KEY. Never expose API keys to browser or client bundles.
2. Never send tenantId or applicationId in POST /v1/challenges payloads. Set context.origin to process.env.APP_PUBLIC_ORIGIN matching our registered Trustlith application origin.
3. Use action: "login" for login step-up or action: "fund_transfer" with transactionContext.type: "fund_transfer" for transfers. Do NOT use unimplemented V2 custom transaction endpoints.
4. Persist pending challengeId bound to the user's primary authenticated session, poll GET /v1/challenges/:id/status from the server, support POST /v1/challenges/:id/cancel, and fail closed unless status === "APPROVED".
5. Add unit/integration tests covering APPROVED, REJECTED, CANCELLED, EXPIRED, and error handling.
```

## Mandatory Verification Checklist After AI Generation
- [ ] Grep client/browser bundle directories to confirm `TRUSTLITH_API_KEY` never appears client-side.
- [ ] Confirm `POST /v1/challenges` request contains no `tenantId` or `applicationId` keys.
- [ ] Confirm `fund_transfer` requests include literal `transactionContext.type === "fund_transfer"` and 2-decimal string `amount`.
- [ ] Confirm protected backend actions fail closed when `status` is `PENDING`, `REJECTED`, `CANCELLED`, or `EXPIRED`.
- [ ] Run end-to-end verification in Trustlith Portal → **Test Authentication** and **Activity & Audit Logs**.

================================================================================
# docs/developer-center/changelog.md
================================================================================

# Trustlith Developer Changelog

Canonical record of Developer Center & Runtime API milestones.

> **Important:** **Public Runtime API v1** features below are live in controlled DEV; **Custom Auditable Transactions V2** (proposed ADR 0022) remains planned and **is not yet deployed**.

---

## `1.0.0-dev-pilot` (2026-12-03) — Controlled V1 Developer Pilot & Developer Center Distribution

### Supported V1 Capabilities (Live)
- **Public Runtime API v1:**
  - `POST /v1/challenges` supporting `action: "login"` and `action: "fund_transfer"` (requiring `transactionContext.type: "fund_transfer"`), strictly derived from authenticated `Authorization: Bearer <key>` credentials.
  - `GET /v1/challenges/:challengeId/status` returning authoritative `PENDING | APPROVED | REJECTED | CANCELLED | EXPIRED` resolution with automatic lazy expiry reconciliation.
  - `POST /v1/challenges/:challengeId/cancel` enforcing atomic `PENDING` + unexpired cancellation paired with `CHALLENGE_CANCELLED` audit emission (hardened in PR #69).
  - `POST /v1/enrollments` & `POST /v1/enrollment-handoffs` enabling programmatic 10-minute enrollments and single-use 5-minute opaque QR/deep-link handoffs.
- **Developer Portal & Developer Center (`PR-2` / `PR #71`):**
  - Dual-path **Developer Center** in Portal (`/workspace/docs`) with **Integrate Manually** and **Integrate with AI Coding Agent** workflows, Node.js/cURL/Python examples, Copy URL, Copy Prompt, and authenticated app-specific integration kit downloads without embedded secrets.
  - Canonical static documentation distribution architecture targeting Cloudflare Pages (`developers.trustlith.com`) and versioned R2 artifacts (`v1.0.0-dev-pilot/` + `latest/`), including `llms.txt`, `llms-full.txt`, `TRUSTLITH-INTEGRATION.md`, OpenAPI `3.1.0` specification, and downloadable `.zip` integration kits.
  - Portal Activity & Auditability (`/workspace/activity`) supporting source/outcome/application filtering, role-only actor attribution, tracked challenge summaries, and redacted JSON export.

### Planned / Not Yet Deployed (Separate Track)
- **Custom Auditable Transactions V2 (`ADR 0022` — Proposed):** Developer-defined transaction schemas (`action: "custom"`), atomic consumption (`/v1/challenges/:id/consume`), execution acknowledgement (`/acknowledge-execution`), and Transaction Studio (`/workspace/transactions`). Do not target V2 endpoints from V1 pilot integrations.
- **Prototype SDK Notice:** `@trustlith/sdk-js` remains a non-production local Phase 1 prototype; call REST endpoints directly from backend code.

================================================================================
# docs/openapi.yaml
================================================================================

```yaml
openapi: 3.1.0
info:
  title: Trustlith Runtime API v1
  version: 1.0.0-dev-pilot
  description: >
    Authoritative REST API for Trustlith cryptographic authentication and
    high-trust transaction authorization (Public Runtime API v1).
    Application-facing routes require a server-side `Authorization: Bearer <key>`
    credential scoped to one tenant and application; Trustlith derives scope
    from the credential and rejects caller-supplied `tenantId` or `applicationId`.
    Device-facing endpoints use `Authorization: Device <retrieval-token>` or
    one-time enrollment handoff redemption. Custom Auditable Transactions (V2)
    remain planned under proposed ADR 0022 and are not exposed on this API.
servers:
  - url: https://provisioning-dev.trustlith.com
    description: Controlled DEV Runtime (Access/WAF protected)
  - url: http://localhost:8787
    description: Local Wrangler development runtime
tags:
  - name: Health
    description: Service availability probe
  - name: Application API (Server-Side)
    description: Endpoints called exclusively from your trusted application backend using Bearer API credentials
  - name: Enrollment & Device Protocol
    description: Endpoints called by Trustlith Authenticator mobile clients using one-time handoffs or device Bearer tokens
paths:
  /health:
    get:
      tags: [Health]
      operationId: getHealth
      summary: Check Trustlith Runtime availability
      responses:
        "200":
          description: Service is reachable and configured.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/HealthResponse"
  /v1/enrollments:
    post:
      tags: [Application API (Server-Side)]
      operationId: createEnrollment
      summary: Create a one-time primary device enrollment for a mapped user
      description: Requires scope `enrollments:create` and an existing `ACTIVE` user mapping for `externalUserId`.
      security: [{ ApplicationBearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateEnrollmentRequest"
      responses:
        "201":
          description: One-time enrollment created (valid for 10 minutes).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreateEnrollmentResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "404": { $ref: "#/components/responses/ApiErrorResponse" }
        "429": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/enrollment-handoffs:
    post:
      tags: [Application API (Server-Side)]
      operationId: createEnrollmentHandoff
      summary: Mint an opaque QR/deep-link handoff token for an existing pending enrollment
      description: Requires scope `enrollments:create`. Returns the single-use opaque `ref` exactly once (expires within 5 minutes, capped by underlying enrollment expiry).
      security: [{ ApplicationBearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateEnrollmentHandoffRequest"
      responses:
        "201":
          description: Opaque handoff created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreateEnrollmentHandoffResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "404": { $ref: "#/components/responses/ApiErrorResponse" }
        "409": { $ref: "#/components/responses/ApiErrorResponse" }
        "410": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/enrollments/{enrollmentId}/complete:
    post:
      tags: [Enrollment & Device Protocol]
      operationId: completeEnrollment
      summary: Complete primary enrollment with a device-generated P-256 public key
      parameters:
        - in: path
          name: enrollmentId
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CompleteEnrollmentRequest"
      responses:
        "201":
          description: Device and P-256 credential registered.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CompleteEnrollmentResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "409": { $ref: "#/components/responses/ApiErrorResponse" }
        "429": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/enrollment-handoffs/redeem:
    post:
      tags: [Enrollment & Device Protocol]
      operationId: redeemEnrollmentHandoff
      summary: Redeem an opaque QR/deep-link handoff reference from Trustlith Authenticator
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RedeemEnrollmentHandoffRequest"
      responses:
        "201":
          description: Handoff redeemed and enrollment or additional-device claim completed.
          content:
            application/json:
              schema:
                type: object
                additionalProperties: true
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "409": { $ref: "#/components/responses/ApiErrorResponse" }
        "410": { $ref: "#/components/responses/ApiErrorResponse" }
        "429": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/challenges:
    post:
      tags: [Application API (Server-Side)]
      operationId: createChallenge
      summary: Create a V1 login or fund_transfer authentication challenge
      description: >
        Requires scope `challenges:create`. Caller must NOT include `tenantId`
        or `applicationId` in the JSON body (`400 SCOPE_NOT_ACCEPTED`).
        `context.origin` must exactly match the registered application origin.
        When `action` is `"fund_transfer"`, `transactionContext` is mandatory and
        must include `type: "fund_transfer"`.
      security: [{ ApplicationBearer: [] }]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CreateChallengeRequest"
      responses:
        "201":
          description: Pending challenge created (TTL 120 seconds).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CreateChallengeResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "404": { $ref: "#/components/responses/ApiErrorResponse" }
        "429": { $ref: "#/components/responses/ApiErrorResponse" }
        "503": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/challenges/{challengeId}/status:
    get:
      tags: [Application API (Server-Side)]
      operationId: getChallengeStatus
      summary: Read authoritative challenge status within the credential's tenant and application
      description: Requires scope `challenges:read`. Lazily expires overdue `PENDING` challenges before returning status.
      security: [{ ApplicationBearer: [] }]
      parameters:
        - in: path
          name: challengeId
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Authoritative challenge status.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChallengeStatusResponse"
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "404": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/challenges/{challengeId}/cancel:
    post:
      tags: [Application API (Server-Side)]
      operationId: cancelChallenge
      summary: Cancel a pending unexpired challenge
      description: >
        Requires scope `challenges:cancel`. Atomically transitions an unexpired
        `PENDING` challenge in the caller's tenant and application to `CANCELLED`.
        Overdue or non-pending challenges fail closed with `409 INVALID_STATE_TRANSITION`.
      security: [{ ApplicationBearer: [] }]
      parameters:
        - in: path
          name: challengeId
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Pending challenge cancelled.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CancelChallengeResponse"
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
        "409": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/devices/{deviceId}/challenges:
    get:
      tags: [Enrollment & Device Protocol]
      operationId: listDeviceChallenges
      summary: Fetch active pending challenges eligible for this registered device
      security: [{ DeviceBearer: [] }]
      parameters:
        - in: path
          name: deviceId
          required: true
          schema: { type: string }
      responses:
        "200":
          description: Pending challenges with canonical TRUSTLITH-AUTH-V1 fields.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DeviceChallengesResponse"
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/challenges/{challengeId}/approve:
    post:
      tags: [Enrollment & Device Protocol]
      operationId: approveChallenge
      summary: Verify an ES256 P-256 device signature over TRUSTLITH-AUTH-V1\0 and approve a challenge
      security: [{ DeviceBearer: [] }]
      parameters:
        - in: path
          name: challengeId
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ApprovalRequest"
      responses:
        "200":
          description: Signature verified (`APPROVED`) or challenge already resolved (`already_resolved`).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChallengeResolutionResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "429": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/challenges/{challengeId}/reject:
    post:
      tags: [Enrollment & Device Protocol]
      operationId: rejectChallenge
      summary: Reject a pending challenge from an authorized device
      description: V1 accepts an authenticated device rejection with `credentialId` (`accepted_unsigned_device_rejection`).
      security: [{ DeviceBearer: [] }]
      parameters:
        - in: path
          name: challengeId
          required: true
          schema: { type: string }
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [credentialId]
              properties:
                credentialId:
                  type: string
                  maxLength: 100
      responses:
        "200":
          description: Challenge rejected or already resolved.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChallengeResolutionResponse"
        "400": { $ref: "#/components/responses/ApiErrorResponse" }
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
  /v1/development/overview:
    get:
      tags: [Application API (Server-Side)]
      operationId: getDevelopmentOverview
      summary: Read application-scoped development observability projections
      description: Requires scope `development:read` (not granted to standard V1 pilot keys unless explicitly provisioned).
      security: [{ ApplicationBearer: [] }]
      responses:
        "200":
          description: Application-scoped telemetry, devices, challenges, and audit summary.
        "401": { $ref: "#/components/responses/ApiErrorResponse" }
        "403": { $ref: "#/components/responses/ApiErrorResponse" }
components:
  securitySchemes:
    ApplicationBearer:
      type: http
      scheme: bearer
      description: "Server-only API credential (`Authorization: Bearer trl_pd1_...`). Scoped strictly to one tenant and application."
    DeviceBearer:
      type: apiKey
      in: header
      name: Authorization
      description: "Device authorization header formatted as `Authorization: Device <retrieval-token>`."
  responses:
    ApiErrorResponse:
      description: Structured error payload
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/ApiError"
  schemas:
    ApiError:
      type: object
      additionalProperties: false
      required: [error]
      properties:
        error:
          type: object
          additionalProperties: false
          required: [code, message]
          properties:
            code: { type: string, example: INVALID_REQUEST }
            message: { type: string }
    HealthResponse:
      type: object
      additionalProperties: false
      required: [status, service, environment, phase]
      properties:
        status: { type: string, const: ok }
        service: { type: string, const: trustlith-api }
        environment: { type: string, enum: [development, staging, production] }
        phase: { type: integer }
    CreateEnrollmentRequest:
      type: object
      additionalProperties: false
      required: [externalUserId]
      properties:
        externalUserId:
          type: string
          minLength: 1
          maxLength: 128
          description: External application user identifier already mapped as ACTIVE in the tenant/application.
    CreateEnrollmentResponse:
      type: object
      additionalProperties: false
      required: [enrollmentId, enrollmentToken, expiresAt, developmentOnly]
      properties:
        enrollmentId: { type: string }
        enrollmentToken: { type: string, description: "One-time enrollment secret; mint a QR handoff or deliver securely without logging." }
        expiresAt: { type: string, format: date-time }
        developmentOnly: { type: boolean }
    CreateEnrollmentHandoffRequest:
      type: object
      additionalProperties: false
      required: [enrollmentId, ceremonyType]
      properties:
        enrollmentId: { type: string, maxLength: 100 }
        ceremonyType: { type: string, enum: [FIRST_DEVICE, ADDITIONAL_DEVICE] }
    CreateEnrollmentHandoffResponse:
      type: object
      additionalProperties: false
      required: [handoffId, ceremonyType, expiresAt, ref]
      properties:
        handoffId: { type: string }
        ceremonyType: { type: string, enum: [FIRST_DEVICE, ADDITIONAL_DEVICE] }
        expiresAt: { type: string, format: date-time }
        ref: { type: string, description: "Opaque one-time QR/deep-link handoff reference; returned once." }
    CompleteEnrollmentRequest:
      type: object
      additionalProperties: false
      required: [enrollmentToken, displayName, platform, publicKeyJwk]
      properties:
        enrollmentToken: { type: string, maxLength: 160 }
        displayName: { type: string, maxLength: 80 }
        platform: { type: string, enum: [IOS, ANDROID, WINDOWS, MACOS] }
        publicKeyJwk:
          type: object
          required: [kty, crv, x, y]
          properties:
            kty: { type: string, const: EC }
            crv: { type: string, const: P-256 }
            x: { type: string }
            y: { type: string }
        assurance:
          type: string
          enum: [SOFTWARE, HARDWARE_BACKED]
          default: SOFTWARE
          description: Device-reported key protection claim (NOT_EVALUATED per ADR 0010; ATTESTED is rejected).
        idempotencyKey: { type: string, maxLength: 200 }
        retrievalTokenHash:
          type: string
          pattern: "^[a-f0-9]{64}$"
          description: Optional SHA-256 hex digest of caller-generated retrieval token for replayable idempotent completion.
    CompleteEnrollmentResponse:
      type: object
      required: [deviceId, credentialId, algorithm, assurance, tenantId, applicationId, externalUserId, serviceName, developmentOnly]
      properties:
        deviceId: { type: string }
        credentialId: { type: string }
        credentialDbId: { type: string }
        credentialPublicId: { type: string }
        retrievalToken: { type: string, description: Present on first completion when server-minted; never replayed. }
        retrievalTokenFrozen: { type: boolean }
        idempotentReplay: { type: boolean }
        algorithm: { type: string, const: ES256 }
        assurance: { type: string, enum: [SOFTWARE, HARDWARE_BACKED] }
        tenantId: { type: string }
        applicationId: { type: string }
        externalUserId: { type: string }
        serviceName: { type: string }
        developmentOnly: { type: boolean }
    RedeemEnrollmentHandoffRequest:
      type: object
      additionalProperties: false
      required: [ref, redemptionId, displayName, platform, publicKeyJwk, retrievalTokenHash]
      properties:
        ref: { type: string }
        redemptionId: { type: string }
        displayName: { type: string, maxLength: 80 }
        platform: { type: string, enum: [IOS, ANDROID, WINDOWS, MACOS] }
        publicKeyJwk:
          type: object
          required: [kty, crv, x, y]
          properties:
            kty: { type: string, const: EC }
            crv: { type: string, const: P-256 }
            x: { type: string }
            y: { type: string }
        assurance: { type: string, enum: [SOFTWARE, HARDWARE_BACKED], default: SOFTWARE }
        retrievalTokenHash: { type: string, pattern: "^[a-f0-9]{64}$" }
    CreateChallengeRequest:
      type: object
      additionalProperties: false
      required: [externalUserId, action, context]
      properties:
        externalUserId:
          type: string
          minLength: 1
          maxLength: 128
          description: Registered ACTIVE external user identifier for this application.
        action:
          type: string
          enum: [login, fund_transfer]
          description: Case-insensitive at ingress; lowercase canonical form is recommended.
        context:
          type: object
          additionalProperties: false
          required: [origin, device]
          properties:
            origin:
              type: string
              maxLength: 200
              description: Must match the registered origin configured on your Trustlith application.
            device:
              type: string
              maxLength: 100
              description: Human-readable initiator label displayed on the Authenticator prompt (e.g. Web Session).
        transactionContext:
          $ref: "#/components/schemas/TransactionContext"
    TransactionContext:
      type: object
      additionalProperties: false
      required: [type, amount, currency, recipientId, recipientDisplay, transactionReference]
      properties:
        type:
          type: string
          const: fund_transfer
          description: Mandatory literal `"fund_transfer"` required by `validateTransaction`.
        amount:
          type: string
          pattern: "^[0-9]{1,12}\\.[0-9]{2}$"
          example: "250.00"
        currency:
          type: string
          pattern: "^[A-Z]{3}$"
          example: "USD"
        recipientId: { type: string, maxLength: 100, example: acct_vendor_01 }
        recipientDisplay: { type: string, maxLength: 120, example: Acme Cloud Services }
        transactionReference: { type: string, maxLength: 100, example: INV-2026-041 }
    CreateChallengeResponse:
      type: object
      additionalProperties: false
      required: [challengeId, status, expiresAt]
      properties:
        challengeId: { type: string }
        status: { type: string, const: PENDING }
        expiresAt: { type: string, format: date-time }
    ChallengeStatusResponse:
      type: object
      additionalProperties: false
      required: [challengeId, status, expiresAt, action]
      properties:
        challengeId: { type: string }
        status:
          type: string
          enum: [PENDING, APPROVED, REJECTED, CANCELLED, EXPIRED]
        expiresAt: { type: string, format: date-time }
        action:
          type: string
          enum: [login, fund_transfer]
    CancelChallengeResponse:
      type: object
      additionalProperties: false
      required: [challengeId, status]
      properties:
        challengeId: { type: string }
        status: { type: string, const: CANCELLED }
    ApprovalRequest:
      type: object
      additionalProperties: false
      required: [credentialId, algorithm, signature]
      properties:
        credentialId: { type: string, maxLength: 100 }
        algorithm: { type: string, const: ES256 }
        signature: { type: string, maxLength: 200, description: Unpadded base64url 64-byte IEEE-P1363 ES256 signature over TRUSTLITH-AUTH-V1\0 payload. }
    ChallengeResolutionResponse:
      type: object
      required: [challengeId, status, result]
      properties:
        challengeId: { type: string }
        status: { type: string, enum: [PENDING, APPROVED, REJECTED, CANCELLED, EXPIRED] }
        result: { type: string }
    DeviceChallengesResponse:
      type: object
      required: [challenges]
      properties:
        challenges:
          type: array
          items:
            $ref: "#/components/schemas/AuthenticationChallenge"
    AuthenticationChallenge:
      type: object
      description: Device-facing canonical TRUSTLITH-AUTH-V1 fields.
      required: [version, challengeId, tenantId, applicationId, externalUserId, action, nonce, origin, device, createdAt, expiresAt, transactionContext, credentialId]
      properties:
        version: { type: integer, minimum: 1 }
        challengeId: { type: string }
        tenantId: { type: string }
        applicationId: { type: string }
        externalUserId: { type: string }
        action: { type: string, enum: [LOGIN, FUND_TRANSFER] }
        nonce: { type: string }
        origin: { type: string }
        device: { type: string }
        createdAt: { type: string, format: date-time }
        expiresAt: { type: string, format: date-time }
        transactionContext:
          oneOf:
            - { type: "null" }
            - { $ref: "#/components/schemas/TransactionContext" }
        credentialId: { type: string }
        status: { type: string, const: PENDING }
        accountDisplay: { type: string }
        applicationName: { type: string }
```
