Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Identity8 * File : sdk/typescript/tests/unit/client.test.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 */4142import { afterEach, describe, expect, it, vi } from "vitest";43import {44 ApiServerError,45 AuthenticationError,46 ConflictError,47 ConnectionError,48 InvalidRequestError,49 MacLustrIdentity,50 MacLustrIdentityError,51 NotFoundError,52 PermissionError,53 RateLimitError,54 backoffDelayMs,55 shouldRetry,56} from "../../src/index";5758type Call = { url: string; method: string; headers: Record<string, string>; body: string | undefined };59type Step = { status: number; body?: unknown; headers?: Record<string, string> } | Error | ((call: Call) => { status: number; body?: unknown; headers?: Record<string, string> });6061function mock(steps: Step[]) {62 const calls: Call[] = [];63 const waits: number[] = [];64 const fetchImpl = (async (url: string, init: RequestInit) => {65 const call: Call = { url, method: init.method as string, headers: init.headers as Record<string, string>, body: init.body as string | undefined };66 calls.push(call);67 let step = steps[Math.min(calls.length - 1, steps.length - 1)] as Step;68 if (step instanceof Error) throw step;69 if (typeof step === "function") step = step(call);70 return new Response(step.body === undefined ? "" : JSON.stringify(step.body), { status: step.status, headers: { "request-id": "req_test", ...(step.headers ?? {}) } });71 }) as unknown as typeof fetch;72 const client = new MacLustrIdentity({ apiKey: "mlid_sk_test_unit", baseUrl: "http://identity.test/", fetch: fetchImpl });73 client._sleep = async (ms) => {74 waits.push(ms);75 };76 return { client, calls, waits };77}7879const err = (status: number, code: string, extra: Record<string, unknown> = {}) => ({ status, body: { error: { type: "x_error", code, message: `m-${code}`, request_id: "req_body", ...extra } } });80const session = { id: "vs_1", object: "verification_session", status: "created" };8182afterEach(() => vi.unstubAllGlobals());8384describe("construction", () => {85 it("requires a well-formed secret key", () => {86 expect(() => new MacLustrIdentity({ apiKey: "" })).toThrow(/apiKey is required/);87 expect(() => new MacLustrIdentity({ apiKey: "vsc_abc" })).toThrow(/mlid_sk_test_ or mlid_sk_live_/);88 expect(new MacLustrIdentity({ apiKey: "mlid_sk_live_x" }).livemode).toBe(true);89 expect(new MacLustrIdentity({ apiKey: "mlid_sk_test_x" }).baseUrl).toBe("https://identity.spboucher.ai");90 });9192 it("throws when constructed in a browser context", () => {93 vi.stubGlobal("window", { document: {} });94 expect(() => new MacLustrIdentity({ apiKey: "mlid_sk_test_x" })).toThrow(/must never be shipped to browsers/);95 try {96 new MacLustrIdentity({ apiKey: "mlid_sk_test_x" });97 } catch (e) {98 expect((e as MacLustrIdentityError).code).toBe("secret_key_in_browser");99 }100 });101102 it("never exposes the key through enumeration or JSON", () => {103 const c = new MacLustrIdentity({ apiKey: "mlid_sk_test_hidden" });104 expect(JSON.stringify(c)).not.toContain("hidden");105 expect(Object.values(c).join(" ")).not.toContain("hidden");106 });107});108109describe("requests", () => {110 it("sends the bearer key, JSON body and path", async () => {111 const { client, calls } = mock([{ status: 200, body: session }]);112 const s = await client.verificationSessions.create({ purpose: "p", external_user_id: "u1" });113 expect(s.id).toBe("vs_1");114 expect(calls[0]!.url).toBe("http://identity.test/v1/verification-sessions");115 expect(calls[0]!.method).toBe("POST");116 expect(calls[0]!.headers.Authorization).toBe("Bearer mlid_sk_test_unit");117 expect(JSON.parse(calls[0]!.body!)).toEqual({ purpose: "p", external_user_id: "u1" });118 });119120 it("encodes query parameters and ids", async () => {121 const { client, calls } = mock([{ status: 200, body: { object: "list", data: [], has_more: false } }]);122 await client.verifications.list({ external_user_id: "a b&c", status: "verified", limit: 5 });123 expect(calls[0]!.url).toBe("http://identity.test/v1/verifications?external_user_id=a+b%26c&status=verified&limit=5");124 await client.verifications.retrieve("ver/../x");125 expect(calls[1]!.url).toBe("http://identity.test/v1/verifications/ver%2F..%2Fx");126 });127});128129describe("idempotency", () => {130 it("adds an Idempotency-Key to every POST and none to GET or DELETE", async () => {131 const { client, calls } = mock([{ status: 200, body: session }]);132 await client.verificationSessions.create({ purpose: "p" });133 await client.verificationSessions.create({ purpose: "p" });134 await client.verificationSessions.retrieve("vs_1");135 await client.verifications.deletePersonalData("ver_1");136 await client.verifications.revoke("ver_1");137 expect(calls[0]!.headers["Idempotency-Key"]).toMatch(/^sdk-[0-9a-f-]{32,36}$/);138 expect(calls[1]!.headers["Idempotency-Key"]).not.toBe(calls[0]!.headers["Idempotency-Key"]);139 expect(calls[2]!.headers["Idempotency-Key"]).toBeUndefined();140 expect(calls[3]!.headers["Idempotency-Key"]).toBeUndefined();141 expect(calls[4]!.headers["Idempotency-Key"]).toBeTruthy();142 });143144 it("lets the caller override the key", async () => {145 const { client, calls } = mock([{ status: 200, body: session }]);146 await client.verificationSessions.create({ purpose: "p" }, { idempotencyKey: "order-42" });147 expect(calls[0]!.headers["Idempotency-Key"]).toBe("order-42");148 });149150 it("reuses the same key across retries of one call", async () => {151 const { client, calls } = mock([err(503, "unavailable"), new TypeError("fetch failed"), { status: 200, body: session }]);152 await client.verificationSessions.create({ purpose: "p" });153 expect(calls).toHaveLength(3);154 expect(new Set(calls.map((c) => c.headers["Idempotency-Key"])).size).toBe(1);155 });156});157158describe("retry policy", () => {159 it("retries 5xx then succeeds, with exponential backoff and jitter", async () => {160 const { client, calls, waits } = mock([err(500, "internal_error"), err(502, "bad_gateway"), { status: 200, body: session }]);161 client._random = () => 1;162 await client.verificationSessions.retrieve("vs_1");163 expect(calls).toHaveLength(3);164 expect(waits).toEqual([500, 1000]);165 });166167 it("applies jitter within [50 %, 100 %] and caps the delay", () => {168 expect(backoffDelayMs(0, () => 0)).toBe(250);169 expect(backoffDelayMs(0, () => 1)).toBe(500);170 expect(backoffDelayMs(3, () => 1)).toBe(4000);171 expect(backoffDelayMs(10, () => 1)).toBe(8000);172 for (let i = 0; i < 50; i++) {173 const d = backoffDelayMs(2);174 expect(d).toBeGreaterThanOrEqual(1000);175 expect(d).toBeLessThanOrEqual(2000);176 }177 });178179 it("retries network errors", async () => {180 const { client, calls } = mock([new TypeError("fetch failed"), { status: 200, body: session }]);181 await client.verificationSessions.retrieve("vs_1");182 expect(calls).toHaveLength(2);183 });184185 it("honours Retry-After on 429", async () => {186 const { client, calls, waits } = mock([{ ...err(429, "rate_limited"), headers: { "retry-after": "7" } }, { status: 200, body: session }]);187 await client.verificationSessions.retrieve("vs_1");188 expect(calls).toHaveLength(2);189 expect(waits).toEqual([7000]);190 });191192 it("gives up after maxRetries and throws the last error", async () => {193 const { client, calls } = mock([err(503, "unavailable")]);194 await expect(client.verificationSessions.retrieve("vs_1")).rejects.toBeInstanceOf(ApiServerError);195 expect(calls).toHaveLength(3); // 1 attempt + 2 retries (default)196 const again = mock([new TypeError("fetch failed")]);197 await expect(again.client.verificationSessions.retrieve("vs_1", { maxRetries: 1 })).rejects.toBeInstanceOf(ConnectionError);198 expect(again.calls).toHaveLength(2);199 });200201 it("surfaces Retry-After on the final RateLimitError", async () => {202 const { client } = mock([{ ...err(429, "rate_limited"), headers: { "retry-after": "3" } }]);203 const e = await client.verificationSessions.retrieve("vs_1", { maxRetries: 0 }).catch((x) => x);204 expect(e).toBeInstanceOf(RateLimitError);205 expect((e as RateLimitError).retryAfter).toBe(3);206 });207208 it.each([400, 401, 403, 404, 409, 413, 422])("never retries %i", async (status) => {209 const { client, calls } = mock([err(status, "nope")]);210 await expect(client.verificationSessions.create({ purpose: "p" })).rejects.toBeInstanceOf(MacLustrIdentityError);211 expect(calls).toHaveLength(1);212 });213214 it("retries webhook creation and secret rotation with the same Idempotency-Key (deduplicated by the service)", async () => {215 const rot = mock([err(503, "service_unavailable"), { status: 200, body: { id: "we_1", secret: "whsec_2" } }]);216 expect((await rot.client.webhooks.rotateSecret("we_1")).secret).toBe("whsec_2");217 expect(rot.calls).toHaveLength(2);218 expect(rot.calls[0]!.headers["Idempotency-Key"]).toMatch(/^sdk-/);219 expect(rot.calls[1]!.headers["Idempotency-Key"]).toBe(rot.calls[0]!.headers["Idempotency-Key"]);220 const create = mock([new TypeError("fetch failed"), { status: 200, body: { id: "we_1", object: "webhook_endpoint", secret: "whsec_1" } }]);221 expect((await create.client.webhooks.create({ url: "https://app.example/hook" })).secret).toBe("whsec_1");222 expect(create.calls).toHaveLength(2);223 expect(create.calls[1]!.headers["Idempotency-Key"]).toBe(create.calls[0]!.headers["Idempotency-Key"]);224 expect(create.calls[1]!.body).toBe(create.calls[0]!.body);225 const optOut = mock([err(503, "service_unavailable")]);226 await expect(optOut.client.webhooks.rotateSecret("we_1", { maxRetries: 0 })).rejects.toBeInstanceOf(ApiServerError);227 expect(optOut.calls).toHaveLength(1);228 });229230 it("two separate rotations use two different keys", async () => {231 const { client, calls } = mock([{ status: 200, body: { id: "we_1", secret: "whsec_2" } }]);232 await client.webhooks.rotateSecret("we_1");233 await client.webhooks.rotateSecret("we_1");234 expect(calls[0]!.headers["Idempotency-Key"]).not.toBe(calls[1]!.headers["Idempotency-Key"]);235 });236237 it("honours Retry-After on 503 service_unavailable and exposes it on the final error", async () => {238 const ok = mock([{ ...err(503, "service_unavailable"), headers: { "retry-after": "5" } }, { status: 200, body: session }]);239 await ok.client.verificationSessions.create({ purpose: "p" });240 expect(ok.waits).toEqual([5000]);241 const ko = mock([{ ...err(503, "service_unavailable"), headers: { "retry-after": "5" } }]);242 const e = await ko.client.verificationSessions.retrieve("vs_1", { maxRetries: 0 }).catch((x) => x);243 expect(e).toBeInstanceOf(ApiServerError);244 expect(e).toMatchObject({ status: 503, code: "service_unavailable", retryAfter: 5 });245 });246247 it("caps an excessive Retry-After at 60 s", async () => {248 const { client, waits } = mock([{ ...err(429, "rate_limited"), headers: { "retry-after": "86400" } }, { status: 200, body: session }]);249 await client.verificationSessions.retrieve("vs_1");250 expect(waits).toEqual([60000]);251 });252253 it.each([254 [413, "payload_too_large"],255 [411, "length_required"],256 [400, "invalid_cursor"],257 ])("maps %i %s to InvalidRequestError without retrying", async (status, code) => {258 const { client, calls } = mock([err(status, code)]);259 const e = await client.verificationSessions.list({ starting_after: "vs_gone" }).catch((x) => x);260 expect(e).toBeInstanceOf(InvalidRequestError);261 expect(e).toMatchObject({ status, code });262 expect(calls).toHaveLength(1);263 });264265 it("maps 403 forbidden_network to PermissionError without retrying", async () => {266 const { client, calls } = mock([err(403, "forbidden_network")]);267 const e = await client.verificationSessions.retrieve("vs_1").catch((x) => x);268 expect(e).toBeInstanceOf(PermissionError);269 expect(e.code).toBe("forbidden_network");270 expect(calls).toHaveLength(1);271 });272273 it("maps a webhook of the other mode to NotFoundError", async () => {274 const { client, calls } = mock([err(404, "resource_missing")]);275 await expect(client.webhooks.rotateSecret("we_live")).rejects.toBeInstanceOf(NotFoundError);276 await expect(client.webhooks.delete("we_live")).rejects.toBeInstanceOf(NotFoundError);277 expect(calls).toHaveLength(2);278 });279280 it("passes unknown fields, statuses and score-less dimensions through untouched", async () => {281 const body = {282 verification_id: "ver_1", object: "verification", status: "some_future_status", reasons: [{ code: "review_not_completed", message: { fr: "a", en: "b" } }, { code: "future_code", message: { fr: "c", en: "d" } }],283 dimensions: { document: { status: "pass" }, face: { status: "review", notes: ["x"] } }, a_new_field: { nested: true },284 };285 const { client } = mock([{ status: 200, body }]);286 const v = await client.verifications.retrieve("ver_1");287 expect(v).toEqual(body);288 expect(v.dimensions.document!.score).toBeUndefined();289 expect(v.reasons[0]!.code).toBe("review_not_completed");290 });291292 it.each(["daily_session_limit", "too_many_uploads", "too_many_challenges"])("does not retry the quota %s", async (code) => {293 const { client, calls } = mock([err(429, code)]);294 await expect(client.verificationSessions.create({ purpose: "p" })).rejects.toBeInstanceOf(RateLimitError);295 expect(calls).toHaveLength(1);296 expect(shouldRetry(429, code)).toBe(false);297 });298299 it("exposes the policy as a pure function", () => {300 expect(shouldRetry(undefined)).toBe(true);301 expect(shouldRetry(429)).toBe(true);302 expect(shouldRetry(500)).toBe(true);303 expect(shouldRetry(599)).toBe(true);304 for (const s of [200, 301, 400, 401, 403, 404, 409, 422]) expect(shouldRetry(s)).toBe(false);305 });306307 it("times out an attempt and reports a ConnectionError", async () => {308 const hanging = ((_url: string, init: RequestInit) =>309 new Promise((_resolve, reject) => {310 init.signal!.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")));311 })) as unknown as typeof fetch;312 const client = new MacLustrIdentity({ apiKey: "mlid_sk_test_unit", baseUrl: "http://identity.test", fetch: hanging, timeoutMs: 20, maxRetries: 0 });313 const e = await client.verificationSessions.retrieve("vs_1").catch((x) => x);314 expect(e).toBeInstanceOf(ConnectionError);315 expect((e as ConnectionError).code).toBe("request_timeout");316 expect((e as ConnectionError).status).toBeUndefined();317 });318});319320describe("error mapping", () => {321 it.each([322 [400, InvalidRequestError],323 [401, AuthenticationError],324 [403, PermissionError],325 [404, NotFoundError],326 [409, ConflictError],327 [413, InvalidRequestError],328 [429, RateLimitError],329 [500, ApiServerError],330 ] as const)("maps %i", async (status, cls) => {331 const { client } = mock([err(status, "some_code", { param: "purpose" })]);332 const e = (await client.verificationSessions.create({ purpose: "p" }, { maxRetries: 0 }).catch((x) => x)) as MacLustrIdentityError;333 expect(e).toBeInstanceOf(cls);334 expect(e).toBeInstanceOf(MacLustrIdentityError);335 expect(e).toBeInstanceOf(Error);336 expect(e.name).toBe(cls.name);337 expect(e.status).toBe(status);338 expect(e.type).toBe("x_error");339 expect(e.code).toBe("some_code");340 expect(e.param).toBe("purpose");341 expect(e.requestId).toBe("req_body");342 expect(e.message).toBe("m-some_code");343 });344345 it("falls back to the Request-Id header and a generic message when the body is not an envelope", async () => {346 const { client } = mock([{ status: 404, body: "<html>" }]);347 const e = (await client.verificationSessions.retrieve("x").catch((x) => x)) as MacLustrIdentityError;348 expect(e).toBeInstanceOf(NotFoundError);349 expect(e.requestId).toBe("req_test");350 expect(e.message).toBe("HTTP 404");351 });352});353354describe("pagination and isUserVerified", () => {355 const ver = (id: string, over: Record<string, unknown> = {}) => ({ verification_id: id, object: "verification", status: "verified", expires_at: null, ...over });356357 it("iterates over every page with the cursor of the last item", async () => {358 const { client, calls } = mock([359 { status: 200, body: { object: "list", data: [{ id: "vs_3" }, { id: "vs_2" }], has_more: true } },360 { status: 200, body: { object: "list", data: [{ id: "vs_1" }], has_more: false } },361 ]);362 const ids: string[] = [];363 for await (const s of client.verificationSessions.listAutoPaging({ limit: 2 })) ids.push(s.id);364 expect(ids).toEqual(["vs_3", "vs_2", "vs_1"]);365 expect(calls[0]!.url).toBe("http://identity.test/v1/verification-sessions?limit=2");366 expect(calls[1]!.url).toBe("http://identity.test/v1/verification-sessions?limit=2&starting_after=vs_2");367 });368369 it("uses verification_id as the cursor for verifications", async () => {370 const { client, calls } = mock([371 { status: 200, body: { object: "list", data: [ver("ver_2")], has_more: true } },372 { status: 200, body: { object: "list", data: [ver("ver_1")], has_more: false } },373 ]);374 const ids: string[] = [];375 for await (const v of client.verifications.listAutoPaging()) ids.push(v.verification_id);376 expect(ids).toEqual(["ver_2", "ver_1"]);377 expect(calls[1]!.url).toContain("starting_after=ver_2");378 });379380 it("isUserVerified returns the newest valid verification", async () => {381 const past = new Date(Date.now() - 1000).toISOString();382 const future = new Date(Date.now() + 86400000).toISOString();383 const { client, calls } = mock([{ status: 200, body: { object: "list", data: [ver("ver_expired", { expires_at: past }), ver("ver_ok", { expires_at: future }), ver("ver_older")], has_more: false } }]);384 const v = await client.isUserVerified("user_1");385 expect(v?.verification_id).toBe("ver_ok");386 expect(calls[0]!.url).toContain("external_user_id=user_1");387 expect(calls[0]!.url).toContain("status=verified");388 });389390 it("isUserVerified returns null when nothing is valid and throws when the service is down", async () => {391 const none = mock([{ status: 200, body: { object: "list", data: [], has_more: false } }]);392 expect(await none.client.isUserVerified("user_1")).toBeNull();393 const down = mock([new TypeError("fetch failed")]);394 await expect(down.client.isUserVerified("user_1")).rejects.toBeInstanceOf(ConnectionError);395 await expect(none.client.isUserVerified("")).rejects.toMatchObject({ code: "external_user_id_required" });396 });397});398