# Trustlith Developer Center (`llms.txt`)

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

## Current Capability Scope & V1 Constraints
- **LIVE (Public Runtime API v1):** Passwordless `login` step-up, `fund_transfer` transaction authorization (`TRUSTLITH-AUTH-V1\0`, ES256 P-256), challenge polling/cancel, and programmatic QR enrollment handoffs (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`).
- **V1 USER MAPPING REQUIREMENT:** V1 currently requires **manually mapped DEV users** in **Developer Portal → Users** (`externalUserId`). Automatic end-user provisioning (`POST /v1/users`) and self-service end-user device/recovery Application Bearer endpoints are **not yet supported** on public V1 API keys.
- **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
- Public Developer Center: `https://developers.trustlith.com`
- `TRUSTLITH-INTEGRATION.md` ([GitHub source](./TRUSTLITH-INTEGRATION.md)): Self-contained integration guide covering the full 10-step journey (developer setup, connectivity check, Account Settings → Security UI, QR enrollment, `action: "login"` confirmation, `optional`/`designated`/`required` policy modes, fail-closed active enforcement, and session-bound anti-bypass).
- `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): Developer config vs end-user onboarding architecture hub.
- [10-Step Integration Journey](./docs/developer-center/quickstart.md): Ordered rollout preventing premature global lockout.
- [User Enrollment, Confirmation & Recovery](./docs/developer-center/user-enrollment.md): Manual V1 user mapping, QR handoffs, cryptographic confirmation, and V1 vs planned device recovery.
- [API Reference](./docs/developer-center/api-reference.md): Verified V1 routes, Portal key scopes, origin matching, and status transitions.
- [Code Examples & Reference UI](./docs/developer-center/examples.md): Backend connectivity, QR enrollment, Reference Account Settings → Security React UI, policy middleware, and session-bound anti-bypass handlers.
- [AI Coding Agent Guide](./docs/developer-center/ai-agent-guide.md): Guardrailed prompts and verification checklist for coding agents.
- [Developer Changelog](./docs/developer-center/changelog.md): Live V1 milestones separated from planned features.

## Non-Negotiable Integration Rules
1. Keep `TRUSTLITH_API_KEY` and `enrollmentToken` exclusively server-side; never bundle into browser/mobile code.
2. Never turn on global mandatory Trustlith enforcement before verifying Runtime availability (`GET /health` — availability only, does not validate keys), credential/mapping validity, Account Settings → Security QR enrollment, and test authentication.
3. Once mandatory authentication is active, **fail closed** on every non-`APPROVED` status (`PENDING`, `REJECTED`, `CANCELLED`, `EXPIRED`) and API failure.
4. Never send `tenantId` or `applicationId` in `POST /v1/challenges` payloads (`400 SCOPE_NOT_ACCEPTED`), and always exact-match `context.origin`.
5. Bind `challengeId` to the server session + immutable action context and enforce single-use consumption (`consumedAt`) inside your **customer backend/database** (V1 Runtime `/status` does not consume challenges; V2 Runtime `/consume` is planned, not deployed).

================================================================================
# 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"`), fund transfer authorization (`action: "fund_transfer"` with `transactionContext.type = "fund_transfer"`), challenge polling (`/status`), atomic challenge cancellation (`/cancel`), and programmatic QR enrollment handoffs (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`), backed by device-bound ES256 P-256 keys (`TRUSTLITH-AUTH-V1\0`).
> - **V1 USER MAPPING LIMITATION (Important):** V1 currently requires **manually mapped DEV users** in **Developer Portal → Users** (`externalUserId`). Automatic end-user provisioning (`POST /v1/users`) is **not yet supported** by the public Application Bearer API.
> - **PLANNED / NOT YET AVAILABLE:** Developer-defined Custom Auditable Transactions V2 (`action: "custom"`, `POST /v1/challenges/:id/consume`, `/acknowledge-execution`, Transaction Studio) under proposed ADR 0022, self-service customer device listing/revocation scopes, and self-service end-user recovery UIs are **not implemented or not available on the V1 Application Bearer API**. Do not invent or call undocumented routes.
> - **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 backend 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 & Rollout Rules (Non-Negotiable)

1. **Separate Developer Setup from End-User Onboarding:** Never turn on global mandatory Trustlith enforcement (`required` on all logins/routes) before verifying backend connectivity (`GET /health`), mapping pilot users in Developer Portal, building **Account Settings → Security** QR enrollment, and confirming at least one live cryptographic verification prompt.
2. **Fail Closed Once Required Auth Is Active:** Once mandatory Trustlith protection is active on an account, designated user allowlist, or protected route, **every failure must fail closed** (`PENDING`, `REJECTED`, `CANCELLED`, `EXPIRED`, network error, `401`, `403`, `404`, `429`, `503` all deny access). Never silently fall back to password-only access once Trustlith is required.
3. **Server-Side Only Secrets:** Store `TRUSTLITH_API_KEY` (`trl_pd1_...`), `enrollmentToken`, `TRUSTLITH_API_BASE_URL`, and `APP_PUBLIC_ORIGIN` strictly on your backend server environment. Never expose API keys or `enrollmentToken` in browser JS/TS, mobile apps, `NEXT_PUBLIC_*` vars, or git commits.
4. **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.
5. **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).
6. **Session-Bound Anti-Bypass & V1 Single-Use Enforcement:** Bind every `challengeId` to the caller's verified primary server session (`sessionId`), `externalUserId`, and immutable target action/`transactionContext`. Enforce protection on **every** protected API route/server action. In V1, `GET /v1/challenges/:challengeId/status` remains `APPROVED` on repeated reads—your **customer backend/database** must record atomic single-use `consumedAt` state per approved `challengeId` (distinct from future planned **V2** Runtime `POST /v1/challenges/:id/consume`).
7. **`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. Complete 10-Step Customer Integration Journey

### Phase A — Developer-Side Configuration (Once per Environment)
1. **Application Registration & Credential Configuration:**
   - Developer Portal → **Applications**: register your app name and exact canonical `APP_PUBLIC_ORIGIN` (e.g., `https://app.example.com`).
   - Developer Portal → **API Credentials**: issue a key (`enrollments:create`, `challenges:create`, `challenges:read`, `challenges:cancel`), complete **one-time reveal**, save to server `TRUSTLITH_API_KEY`, and click **Activate** (inactive keys fail `401`).
   - Developer Portal → **Users**: manually map each pilot `externalUserId` (exact match to your app database user ID). Automatic user creation via public API is not supported in V1.
2. **Backend Connectivity Verification:**
   - Implement a server check verifying `TRUSTLITH_API_BASE_URL`, `TRUSTLITH_API_KEY`, `APP_PUBLIC_ORIGIN`, and `GET <TRUSTLITH_API_BASE_URL>/health` → HTTP `200` (`{ "status": "ok" }`).
   - **Important:** `GET /health` verifies **Runtime network availability only**; it is unauthenticated and does **not** prove that `TRUSTLITH_API_KEY` is active, properly scoped, or origin-matched. Confirm credential validity via a test `POST /v1/challenges` / `GET /v1/challenges/:id/status` (or `/v1/enrollments`) call before enabling enforcement.

### Phase B — End-User Onboarding (`Account Settings → Security`)
3. **End-User Account Settings → Security UI:**
   - Give signed-in users a dedicated **Account Settings → Security → Trustlith Authenticator** section showing status (`Not Enrolled` → `QR Pending` → `Confirmed (Inactive)` → `Active (Required)`).
4. **Programmatic QR Enrollment (V1 Public APIs):**
   - Server route derives `externalUserId` strictly from the verified user session, calls `POST /v1/enrollments` (`{ externalUserId }`, keeps `enrollmentToken` server-side), then calls `POST /v1/enrollment-handoffs` (`{ enrollmentId, ceremonyType: "FIRST_DEVICE" }`) and returns `{ handoffId, expiresAt, ref }` to render a QR (`trustlith://enroll?env=provisioning-dev&ref=<ref>`, 5-minute TTL). Authenticator requires both the pinned `env` parameter (such as `provisioning-dev`) and the single-use `ref`. Handle `404 USER_NOT_AVAILABLE` gracefully when a V1 pilot user is not yet mapped in Portal.
5. **Device Enrollment Confirmation (Supported V1 Mechanisms):**
   - V1 Application Bearer keys do **not** expose `GET /v1/enrollments/:id` or `GET /v1/devices`.
   - Confirm enrollment cryptographically by triggering a **Verification Test Challenge** (`POST /v1/challenges`, `action: "login"`, `device: "Enrollment Confirmation"`) and polling `GET /v1/challenges/:id/status` until `APPROVED`, then persisting `trustlithEnrolledAt` in your DB. Operators can also inspect registered devices in **Developer Portal → Enrollment / Devices**.
6. **Test Authentication Before Activating Protection:**
   - Let the user run **Verify / Test Prompt** (testing approve, reject, or cancel via `POST /v1/challenges/:id/cancel`) before switching enforcement on for their account.

### Phase C — Activation, Policies & Session Enforcement
7. **Server-Side Account-Level Activation & Enforcement:**
   - Require `trustlithEnrolledAt !== null` before `POST /api/security/trustlith/activate` allows `trustlithEnabled = true`. Once active, fail closed on every non-`APPROVED` status or API error.
8. **Optional, Mandatory & Designated-User Policy Modes:**
   - Support server-controlled `TRUSTLITH_ENFORCEMENT_MODE = "optional" | "designated" | "required"` (recommend starting with `optional` or `designated` allowlist for pilot users, switching to `required` globally only after all target users are mapped and confirmed).
9. **Device Management & Recovery Guidance (V1 vs Planned):**
   - **Supported V1:** Developer Portal **Devices / Enrollment** views, per-challenge cancellation, additional-device handoffs (`ADDITIONAL_DEVICE`), fail-closed denial when an active user loses their device, and operator recovery support via Developer Portal.
   - **Planned:** Public Application Bearer self-service user device listing/revocation (`GET /v1/users/.../devices`, self-service revoke/recovery endpoints) and end-user self-service recovery UIs.
10. **Session-Bound Authorization & Direct API Bypass Prevention:**
   - Store primary auth level (`aal: "primary" | "trustlith_verified"`) and pending challenge rows (`{ challengeId, sessionId, externalUserId, action, expectedPayloadDigest, expiresAt, consumedAt }`) on the server.
   - Protect every privileged API route and server action with a shared guard verifying session binding, authoritative `APPROVED` status from `GET /v1/challenges/:id/status`, and atomic single-use `consumedAt` updates.

---

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

| Method & Path | Scope | Purpose |
| --- | --- | --- |
| `GET /health` | None | Unauthenticated Runtime availability check (`{ status: "ok", ... }`); does not validate API keys. |
| `POST /v1/enrollments` | `enrollments:create` | Create a 10-minute one-time primary enrollment for an `ACTIVE` manually 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 Backend Integration & Policy Code (TypeScript / Node.js 20+)

```ts
const BASE_URL = (process.env.TRUSTLITH_API_BASE_URL ?? "").replace(/\/+$/, ""); // e.g. https://provisioning-dev.trustlith.com
const ENROLLMENT_ENV = process.env.TRUSTLITH_ENROLLMENT_ENV ?? "provisioning-dev";
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";
export type TrustlithEnforcementMode = "optional" | "designated" | "required";

async function trustlithFetch<T>(path: string, init?: RequestInit): Promise<T> {
  if (!BASE_URL || !API_KEY || !APP_ORIGIN) {
    throw new Error("Missing TRUSTLITH_API_BASE_URL, TRUSTLITH_API_KEY, or APP_PUBLIC_ORIGIN.");
  }
  const res = await fetch(`${BASE_URL}${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 verifyTrustlithConnectivity() {
  const res = await fetch(`${BASE_URL}/health`);
  if (!res.ok) throw new Error(`Trustlith /health returned ${res.status}`);
  return (await res.json()) as { status: string; service: string; environment: string };
}

export async function startQrEnrollmentForMappedUser(externalUserId: string) {
  const enrollment = await trustlithFetch<{ enrollmentId: string; enrollmentToken: string; expiresAt: string }>(
    "/v1/enrollments",
    { method: "POST", body: JSON.stringify({ externalUserId }) },
  );
  // Keep enrollment.enrollmentToken strictly on the backend; return only the opaque ref to the frontend UI
  const handoff = await trustlithFetch<{ handoffId: string; ceremonyType: string; expiresAt: string; ref: string }>(
    "/v1/enrollment-handoffs",
    { method: "POST", body: JSON.stringify({ enrollmentId: enrollment.enrollmentId, ceremonyType: "FIRST_DEVICE" }) },
  );
  return {
    handoffId: handoff.handoffId,
    expiresAt: handoff.expiresAt,
    ref: handoff.ref,
    deepLink: `trustlith://enroll?env=${encodeURIComponent(ENROLLMENT_ENV)}&ref=${encodeURIComponent(handoff.ref)}`,
  };
}

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" },
  );
}

