SPB Git

Repository Public

browser.test.ts 14.8 KB 309 lines typescript

1// @vitest-environment jsdom2/**3 * =============================================================================4 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION5 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project          : MacLustr Identity9 * File             : sdk/typescript/tests/unit/browser.test.ts10 * Module           : sdk11 * Repository       : https://git.spboucher.ai/maclustr-identity12 * Project Website  : https://identity.spboucher.ai13 * Created          : 2026-12-0114 * Last Modified    : 2026-12-0115 *16 * Author           : Simon-Pierre Boucher17 * Position         : Professor of Finance18 * Institution      : Université du Québec en Outaouais (UQO)19 * Organization     : SP Boucher20 * Website          : https://spboucher.ai21 * Git              : https://git.spboucher.ai22 *23 * Preferred Contact: admin@spboucher.ai24 * Technical Contact: dev@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";44import { _internals, acceptMessage, assertNoSecretKey, checkCameraSupport, openVerification, parseVerificationUrl } from "../../src/browser";4546const ORIGIN = "https://identity.spboucher.ai";47const URL_OK = `${ORIGIN}/verify/vs_123#vsc_secret`;4849function post(data: unknown, origin = ORIGIN) {50  window.dispatchEvent(new MessageEvent("message", { data, origin }));51}52const msg = (type: string, extra: Record<string, unknown> = {}) => ({ source: "maclustr-identity", type, session_id: "vs_123", ...extra });53const dialog = () => document.querySelector<HTMLElement>('[data-maclustr-identity="modal"]');5455let navigate: ReturnType<typeof vi.spyOn>;5657beforeEach(() => {58  document.body.innerHTML = '<main id="app"><button id="start">Verify</button></main>';59  navigate = vi.spyOn(_internals, "navigate").mockImplementation(() => {});60});61afterEach(() => {62  vi.restoreAllMocks();63  vi.useRealTimers();64  document.body.innerHTML = "";65});6667describe("URL and secret-key guards", () => {68  it("parses the session URL", () => {69    expect(parseVerificationUrl(URL_OK)).toEqual({ href: URL_OK, origin: ORIGIN, sessionId: "vs_123" });70    expect(parseVerificationUrl("http://localhost:8870/verify/vs_9#x").origin).toBe("http://localhost:8870");71  });7273  it("rejects relative, non-https, credentialed or javascript URLs", () => {74    for (const u of ["/verify/vs_1", "http://identity.example/verify/vs_1", "https://user:pw@identity.example/verify/vs_1", "javascript:alert(1)", "data:text/html,x"]) {75      expect(() => openVerification({ url: u })).toThrow(/maclustr-identity/);76    }77    expect(dialog()).toBeNull();78  });7980  it("refuses a secret key anywhere in the options", () => {81    expect(() => assertNoSecretKey("mlid_sk_test_abc")).toThrow(/must stay on your server/);82    expect(() => openVerification({ url: URL_OK, title: "mlid_sk_live_abc" })).toThrow(/Secret keys/i);83    expect(() => openVerification({ url: `${ORIGIN}/verify/vs_1?k=mlid_sk_test_abc` })).toThrow(/secret API key/);84    expect(() => assertNoSecretKey("vsc_session_secret")).not.toThrow();85  });86});8788describe("origin validation", () => {89  const expected = { origin: ORIGIN, sessionId: "vs_123" };90  it("accepts only the exact origin of the session URL", () => {91    expect(acceptMessage({ origin: ORIGIN, data: msg("completed"), source: null }, expected)).toMatchObject({ type: "completed" });92    for (const origin of ["https://evil.example", "https://identity.spboucher.ai.evil.example", "http://identity.spboucher.ai", "https://identity.spboucher.ai:8443", "null", ""]) {93      expect(acceptMessage({ origin, data: msg("completed"), source: null }, expected)).toBeNull();94    }95  });9697  it("requires source === 'maclustr-identity' and a known type", () => {98    expect(acceptMessage({ origin: ORIGIN, data: { ...msg("completed"), source: "other" }, source: null }, expected)).toBeNull();99    expect(acceptMessage({ origin: ORIGIN, data: { type: "completed" }, source: null }, expected)).toBeNull();100    expect(acceptMessage({ origin: ORIGIN, data: msg("verified"), source: null }, expected)).toBeNull();101    expect(acceptMessage({ origin: ORIGIN, data: "completed", source: null }, expected)).toBeNull();102    expect(acceptMessage({ origin: ORIGIN, data: null, source: null }, expected)).toBeNull();103  });104105  it("ignores another session and another window", () => {106    expect(acceptMessage({ origin: ORIGIN, data: msg("completed", { session_id: "vs_other" }), source: null }, expected)).toBeNull();107    const w1 = {} as MessageEventSource;108    const w2 = {} as MessageEventSource;109    expect(acceptMessage({ origin: ORIGIN, data: msg("ready"), source: w1 }, { ...expected, sourceWindow: w2 })).toBeNull();110    expect(acceptMessage({ origin: ORIGIN, data: msg("ready"), source: w1 }, { ...expected, sourceWindow: w1 })).not.toBeNull();111  });112});113114describe("modal mode", () => {115  it("injects an accessible dialog with a camera-enabled iframe", () => {116    const h = openVerification({ url: URL_OK, mode: "modal", title: "Verify your identity" });117    const d = dialog()!;118    expect(h.mode).toBe("modal");119    expect(h.sessionId).toBe("vs_123");120    expect(d.getAttribute("role")).toBe("dialog");121    expect(d.getAttribute("aria-modal")).toBe("true");122    expect(document.getElementById(d.getAttribute("aria-labelledby")!)!.textContent).toBe("Verify your identity");123    const frame = d.querySelector("iframe")!;124    expect(frame.getAttribute("src")).toBe(URL_OK);125    expect(frame.getAttribute("allow")).toBe("camera");126    expect(frame.title).toBe("Verify your identity");127    expect(document.activeElement).toBe(d.querySelector("[data-mlid-close]"));128    expect(document.getElementById("app")!.getAttribute("aria-hidden")).toBe("true");129    expect(document.body.style.overflow).toBe("hidden");130    h.close();131    expect(dialog()).toBeNull();132    expect(document.getElementById("app")!.hasAttribute("aria-hidden")).toBe(false);133    expect(h.closed).toBe(true);134  });135136  it("ignores messages from other origins and reacts to the verification origin", () => {137    const onReady = vi.fn();138    const onComplete = vi.fn();139    const onCancel = vi.fn();140    openVerification({ url: URL_OK, onReady, onComplete, onCancel });141    post(msg("completed", { status: "verified" }), "https://evil.example");142    post({ ...msg("completed"), source: "evil" });143    post(msg("completed", { session_id: "vs_other" }));144    expect(onComplete).not.toHaveBeenCalled();145    expect(dialog()).not.toBeNull();146    post(msg("ready"));147    expect(onReady).toHaveBeenCalledWith({ sessionId: "vs_123" });148    post(msg("completed", { status: "verified" }));149    expect(onComplete).toHaveBeenCalledTimes(1);150    expect(onComplete).toHaveBeenCalledWith({ sessionId: "vs_123", status: "verified" });151    expect(dialog()).toBeNull();152    post(msg("completed", { status: "verified" }));153    post(msg("cancelled"));154    expect(onComplete).toHaveBeenCalledTimes(1);155    expect(onCancel).not.toHaveBeenCalled();156  });157158  it("reports cancellation from the page and page errors", () => {159    const onCancel = vi.fn();160    const onError = vi.fn();161    openVerification({ url: URL_OK, onCancel, onError });162    post(msg("error", { status: "camera_unavailable" }));163    expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "camera_unavailable", sessionId: "vs_123" }));164    expect(dialog()).not.toBeNull();165    post(msg("cancelled"));166    expect(onCancel).toHaveBeenCalledWith({ sessionId: "vs_123", reason: "page" });167    expect(dialog()).toBeNull();168  });169170  it("closes on Escape, reports a dismissal and restores focus", () => {171    const start = document.getElementById("start") as HTMLButtonElement;172    start.focus();173    const onCancel = vi.fn();174    const h = openVerification({ url: URL_OK, onCancel });175    expect(document.activeElement).not.toBe(start);176    document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));177    expect(dialog()).toBeNull();178    expect(h.closed).toBe(true);179    expect(onCancel).toHaveBeenCalledWith({ sessionId: "vs_123", reason: "dismissed" });180    expect(document.activeElement).toBe(start);181    expect(document.body.style.overflow).toBe("");182    // listeners are gone: a late message does nothing183    post(msg("completed"));184    expect(onCancel).toHaveBeenCalledTimes(1);185  });186187  it("closes with the close button and traps focus inside the dialog", () => {188    const onCancel = vi.fn();189    openVerification({ url: URL_OK, onCancel, closeLabel: "Fermer" });190    const d = dialog()!;191    const close = d.querySelector<HTMLButtonElement>("[data-mlid-close]")!;192    const frame = d.querySelector("iframe")!;193    const sentinels = d.querySelectorAll<HTMLElement>("[data-mlid-sentinel]");194    expect(close.textContent).toBe("Fermer");195    sentinels[1]!.focus(); // tabbing past the iframe wraps to the close button196    expect(document.activeElement).toBe(close);197    sentinels[0]!.focus(); // shift-tabbing before the close button wraps to the iframe198    expect(document.activeElement).toBe(frame);199    close.click();200    expect(dialog()).toBeNull();201    expect(onCancel).toHaveBeenCalledWith({ sessionId: "vs_123", reason: "dismissed" });202  });203204  it("keeps the dialog open when autoClose is false and mounts in a custom container", () => {205    const box = document.createElement("div");206    document.body.appendChild(box);207    const onComplete = vi.fn();208    const h = openVerification({ url: URL_OK, container: box, autoClose: false, onComplete });209    expect(box.querySelector("iframe")).not.toBeNull();210    post(msg("completed", { status: "manual_review" }));211    expect(onComplete).toHaveBeenCalledWith({ sessionId: "vs_123", status: "manual_review" });212    expect(dialog()).not.toBeNull();213    h.close();214    h.close();215    expect(dialog()).toBeNull();216  });217});218219describe("popup and redirect modes", () => {220  it("redirect navigates the current tab", () => {221    const h = openVerification({ url: URL_OK, mode: "redirect" });222    expect(navigate).toHaveBeenCalledWith(URL_OK);223    expect(h.mode).toBe("redirect");224    expect(dialog()).toBeNull();225  });226227  it("falls back to redirect when the popup is blocked", () => {228    vi.spyOn(_internals, "openWindow").mockReturnValue(null);229    const h = openVerification({ url: URL_OK, mode: "popup" });230    expect(h.mode).toBe("redirect");231    expect(navigate).toHaveBeenCalledWith(URL_OK);232    vi.spyOn(_internals, "openWindow").mockImplementation(() => {233      throw new Error("blocked");234    });235    expect(openVerification({ url: URL_OK, mode: "popup" }).mode).toBe("redirect");236  });237238  it("popup: validates origin, completes and closes the window", () => {239    const win = { closed: false, close: vi.fn() } as unknown as Window;240    const open = vi.spyOn(_internals, "openWindow").mockReturnValue(win);241    const onComplete = vi.fn();242    const h = openVerification({ url: URL_OK, mode: "popup", onComplete });243    expect(h.mode).toBe("popup");244    expect(open.mock.calls[0]![0]).toBe(URL_OK);245    expect(navigate).not.toHaveBeenCalled();246    post(msg("completed", { status: "verified" }), "https://evil.example");247    expect(onComplete).not.toHaveBeenCalled();248    post(msg("completed", { status: "verified" }));249    expect(onComplete).toHaveBeenCalledWith({ sessionId: "vs_123", status: "verified" });250    expect(win.close).toHaveBeenCalled();251    expect(h.closed).toBe(true);252  });253254  it("popup: a window closed by the person after 'ready' is a cancellation; before any message it is a lost channel", () => {255    vi.useFakeTimers();256    const win1 = { closed: false, close: vi.fn() } as unknown as { closed: boolean; close: () => void };257    vi.spyOn(_internals, "openWindow").mockReturnValue(win1 as unknown as Window);258    const onCancel = vi.fn();259    const onError = vi.fn();260    openVerification({ url: URL_OK, mode: "popup", onCancel, onError });261    post(msg("ready"));262    win1.closed = true;263    vi.advanceTimersByTime(600);264    expect(onCancel).toHaveBeenCalledWith({ sessionId: "vs_123", reason: "dismissed" });265    expect(onError).not.toHaveBeenCalled();266267    const win2 = { closed: true, close: vi.fn() };268    vi.spyOn(_internals, "openWindow").mockReturnValue(win2 as unknown as Window);269    openVerification({ url: URL_OK, mode: "popup", onCancel, onError });270    vi.advanceTimersByTime(600);271    expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: "popup_channel_lost" }));272    expect(onCancel).toHaveBeenCalledTimes(1);273  });274});275276describe("checkCameraSupport", () => {277  const setNav = (props: Record<string, unknown>) => {278    for (const [k, v] of Object.entries(props)) Object.defineProperty(window.navigator, k, { value: v, configurable: true });279  };280  afterEach(() => setNav({ mediaDevices: undefined, permissions: undefined }));281282  it("reports missing media devices", async () => {283    setNav({ mediaDevices: undefined });284    expect(await checkCameraSupport()).toMatchObject({ supported: false, hasMediaDevices: false, reason: "no_media_devices" });285  });286287  it("reports a usable camera without prompting", async () => {288    const getUserMedia = vi.fn();289    setNav({290      mediaDevices: { getUserMedia, enumerateDevices: async () => [{ kind: "audioinput" }, { kind: "videoinput" }] },291      permissions: { query: async () => ({ state: "prompt" }) },292    });293    expect(await checkCameraSupport()).toEqual({ supported: true, secureContext: true, hasMediaDevices: true, hasCamera: true, permission: "prompt" });294    expect(getUserMedia).not.toHaveBeenCalled();295  });296297  it("reports a denied permission, no camera, and an unknown permission name", async () => {298    setNav({ mediaDevices: { getUserMedia() {}, enumerateDevices: async () => [{ kind: "videoinput" }] }, permissions: { query: async () => ({ state: "denied" }) } });299    expect(await checkCameraSupport()).toMatchObject({ supported: false, reason: "permission_denied" });300    setNav({ mediaDevices: { getUserMedia() {}, enumerateDevices: async () => [{ kind: "audioinput" }] } });301    expect(await checkCameraSupport()).toMatchObject({ supported: false, reason: "no_camera" });302    setNav({303      mediaDevices: { getUserMedia() {}, enumerateDevices: async () => [{ kind: "videoinput" }] },304      permissions: { query: async () => Promise.reject(new TypeError("unknown permission")) },305    });306    expect(await checkCameraSupport()).toMatchObject({ supported: true, permission: "unknown" });307  });308});309
Files main
Menu

Theme