SPB Git

Repository Public

SDK_WEB.md 20.7 KB

# MacLustr Identity — Web SDK (TypeScript)

Package @maclustr/identity, source in sdk/typescript. Zero runtime dependencies, ESM + CommonJS + type declarations, Node 18+ and modern browsers.

Status: not published to npm. Install from the repository path (see below). Version 0.1.0.

Import Runs on Purpose
@maclustr/identity or @maclustr/identity/server your server API client, webhook verification, errors, types
@maclustr/identity/browser browser open the hosted verification page (modal / popup / redirect), camera pre-check
@maclustr/identity/react browser useVerification(), <VerifyButton> (React 18+, optional peer dependency)
@maclustr/identity/testing tests completeSandboxSession()

# Security rule: secret keys never reach a browser

A secret key (mlid_sk_test_…, mlid_sk_live_…) can read, revoke and erase every verification of your application. It belongs in server-side configuration only.

What the SDK enforces:

  • new MacLustrIdentity(...) throws (code: "secret_key_in_browser") when it runs in a page or a web worker.
  • openVerification() and parseVerificationUrl() throw when any option contains something that looks like a secret key.
  • The browser and React entries have no parameter for a key. Their only input is the session url.
  • The client keeps the key in a private field: it is absent from JSON.stringify(client) and from enumeration.

What you must do: create sessions on your server, send only session.url to the browser, and never put the key in a NEXT_PUBLIC_… / VITE_… variable. A webhook signing secret (whsec_…) is server-side only as well.

# Install

bash
cd /path/to/maclustr-identity/sdk/typescript
npm install && npm run build            # produces dist/
cd /path/to/your-app
npm install /path/to/maclustr-identity/sdk/typescript

integrations/demo-marketplace/package.json shows the equivalent "file:" dependency.

# Quickstart

Server (any Node framework):

ts
import { MacLustrIdentity, ConnectionError } from "@maclustr/identity";

const identity = new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY! });

// Gate
let verification = null;
try {
  verification = await identity.isUserVerified(user.id);
} catch (e) {
  if (!(e instanceof ConnectionError)) throw e; // unreachable service: stay refused (fail closed)
}
if (!verification) return res.status(403).json({ error: "identity_verification_required" });

// Session creation endpoint
const session = await identity.verificationSessions.create({ purpose: "Publish listings", external_user_id: user.id });
res.json({ url: session.url });

Browser:

ts
import { openVerification } from "@maclustr/identity/browser";

const { url } = await fetch("/api/identity/session", { method: "POST" }).then((r) => r.json());
openVerification({ url, mode: "modal", onComplete: () => location.reload() });

A complete application is in integrations/demo-marketplace; the generic guide is in integrations/README.md.

# Server reference

# new MacLustrIdentity(options)

Option Type Default
apiKey string required must start with mlid_sk_test_ or mlid_sk_live_
baseUrl string https://identity.spboucher.ai origin of the service, no path
timeoutMs number 30000 per attempt
maxRetries number 2 retries after the first attempt
fetch typeof fetch global fetch custom implementation

Properties: baseUrl, livemode, verificationSessions, verifications, webhooks.

Every resource method accepts a last argument RequestOptions: { idempotencyKey?: string; timeoutMs?: number; maxRetries?: number; signal?: AbortSignal }.

# verificationSessions

Method Returns Endpoint
create(params) CreatedVerificationSession POST /v1/verification-sessions
retrieve(id) VerificationSession GET /v1/verification-sessions/{id}
list(params?) List<VerificationSession> GET /v1/verification-sessions
listAutoPaging(params?) AsyncGenerator<VerificationSession> same, every page
cancel(id) VerificationSession POST /v1/verification-sessions/{id}/cancel

create parameters:

Field Type
purpose string, required, ≤ 120 chars shown to the person
external_user_id string, ≤ 200 chars your opaque user id; needed for isUserVerified
verification_policy string identity_document_face_v1 (default) or identity_document_v1, or a policy of your application
return_url string must be allowed for the application (in sandbox without configured URLs: https or localhost)
locale string default fr-CA
metadata object, ≤ 2000 bytes no personal data
expires_in_minutes number clamped to 10..1440, default 60