export function shouldRequireTrustlith(input: {
  mode: TrustlithEnforcementMode;
  externalUserId: string;
  designatedUserIds: Set<string>;
  userTrustlithEnabled: boolean;
  userEnrolledConfirmed: boolean;
}): boolean {
  if (input.mode === "required") return true;
  if (input.mode === "designated") {
    return input.designatedUserIds.has(input.externalUserId) || (input.userEnrolledConfirmed && input.userTrustlithEnabled);
  }
  return input.userEnrolledConfirmed && input.userTrustlithEnabled;
}
```

---

## 5. Reference Account Settings → Security UI Pattern

Every customer integration should expose an authenticated **Account Settings → Security** view with these explicit stages:
1. **`Not Enrolled`:** Button **Connect Trustlith Authenticator** calls your backend `POST /api/security/trustlith/enrollment/start` (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`) and renders the QR code (`trustlith://enroll?env=<envKey>&ref=<ref>`, e.g. `env=provisioning-dev`) with a 5-minute countdown. Show a clear message if a V1 test user still needs manual mapping in Developer Portal.
2. **`QR Generated / Pending Confirmation`:** Button **Verify Authenticator Setup** calls `POST /v1/challenges` (`action: "login"`, `device: "Enrollment Confirmation"`) and polls status. When `APPROVED`, your backend persists `trustlithEnrolledAt = NOW()`.
3. **`Confirmed (Not Required Yet)`:** Button **Activate Required Protection** refuses activation unless `trustlithEnrolledAt` is present; once clicked, persists `trustlithEnabled = true`.
4. **`Active (Required)`:** User may run **Test Authentication** (`Approve` / `Cancel` via `/cancel`). Protected logins/routes enforce fail-closed verification, and UI explains that self-service device removal/recovery is planned while V1 lost-device resets go through operator support in Developer Portal.

---

