SPB Git

Repository Public

SDK_WEB.md 20.7 KB 382 lines markdown

1# MacLustr Identity — Web SDK (TypeScript)23Package `@maclustr/identity`, source in [`sdk/typescript`](../sdk/typescript). Zero runtime dependencies,4ESM + CommonJS + type declarations, Node 18+ and modern browsers.56**Status: not published to npm.** Install from the repository path (see below). Version 0.1.0.78| Import | Runs on | Purpose |9|---|---|---|10| `@maclustr/identity` or `@maclustr/identity/server` | your server | API client, webhook verification, errors, types |11| `@maclustr/identity/browser` | browser | open the hosted verification page (modal / popup / redirect), camera pre-check |12| `@maclustr/identity/react` | browser | `useVerification()`, `<VerifyButton>` (React 18+, optional peer dependency) |13| `@maclustr/identity/testing` | tests | `completeSandboxSession()` |1415## Security rule: secret keys never reach a browser1617A secret key (`mlid_sk_test_…`, `mlid_sk_live_…`) can read, revoke and erase every verification of your18application. It belongs in server-side configuration only.1920What the SDK enforces:2122- `new MacLustrIdentity(...)` **throws** (`code: "secret_key_in_browser"`) when it runs in a page or a web worker.23- `openVerification()` and `parseVerificationUrl()` **throw** when any option contains something that looks24  like a secret key.25- The browser and React entries have no parameter for a key. Their only input is the session `url`.26- The client keeps the key in a private field: it is absent from `JSON.stringify(client)` and from enumeration.2728What you must do: create sessions on your server, send only `session.url` to the browser, and never put the key29in a `NEXT_PUBLIC_…` / `VITE_…` variable. A webhook signing secret (`whsec_…`) is server-side only as well.3031## Install3233```bash34cd /path/to/maclustr-identity/sdk/typescript35npm install && npm run build            # produces dist/36cd /path/to/your-app37npm install /path/to/maclustr-identity/sdk/typescript38```3940`integrations/demo-marketplace/package.json` shows the equivalent `"file:"` dependency.4142## Quickstart4344Server (any Node framework):4546```ts47import { MacLustrIdentity, ConnectionError } from "@maclustr/identity";4849const identity = new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY! });5051// Gate52let verification = null;53try {54  verification = await identity.isUserVerified(user.id);55} catch (e) {56  if (!(e instanceof ConnectionError)) throw e; // unreachable service: stay refused (fail closed)57}58if (!verification) return res.status(403).json({ error: "identity_verification_required" });5960// Session creation endpoint61const session = await identity.verificationSessions.create({ purpose: "Publish listings", external_user_id: user.id });62res.json({ url: session.url });63```6465Browser:6667```ts68import { openVerification } from "@maclustr/identity/browser";6970const { url } = await fetch("/api/identity/session", { method: "POST" }).then((r) => r.json());71openVerification({ url, mode: "modal", onComplete: () => location.reload() });72```7374A complete application is in [`integrations/demo-marketplace`](../integrations/demo-marketplace); the generic75guide is in [`integrations/README.md`](../integrations/README.md).7677## Server reference7879### `new MacLustrIdentity(options)`8081| Option | Type | Default | |82|---|---|---|---|83| `apiKey` | `string` | required | must start with `mlid_sk_test_` or `mlid_sk_live_` |84| `baseUrl` | `string` | `https://identity.spboucher.ai` | origin of the service, no path |85| `timeoutMs` | `number` | `30000` | per attempt |86| `maxRetries` | `number` | `2` | retries after the first attempt |87| `fetch` | `typeof fetch` | global `fetch` | custom implementation |8889Properties: `baseUrl`, `livemode`, `verificationSessions`, `verifications`, `webhooks`.9091Every resource method accepts a last argument `RequestOptions`:92`{ idempotencyKey?: string; timeoutMs?: number; maxRetries?: number; signal?: AbortSignal }`.9394### `verificationSessions`9596| Method | Returns | Endpoint |97|---|---|---|98| `create(params)` | `CreatedVerificationSession` | `POST /v1/verification-sessions` |99| `retrieve(id)` | `VerificationSession` | `GET /v1/verification-sessions/{id}` |100| `list(params?)` | `List<VerificationSession>` | `GET /v1/verification-sessions` |101| `listAutoPaging(params?)` | `AsyncGenerator<VerificationSession>` | same, every page |102| `cancel(id)` | `VerificationSession` | `POST /v1/verification-sessions/{id}/cancel` |103104`create` parameters:105106| Field | Type | |107|---|---|---|108| `purpose` | `string`, required, ≤ 120 chars | shown to the person |109| `external_user_id` | `string`, ≤ 200 chars | your opaque user id; needed for `isUserVerified` |110| `verification_policy` | `string` | `identity_document_face_v1` (default) or `identity_document_v1`, or a policy of your application |111| `return_url` | `string` | must be allowed for the application (in sandbox without configured URLs: https or localhost) |112| `locale` | `string` | default `fr-CA` |113| `metadata` | `object`, ≤ 2000 bytes | no personal data |114| `expires_in_minutes` | `number` | clamped to 10..1440, default 60 |115116`CreatedVerificationSession` adds `client_secret` (`vsc_…`) and `url`117(`{origin}/verify/{id}#{client_secret}`). They are returned by `create` only.118119List parameters: `limit` (1..100, default 20), `starting_after` (id of the last item of the previous page),120`status`, `external_user_id`. Lists are ordered newest first.121122`cancel` throws `ConflictError` (`session_not_cancellable`) once the session has a decision, is in manual123review, or is already cancelled or expired. A cancellation emits `verification.cancelled`. An unknown124`starting_after` is refused with `InvalidRequestError` (`invalid_cursor`).125126Session statuses: `created`, `awaiting_consent`, `awaiting_document`, `awaiting_selfie`, `processing`,127`manual_review`, `verified`, `inconclusive`, `rejected`, `expired`, `cancelled`, `revoked`. The TypeScript types128are open unions (`| (string & {})`): a status, reason code or event type added by a later service version is129passed through untouched, so keep a default branch. `RETRYABLE_SESSION_STATUSES` (`inconclusive`, `expired`,130`cancelled`) lists the statuses after which the person may simply start a new session.131132`Verification.dimensions` maps each dimension to `{ status, notes? }`. Scores are not kept once a decision is133made: do not read `score`. `Verification.reasons[].code` includes `review_not_completed` (the review by a person134was not completed before its deadline: the result is `inconclusive` and the person may start again) and135`decision_overturned` (a contested decision was set aside).136137### `verifications`138139| Method | Returns | Endpoint |140|---|---|---|141| `retrieve(id)` | `Verification` | `GET /v1/verifications/{id}` |142| `status(id)` | `VerificationStatusSummary` | `GET /v1/verifications/{id}/status` |143| `list(params?)` | `List<Verification>` | `GET /v1/verifications` |144| `listAutoPaging(params?)` | `AsyncGenerator<Verification>` | same, every page |145| `revoke(id, { reason? })` | `Verification` | `POST /v1/verifications/{id}/revoke` |146| `deletePersonalData(id)` | `PersonalDataDeletion` | `DELETE /v1/verifications/{id}/personal-data` |147148`Verification` fields: `verification_id`, `object`, `session_id`, `status`, `assurance_level`, `method`,149`verification_policy`, `policy_version`, `livemode`, `simulated`, `external_user_id`, `reasons`150(`{ code, message: { fr, en } }[]`), `dimensions`, `decision_engine`, `created_at`, `verified_at`,151`expires_at`, `revoked_at`, `personal_data_deleted_at`. It never contains a name, a document number, an image152or any extracted field.153154Verification statuses: `verified`, `manual_review`, `inconclusive`, `rejected`, `revoked`.155Assurance levels: `document_check`, `document_face_liveness_check`, `document_manual_review`,156`document_face_manual_review`, and `sandbox_simulated` for sandbox results (`simulated: true`).157158`VerificationStatusSummary`: `{ verification_id, status, valid, assurance_level, expires_at }`; `valid` is159`true` only for a `verified`, non-expired verification.160161`revoke` only applies to a `verified` verification (`ConflictError` `not_revocable` otherwise) and is162idempotent on a revoked one.163164### `isUserVerified(externalUserId)`165166Lists the user's `verified` verifications (newest first) and returns the first one that has not expired, or167`null`. Throws like any other call when the service is unreachable: treat that as "not verified".168169### `webhooks`170171| Method | Returns | Endpoint |172|---|---|---|173| `create({ url, events?, description? })` | `CreatedWebhookEndpoint` (with `secret`, once) | `POST /v1/webhooks` |174| `list()` | `List<WebhookEndpoint>` | `GET /v1/webhooks` |175| `delete(id)` | `{ id, deleted: true }` | `DELETE /v1/webhooks/{id}` |176| `rotateSecret(id)` | `{ id, secret }` | `POST /v1/webhooks/{id}/rotate-secret` |177| `constructEvent(rawBody, signatureHeader, secret, toleranceSec = 300)` | `Promise<WebhookEvent>` | local |178| `verifySignature(rawBody, signatureHeader, secret, toleranceSec = 300)` | `Promise<void>` | local |179180`constructEvent`, `verifySignature`, `signPayload`, `parseSignatureHeader` and `timingSafeEqual` are also181exported as standalone functions (no client or key needed).182183### Verifying webhooks184185Each delivery carries:186187| Header | |188|---|---|189| `MLID-Signature` | `t=<unix seconds>,v1=<hex>[,v1=<hex>]` |190| `MLID-Event-Id` | `evt_…`, stable across retries: deduplicate on it |191| `MLID-Delivery-Id` | `whd_…`, one per endpoint and event |192| `MLID-Event-Type` | same as `event.type` |193194Each `v1` is HMAC-SHA256(secret, `"<t>." + raw body`), hex encoded. After `rotateSecret`, deliveries carry two195`v1` values (new and previous secret) for 24 hours: verification succeeds with either.196197```ts198const event = await identity.webhooks.constructEvent(rawBody, req.headers["mlid-signature"], process.env.MLID_WEBHOOK_SECRET!);199```200201- `rawBody` must be the exact bytes received: `string`, `Buffer` / `Uint8Array` or `ArrayBuffer`. A parsed202  object is refused (`payload_not_raw`).203- The comparison is constant-time. HMAC uses WebCrypto when available, otherwise `node:crypto`.204- The timestamp must be within `toleranceSec` of the current time, in both directions.205- Failure throws `SignatureVerificationError` with `code` among `signature_header_invalid`,206  `signature_mismatch`, `signature_expired`, `payload_not_raw`, `payload_invalid`, `secret_missing`.207208Event object:209210```ts211{ id: "evt_…", object: "event", type: "verification.verified", api_version: "2026-12-01",212  created: 1796140800, livemode: false, data: { object: Verification | VerificationSession } }213```214215| Type | `data.object` |216|---|---|217| `verification.created`, `verification.processing`, `verification.expired`, `verification.cancelled` | `VerificationSession` |218| `verification.completed`, `verification.verified`, `verification.inconclusive`, `verification.manual_review`, `verification.rejected`, `verification.revoked` | `Verification` |219220`isDecisionEvent(event)` narrows to the second group, `isSessionEvent(event)` to the first; both look at the221object, so they are safe on an event type this SDK version does not know (`constructEvent` returns it as is).222`sessionEndedWithoutDecision(event)` is true for `verification.cancelled` and `verification.expired`.223`verification.completed` is sent together with the specific outcome event for every final decision (not for224`manual_review`). `verification.cancelled` is sent when your server cancels a session and when the person225withdraws consent, including during a manual review; in that last case no decision event follows and the226session object carries the `verification_id` of the review that will never conclude. Deliveries are227at-least-once and unordered, and are retried with a growing delay when your endpoint does not answer 2xx.228229### Idempotency230231Every `POST` sends an `Idempotency-Key` (`sdk-<uuid>`), identical across the automatic retries of that call.232Override it with `{ idempotencyKey }` to cover your own retries. The service honours it on session creation,233session cancellation, verification revocation, webhook creation and secret rotation: a repeated key with the234same body returns the original response (HTTP header `Idempotent-Replayed: true`; the SDK returns the body, it235does not expose the header), `409 idempotency_key_reused` when the body differs, and236`409 idempotency_in_progress` while the first request is still running.237238### Retries239240Only network errors, HTTP 429 and HTTP 5xx are retried, up to `maxRetries` times. Delay before retry *n*241(0-based): a random value in [50 %, 100 %] of `min(8 s, 0.5 s × 2ⁿ)`. When the response carries `Retry-After`242(429 `rate_limited`, 503 `service_unavailable`), that delay is used instead, capped at 60 s. Quotas243(`429 daily_session_limit`) are not retried. No other 4xx is ever retried. `backoffDelayMs(attempt)` and244`shouldRetry(status, code)` are exported. `webhooks.create` and `webhooks.rotateSecret` are retried like every245other POST, with the same key: a retry returns the endpoint (and its secret) or the rotated secret of the246first attempt, it never creates or rotates twice. Two separate calls use two keys: calling `rotateSecret`247again rotates again. Rate limits are shared by every process of the service: several of your servers using248the same key share one budget.249250### Errors251252`MacLustrIdentityError` fields: `message`, `status` (undefined without a response), `type`, `code`, `param`,253`requestId`, `headers`.254255| Class | HTTP | Typical `code` |256|---|---|---|257| `InvalidRequestError` | 400, 411, 413, 422 | `purpose_required`, `unknown_policy`, `return_url_not_allowed`, `invalid_webhook_url`, `invalid_cursor`, `payload_too_large` (413, body over 256 KB), `length_required` (411) |258| `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key` |259| `PermissionError` | 403 | `insufficient_scope`, `application_suspended`, `compliance_gate_closed`, `forbidden_network` |260| `NotFoundError` | 404 | `resource_missing` (also for objects of another application or mode, including a webhook endpoint deleted or rotated with a key of the other mode) |261| `ConflictError` | 409 | `session_not_cancellable`, `not_revocable`, `idempotency_key_reused`, `idempotency_in_progress` |262| `RateLimitError` | 429 | `rate_limited`, `daily_session_limit`; has `retryAfter` |263| `ApiServerError` | 5xx | `internal_error`, `service_unavailable` (503); has `retryAfter` |264| `ConnectionError` | none | `connection_failed`, `request_timeout`, `request_aborted` |265| `SignatureVerificationError` | none | see above |266267Configuration mistakes throw `MacLustrIdentityError` with `type: "configuration_error"` (`api_key_missing`,268`api_key_malformed`, `secret_key_in_browser`, `fetch_missing`).269270## Browser reference271272### `openVerification(options): VerificationHandle`273274| Option | Type | Default | |275|---|---|---|---|276| `url` | `string` | required | session URL from your server; https (http for localhost only) |277| `mode` | `"modal" \| "popup" \| "redirect"` | `"modal"` | |278| `container` | `HTMLElement` | `document.body` | modal mode |279| `title` | `string` | `"Identity verification"` | dialog name and iframe title |280| `closeLabel` | `string` | `"Close"` | |281| `autoClose` | `boolean` | `true` | close after `completed` / `cancelled` |282| `onReady` | `({ sessionId }) => void` | | the hosted page is loaded |283| `onComplete` | `({ sessionId, status }) => void` | | the person finished; `status` is a hint |284| `onCancel` | `({ sessionId, reason }) => void` | | `reason`: `"page"` or `"dismissed"` |285| `onError` | `({ sessionId, code, message }) => void` | | page error, or `popup_channel_lost` |286287Handle: `{ mode, sessionId, closed, close() }`. `close()` removes the dialog or closes the popup, removes every288listener and fires no callback.289290Message contract with the hosted page: it posts291`{ source: "maclustr-identity", type: "ready" | "completed" | "cancelled" | "error", session_id, status }` to its292parent or opener. A message is accepted only when **all** of these hold: `event.origin` equals the origin of293`url`; `data.source === "maclustr-identity"`; the type is known; `session_id`, when present, matches the session294in `url`; and the sending window is the iframe or popup that was opened. `acceptMessage()` is exported for295custom integrations.296297**Modal.** Injects a full-screen `role="dialog"` `aria-modal="true"` element labelled by its title, with a close298button and an `<iframe allow="camera" referrerpolicy="no-referrer">`. Focus moves to the close button, is kept299inside the dialog (sentinels at both ends), and returns to the previously focused element on close. Sibling300elements of `document.body` are made `inert` and `aria-hidden` while it is open, and page scrolling is locked.301Escape and the close button call `onCancel({ reason: "dismissed" })`. Requirements: the origin of your page302must be listed in the application's `allowed_origins`, and your own Content-Security-Policy must allow303`frame-src` for the identity origin. Escape pressed while focus is inside the cross-origin frame is not304visible to your page.305306**Popup.** Opens a 480 × 760 window. If the browser blocks it, the SDK navigates the current tab instead and307the handle reports `mode: "redirect"`. If the window goes away after `ready`, `onCancel({ reason: "dismissed" })`308fires; if it goes away before any message, `onError({ code: "popup_channel_lost" })` fires. See the known309limitation below.310311**Redirect.** `window.location.assign(url)`. Create the session with `return_url`; when the person comes back,312look the result up on your server.313314Whatever the mode, the result given to `onComplete` is for display. Unlock features from your server's record.315316### `checkCameraSupport(): Promise<CameraSupport>`317318`{ supported, secureContext, hasMediaDevices, hasCamera, permission, reason? }` with `permission` in319`granted | denied | prompt | unknown` and `reason` in320`not_a_browser | insecure_context | no_media_devices | no_camera | permission_denied`. It never prompts and321never opens the camera. In modal mode the permission that finally matters is the one of the identity origin322inside the frame; this helper describes the embedding page and the device.323324### Other exports325326`parseVerificationUrl(url)` → `{ href, origin, sessionId }` (throws on an invalid URL);327`assertNoSecretKey(value)`.328329## React reference330331```tsx332import { VerifyButton, useVerification } from "@maclustr/identity/react";333```334335`useVerification(options)` → `{ state, result, error, open, close }`, with `state` in336`idle | creating | open | completed | cancelled | error`. Options: `createSession` (required; calls **your**337backend and resolves to the URL or to `{ url }`), plus `mode`, `container`, `title`, `closeLabel`, `autoClose`,338`onReady`, `onComplete`, `onCancel`, `onError`. The dialog is closed when the component unmounts.339A failing `createSession` gives `state: "error"` with `error.code === "session_creation_failed"`.340341`<VerifyButton>` takes the same options plus any `<button>` attribute, `children` and `busyLabel`. While the342flow is open it sets `aria-disabled` rather than `disabled`, so focus can return to it; `data-state` mirrors343the hook state.344345Next.js App Router example (session route, webhook route reading the raw body, client component):346[`sdk/typescript/examples/nextjs`](../sdk/typescript/examples/nextjs). It is reference code and is not built347or executed by the test suite.348349## Testing helper350351```ts352import { completeSandboxSession } from "@maclustr/identity/testing";353await completeSandboxSession({ url: session.url, scenario: "verified" });354```355356Options: `url` (or `sessionId` + `clientSecret` + `baseUrl`), `scenario`357(`verified | manual_review | inconclusive | rejected`, default `verified`), `method` (default: the first358method of the policy), `fetch`. It calls `GET /v1/sessions/{id}`, `POST …/consent` and `POST …/sandbox` with359the session client secret. It throws on a live session.360361## Tests362363```bash364cd sdk/typescript365npm test                  # 84 unit tests: signature, retry policy, idempotency, error mapping, browser (jsdom), React366npm run test:integration  # 13 tests against the local backend (MLID_BASE_URL, default http://localhost:8870) with its dispatcher367```368369## Known limitations370371- **Popup mode.** The service used to send `Cross-Origin-Opener-Policy: same-origin` on every response, which372  detached a cross-origin popup from its opener (`popup_channel_lost`). It now sends `unsafe-none` on373  `/verify/…`. Popup mode has not been run again in a browser since that change: treat it as unverified and374  prefer the modal or the redirect, which are covered by `integrations/browser-check.mjs`.375- `webhooks.list()` is not paginated by the service (at most 16 endpoints per application and mode).376- `webhooks.delete` and `verifications.deletePersonalData` are `DELETE` calls: the service does not deduplicate377  them. A retried `webhooks.delete` whose first answer was lost throws `NotFoundError`: the endpoint is gone,378  which is what was asked.379- The `Idempotent-Replayed` response header is not exposed by the SDK.380- A 413 `payload_too_large` is answered before the body is read and the connection is closed: some HTTP stacks381  report it as a connection error (`ConnectionError`) instead of the 413 when the body is still being sent.382
Files main
Menu

Theme