CreatedVerificationSession adds client_secret (vsc_…) and url ({origin}/verify/{id}#{client_secret}). They are returned by create only.

List parameters: limit (1..100, default 20), starting_after (id of the last item of the previous page), status, external_user_id. Lists are ordered newest first.

cancel throws ConflictError (session_not_cancellable) once the session has a decision, is in manual review, or is already cancelled or expired. A cancellation emits verification.cancelled. An unknown starting_after is refused with InvalidRequestError (invalid_cursor).

Session statuses: created, awaiting_consent, awaiting_document, awaiting_selfie, processing, manual_review, verified, inconclusive, rejected, expired, cancelled, revoked. The TypeScript types are open unions (| (string & {})): a status, reason code or event type added by a later service version is passed through untouched, so keep a default branch. RETRYABLE_SESSION_STATUSES (inconclusive, expired, cancelled) lists the statuses after which the person may simply start a new session.

Verification.dimensions maps each dimension to { status, notes? }. Scores are not kept once a decision is made: do not read score. Verification.reasons[].code includes review_not_completed (the review by a person was not completed before its deadline: the result is inconclusive and the person may start again) and decision_overturned (a contested decision was set aside).

# verifications

Method Returns Endpoint
retrieve(id) Verification GET /v1/verifications/{id}
status(id) VerificationStatusSummary GET /v1/verifications/{id}/status
list(params?) List<Verification> GET /v1/verifications
listAutoPaging(params?) AsyncGenerator<Verification> same, every page
revoke(id, { reason? }) Verification POST /v1/verifications/{id}/revoke
deletePersonalData(id) PersonalDataDeletion DELETE /v1/verifications/{id}/personal-data

Verification fields: verification_id, object, session_id, status, assurance_level, method, verification_policy, policy_version, livemode, simulated, external_user_id, reasons ({ code, message: { fr, en } }[]), dimensions, decision_engine, created_at, verified_at, expires_at, revoked_at, personal_data_deleted_at. It never contains a name, a document number, an image or any extracted field.

Verification statuses: verified, manual_review, inconclusive, rejected, revoked. Assurance levels: document_check, document_face_liveness_check, document_manual_review, document_face_manual_review, and sandbox_simulated for sandbox results (simulated: true).

VerificationStatusSummary: { verification_id, status, valid, assurance_level, expires_at }; valid is true only for a verified, non-expired verification.

revoke only applies to a verified verification (ConflictError not_revocable otherwise) and is idempotent on a revoked one.

# isUserVerified(externalUserId)

Lists the user's verified verifications (newest first) and returns the first one that has not expired, or null. Throws like any other call when the service is unreachable: treat that as "not verified".

# webhooks

Method Returns Endpoint
create({ url, events?, description? }) CreatedWebhookEndpoint (with secret, once) POST /v1/webhooks
list() List<WebhookEndpoint> GET /v1/webhooks
delete(id) { id, deleted: true } DELETE /v1/webhooks/{id}
rotateSecret(id) { id, secret } POST /v1/webhooks/{id}/rotate-secret
constructEvent(rawBody, signatureHeader, secret, toleranceSec = 300) Promise<WebhookEvent> local
verifySignature(rawBody, signatureHeader, secret, toleranceSec = 300) Promise<void> local

constructEvent, verifySignature, signPayload, parseSignatureHeader and timingSafeEqual are also exported as standalone functions (no client or key needed).

# Verifying webhooks

Each delivery carries:

Header
MLID-Signature t=<unix seconds>,v1=<hex>[,v1=<hex>]
MLID-Event-Id evt_…, stable across retries: deduplicate on it
MLID-Delivery-Id whd_…, one per endpoint and event
MLID-Event-Type same as event.type

Each v1 is HMAC-SHA256(secret, "<t>." + raw body), hex encoded. After rotateSecret, deliveries carry two v1 values (new and previous secret) for 24 hours: verification succeeds with either.

ts
const event = await identity.webhooks.constructEvent(rawBody, req.headers["mlid-signature"], process.env.MLID_WEBHOOK_SECRET!);
  • rawBody must be the exact bytes received: string, Buffer / Uint8Array or ArrayBuffer. A parsed object is refused (payload_not_raw).
  • The comparison is constant-time. HMAC uses WebCrypto when available, otherwise node:crypto.
  • The timestamp must be within toleranceSec of the current time, in both directions.
  • Failure throws SignatureVerificationError with code among signature_header_invalid, signature_mismatch, signature_expired, payload_not_raw, payload_invalid, secret_missing.

Event object:

ts
{ id: "evt_…", object: "event", type: "verification.verified", api_version: "2026-12-01",
  created: 1796140800, livemode: false, data: { object: Verification | VerificationSession } }
Type data.object
verification.created, verification.processing, verification.expired, verification.cancelled VerificationSession
verification.completed, verification.verified, verification.inconclusive, verification.manual_review, verification.rejected, verification.revoked Verification

isDecisionEvent(event) narrows to the second group, isSessionEvent(event) to the first; both look at the object, so they are safe on an event type this SDK version does not know (constructEvent returns it as is). sessionEndedWithoutDecision(event) is true for verification.cancelled and verification.expired. verification.completed is sent together with the specific outcome event for every final decision (not for manual_review). verification.cancelled is sent when your server cancels a session and when the person withdraws consent, including during a manual review; in that last case no decision event follows and the session object carries the verification_id of the review that will never conclude. Deliveries are at-least-once and unordered, and are retried with a growing delay when your endpoint does not answer 2xx.

# Idempotency

Every POST sends an Idempotency-Key (sdk-<uuid>), identical across the automatic retries of that call. Override it with { idempotencyKey } to cover your own retries. The service honours it on session creation, session cancellation, verification revocation, webhook creation and secret rotation: a repeated key with the same body returns the original response (HTTP header Idempotent-Replayed: true; the SDK returns the body, it does not expose the header), 409 idempotency_key_reused when the body differs, and 409 idempotency_in_progress while the first request is still running.

# Retries

Only network errors, HTTP 429 and HTTP 5xx are retried, up to maxRetries times. Delay before retry n (0-based): a random value in [50 %, 100 %] of min(8 s, 0.5 s × 2ⁿ). When the response carries Retry-After (429 rate_limited, 503 service_unavailable), that delay is used instead, capped at 60 s. Quotas (429 daily_session_limit) are not retried. No other 4xx is ever retried. backoffDelayMs(attempt) and shouldRetry(status, code) are exported. webhooks.create and webhooks.rotateSecret are retried like every other POST, with the same key: a retry returns the endpoint (and its secret) or the rotated secret of the first attempt, it never creates or rotates twice. Two separate calls use two keys: calling rotateSecret again rotates again. Rate limits are shared by every process of the service: several of your servers using the same key share one budget.

# Errors

MacLustrIdentityError fields: message, status (undefined without a response), type, code, param, requestId, headers.

Class HTTP Typical code
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)
AuthenticationError 401 missing_api_key, invalid_api_key
PermissionError 403 insufficient_scope, application_suspended, compliance_gate_closed, forbidden_network
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)
ConflictError 409 session_not_cancellable, not_revocable, idempotency_key_reused, idempotency_in_progress
RateLimitError 429 rate_limited, daily_session_limit; has retryAfter
ApiServerError 5xx internal_error, service_unavailable (503); has retryAfter
ConnectionError none connection_failed, request_timeout, request_aborted
SignatureVerificationError none see above