## 6. 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. Fail closed when enforcement is active. |
| `403` | `FORBIDDEN` / `ENTITLEMENT_INACTIVE` | Key lacks the required route scope or organization entitlement is inactive. |
| `403` | `RECENT_RECOVERY_RESTRICTED` | Account completed a recent recovery and high-risk `fund_transfer` is temporarily restricted. |
| `404` | `USER_OR_ORIGIN_NOT_AVAILABLE` / `USER_NOT_AVAILABLE` / `CHALLENGE_NOT_FOUND` | Verify `externalUserId` is manually mapped as `ACTIVE` in Developer Portal → **Users** and `context.origin` matches the registered Portal origin. Fail closed if mandatory enforcement is active. |
| `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. |

---

## 7. 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.
- Never globally enable mandatory Trustlith enforcement (`mode = "required"`) before implementing backend connectivity verification (`GET /health`), Account Settings → Security enrollment + cryptographic test confirmation, and verifying mapped pilot users.
- Enforce **fail-closed** denial (`403` / session blocked) for any active mandatory rule on `PENDING`, `REJECTED`, `CANCELLED`, `EXPIRED`, `401`, `404`, `429`, `503`, or timeout.
- Bind `externalUserId` strictly from the caller's verified primary session (never accept raw `externalUserId` from untrusted client form fields).
- Enforce shared server-side session guards (`session.aal === "trustlith_verified"`) and **customer-backend** atomic single-use `challengeId` consumption (`consumedAt` in your app DB, because V1 Runtime `/status` does not consume `APPROVED` challenges and V2 Runtime `/consume` is not deployed) so direct API calls or challenge replays cannot bypass Trustlith.
- Do not invent undocumented endpoints (`POST /v1/users`, `GET /v1/enrollments/:id`, self-service device revoke APIs, or unimplemented V2 routes).

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

# Trustlith Developer Center

Integrate hardware-backed ES256 cryptographic authentication and transaction authorization into your SaaS backend safely—from developer setup and user onboarding through production-style fail-closed enforcement.

> **Current Platform Capability Matrix (Public Runtime API v1)**
> - **LIVE — Public Runtime API v1:** `login` step-up authentication, `fund_transfer` transaction authorization (`TRUSTLITH-AUTH-V1\0` ES256 P-256), challenge status polling, atomic challenge cancellation, and programmatic enrollment handoffs (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`).
> - **V1 User Mapping Constraint:** V1 currently requires **manually mapped DEV users** in Developer Portal → **Users** (`externalUserId`). Automatic end-user provisioning via the public Application Bearer API is **not yet supported**.
> - **PLANNED — Custom Auditable Transactions V2:** Developer-defined custom transaction schemas (`action: "custom"`, `/consume`, `/acknowledge-execution`, Transaction Studio) remain specified in proposed **ADR 0022** and are **not deployed on Runtime API v1**.
> - **Prototype SDK Notice:** `@trustlith/sdk-js` in `packages/sdk-js` is a local Phase 1 prototype only and must **not** be used in production. Call the verified HTTPS REST endpoints directly from your backend server.

---

## Developer-Side Configuration vs End-User Onboarding

Do **not** enable mandatory Trustlith authentication globally on login or protected routes before completing connectivity checks and end-user onboarding:

| Responsibility | Owner | Where It Happens |
| --- | --- | --- |
| **Developer-Side Configuration** | Integrating team (once per environment) | Register application & origin, issue/activate `TRUSTLITH_API_KEY`, verify `GET /health`, and map pilot `externalUserId` values in **Developer Portal**. |
| **End-User Onboarding & Activation** | End user inside your product UI | Signed-in user visits your **Account Settings → Security**, scans a programmatic QR handoff from `POST /v1/enrollment-handoffs`, runs a **verification test prompt**, and enables Trustlith protection for their account. |
| **Server-Side Policy Enforcement** | Your application backend | Enforce `optional`, `designated`, or `required` policy per verified server session; once required authentication is active for an account or route, every failure must **fail closed**. |

---

## Two Integration Paths

### Path A: Integrate Manually
1. [10-Step Customer Integration Journey](./quickstart.md) — Complete developer setup, connectivity verification, Account Settings → Security onboarding, test auth, policy rollout, and session anti-bypass rules.
2. [User Enrollment, Confirmation & Recovery Guide](./user-enrollment.md) — Manual V1 user mapping, programmatic QR handoffs, supported enrollment confirmation, and V1 vs planned device/recovery boundaries.
3. [API Reference](./api-reference.md) — Verified V1 routes, Portal credential scopes, challenge state machine, and fail-closed error matrix (`docs/openapi.yaml`).
4. [Code Examples & Reference Account Security UI](./examples.md) — Server connectivity check, QR enrollment, Reference Account Settings → Security React UI, policy middleware (`optional` / `required` / `designated`), and session-bound anti-bypass handlers.
5. [Developer Changelog](./changelog.md) — V1 release notes clearly separated from planned features.

### Path B: Integrate with an AI Coding Agent
1. [AI Coding Agent Guide](./ai-agent-guide.md) — Guardrailed prompt templates that build onboarding + connectivity + test verification **before** mandatory enforcement.
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 corpus), and [`openapi.yaml`](../openapi.yaml).

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

# Complete Customer Integration Journey (10 Steps — V1)

Follow this ordered sequence so your application supports Trustlith enrollment and testing **before** turning on mandatory enforcement. Skipping steps `2`–`6` and enabling global mandatory step-up immediately will lock out unenrolled users.

---

## Phase 1 — Developer-Side Setup (Once per Application)

### Step 1 — Application Registration & API Credential Configuration
1. Open Developer Portal → **Applications** and register your application's exact canonical public origin (for example `https://app.example.com` or `http://localhost:3000` for local dev). Every `POST /v1/challenges` call must match this `context.origin` string verbatim.
2. Open Developer Portal → **API Credentials**, issue a key, complete the **one-time reveal**, store it in your backend secret store as `TRUSTLITH_API_KEY`, and click **Activate**. Keys left in `ISSUED`, `REVOKED`, or `EXPIRED` fail `401`.
3. Store `TRUSTLITH_API_BASE_URL` (DEV: `https://provisioning-dev.trustlith.com`) and `APP_PUBLIC_ORIGIN` strictly on your server.
4. **Map V1 Pilot Users Manually (Portal → Users):** Public Application Bearer keys in V1 do **not** expose automatic user provisioning. Every pilot `externalUserId` (immutable DB user ID, max 128 chars) must be registered and `ACTIVE` in **Developer Portal → Users** before enrollment or challenge calls succeed.

> **Never Expose Backend Secrets:** Never put `TRUSTLITH_API_KEY` in browser JS, mobile builds, `NEXT_PUBLIC_*` variables, or URL query strings.

### Step 2 — Backend Connectivity Verification
Before changing login flows or requiring MFA, add a server-only availability & config check:
1. Verify `TRUSTLITH_API_BASE_URL`, `TRUSTLITH_API_KEY`, and `APP_PUBLIC_ORIGIN` are set on the backend.
2. Call `GET <TRUSTLITH_API_BASE_URL>/health` from your server and verify HTTP `200` (`{ "status": "ok", "service": "trustlith-api" }`).
3. **Important:** `GET /health` is an unauthenticated **availability check only**—it proves Trustlith Runtime reachability, **not** that `TRUSTLITH_API_KEY`, origin configuration, or user mappings are valid. Confirm credential validity via a test `POST /v1/challenges` / `GET /v1/challenges/:id/status` (or `/v1/enrollments`) call.
4. Keep global enforcement in **`optional`** or **`designated`** mode until onboarding and test authentication succeed.

---

## Phase 2 — End-User Onboarding (Account Settings → Security)

### Step 3 — End-User Account Settings → Security Integration
Build a dedicated **Account Settings → Security → Trustlith Authenticator** section inside your app for already-signed-in users (see the full Reference UI in [Code Examples](./examples.md)):
- Show the user's current status stored in your application DB: `Not Enrolled` → `QR Pending Scan` → `Enrolled (Ready to Test)` → `Active (Required on Sign-In)`.
- Gate all Trustlith security routes behind the user's verified primary session (`session.userId`) and never accept `externalUserId` from browser form inputs.

