# 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).
