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

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

---

## 1. Security Rules (Non-Negotiable)

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

---

## 2. Five-Step Pilot Onboarding Checklist

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

---

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

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

---

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

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

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

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

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

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

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

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

---

## 5. Error Codes & Handling Matrix

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

---

## 6. AI Coding Agent Guardrails

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