### Step 4 — Programmatic QR Enrollment Using Existing V1 Public APIs
When a signed-in user clicks **Connect Trustlith Authenticator**:
1. Your backend looks up `session.user.externalUserId` (mapped in Portal → **Users**) and calls `POST /v1/enrollments` (`scope: enrollments:create`, 10-minute TTL). Keep `enrollmentToken` strictly on the server.
2. Immediately call `POST /v1/enrollment-handoffs` with `{ enrollmentId, ceremonyType: "FIRST_DEVICE" }` (`scope: enrollments:create`, 5-minute TTL).
3. Return `{ handoffId, expiresAt, ref }` to the browser (never `enrollmentToken`). Render a QR code encoding `trustlith://enroll?env=<envKey>&ref=<ref>` (for DEV: `env=provisioning-dev`; Trustlith Authenticator requires both the pinned `env` key and `ref`) with an expiration timer and a **Generate New QR Code** action.
4. Note: If `POST /v1/enrollments` returns `404 USER_NOT_AVAILABLE`, the `externalUserId` is not manually mapped in Developer Portal → **Users** yet. Display a friendly DEV notice rather than crashing login.

### Step 5 — Device Enrollment Confirmation Using Supported Mechanisms
Public Runtime API v1 does **not** expose `GET /v1/enrollments/:id` or `GET /v1/devices` on standard Application Bearer keys (`enrollments:create`, `challenges:create`, `challenges:read`, `challenges:cancel`). Confirm enrollment using V1-supported mechanisms:
1. **Cryptographic Verification Prompt (Recommended in Account Settings → Security):** After scanning the QR code and finishing the biometric prompt in Trustlith Authenticator, have the user click **Verify Authenticator Setup**. Your backend triggers a live `POST /v1/challenges` (`action: "login"`, `device: "Security Setup Verification"`) and polls `GET /v1/challenges/:challengeId/status`. Only when status reaches `APPROVED` is the device cryptographically proven active and reachable—persist `trustlith_enrolled_at = NOW()` in your DB.
2. **Developer Portal Verification:** Developers/operators can independently inspect **Developer Portal → Enrollment** and **Devices** to confirm an `ACTIVE` device and P-256 credential exist for that mapped `externalUserId`.

### Step 6 — Test Authentication Before Activating Protection
Provide a **Test Authentication Prompt** action inside **Account Settings → Security** (and use Developer Portal → **Authenticate**) before enabling required protection:
- Confirm `APPROVED` succeeds and displays the expected origin and device context in Authenticator.
- Confirm `REJECTED`, `CANCELLED` (`POST /v1/challenges/:id/cancel`), and `EXPIRED` (`120s` TTL) fail cleanly without granting access or corrupting account state.

---

## Phase 3 — Activation, Policy Rollout & Fail-Closed Enforcement

### Step 7 — Server-Side Account-Level Activation & Enforcement
Only after `trustlith_enrolled_at` and test verification succeed should your backend allow activating enforcement (`trustlith_required = true` via `POST /api/security/trustlith/activate`):
- Enforce an invariant in your DB/API: refuse activation (`400`) unless the user has verified enrollment (`trustlith_enrolled_at !== null`).
- **Fail-Closed Rule:** Once required authentication is active for an account or policy, any error (`401`, `403`, `404`, `429`, `503`, timeout, `PENDING`, `REJECTED`, `CANCELLED`, `EXPIRED`) **must deny authentication or sensitive execution**. Never downgrade to password-only access silently when Trustlith is required.

### Step 8 — Choose Optional, Designated-User, or Mandatory Policy
Roll out safely with explicit server policy modes (see complete TypeScript examples in [Code Examples](./examples.md)):
- **`optional`**: Prompt only users who opted in (`user.trustlithRequired === true && user.trustlithEnrolled`). Ideal for end-user self-onboarding.
- **`designated` (Recommended Pilot Rollout)**: Enforce Trustlith strictly for specific pilot/admin accounts (`TRUSTLITH_REQUIRED_USER_IDS` allowlist or admin role) after those users enroll via Step 4–6.
- **`required` (Full Mandatory Mode)**: Require Trustlith on every sign-in or sensitive route. **Only enable globally after every target user is mapped and verified enrolled.**

### Step 9 — Device Management & Recovery Guidance
Clearly separate V1 capabilities from planned self-service features (details in [User Enrollment & Recovery Guide](./user-enrollment.md)):
- **Supported Now (V1):** Developer Portal **Devices**, **Users**, and **Enrollment** management; challenge cancellation (`POST /v1/challenges/:id/cancel`); fail-closed denial if an enrolled device is unavailable.
- **Planned (Not Yet on Public Application Bearer API):** End-user self-service device listing/removal endpoints and automated self-service device recovery flows. During the V1 pilot, a lost device requires fail-closed denial followed by operator review in Developer Portal before issuing replacement enrollment.

### Step 10 — Session-Bound Authorization & Direct API Bypass Prevention
Never allow browser state or a single API call to bypass step-up verification:
1. Track primary authentication (`aal: "primary"`) separately from step-up completion (`aal: "trustlith_verified"`) in a server-side session or database table (`auth_sessions` / `pending_challenges`).
2. When starting a `login` or `fund_transfer` challenge, store `{ challengeId, sessionId, externalUserId, action, expectedTransactionDigest, expiresAt, consumedAt: null }` on the server.
3. Require **all** protected API endpoints and server actions to pass a shared middleware/guard verifying `session.aal === "trustlith_verified"` (for session login) **and**, for high-trust mutations like `fund_transfer`, verifying an unconsumed (`consumedAt === null`) customer-backend challenge record matching the caller's `sessionId`, `externalUserId`, and exact server-side transaction parameters (`status === "APPROVED"`), atomically marking `consumedAt` inside your **customer database** so neither primary-only cookies nor replayed `challengeId`s can bypass enforcement. *(In Public Runtime API v1, Trustlith Runtime does not consume `APPROVED` challenges—server-side Runtime `/consume` is a planned V2 ADR 0022 feature.)*

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

# User Enrollment, Confirmation & Recovery Guide (V1)

Before a user can approve `login` or `fund_transfer` challenges, three prerequisites must hold:
1. Their immutable `externalUserId` is mapped as `ACTIVE` in your application's Trustlith tenant/app.
2. They hold at least one active hardware-bound P-256 credential in **Trustlith Authenticator**.
3. Your backend has confirmed reachability (cryptographic test prompt and/or Portal check) **before** marking Trustlith mandatory on their account.

---

## 1. Important V1 Constraint: Manual DEV User Mapping

> **V1 Scoping Notice:** Public Runtime API v1 (`enrollments:create`, `challenges:create`, `challenges:read`, `challenges:cancel`) does **not** currently expose automatic user creation (`POST /v1/users`).
> - During the V1 pilot, you **must manually map every external user ID** in **Developer Portal → Test Users** before your app can call `POST /v1/enrollments` or `POST /v1/challenges` for that user.
> - Calling `/v1/enrollments` or `/v1/challenges` for an unmapped `externalUserId` fails fail-closed with `404 USER_NOT_AVAILABLE` / `USER_OR_ORIGIN_NOT_AVAILABLE`.
> - Automatic end-user provisioning via public application API is a **planned enhancement** and must not be assumed in V1 integrations.

---

## 2. Option A — Developer Portal Enrollment Workbench (Pilot Bootstrapping)