Configuration mistakes throw MacLustrIdentityError with type: "configuration_error" (api_key_missing, api_key_malformed, secret_key_in_browser, fetch_missing).

# Browser reference

# openVerification(options): VerificationHandle

Option Type Default
url string required session URL from your server; https (http for localhost only)
mode "modal" | "popup" | "redirect" "modal"
container HTMLElement document.body modal mode
title string "Identity verification" dialog name and iframe title
closeLabel string "Close"
autoClose boolean true close after completed / cancelled
onReady ({ sessionId }) => void the hosted page is loaded
onComplete ({ sessionId, status }) => void the person finished; status is a hint
onCancel ({ sessionId, reason }) => void reason: "page" or "dismissed"
onError ({ sessionId, code, message }) => void page error, or popup_channel_lost

Handle: { mode, sessionId, closed, close() }. close() removes the dialog or closes the popup, removes every listener and fires no callback.

Message contract with the hosted page: it posts { source: "maclustr-identity", type: "ready" | "completed" | "cancelled" | "error", session_id, status } to its parent or opener. A message is accepted only when all of these hold: event.origin equals the origin of url; data.source === "maclustr-identity"; the type is known; session_id, when present, matches the session in url; and the sending window is the iframe or popup that was opened. acceptMessage() is exported for custom integrations.

