SPB Git

Repository Public

README.md 11.3 KB 239 lines markdown

1# @maclustr/identity23TypeScript SDK for **MacLustr Identity**, the self-hosted identity-verification platform.4Zero runtime dependencies. ESM, CommonJS and type declarations. Node 18+ and modern browsers.56| Entry | Where it runs | What it is |7|---|---|---|8| `@maclustr/identity` (alias `@maclustr/identity/server`) | **your server only** | API client, webhook verification, typed errors |9| `@maclustr/identity/browser` | browser | opens the hosted verification page (modal, popup or redirect) |10| `@maclustr/identity/react` | browser | `useVerification()` and `<VerifyButton>` |11| `@maclustr/identity/testing` | tests | plays the person's part of a sandbox session |1213> **Secret keys never leave your server.** `mlid_sk_test_…` and `mlid_sk_live_…` give full access to your14> application's verifications. Never ship them in a web page, a mobile app, a desktop app or a public repository.15> The server client throws at construction when it detects a browser context, and the browser entry rejects any16> option that looks like a secret key. The browser only ever receives the session `url`.1718## Install1920Nothing is published to npm yet. Install from the repository path:2122```bash23cd sdk/typescript && npm install && npm run build24# in your application25npm install /absolute/path/to/maclustr-identity/sdk/typescript26```2728## Server quickstart2930```ts31import { MacLustrIdentity } from "@maclustr/identity";3233const identity = new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY! });3435// 1. Gate the sensitive action on your server.36const verified = await identity.isUserVerified(user.id); // newest valid verification, or null37if (!verified) {38  // 2. Create a session and send only its URL to the browser.39  const session = await identity.verificationSessions.create({40    purpose: "Publish listings",41    external_user_id: user.id, // opaque id, never an e-mail or a name42  });43  return { url: session.url };44}45```4647`isUserVerified` throws `ConnectionError` when the service cannot be reached: catch it and keep the action48refused (fail closed).4950### Client options5152```ts53new MacLustrIdentity({54  apiKey,                                   // required, mlid_sk_test_… or mlid_sk_live_…55  baseUrl: "https://identity.spboucher.ai", // default56  timeoutMs: 30000,                         // per attempt57  maxRetries: 2,                            // after the first attempt58  fetch,                                    // optional custom fetch59});60```6162Every method takes a last optional argument `{ idempotencyKey, timeoutMs, maxRetries, signal }`.6364### Resources6566| Call | HTTP |67|---|---|68| `verificationSessions.create(params)` | `POST /v1/verification-sessions` |69| `verificationSessions.retrieve(id)` | `GET /v1/verification-sessions/{id}` |70| `verificationSessions.list(params)` / `.listAutoPaging(params)` | `GET /v1/verification-sessions` |71| `verificationSessions.cancel(id)` | `POST /v1/verification-sessions/{id}/cancel` |72| `verifications.retrieve(id)` | `GET /v1/verifications/{id}` |73| `verifications.status(id)` | `GET /v1/verifications/{id}/status` |74| `verifications.list(params)` / `.listAutoPaging(params)` | `GET /v1/verifications` |75| `verifications.revoke(id, { reason })` | `POST /v1/verifications/{id}/revoke` |76| `verifications.deletePersonalData(id)` | `DELETE /v1/verifications/{id}/personal-data` |77| `webhooks.create({ url, events, description })` | `POST /v1/webhooks` |78| `webhooks.list()` | `GET /v1/webhooks` |79| `webhooks.delete(id)` | `DELETE /v1/webhooks/{id}` |80| `webhooks.rotateSecret(id)` | `POST /v1/webhooks/{id}/rotate-secret` |81| `webhooks.constructEvent(rawBody, header, secret, toleranceSec?)` | local |82| `isUserVerified(externalUserId)` | `GET /v1/verifications?external_user_id=…&status=verified` |8384Objects use the wire field names (`external_user_id`, `verification_id`, `expires_at`…). `client_secret` and85`url` are returned by `create` only; a webhook `secret` by `webhooks.create` and `rotateSecret` only.8687```ts88for await (const v of identity.verifications.listAutoPaging({ status: "verified" })) {89  console.log(v.verification_id, v.assurance_level);90}91```9293### Idempotency and retries9495- Every `POST` carries an `Idempotency-Key` generated by the SDK; the same key is reused when that call is96  retried. Pass `{ idempotencyKey: "order-42" }` to make your own retries safe as well. The service deduplicates97  every keyed POST: session creation and cancellation, revocation, webhook creation and secret rotation. A replay98  returns the first response (HTTP header `Idempotent-Replayed: true`); the same key with another body is a99  `409 idempotency_key_reused`.100- Retries happen only on network errors, HTTP 429 and HTTP 5xx, with exponential backoff and jitter101  (0.5 s, 1 s, 2 s… capped at 8 s, each multiplied by a random factor in [0.5, 1]). `Retry-After` is honoured102  on 429 `rate_limited` and 503 `service_unavailable` (capped at 60 s). Quotas (`daily_session_limit`) are not103  retried. 4xx errors are never retried. `webhooks.create` and `webhooks.rotateSecret` are retried like any other104  POST, with the same key: a retry returns the endpoint or the secret of the first attempt.105106### Errors107108All errors extend `MacLustrIdentityError` and expose `status`, `type`, `code`, `param`, `requestId`.109110| Class | When |111|---|---|112| `InvalidRequestError` | 400, 411, 413, 422 (`invalid_cursor`, `payload_too_large`, `length_required`…) |113| `AuthenticationError` | 401 |114| `PermissionError` | 403 (missing scope, suspended application, closed compliance gate) |115| `NotFoundError` | 404 (also for objects of another application or mode) |116| `ConflictError` | 409 (state conflict, idempotency key reused with another body) |117| `RateLimitError` | 429 (`retryAfter` in seconds) |118| `ApiServerError` | 5xx (`retryAfter` in seconds on 503 `service_unavailable`) |119| `ConnectionError` | no response (`code`: `connection_failed`, `request_timeout`, `request_aborted`) |120| `SignatureVerificationError` | webhook signature missing, malformed, expired or not matching |121122## Webhooks123124Deliveries are signed: `MLID-Signature: t=<unix>,v1=<hex>[,v1=<hex>]`, each `v1` being125HMAC-SHA256(secret, `"<t>." + raw body`). During a secret rotation two `v1` values are sent for 24 hours.126Other headers: `MLID-Event-Id`, `MLID-Delivery-Id`, `MLID-Event-Type`.127128```ts129import { createServer } from "node:http";130import { MacLustrIdentity, isDecisionEvent, SignatureVerificationError } from "@maclustr/identity";131132const identity = new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY! });133const seen = new Set<string>(); // use a unique column in your database134135createServer(async (req, res) => {136  const chunks: Buffer[] = [];137  for await (const c of req) chunks.push(c as Buffer);138  const raw = Buffer.concat(chunks); // the raw bytes: do not parse and re-serialize139  try {140    const event = await identity.webhooks.constructEvent(raw, req.headers["mlid-signature"] as string, process.env.MLID_WEBHOOK_SECRET!);141    if (!seen.has(event.id)) {142      seen.add(event.id);143      if (isDecisionEvent(event)) {144        const v = event.data.object; // Verification145        // store v.verification_id, v.status, v.assurance_level, v.expires_at for v.external_user_id146      }147    }148    res.writeHead(200).end();149  } catch (e) {150    res.writeHead(e instanceof SignatureVerificationError ? 400 : 500).end();151  }152}).listen(3000);153```154155`constructEvent` is asynchronous (WebCrypto; `node:crypto` fallback on Node 18 without the global), compares in156constant time, and rejects timestamps more than `toleranceSec` (default 300) away from now.157158Event types: `verification.created`, `.processing`, `.expired`, `.cancelled` (payload: a verification session,159`isSessionEvent`) and `.completed`, `.verified`, `.inconclusive`, `.manual_review`, `.rejected`, `.revoked`160(payload: a verification, `isDecisionEvent`). After `.cancelled`, `.expired` or an `inconclusive` result (for161example reason `review_not_completed`: the manual review was not handled before its deadline) the person may162simply start a new session. Deliveries are at-least-once and unordered: deduplicate on `event.id`. Statuses,163reason codes and event types are open unions: keep a default branch, a later service version may add values.164165## Browser166167```ts168import { openVerification, checkCameraSupport } from "@maclustr/identity/browser";169170const { url } = await fetch("/api/identity/session", { method: "POST" }).then((r) => r.json());171const handle = openVerification({172  url,173  mode: "modal", // "modal" (default) | "popup" | "redirect"174  onReady: () => {},175  onComplete: ({ sessionId, status }) => refreshFromServer(),176  onCancel: ({ reason }) => {}, // "page" | "dismissed"177  onError: ({ code, message }) => {},178});179handle.close(); // programmatic close, fires no callback180```181182- **modal**: full-screen `role="dialog"` with an `<iframe allow="camera">`, focus trap, Escape and a close button,183  page content made inert, focus restored on close. The origin of your page must be in the application's184  `allowed_origins`, otherwise the browser refuses to frame the page.185- **popup**: opens a window; when the popup is blocked the SDK falls back to **redirect** (`handle.mode` tells).186  If the window disappears before any message was received, `onError` fires with `popup_channel_lost`.187- **redirect**: navigates the tab. Create the session with a `return_url` and check the status on your server188  when the person comes back.189- Messages are accepted only when `event.origin` equals the origin of `url`, `data.source === "maclustr-identity"`,190  the type is known and the session id matches.191- The status passed to `onComplete` is a display hint. Unlock features from your server's own record only.192- Escape pressed while focus is inside the cross-origin iframe is not visible to the embedding page; the close193  button always works.194195`checkCameraSupport()` resolves to `{ supported, secureContext, hasMediaDevices, hasCamera, permission, reason? }`196without prompting for permission.197198## React199200```tsx201import { VerifyButton, useVerification } from "@maclustr/identity/react";202203<VerifyButton createSession={() => fetch("/api/identity/session", { method: "POST" }).then((r) => r.json())} onComplete={() => router.refresh()}>204  Verify my identity205</VerifyButton>;206207const { state, open, close, result, error } = useVerification({ createSession, mode: "modal" });208// state: "idle" | "creating" | "open" | "completed" | "cancelled" | "error"209```210211A Next.js App Router example (session route, webhook route on the raw body, client component) is in212[`examples/nextjs`](examples/nextjs).213214## Testing your integration215216```ts217import { completeSandboxSession } from "@maclustr/identity/testing";218219const session = await identity.verificationSessions.create({ purpose: "Test", external_user_id: "u1" });220await completeSandboxSession({ url: session.url, scenario: "verified" }); // or manual_review | inconclusive | rejected221```222223It records consent and applies a sandbox scenario using the session client secret only. Sandbox results are224flagged `simulated: true` with `assurance_level: "sandbox_simulated"`. Live sessions refuse it.225226## Development227228```bash229npm install230npm run typecheck231npm run build             # dist/ (ESM + CJS + .d.ts)232npm test                  # unit tests233npm run test:integration  # needs the local backend on http://localhost:8870 and its dispatcher234```235236Integration tests provision two sandbox applications through the backend CLI (`.venv` of the repository,237database `maclustr_identity_sdk`), or use `MLID_SECRET_KEY` / `MLID_SECRET_KEY_B` when set. They refuse to run238against anything but localhost.239
Files main
Menu

Theme