Fastest path for bootstrapping your first pilot/admin accounts:
1. Open **Developer Portal → Users** and register each pilot user's immutable `externalUserId` (exact match to your app database user ID).
2. Open **Developer Portal → Enrollment**, select the mapped user, and click **Start First-Device QR Enrollment**.
3. Scan the QR code in **Trustlith Authenticator** on Android/iOS and approve the biometric key-generation prompt.
4. Confirm the device appears active in **Developer Portal → Devices** and verify with **Developer Portal → Authenticate**.

---

## 3. Option B — Programmatic Customer In-App QR Enrollment (`Account Settings → Security`)

For customer self-onboarding inside your app's **Account Settings → Security** page (for already-mapped users):

### Step 1 — Create a 10-Minute Enrollment (`POST /v1/enrollments`)

Call from your **authenticated server route** using the signed-in user's server session `externalUserId`:

```http
POST /v1/enrollments
Authorization: Bearer <TRUSTLITH_API_KEY>
Content-Type: application/json

{ "externalUserId": "user_12345" }
```

Returns `{ enrollmentId, enrollmentToken, expiresAt, developmentOnly }`. Keep `enrollmentToken` strictly on your backend server—never send it to the browser.

### Step 2 — Mint an Opaque Single-Use QR / Deep-Link Handoff (`POST /v1/enrollment-handoffs`)

```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` is returned **once**, expires in `5` minutes (capped by the underlying enrollment's `expiresAt`), and is never logged or replayable after redemption.
- Render a QR code in your **Account Settings → Security** UI encoding `trustlith://enroll?env=<envKey>&ref=<ref>` (for controlled DEV: `env=provisioning-dev`; Authenticator rejects deep links without a valid pinned `env` key) together with a countdown timer and a manual **Refresh QR** button.
- Trustlith Authenticator redeems `ref` directly with Runtime (`/v1/enrollment-handoffs/redeem`) without ever receiving `enrollmentToken`.

---

## 4. Device Enrollment Confirmation Using Supported V1 Mechanisms

Standard V1 Application Bearer credentials have scopes `enrollments:create`, `challenges:create`, `challenges:read`, `challenges:cancel`. There is **no public `GET /v1/enrollments/:id` or `GET /v1/devices` polling endpoint** on V1 Application Bearer keys.

Use these supported V1 confirmation mechanisms:

1. **In-App Cryptographic Confirmation (Recommended):**
   - Right after the user scans the QR code and completes biometric enrollment in Trustlith Authenticator, display a **"Verify & Activate Authenticator"** button in your **Account Settings → Security** panel.
   - Your backend creates a verification challenge (`POST /v1/challenges`, `action: "login"`, `context.device: "Enrollment Confirmation"`) and polls `GET /v1/challenges/:challengeId/status`.
   - When `GET /v1/challenges/:challengeId/status` returns `status === "APPROVED"`, you have cryptographic proof that the device key is enrolled, reachable, and controlled by the user.
   - Only then persist `trustlith_enrolled = true` in your application database and allow enabling mandatory enforcement (`trustlith_required = true`).
2. **Developer Portal Device Check (Operator Confirmation):**
   - Developers/administrators can verify registered devices directly in **Developer Portal → Enrollment** and **Developer Portal → Devices**.

---

## 5. Device Management & Recovery Guidance (Supported V1 vs Planned)

| Capability | V1 Current Support | Planned / Future |
| --- | --- | --- |
| **Inspect user's enrolled devices** | **Supported in Developer Portal** (`/workspace/devices` & `/workspace/enrollment`) | Public Application Bearer device-listing endpoint (`GET /v1/users/.../devices`) |
| **Additional-device handoffs** | **Supported in Portal & Runtime** (`ceremonyType: "ADDITIONAL_DEVICE"` when an additional-device enrollment exists) | Self-service in-app customer device-add orchestration without Portal involvement |
| **Lost / stolen device handling** | **Fail-closed on enforcement**; operator reviews user/devices in **Developer Portal → Devices / Users** and follows tenant support procedures before re-enrolling a new mapped device | Self-service end-user device loss/revoke API (`POST /v1/device-lifecycle-operations` / credential revoke exposed cleanly for customer UIs) |
| **Account recovery (`ADR 0012`)** | Runtime recovery core exists internally with primary-auth + recovery-factor dual control & recent-recovery restriction window, **not yet exposed as self-service UI/scopes on standard V1 pilot API keys** | Customer-facing recovery setup, recovery code rotation, and replacement-device ceremony UI/scopes |

> **Safe Pilot Lockout Prevention Rule:** Never allow a user with zero confirmed active devices in your database (or an unmapped user) to sit behind a global mandatory check unless your operational support team can manually assist via Developer Portal. Always verify enrollment + test challenge **first**, and once `required` is active, **never** bypass failed checks automatically.

================================================================================
# 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>` (Trustlith Authenticator mobile routes).
- **Provisioned Portal API Key Scopes (V1 Pilot):** Standard V1 credentials issued via Developer Portal carry strictly:
  - `enrollments:create`
  - `challenges:create`
  - `challenges:read`
  - `challenges:cancel`
- **No Automatic User Provisioning API in V1:** External users (`externalUserId`) must be mapped manually and `ACTIVE` in **Developer Portal → Users** before calling enrollment or challenge endpoints.
- **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 (Live V1)

| Method & Path | Required Scope | Request Body | Success Response |
| --- | --- | --- | --- |
| `GET /health` | None | — | `200 { status: "ok", service: "trustlith-api", environment, phase }` *(unauthenticated Runtime availability check only; does not validate `TRUSTLITH_API_KEY`)* |
| `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" }` |

> **What Is NOT Exposed on Standard V1 Application Keys:** There is no public `POST /v1/users` provisioning route, no `GET /v1/enrollments/:id` or `GET /v1/devices` polling route, no self-service end-user device revocation/recovery API on standard pilot scopes, and no V2 Custom Auditable Transactions (`action: "custom"`, `/consume`, `/acknowledge-execution`). Use `action: "login"` to cryptographically confirm device enrollment in-app and inspect devices in Developer Portal.

## 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`. **Only this status grants access or executes protected mutations.** Note: in V1, `GET /v1/challenges/:challengeId/status` continues returning `APPROVED` on repeated reads; enforce single-use consumption in your customer backend DB (V2 Runtime `POST /v1/challenges/:id/consume` is planned, not deployed).
- `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 & Fail-Closed Handling
- `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 (`ISSUED`), 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.
- `403 RECENT_RECOVERY_RESTRICTED` — Account recently completed recovery and high-risk `fund_transfer` is temporarily restricted.
- `404 USER_OR_ORIGIN_NOT_AVAILABLE` / `USER_NOT_AVAILABLE` — `externalUserId` is not mapped/active in Developer Portal → **Users** OR `context.origin` does not match the registered origin. During **Account Settings → Security** onboarding, prompt the operator/user nicely; once mandatory enforcement is **active**, **fail closed**.
- `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. Back off polling (`2`–`3s`) and fail closed if enforcement is mandatory.

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

# Integration Code Examples & Reference Security UI (V1)

> Use all Trustlith API calls **exclusively on your backend server**. Never expose `TRUSTLITH_API_KEY` to browser code, and never globally enable mandatory enforcement before verifying connectivity and completing user onboarding.

---

## 1. Backend Availability Check (`/health`) & Core V1 Client (Node.js / TypeScript)

> Note: `GET /health` checks unauthenticated Runtime network availability only. It does **not** prove that `TRUSTLITH_API_KEY` or `APP_PUBLIC_ORIGIN` are valid—verify credential validity using an authenticated Application Bearer call (`POST /v1/enrollments` or test `POST /v1/challenges`).

```ts
const baseUrl = (process.env.TRUSTLITH_API_BASE_URL ?? "").replace(/\/+$/, "");
const enrollmentEnv = process.env.TRUSTLITH_ENROLLMENT_ENV ?? "provisioning-dev";
const apiKey = process.env.TRUSTLITH_API_KEY ?? "";
const appOrigin = process.env.APP_PUBLIC_ORIGIN ?? "";

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

export async function verifyTrustlithConnectivity() {
  if (!baseUrl || !apiKey || !appOrigin) {
    return {
      ok: false as const,
      reason: "TRUSTLITH_API_BASE_URL, TRUSTLITH_API_KEY, and APP_PUBLIC_ORIGIN must be set.",
    };
  }
  const res = await fetch(`${baseUrl}/health`, { method: "GET" });
  if (!res.ok) {
    return { ok: false as const, reason: `Health probe returned HTTP ${res.status}` };
  }
  const body = (await res.json()) as { status: string; environment: string };
  return { ok: body.status === "ok", environment: body.environment };
}

async function trustlithPost<T>(path: string, payload?: unknown): Promise<T> {
  const res = await fetch(`${baseUrl}${path}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${apiKey}`,
    },
    body: payload ? JSON.stringify(payload) : undefined,
  });
  const data = (await res.json()) as T & { error?: { code: string; message: string } };
  if (!res.ok) {
    throw new Error(`Trustlith ${res.status} (${data.error?.code ?? "ERROR"})`);
  }
  return data;
}

