SPB Git

Repository Public

README.md 11.3 KB

# @maclustr/identity

TypeScript SDK for MacLustr Identity, the self-hosted identity-verification platform. Zero runtime dependencies. ESM, CommonJS and type declarations. Node 18+ and modern browsers.

Entry Where it runs What it is
@maclustr/identity (alias @maclustr/identity/server) your server only API client, webhook verification, typed errors
@maclustr/identity/browser browser opens the hosted verification page (modal, popup or redirect)
@maclustr/identity/react browser useVerification() and <VerifyButton>
@maclustr/identity/testing tests plays the person's part of a sandbox session

Secret keys never leave your server. mlid_sk_test_… and mlid_sk_live_… give full access to your application's verifications. Never ship them in a web page, a mobile app, a desktop app or a public repository. The server client throws at construction when it detects a browser context, and the browser entry rejects any option that looks like a secret key. The browser only ever receives the session url.

# Install

Nothing is published to npm yet. Install from the repository path:

bash
cd sdk/typescript && npm install && npm run build
# in your application
npm install /absolute/path/to/maclustr-identity/sdk/typescript

# Server quickstart

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

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

// 1. Gate the sensitive action on your server.
const verified = await identity.isUserVerified(user.id); // newest valid verification, or null
if (!verified) {
  // 2. Create a session and send only its URL to the browser.
  const session = await identity.verificationSessions.create({
    purpose: "Publish listings",
    external_user_id: user.id, // opaque id, never an e-mail or a name
  });
  return { url: session.url };
}

isUserVerified throws ConnectionError when the service cannot be reached: catch it and keep the action refused (fail closed).

# Client options

ts
new MacLustrIdentity({
  apiKey,                                   // required, mlid_sk_test_… or mlid_sk_live_…
  baseUrl: "https://identity.spboucher.ai", // default
  timeoutMs: 30000,                         // per attempt
  maxRetries: 2,                            // after the first attempt
  fetch,                                    // optional custom fetch
});

Every method takes a last optional argument { idempotencyKey, timeoutMs, maxRetries, signal }.

# Resources

Call HTTP
verificationSessions.create(params) POST /v1/verification-sessions
verificationSessions.retrieve(id) GET /v1/verification-sessions/{id}
verificationSessions.list(params) / .listAutoPaging(params) GET /v1/verification-sessions
verificationSessions.cancel(id) POST /v1/verification-sessions/{id}/cancel
verifications.retrieve(id) GET /v1/verifications/{id}
verifications.status(id) GET /v1/verifications/{id}/status
verifications.list(params) / .listAutoPaging(params) GET /v1/verifications
verifications.revoke(id, { reason }) POST /v1/verifications/{id}/revoke
verifications.deletePersonalData(id) DELETE /v1/verifications/{id}/personal-data
webhooks.create({ url, events, description }) POST /v1/webhooks
webhooks.list() GET /v1/webhooks
webhooks.delete(id) DELETE /v1/webhooks/{id}
webhooks.rotateSecret(id) POST /v1/webhooks/{id}/rotate-secret
webhooks.constructEvent(rawBody, header, secret, toleranceSec?) local
isUserVerified(externalUserId) GET /v1/verifications?external_user_id=…&status=verified

Objects use the wire field names (external_user_id, verification_id, expires_at…). client_secret and url are returned by create only; a webhook secret by webhooks.create and rotateSecret only.

ts
for await (const v of identity.verifications.listAutoPaging({ status: "verified" })) {
  console.log(v.verification_id, v.assurance_level);
}

# Idempotency and retries

  • Every POST carries an Idempotency-Key generated by the SDK; the same key is reused when that call is retried. Pass { idempotencyKey: "order-42" } to make your own retries safe as well. The service deduplicates every keyed POST: session creation and cancellation, revocation, webhook creation and secret rotation. A replay returns the first response (HTTP header Idempotent-Replayed: true); the same key with another body is a 409 idempotency_key_reused.
  • Retries happen only on network errors, HTTP 429 and HTTP 5xx, with exponential backoff and jitter (0.5 s, 1 s, 2 s… capped at 8 s, each multiplied by a random factor in [0.5, 1]). Retry-After is honoured on 429 rate_limited and 503 service_unavailable (capped at 60 s). Quotas (daily_session_limit) are not retried. 4xx errors are never retried. webhooks.create and webhooks.rotateSecret are retried like any other POST, with the same key: a retry returns the endpoint or the secret of the first attempt.

# Errors

All errors extend MacLustrIdentityError and expose status, type, code, param, requestId.

Class When
InvalidRequestError 400, 411, 413, 422 (invalid_cursor, payload_too_large, length_required…)
AuthenticationError 401
PermissionError 403 (missing scope, suspended application, closed compliance gate)
NotFoundError 404 (also for objects of another application or mode)
ConflictError 409 (state conflict, idempotency key reused with another body)
RateLimitError 429 (retryAfter in seconds)
ApiServerError 5xx (retryAfter in seconds on 503 service_unavailable)
ConnectionError no response (code: connection_failed, request_timeout, request_aborted)
SignatureVerificationError webhook signature missing, malformed, expired or not matching