Modal. Injects a full-screen role="dialog" aria-modal="true" element labelled by its title, with a close button and an <iframe allow="camera" referrerpolicy="no-referrer">. Focus moves to the close button, is kept inside the dialog (sentinels at both ends), and returns to the previously focused element on close. Sibling elements of document.body are made inert and aria-hidden while it is open, and page scrolling is locked. Escape and the close button call onCancel({ reason: "dismissed" }). Requirements: the origin of your page must be listed in the application's allowed_origins, and your own Content-Security-Policy must allow frame-src for the identity origin. Escape pressed while focus is inside the cross-origin frame is not visible to your page.

Popup. Opens a 480 × 760 window. If the browser blocks it, the SDK navigates the current tab instead and the handle reports mode: "redirect". If the window goes away after ready, onCancel({ reason: "dismissed" }) fires; if it goes away before any message, onError({ code: "popup_channel_lost" }) fires. See the known limitation below.

Redirect. window.location.assign(url). Create the session with return_url; when the person comes back, look the result up on your server.

Whatever the mode, the result given to onComplete is for display. Unlock features from your server's record.

# checkCameraSupport(): Promise<CameraSupport>

{ supported, secureContext, hasMediaDevices, hasCamera, permission, reason? } with permission in granted | denied | prompt | unknown and reason in not_a_browser | insecure_context | no_media_devices | no_camera | permission_denied. It never prompts and never opens the camera. In modal mode the permission that finally matters is the one of the identity origin inside the frame; this helper describes the embedding page and the device.

# Other exports

parseVerificationUrl(url) → { href, origin, sessionId } (throws on an invalid URL); assertNoSecretKey(value).

# React reference

tsx
import { VerifyButton, useVerification } from "@maclustr/identity/react";

useVerification(options) → { state, result, error, open, close }, with state in idle | creating | open | completed | cancelled | error. Options: createSession (required; calls your backend and resolves to the URL or to { url }), plus mode, container, title, closeLabel, autoClose, onReady, onComplete, onCancel, onError. The dialog is closed when the component unmounts. A failing createSession gives state: "error" with error.code === "session_creation_failed".

<VerifyButton> takes the same options plus any <button> attribute, children and busyLabel. While the flow is open it sets aria-disabled rather than disabled, so focus can return to it; data-state mirrors the hook state.

Next.js App Router example (session route, webhook route reading the raw body, client component): sdk/typescript/examples/nextjs. It is reference code and is not built or executed by the test suite.

# Testing helper

ts
import { completeSandboxSession } from "@maclustr/identity/testing";
await completeSandboxSession({ url: session.url, scenario: "verified" });

Options: url (or sessionId + clientSecret + baseUrl), scenario (verified | manual_review | inconclusive | rejected, default verified), method (default: the first method of the policy), fetch. It calls GET /v1/sessions/{id}, POST …/consent and POST …/sandbox with the session client secret. It throws on a live session.

# Tests

bash
cd sdk/typescript
npm test                  # 84 unit tests: signature, retry policy, idempotency, error mapping, browser (jsdom), React
npm run test:integration  # 13 tests against the local backend (MLID_BASE_URL, default http://localhost:8870) with its dispatcher

# Known limitations

  • Popup mode. The service used to send Cross-Origin-Opener-Policy: same-origin on every response, which detached a cross-origin popup from its opener (popup_channel_lost). It now sends unsafe-none on /verify/…. Popup mode has not been run again in a browser since that change: treat it as unverified and prefer the modal or the redirect, which are covered by integrations/browser-check.mjs.
  • webhooks.list() is not paginated by the service (at most 16 endpoints per application and mode).
  • webhooks.delete and verifications.deletePersonalData are DELETE calls: the service does not deduplicate them. A retried webhooks.delete whose first answer was lost throws NotFoundError: the endpoint is gone, which is what was asked.
  • The Idempotent-Replayed response header is not exposed by the SDK.
  • A 413 payload_too_large is answered before the body is read and the connection is closed: some HTTP stacks report it as a connection error (ConnectionError) instead of the 413 when the body is still being sent.
Files main
Menu

Theme