export function startProgrammaticEnrollmentHandoff(externalUserId: string) {
  return (async () => {
    // Requires externalUserId to be manually mapped as ACTIVE in Developer Portal -> Users (V1)
    const enrollment = await trustlithPost<{
      enrollmentId: string;
      enrollmentToken: string;
      expiresAt: string;
    }>("/v1/enrollments", { externalUserId });

    // Keep enrollment.enrollmentToken strictly on the backend; return only opaque ref to UI
    const handoff = await trustlithPost<{
      handoffId: string;
      ceremonyType: "FIRST_DEVICE" | "ADDITIONAL_DEVICE";
      expiresAt: string;
      ref: string;
    }>("/v1/enrollment-handoffs", {
      enrollmentId: enrollment.enrollmentId,
      ceremonyType: "FIRST_DEVICE",
    });

    return {
      handoffId: handoff.handoffId,
      expiresAt: handoff.expiresAt,
      ref: handoff.ref,
      deepLink: `trustlith://enroll?env=${encodeURIComponent(enrollmentEnv)}&ref=${encodeURIComponent(handoff.ref)}`,
    };
  })();
}

export function createLoginChallenge(externalUserId: string, deviceLabel: string) {
  return trustlithPost<{ challengeId: string; status: "PENDING"; expiresAt: string }>(
    "/v1/challenges",
    {
      externalUserId,
      action: "login",
      context: { origin: appOrigin, device: deviceLabel },
    },
  );
}

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}`);
  return (await res.json()) as {
    challengeId: string;
    status: TrustlithChallengeStatus;
    expiresAt: string;
    action: "login" | "fund_transfer";
  };
}

export function cancelChallenge(challengeId: string) {
  return trustlithPost<{ challengeId: string; status: "CANCELLED" }>(
    `/v1/challenges/${encodeURIComponent(challengeId)}/cancel`,
  );
}
```

---

## 2. Authentication Policy & Fail-Closed Activation Guard

Use explicit server-side policy modes so onboarding always happens **before** mandatory enforcement—and enforcement always **fails closed** once active:

```ts
export type TrustlithPolicyMode = "optional" | "designated" | "required";

export interface AppUserSecurityRecord {
  id: string;
  externalUserId: string;        // Mapped in Trustlith Developer Portal -> Users
  trustlithEnrolledAt: string | null; // Set ONLY after cryptographic confirmation challenge APPROVED
  trustlithEnabled: boolean;     // Account-level user activation toggle
}

export function shouldRequireTrustlith(
  user: AppUserSecurityRecord,
  mode: TrustlithPolicyMode,
  designatedIds: Set<string>,
): boolean {
  if (mode === "required") return true;
  if (mode === "designated") {
    return (
      designatedIds.has(user.externalUserId) ||
      (user.trustlithEnrolledAt !== null && user.trustlithEnabled)
    );
  }
  return user.trustlithEnrolledAt !== null && user.trustlithEnabled;
}

export function assertCanActivateAccountProtection(user: AppUserSecurityRecord) {
  // Refuse turning on account-level protection before cryptographic enrollment confirmation succeeds
  if (!user.trustlithEnrolledAt) {
    throw new Error("Complete QR enrollment and verify an Authenticator test prompt before activating protection.");
  }
}

export async function enforceRequiredStepUpFailClosed(input: {
  user: AppUserSecurityRecord;
  sessionId: string;
  challengeId: string;
  expectedAction: "login" | "fund_transfer";
  required: boolean;
  db: {
    findPendingChallenge: (challengeId: string) => Promise<{
      challengeId: string;
      sessionId: string;
      externalUserId: string;
      action: "login" | "fund_transfer";
      consumedAt: string | null;
    } | null>;
    markChallengeConsumedOnce: (challengeId: string, nowIso: string) => Promise<boolean>;
  };
}): Promise<{ ok: true } | { ok: false; status: 403 | 409; reason: string }> {
  if (!input.required) return { ok: true };
  if (!input.user.trustlithEnrolledAt) {
    // Once required is active, never silently downgrade unenrolled accounts
    return { ok: false, status: 403, reason: "TRUSTLITH_ENROLLMENT_REQUIRED" };
  }
  const pending = await input.db.findPendingChallenge(input.challengeId);
  if (
    !pending ||
    pending.sessionId !== input.sessionId ||
    pending.externalUserId !== input.user.externalUserId ||
    pending.action !== input.expectedAction ||
    pending.consumedAt !== null
  ) {
    // Reject cross-session, cross-user, wrong-action, or already-consumed challenge IDs
    return { ok: false, status: 403, reason: "CHALLENGE_SESSION_BINDING_MISMATCH" };
  }
  try {
    const resolved = await getChallengeStatus(input.challengeId);
    if (resolved.status !== "APPROVED" || resolved.action !== input.expectedAction) {
      return { ok: false, status: 403, reason: `CHALLENGE_${resolved.status}` };
    }
    // Single-use consumption in customer DB (V1 Runtime /status does not consume challenges)
    const claimed = await input.db.markChallengeConsumedOnce(
      input.challengeId,
      new Date().toISOString(),
    );
    if (!claimed) {
      return { ok: false, status: 409, reason: "CHALLENGE_ALREADY_CONSUMED" };
    }
    return { ok: true };
  } catch {
    // Network/API/401/403/429/503 failures MUST fail closed once mandatory auth is active
    return { ok: false, status: 403, reason: "TRUSTLITH_VERIFICATION_UNAVAILABLE" };
  }
}
```

---

## 3. Session-Bound Authorization & Customer-Side Single-Use Consumption (V1)

Never accept `"trustlithApproved: true"` from client payloads or reuse one `challengeId` across requests. Bind every challenge to a customer-backend session row and verify/consume it atomically in your own database before executing protected work. *(In Public Runtime API v1, Trustlith Runtime returns `APPROVED` on repeated `/status` polls without consuming the challenge; server-side Runtime `POST /v1/challenges/:id/consume` is planned for future V2 `ADR 0022`.)*