# Webhooks

Deliveries are signed: MLID-Signature: t=<unix>,v1=<hex>[,v1=<hex>], each v1 being HMAC-SHA256(secret, "<t>." + raw body). During a secret rotation two v1 values are sent for 24 hours. Other headers: MLID-Event-Id, MLID-Delivery-Id, MLID-Event-Type.

ts
import { createServer } from "node:http";
import { MacLustrIdentity, isDecisionEvent, SignatureVerificationError } from "@maclustr/identity";

const identity = new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY! });
const seen = new Set<string>(); // use a unique column in your database

createServer(async (req, res) => {
  const chunks: Buffer[] = [];
  for await (const c of req) chunks.push(c as Buffer);
  const raw = Buffer.concat(chunks); // the raw bytes: do not parse and re-serialize
  try {
    const event = await identity.webhooks.constructEvent(raw, req.headers["mlid-signature"] as string, process.env.MLID_WEBHOOK_SECRET!);
    if (!seen.has(event.id)) {
      seen.add(event.id);
      if (isDecisionEvent(event)) {
        const v = event.data.object; // Verification
        // store v.verification_id, v.status, v.assurance_level, v.expires_at for v.external_user_id
      }
    }
    res.writeHead(200).end();
  } catch (e) {
    res.writeHead(e instanceof SignatureVerificationError ? 400 : 500).end();
  }
}).listen(3000);

constructEvent is asynchronous (WebCrypto; node:crypto fallback on Node 18 without the global), compares in constant time, and rejects timestamps more than toleranceSec (default 300) away from now.

Event types: verification.created, .processing, .expired, .cancelled (payload: a verification session, isSessionEvent) and .completed, .verified, .inconclusive, .manual_review, .rejected, .revoked (payload: a verification, isDecisionEvent). After .cancelled, .expired or an inconclusive result (for example reason review_not_completed: the manual review was not handled before its deadline) the person may simply start a new session. Deliveries are at-least-once and unordered: deduplicate on event.id. Statuses, reason codes and event types are open unions: keep a default branch, a later service version may add values.

# Browser

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

const { url } = await fetch("/api/identity/session", { method: "POST" }).then((r) => r.json());
const handle = openVerification({
  url,
  mode: "modal", // "modal" (default) | "popup" | "redirect"
  onReady: () => {},
  onComplete: ({ sessionId, status }) => refreshFromServer(),
  onCancel: ({ reason }) => {}, // "page" | "dismissed"
  onError: ({ code, message }) => {},
});
handle.close(); // programmatic close, fires no callback
  • modal: full-screen role="dialog" with an <iframe allow="camera">, focus trap, Escape and a close button, page content made inert, focus restored on close. The origin of your page must be in the application's allowed_origins, otherwise the browser refuses to frame the page.
  • popup: opens a window; when the popup is blocked the SDK falls back to redirect (handle.mode tells). If the window disappears before any message was received, onError fires with popup_channel_lost.
  • redirect: navigates the tab. Create the session with a return_url and check the status on your server when the person comes back.
  • Messages are accepted only when event.origin equals the origin of url, data.source === "maclustr-identity", the type is known and the session id matches.
  • The status passed to onComplete is a display hint. Unlock features from your server's own record only.
  • Escape pressed while focus is inside the cross-origin iframe is not visible to the embedding page; the close button always works.

checkCameraSupport() resolves to { supported, secureContext, hasMediaDevices, hasCamera, permission, reason? } without prompting for permission.

# React

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

<VerifyButton createSession={() => fetch("/api/identity/session", { method: "POST" }).then((r) => r.json())} onComplete={() => router.refresh()}>
  Verify my identity
</VerifyButton>;

const { state, open, close, result, error } = useVerification({ createSession, mode: "modal" });
// state: "idle" | "creating" | "open" | "completed" | "cancelled" | "error"

A Next.js App Router example (session route, webhook route on the raw body, client component) is in examples/nextjs.

# Testing your integration

ts
import { completeSandboxSession } from "@maclustr/identity/testing";

const session = await identity.verificationSessions.create({ purpose: "Test", external_user_id: "u1" });
await completeSandboxSession({ url: session.url, scenario: "verified" }); // or manual_review | inconclusive | rejected

It records consent and applies a sandbox scenario using the session client secret only. Sandbox results are flagged simulated: true with assurance_level: "sandbox_simulated". Live sessions refuse it.

# Development

bash
npm install
npm run typecheck
npm run build             # dist/ (ESM + CJS + .d.ts)
npm test                  # unit tests
npm run test:integration  # needs the local backend on http://localhost:8870 and its dispatcher

Integration tests provision two sandbox applications through the backend CLI (.venv of the repository, database maclustr_identity_sdk), or use MLID_SECRET_KEY / MLID_SECRET_KEY_B when set. They refuse to run against anything but localhost.

Files main
Menu

Theme