SPB Git

Repository Public

client.ts 19.3 KB 426 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : sdk/typescript/src/client.ts9 * Module           : sdk10 * Repository       : https://git.spboucher.ai/maclustr-identity11 * Project Website  : https://identity.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * Server-side client. It holds a secret API key (`mlid_sk_test_…` or `mlid_sk_live_…`):44 * never construct it in a browser, a mobile app or any code shipped to end users.45 */46import { ConnectionError, MacLustrIdentityError, errorFromResponse, parseRetryAfter } from "./errors";47import { constructEvent, verifySignature, DEFAULT_TOLERANCE_SEC, type RawBody } from "./signature";48import type {49  CreatedVerificationSession,50  CreatedWebhookEndpoint,51  DeletedWebhookEndpoint,52  List,53  PersonalDataDeletion,54  RotatedWebhookSecret,55  Verification,56  VerificationListParams,57  VerificationRevokeParams,58  VerificationSession,59  VerificationSessionCreateParams,60  VerificationSessionListParams,61  VerificationStatusSummary,62  WebhookEndpoint,63  WebhookEndpointCreateParams,64  WebhookEvent,65} from "./types";6667export const DEFAULT_BASE_URL = "https://identity.spboucher.ai";68export const SDK_VERSION = "0.1.0";6970export interface MacLustrIdentityOptions {71  /** Secret API key. Server-side only. */72  apiKey: string;73  /** Origin of the identity service. Default: https://identity.spboucher.ai */74  baseUrl?: string;75  /** Per-attempt timeout in milliseconds. Default 30000. */76  timeoutMs?: number;77  /** Retries after the first attempt, on network errors, 429 and 5xx only. Default 2. */78  maxRetries?: number;79  /** Custom fetch implementation (tests, proxies). Defaults to the global `fetch`. */80  fetch?: typeof fetch;81}8283export interface RequestOptions {84  /** Overrides the automatically generated `Idempotency-Key` of a POST request. */85  idempotencyKey?: string;86  /** Overrides the client's timeout for this call. */87  timeoutMs?: number;88  /** Overrides the client's retry budget for this call. */89  maxRetries?: number;90  /** Aborts the call (including the waits between retries). */91  signal?: AbortSignal;92}9394type Query = Record<string, string | number | boolean | undefined | null>;9596interface InternalRequest {97  method: "GET" | "POST" | "DELETE";98  path: string;99  query?: Query;100  body?: unknown;101  options?: RequestOptions;102}103104const INITIAL_BACKOFF_MS = 500;105const MAX_BACKOFF_MS = 8000;106const MAX_RETRY_AFTER_MS = 60000;107108/** True in a web page or a web worker, where a secret key would be exposed to the end user. */109export function isBrowserContext(): boolean {110  const g = globalThis as { window?: { document?: unknown }; document?: unknown; importScripts?: unknown; WorkerGlobalScope?: unknown };111  if (typeof g.window !== "undefined" && typeof g.window.document !== "undefined") return true;112  return typeof g.importScripts === "function" && typeof g.WorkerGlobalScope !== "undefined" && typeof (globalThis as { process?: unknown }).process === "undefined";113}114115function randomIdempotencyKey(): string {116  const c = (globalThis as { crypto?: Crypto }).crypto;117  if (c && typeof c.randomUUID === "function") return `sdk-${c.randomUUID()}`;118  let out = "sdk-";119  for (let i = 0; i < 32; i++) out += Math.floor(Math.random() * 16).toString(16);120  return out;121}122123function sleep(ms: number, signal?: AbortSignal): Promise<void> {124  return new Promise((resolve, reject) => {125    if (signal?.aborted) return reject(signal.reason ?? new Error("aborted"));126    const timer = setTimeout(() => {127      signal?.removeEventListener("abort", onAbort);128      resolve();129    }, ms);130    const onAbort = () => {131      clearTimeout(timer);132      reject(signal?.reason ?? new Error("aborted"));133    };134    signal?.addEventListener("abort", onAbort, { once: true });135  });136}137138/** Exponential backoff with jitter: a random delay in [50 %, 100 %] of min(8 s, 0.5 s * 2^attempt). */139export function backoffDelayMs(attempt: number, random: () => number = Math.random): number {140  const ceiling = Math.min(MAX_BACKOFF_MS, INITIAL_BACKOFF_MS * 2 ** attempt);141  return Math.round(ceiling * (0.5 + random() * 0.5));142}143144/** 429 codes that are quotas, not a per-minute rate: they will not clear within a retry window. */145const QUOTA_CODES = new Set(["daily_session_limit", "too_many_uploads", "too_many_challenges"]);146147/** Retry policy: network errors (no status), 429 (rate limit, not quotas) and 5xx. Nothing else is ever retried. */148export function shouldRetry(status: number | undefined, code?: string): boolean {149  if (status === undefined) return true;150  if (status === 429) return !QUOTA_CODES.has(code ?? "");151  return status >= 500 && status <= 599;152}153154export class MacLustrIdentity {155  readonly baseUrl: string;156  readonly verificationSessions: VerificationSessions;157  readonly verifications: Verifications;158  readonly webhooks: Webhooks;159160  readonly #apiKey: string;161  readonly #timeoutMs: number;162  readonly #maxRetries: number;163  readonly #fetch: typeof fetch;164  /** Test hooks: replaced in unit tests to avoid real waits. */165  _sleep: (ms: number, signal?: AbortSignal) => Promise<void> = sleep;166  _random: () => number = Math.random;167168  constructor(options: MacLustrIdentityOptions) {169    if (!options || typeof options.apiKey !== "string" || !options.apiKey) {170      throw new MacLustrIdentityError("apiKey is required: new MacLustrIdentity({ apiKey: process.env.MLID_SECRET_KEY }).", {171        type: "configuration_error",172        code: "api_key_missing",173      });174    }175    if (isBrowserContext()) {176      throw new MacLustrIdentityError(177        "MacLustrIdentity was constructed in a browser context. Secret keys (mlid_sk_…) must never be shipped to browsers or apps: " +178          "create the verification session on your server and give the browser only the session `url`. " +179          "Use `@maclustr/identity/browser` on the client side.",180        { type: "configuration_error", code: "secret_key_in_browser" },181      );182    }183    if (!/^mlid_sk_(test|live)_/.test(options.apiKey)) {184      throw new MacLustrIdentityError("apiKey must be a secret key starting with mlid_sk_test_ or mlid_sk_live_.", {185        type: "configuration_error",186        code: "api_key_malformed",187      });188    }189    const f = options.fetch ?? (globalThis as { fetch?: typeof fetch }).fetch;190    if (typeof f !== "function") {191      throw new MacLustrIdentityError("No fetch implementation is available: use Node >= 18 or pass options.fetch.", {192        type: "configuration_error",193        code: "fetch_missing",194      });195    }196    this.#apiKey = options.apiKey;197    this.#fetch = options.fetch ?? f.bind(globalThis);198    this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");199    this.#timeoutMs = options.timeoutMs ?? 30000;200    this.#maxRetries = Math.max(0, options.maxRetries ?? 2);201    this.verificationSessions = new VerificationSessions(this);202    this.verifications = new Verifications(this);203    this.webhooks = new Webhooks(this);204  }205206  /** The key is kept in a private field: it does not appear in JSON, enumeration or console inspection. */207  toJSON(): { baseUrl: string; livemode: boolean } {208    return { baseUrl: this.baseUrl, livemode: this.livemode };209  }210211  /** True when the key is a live key (`mlid_sk_live_…`). */212  get livemode(): boolean {213    return this.#apiKey.startsWith("mlid_sk_live_");214  }215216  /**217   * Returns the newest valid `verified` verification of one of your users, or `null`.218   * "Valid" means status `verified` and not expired. A revoked, expired, rejected or pending verification never counts.219   * This call throws when the identity service cannot be reached: treat that as "not verified" (fail closed).220   */221  async isUserVerified(externalUserId: string, options?: RequestOptions): Promise<Verification | null> {222    if (typeof externalUserId !== "string" || !externalUserId) {223      throw new MacLustrIdentityError("externalUserId is required.", { type: "invalid_request_error", code: "external_user_id_required", param: "external_user_id" });224    }225    const now = Date.now();226    // Verifications are listed newest first.227    for await (const v of this.verifications.listAutoPaging({ external_user_id: externalUserId, status: "verified", limit: 100 }, options)) {228      if (v.status === "verified" && (v.expires_at === null || Date.parse(v.expires_at) > now)) return v;229    }230    return null;231  }232233  /** Low-level request. Prefer the resource methods. */234  async request<T>(req: InternalRequest): Promise<T> {235    const url = new URL(`${this.baseUrl}/v1${req.path}`);236    for (const [k, v] of Object.entries(req.query ?? {})) {237      if (v !== undefined && v !== null) url.searchParams.set(k, String(v));238    }239    const headers: Record<string, string> = {240      Authorization: `Bearer ${this.#apiKey}`,241      Accept: "application/json",242      "User-Agent": `maclustr-identity-node/${SDK_VERSION}`,243    };244    let body: string | undefined;245    if (req.method === "POST") {246      // The same key is sent on every retry of this call. The service deduplicates every keyed POST (session creation and247      // cancellation, revocation, webhook creation, secret rotation): a retried call never acts twice.248      headers["Idempotency-Key"] = req.options?.idempotencyKey ?? randomIdempotencyKey();249      headers["Content-Type"] = "application/json";250      body = JSON.stringify(req.body ?? {});251    }252    const maxRetries = Math.max(0, req.options?.maxRetries ?? this.#maxRetries);253    const timeoutMs = req.options?.timeoutMs ?? this.#timeoutMs;254    const outer = req.options?.signal;255256    for (let attempt = 0; ; attempt++) {257      let error: MacLustrIdentityError;258      let retryAfterMs: number | undefined;259      const controller = new AbortController();260      const timer = setTimeout(() => controller.abort(), timeoutMs);261      const onOuterAbort = () => controller.abort();262      outer?.addEventListener("abort", onOuterAbort, { once: true });263      try {264        if (outer?.aborted) throw outer.reason ?? new Error("aborted");265        const res = await this.#fetch(url.toString(), { method: req.method, headers, body, signal: controller.signal, redirect: "error" });266        const text = await res.text();267        let parsed: unknown = undefined;268        if (text) {269          try {270            parsed = JSON.parse(text);271          } catch {272            parsed = undefined;273          }274        }275        if (res.ok && parsed !== undefined) return parsed as T;276        const resHeaders: Record<string, string> = {};277        res.headers.forEach((value, key) => {278          resHeaders[key.toLowerCase()] = value;279        });280        error = res.ok281          ? new MacLustrIdentityError("The service returned a response that is not JSON.", { status: res.status, code: "invalid_response", requestId: resHeaders["request-id"], headers: resHeaders })282          : errorFromResponse(res.status, parsed, resHeaders);283        if (res.ok || !shouldRetry(res.status, error.code)) throw error;284        const ra = parseRetryAfter(resHeaders["retry-after"]);285        if (ra !== undefined) retryAfterMs = Math.min(MAX_RETRY_AFTER_MS, ra * 1000);286      } catch (cause) {287        if (cause instanceof MacLustrIdentityError && !(shouldRetry(cause.status, cause.code) && cause.code !== "invalid_response")) throw cause;288        if (cause instanceof MacLustrIdentityError) {289          error = cause;290        } else {291          if (outer?.aborted) throw new ConnectionError("The request was aborted by the caller.", { type: "connection_error", code: "request_aborted", cause });292          const timedOut = controller.signal.aborted;293          error = new ConnectionError(294            timedOut ? `The identity service did not answer within ${timeoutMs} ms.` : `Could not reach the identity service at ${this.baseUrl}.`,295            { type: "connection_error", code: timedOut ? "request_timeout" : "connection_failed", cause },296          );297        }298      } finally {299        clearTimeout(timer);300        outer?.removeEventListener("abort", onOuterAbort);301      }302      if (attempt >= maxRetries) throw error;303      const wait = retryAfterMs ?? backoffDelayMs(attempt, this._random);304      try {305        await this._sleep(wait, outer);306      } catch (cause) {307        throw new ConnectionError("The request was aborted by the caller.", { type: "connection_error", code: "request_aborted", cause });308      }309    }310  }311312  /** @internal Async iterator over every page of a cursor-paginated list. */313  async *_paginate<T extends { id?: string; verification_id?: string | null }>(path: string, params: Query, options?: RequestOptions): AsyncGenerator<T, void, undefined> {314    let cursor = params.starting_after as string | undefined;315    for (;;) {316      const page = await this.request<List<T>>({ method: "GET", path, query: { ...params, starting_after: cursor }, options });317      for (const item of page.data) yield item;318      const last = page.data[page.data.length - 1];319      if (!page.has_more || !last) return;320      cursor = (last.id ?? last.verification_id) as string;321    }322  }323}324325const enc = encodeURIComponent;326327export class VerificationSessions {328  constructor(private readonly client: MacLustrIdentity) {}329330  /** Creates a session. The response is the only time `client_secret` and `url` are returned. */331  create(params: VerificationSessionCreateParams, options?: RequestOptions): Promise<CreatedVerificationSession> {332    return this.client.request({ method: "POST", path: "/verification-sessions", body: params, options });333  }334335  retrieve(id: string, options?: RequestOptions): Promise<VerificationSession> {336    return this.client.request({ method: "GET", path: `/verification-sessions/${enc(id)}`, options });337  }338339  /** One page, newest first. */340  list(params: VerificationSessionListParams = {}, options?: RequestOptions): Promise<List<VerificationSession>> {341    return this.client.request({ method: "GET", path: "/verification-sessions", query: { ...params }, options });342  }343344  /** Every matching session, fetching pages as needed: `for await (const s of client.verificationSessions.listAutoPaging())`. */345  listAutoPaging(params: VerificationSessionListParams = {}, options?: RequestOptions): AsyncGenerator<VerificationSession, void, undefined> {346    return this.client._paginate<VerificationSession>("/verification-sessions", { ...params }, options);347  }348349  /** Cancels a session that has no decision yet. Uploaded material is destroyed. Throws `ConflictError` otherwise. */350  cancel(id: string, options?: RequestOptions): Promise<VerificationSession> {351    return this.client.request({ method: "POST", path: `/verification-sessions/${enc(id)}/cancel`, options });352  }353}354355export class Verifications {356  constructor(private readonly client: MacLustrIdentity) {}357358  retrieve(id: string, options?: RequestOptions): Promise<Verification> {359    return this.client.request({ method: "GET", path: `/verifications/${enc(id)}`, options });360  }361362  /** Lightweight status: `{ status, valid, assurance_level, expires_at }`. */363  status(id: string, options?: RequestOptions): Promise<VerificationStatusSummary> {364    return this.client.request({ method: "GET", path: `/verifications/${enc(id)}/status`, options });365  }366367  /** One page, newest first. */368  list(params: VerificationListParams = {}, options?: RequestOptions): Promise<List<Verification>> {369    return this.client.request({ method: "GET", path: "/verifications", query: { ...params }, options });370  }371372  listAutoPaging(params: VerificationListParams = {}, options?: RequestOptions): AsyncGenerator<Verification, void, undefined> {373    return this.client._paginate<Verification>("/verifications", { ...params }, options);374  }375376  /** Revokes a `verified` verification (idempotent on an already revoked one). */377  revoke(id: string, params: VerificationRevokeParams = {}, options?: RequestOptions): Promise<Verification> {378    return this.client.request({ method: "POST", path: `/verifications/${enc(id)}/revoke`, body: params, options });379  }380381  /** Destroys every personal data element kept for this verification (right to erasure). The result record itself remains. */382  deletePersonalData(id: string, options?: RequestOptions): Promise<PersonalDataDeletion> {383    return this.client.request({ method: "DELETE", path: `/verifications/${enc(id)}/personal-data`, options });384  }385}386387export class Webhooks {388  constructor(private readonly client: MacLustrIdentity) {}389390  /**391   * Creates an endpoint. The signing secret (`whsec_…`) is returned once: store it server-side.392   * Retried like any other POST: the service deduplicates on the `Idempotency-Key`, so a retry returns the endpoint393   * (and the secret) of the first attempt instead of creating a second one.394   */395  create(params: WebhookEndpointCreateParams, options?: RequestOptions): Promise<CreatedWebhookEndpoint> {396    return this.client.request({ method: "POST", path: "/webhooks", body: params, options });397  }398399  list(options?: RequestOptions): Promise<List<WebhookEndpoint>> {400    return this.client.request({ method: "GET", path: "/webhooks", options });401  }402403  delete(id: string, options?: RequestOptions): Promise<DeletedWebhookEndpoint> {404    return this.client.request({ method: "DELETE", path: `/webhooks/${enc(id)}`, options });405  }406407  /**408   * Returns a new secret. Deliveries carry both signatures for 24 hours, so you can switch without losing events.409   * Retried like any other POST with the same `Idempotency-Key`: the retry returns the secret of the first attempt,410   * it never rotates twice. To rotate again later, make a new call (or pass a new `idempotencyKey`).411   */412  rotateSecret(id: string, options?: RequestOptions): Promise<RotatedWebhookSecret> {413    return this.client.request({ method: "POST", path: `/webhooks/${enc(id)}/rotate-secret`, options });414  }415416  /** Verifies `MLID-Signature` against the raw body, then returns the parsed event. Throws `SignatureVerificationError`. */417  constructEvent(rawBody: RawBody, signatureHeader: string | null | undefined, secret: string, toleranceSec: number = DEFAULT_TOLERANCE_SEC): Promise<WebhookEvent> {418    return constructEvent(rawBody, signatureHeader, secret, toleranceSec);419  }420421  /** Verifies the signature only. Throws `SignatureVerificationError`. */422  verifySignature(rawBody: RawBody, signatureHeader: string | null | undefined, secret: string, toleranceSec: number = DEFAULT_TOLERANCE_SEC): Promise<void> {423    return verifySignature(rawBody, signatureHeader, secret, toleranceSec);424  }425}426
Files main
Menu

Theme