```ts
export async function requireVerifiedTransferAndExecute(input: {
  sessionId: string;
  sessionAal: "primary" | "trustlith_verified";
  externalUserId: string;
  challengeId: string;
  amount: string;
  currency: string;
  recipientId: string;
  db: {
    findPendingChallenge: (challengeId: string) => Promise<{
      challengeId: string;
      sessionId: string;
      externalUserId: string;
      action: "fund_transfer";
      amount: string;
      currency: string;
      recipientId: string;
      consumedAt: string | null;
    } | null>;
    markChallengeConsumedOnce: (challengeId: string, nowIso: string) => Promise<boolean>;
    executeTransferMutation: () => Promise<void>;
  };
}) {
  // 1. Prevent primary-only session bypass on protected APIs
  const pending = await input.db.findPendingChallenge(input.challengeId);
  if (
    !pending ||
    pending.sessionId !== input.sessionId ||
    pending.externalUserId !== input.externalUserId ||
    pending.amount !== input.amount ||
    pending.currency !== input.currency ||
    pending.recipientId !== input.recipientId ||
    pending.consumedAt !== null
  ) {
    throw new Error("403 FORBIDDEN: Challenge does not match session, user, or immutable transfer context.");
  }

  // 2. Authoritative server verification (never trust client-supplied status)
  const resolved = await getChallengeStatus(input.challengeId);
  if (resolved.status !== "APPROVED" || resolved.action !== "fund_transfer") {
    throw new Error(`403 FORBIDDEN: Challenge status is ${resolved.status}, not APPROVED.`);
  }

  // 3. Single-use atomic claim prevents replay of an approved challengeId
  const claimed = await input.db.markChallengeConsumedOnce(
    input.challengeId,
    new Date().toISOString(),
  );
  if (!claimed) {
    throw new Error("409 CONFLICT: Approved challenge already consumed.");
  }

  await input.db.executeTransferMutation();
}
```

---

## 4. Reference Account Settings → Security UI (React / TypeScript)

Render this panel inside your application's **Account Settings → Security** page so end users can connect Trustlith Authenticator, cryptographically confirm enrollment via a live prompt, test prompts, and activate protection safely:

```tsx
"use client";
import { useState } from "react";

type EnrollmentStage = "not_enrolled" | "qr_pending" | "confirmed_inactive" | "active_required";

export function AccountSecurityTrustlithCard(props: {
  initialStage: EnrollmentStage;
  supportsSelfServiceRecovery: false; // V1: Portal admin/operator workflow
}) {
  const [stage, setStage] = useState<EnrollmentStage>(props.initialStage);
  const [handoff, setHandoff] = useState<{ deepLink: string; expiresAt: string } | null>(null);
  const [challengeId, setChallengeId] = useState<string | null>(null);
  const [statusMessage, setStatusMessage] = useState<string>("");
  const [busy, setBusy] = useState(false);

  async function startQrEnrollment() {
    setBusy(true);
    setStatusMessage("");
    try {
      // Server route derives externalUserId from verified session & calls POST /v1/enrollments + /v1/enrollment-handoffs
      const res = await fetch("/api/security/trustlith/enrollment/start", { method: "POST" });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || "User must be mapped in Trustlith Portal first.");
      setHandoff({ deepLink: data.deepLink, expiresAt: data.expiresAt });
      setStage("qr_pending");
      setStatusMessage("Scan the QR code or open the link in Trustlith Authenticator within 5 minutes.");
    } catch (err) {
      setStatusMessage(err instanceof Error ? err.message : "Unable to start QR enrollment.");
    } finally {
      setBusy(false);
    }
  }

  async function runVerificationPrompt(activateAfterApprove: boolean) {
    setBusy(true);
    setStatusMessage("Sending verification prompt to Trustlith Authenticator...");
    try {
      // Server route calls POST /v1/challenges (action: "login")
      const startRes = await fetch("/api/security/trustlith/test/start", { method: "POST" });
      const startData = await startRes.json();
      if (!startRes.ok) throw new Error(startData.message || "Could not start test prompt.");
      setChallengeId(startData.challengeId);

      // Poll backend /status wrapper every 2s until terminal status
      for (let i = 0; i < 60; i += 1) {
        await new Promise((r) => setTimeout(r, 2000));
        const pollRes = await fetch(`/api/security/trustlith/challenges/${startData.challengeId}`);
        const pollData = await pollRes.json();
        if (pollData.status === "APPROVED") {
          setChallengeId(null);
          if (activateAfterApprove) {
            // Persists trustlith_enrolled_at + trustlith_required=true on backend only after APPROVED
            const actRes = await fetch("/api/security/trustlith/activate", { method: "POST" });
            if (!actRes.ok) throw new Error("Enrollment confirmed, but account activation failed.");
            setStage("active_required");
            setStatusMessage("Device confirmed and Trustlith protection is now active for your account.");
          } else {
            setStage("confirmed_inactive");
            setStatusMessage("Device confirmed! You can now activate mandatory Trustlith protection.");
          }
          return;
        }
        if (pollData.status !== "PENDING") {
          setChallengeId(null);
          setStatusMessage(`Prompt ended with status: ${pollData.status}. Protection was not changed.`);
          return;
        }
      }
      setStatusMessage("Verification prompt timed out. Retry when your Authenticator is open.");
    } catch (err) {
      setStatusMessage(err instanceof Error ? err.message : "Verification failed.");
    } finally {
      setBusy(false);
    }
  }

  async function cancelActiveTestPrompt() {
    if (!challengeId) return;
    await fetch(`/api/security/trustlith/challenges/${challengeId}/cancel`, { method: "POST" });
    setChallengeId(null);
    setStatusMessage("Verification prompt cancelled.");
  }

  return (
    <section aria-label="Trustlith Authenticator Security Settings">
      <h3>Hardware-Backed Authentication (Trustlith)</h3>
      <p>
        Status: <strong>{stage}</strong>
      </p>

      <div>
        <button type="button" disabled={busy} onClick={startQrEnrollment}>
          {stage === "not_enrolled" ? "Connect Trustlith Authenticator" : "Generate New Enrollment QR"}
        </button>

        {stage !== "not_enrolled" ? (
          <button type="button" disabled={busy} onClick={() => runVerificationPrompt(false)}>
            Verify / Test Prompt
          </button>
        ) : null}

        {stage === "confirmed_inactive" ? (
          <button type="button" disabled={busy} onClick={() => runVerificationPrompt(true)}>
            Activate Required Protection
          </button>
        ) : null}

        {challengeId ? (
          <button type="button" onClick={cancelActiveTestPrompt}>
            Cancel Pending Prompt
          </button>
        ) : null}
      </div>

      {handoff ? (
        <div>
          <p>Render QR SVG for: <code>{handoff.deepLink}</code> (expires {handoff.expiresAt})</p>
          <p>After approving the biometric prompt in Trustlith Authenticator, click <strong>Verify / Test Prompt</strong>.</p>
        </div>
      ) : null}

      {statusMessage ? <p role="status">{statusMessage}</p> : null}

      <p>
        Device management &amp; recovery: Active V1 devices are inspected via Developer Portal; if your device is lost while protection is required, sign-in remains fail-closed until your administrator assists with replacement enrollment.
      </p>
    </section>
  );
}
```

---

## 5. 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"
}) {
  return trustlithPost<{ challengeId: string; status: "PENDING"; expiresAt: string }>(
    "/v1/challenges",
    {
      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,
      },
    },
  );
}
```

---

## 6. Python (`urllib`) & cURL

```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 verify_connectivity() -> dict:
    with urllib.request.urlopen(f"{BASE_URL}/health", timeout=10) as resp:
        return json.loads(resp.read().decode("utf-8"))


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"))
```

```bash
# 1. Verify connectivity first
curl -sS "$TRUSTLITH_API_BASE_URL/health"

