SPB Git

Repository Public

testing.ts 6.1 KB 131 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Identity8 * File             : sdk/typescript/src/testing.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 * @maclustr/identity/testing — helpers for automated tests of YOUR integration.44 *45 * `completeSandboxSession` plays the person's part of a SANDBOX session through the session-flow endpoints,46 * using only the session client secret (`vsc_…`): no image, no document, no secret key.47 * It is refused by the service for live sessions.48 */49import { errorFromResponse, MacLustrIdentityError } from "./errors";50import type { VerificationMethod, VerificationReason, VerificationSessionStatus } from "./types";5152export type SandboxScenario = "verified" | "manual_review" | "inconclusive" | "rejected";5354export interface CompleteSandboxSessionOptions {55  /** Hosted URL returned at creation (`…/verify/{id}#{client_secret}`). Alternative to sessionId + clientSecret + baseUrl. */56  url?: string;57  sessionId?: string;58  clientSecret?: string;59  /** Origin of the identity service; taken from `url` when given. */60  baseUrl?: string;61  /** Default `verified`. */62  scenario?: SandboxScenario;63  /** Method to consent to; default: the first one offered by the session's policy. */64  method?: VerificationMethod;65  fetch?: typeof fetch;66}6768export interface SandboxFlowState {69  id: string;70  status: VerificationSessionStatus;71  livemode: boolean;72  method: VerificationMethod | null;73  result?: { status: string; reasons: unknown[]; verified_at: string | null };74  /** Why the last attempt has to be redone (empty when there is nothing to report). */75  last_issue?: VerificationReason[];76  attempts_left?: number;77  max_attempts?: number;78  /** Which sides of the document are expected and which document types are accepted. */79  document?: { front?: string; back?: string; back_required_for?: string[]; accepted?: string[]; [key: string]: unknown };80  [key: string]: unknown;81}8283export async function completeSandboxSession(options: CompleteSandboxSessionOptions): Promise<SandboxFlowState> {84  let { sessionId, clientSecret, baseUrl } = options;85  if (options.url) {86    const u = new URL(options.url);87    const m = /\/verify\/([^/?#]+)/.exec(u.pathname);88    sessionId = sessionId ?? (m ? decodeURIComponent(m[1] as string) : undefined);89    clientSecret = clientSecret ?? (u.hash ? u.hash.slice(1) : undefined);90    baseUrl = baseUrl ?? u.origin;91  }92  if (!sessionId || !clientSecret || !baseUrl) {93    throw new MacLustrIdentityError("Provide `url`, or `sessionId`, `clientSecret` and `baseUrl`.", { type: "invalid_request_error", code: "sandbox_arguments_missing" });94  }95  const f = options.fetch ?? fetch;96  const base = `${baseUrl.replace(/\/+$/, "")}/v1/sessions/${encodeURIComponent(sessionId)}`;97  const call = async <T>(method: "GET" | "POST", path: string, body?: unknown): Promise<T> => {98    const res = await f(base + path, {99      method,100      headers: { Authorization: `Bearer ${clientSecret}`, Accept: "application/json", ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },101      body: body !== undefined ? JSON.stringify(body) : undefined,102    });103    const text = await res.text();104    let parsed: unknown;105    try {106      parsed = text ? JSON.parse(text) : undefined;107    } catch {108      parsed = undefined;109    }110    if (!res.ok) {111      const headers: Record<string, string> = {};112      res.headers.forEach((v, k) => (headers[k.toLowerCase()] = v));113      throw errorFromResponse(res.status, parsed, headers);114    }115    return parsed as T;116  };117  type Flow = SandboxFlowState & { methods: Array<{ id: VerificationMethod; biometric: boolean; consent: Record<string, { version: string }> }> };118  const state = await call<Flow>("GET", "");119  if (state.livemode) {120    throw new MacLustrIdentityError("completeSandboxSession only works on sandbox sessions (created with an mlid_sk_test_ key).", { type: "invalid_request_error", code: "sandbox_only" });121  }122  const method = state.methods.find((m) => m.id === options.method) ?? (options.method ? undefined : state.methods[0]);123  if (!method) {124    throw new MacLustrIdentityError(`Method ${options.method ?? "(none)"} is not offered by this session.`, { type: "invalid_request_error", code: "method_not_available", param: "method" });125  }126  // The consent text version is always the one the service just sent: it changes whenever the text does.127  const version = Object.values(method.consent ?? {})[0]?.version;128  await call("POST", "/consent", { method: method.id, accepted: true, biometric_consent: method.biometric ? true : undefined, text_version: version });129  return call<SandboxFlowState>("POST", "/sandbox", { scenario: options.scenario ?? "verified" });130}131
Files main
Menu

Theme