# 2. Trigger a login challenge (after user is mapped in Portal and enrolled)
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"
    }
  }'

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

# 4. 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 using [`TRUSTLITH-INTEGRATION.md`](../../TRUSTLITH-INTEGRATION.md), [`llms.txt`](../../llms.txt), and [`docs/openapi.yaml`](../openapi.yaml).

## Critical Rollout Rule for AI Coding Agents (Learned from Real Integrations)
**Do NOT configure global mandatory Trustlith enforcement (`required` on all logins/routes) before the customer application has:**
1. Verified backend availability (`GET /health`) and confirmed an active `TRUSTLITH_API_KEY` + origin via an authenticated test call (`GET /health` checks Runtime availability only and does not prove API credential validity).
2. Accounted for V1 manual user mapping in **Developer Portal → Users** (automatic end-user provisioning API does not exist in V1).
3. Implemented **Account Settings → Security** programmatic QR enrollment (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`), supported cryptographic enrollment confirmation (`action: "login"` → `APPROVED`), and user-side **Test Authentication** before account-level activation.

Once mandatory Trustlith authentication **is** enabled for an account, user allowlist (`designated`), or route, **all verification failures must remain strictly fail-closed**.

---

## Quick Workflow for Claude Code, Cursor, Codex, and Antigravity
1. Download [`TRUSTLITH-INTEGRATION.md`](../../TRUSTLITH-INTEGRATION.md) into your repository root (or download the app-specific kit from **Developer Portal → Documentation**).
2. Store `TRUSTLITH_API_KEY`, `TRUSTLITH_API_BASE_URL`, `APP_PUBLIC_ORIGIN`, and `TRUSTLITH_ENFORCEMENT_MODE` (`optional` / `designated` / `required`) in your server `.env` / secret store—never in 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 implement the complete end-to-end Trustlith Public Runtime API v1 customer journey—without turning on global mandatory enforcement prematurely.

Strict requirements:
1. Developer config vs user onboarding: Place all Trustlith API calls strictly on the backend using process.env.TRUSTLITH_API_BASE_URL and process.env.TRUSTLITH_API_KEY. Never expose API keys in browser/client bundles or invent undocumented endpoints (V1 requires manually mapped users in Portal -> Users; auto user provisioning is not supported yet).
2. Availability & Rollout Safety: Add a backend GET /health probe (remembering /health checks unauthenticated Runtime availability only and does NOT prove TRUSTLITH_API_KEY validity; validate keys via authenticated calls) and configurable TRUSTLITH_ENFORCEMENT_MODE ("optional" | "designated" | "required"), defaulting to "optional" or "designated" until enrollment + test verification pass. Never globally lock out unenrolled users during initial setup.
3. End-User Account Settings -> Security UI & Routes: Build an authenticated Account Settings -> Security section allowing signed-in users to start programmatic QR enrollment (POST /v1/enrollments + POST /v1/enrollment-handoffs with FIRST_DEVICE), scan the handoff ref, confirm enrollment via a live test login challenge (POST /v1/challenges action: "login"), cancel pending prompts (POST /v1/challenges/:id/cancel), and activate account-level protection only after APPROVED confirmation.
4. Fail-Closed Session-Bound Enforcement: Never send tenantId or applicationId in POST /v1/challenges; exact-match context.origin to APP_PUBLIC_ORIGIN; use action: "login" or action: "fund_transfer" with transactionContext.type: "fund_transfer" (never call unimplemented V2 routes such as /consume). Bind every challengeId to the server session + immutable action context, reject direct API bypasses with a shared server guard, enforce single-use consumption in your customer database (V1 Runtime /status does not consume APPROVED challenges), and fail closed unless GET /v1/challenges/:id/status returns status === "APPROVED" once required.
5. Device & Recovery Boundaries: Document and reflect in UI that V1 device inspection uses Developer Portal while self-service end-user device revocation/recovery APIs are planned features.
6. Add automated tests covering connectivity, QR enrollment handoff, cryptographic enrollment confirmation, optional/designated/required policy modes, fail-closed active enforcement (APPROVED, REJECTED, CANCELLED, EXPIRED, API error), and direct API bypass prevention.
```

## Mandatory Verification Checklist After AI Generation
- [ ] Grep client/browser bundle directories to confirm `TRUSTLITH_API_KEY` and `enrollmentToken` never appear client-side.
- [ ] Confirm `POST /v1/challenges` requests omit `tenantId` / `applicationId` and match `APP_PUBLIC_ORIGIN`.
- [ ] Confirm global mandatory enforcement is not enabled before connectivity and Account Settings → Security onboarding/test verification work cleanly.
- [ ] Confirm protected routes fail closed when required (`PENDING`, `REJECTED`, `CANCELLED`, `EXPIRED`, error, or missing session binding all return denied).
- [ ] Confirm `fund_transfer` requests include `transactionContext.type === "fund_transfer"`, 2-decimal `amount`, and single-use server consumption per `challengeId`.
- [ ] Confirm V1 manual user mapping and V1 vs planned device/recovery limitations are surfaced accurately.

================================================================================
# 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) and self-service user-provisioning/device-recovery Application Bearer APIs remain planned and **are not yet deployed**.

---

## `1.0.1-dev-pilot` (2026-12-04) — Complete Customer Integration Journey Update

- **Developer Experience & Distribution Update (VideoKiosk Feedback):**
  - Assigned documentation/artifact release revision `1.0.1-dev-pilot` (Runtime Public API v1 contract remains `1.0.0-dev-pilot`; immutable `v1.0.0-dev-pilot/*` R2 artifacts preserved).
  - Expanded the Developer Center quickstart, enrollment guide, AI agent prompts, `TRUSTLITH-INTEGRATION.md`, `llms.txt`, and integration kits into a 10-step customer integration journey clearly separating **developer-side setup** from **end-user onboarding** and **server-side enforcement**.
  - Clarified that `GET /health` is an unauthenticated Runtime availability check only (not API key validation), and that V1 single-use challenge consumption is enforced inside the customer backend/database (distinct from planned V2 Runtime `/consume` under ADR 0022).
  - Added explicit guidance prohibiting global mandatory Trustlith activation prior to connectivity checks, manual V1 user mapping (`Portal → Users`), Account Settings → Security QR enrollment (`POST /v1/enrollments` + `POST /v1/enrollment-handoffs`), supported cryptographic enrollment confirmation (`action: "login"` → `APPROVED`), and user test authentication—while preserving strict fail-closed enforcement once active.
  - Added Reference **Account Settings → Security UI** component, `optional` / `designated` / `required` authentication policy examples, V1 vs planned device management & recovery guidance, and session-bound authorization + direct API bypass prevention patterns.
  - Fixed indented Markdown fenced code rendering on `/guides/`.

---

## `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 private R2 release archive (`trustlith-developer-docs-artifacts`), 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)
- **Automatic End-User Provisioning & Self-Service Device/Recovery Scopes:** Automatic user creation (`POST /v1/users`), public Application Bearer device listing/revocation, and end-user self-service recovery UI remain planned enhancements; V1 requires manually mapped users in **Developer Portal → Users**.
- **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 (unauthenticated)
      description: >
        Unauthenticated reachability probe only. Returning 200 proves the Trustlith
        Runtime service is reachable, NOT that your `TRUSTLITH_API_KEY`, scopes,
        origin, or user mappings are valid. Validate credentials with an
        authenticated Application Bearer endpoint (for example test `POST /v1/challenges`).
      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. In Public Runtime API v1, Trustlith does not mark
        `APPROVED` challenges consumed server-side—enforce single-use consumption in your
        own customer backend/database (server-side Runtime `/consume` is planned V2 ADR 0022).
      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 }
```
