Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Identity8 * File : sdk/typescript/src/browser.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/browser — opens the hosted verification page from a web page.44 *45 * This entry NEVER takes a secret key. The only input is the session `url` that your server obtained from46 * `verificationSessions.create()`. The result reported here is a user-interface hint: before unlocking anything,47 * always confirm the status on your server (webhook or `verifications.retrieve`).48 */4950export type VerificationMode = "redirect" | "popup" | "modal";51export type VerificationMessageType = "ready" | "completed" | "cancelled" | "error";5253/** Shape posted by the hosted page: `window.postMessage({source: "maclustr-identity", type, session_id, status})`. */54export interface VerificationMessage {55 source: "maclustr-identity";56 type: VerificationMessageType;57 session_id?: string;58 status?: string;59}6061export interface VerificationResult {62 sessionId: string | null;63 /** Session status reported by the hosted page (for example `verified`, `manual_review`, `rejected`). Not authoritative. */64 status: string | null;65}6667export interface VerificationCancel {68 sessionId: string | null;69 /** `page`: the person cancelled inside the hosted page. `dismissed`: the dialog or popup was closed. */70 reason: "page" | "dismissed";71}7273export interface VerificationFlowError {74 sessionId: string | null;75 /** `page_error`, `popup_channel_lost` or the status reported by the page. */76 code: string;77 message: string;78}7980export interface OpenVerificationOptions {81 /** Session URL returned by your server (`https://…/verify/{id}#{client_secret}`). */82 url: string;83 /** Default `modal`. */84 mode?: VerificationMode;85 /** Modal mode: element receiving the dialog. Default `document.body`. */86 container?: HTMLElement;87 /** Accessible name of the dialog and title of the iframe. */88 title?: string;89 /** Label of the close button. */90 closeLabel?: string;91 /** Close the dialog or popup automatically after `completed` or `cancelled`. Default true. */92 autoClose?: boolean;93 onReady?: (info: { sessionId: string | null }) => void;94 onComplete?: (result: VerificationResult) => void;95 onCancel?: (info: VerificationCancel) => void;96 onError?: (error: VerificationFlowError) => void;97}9899export interface VerificationHandle {100 /** Mode actually used (a blocked popup falls back to `redirect`). */101 readonly mode: VerificationMode;102 readonly sessionId: string | null;103 readonly closed: boolean;104 /** Closes the dialog or popup and removes every listener. Fires no callback. Idempotent. */105 close(): void;106}107108const SOURCE = "maclustr-identity";109const TYPES: ReadonlySet<string> = new Set(["ready", "completed", "cancelled", "error"]);110const SECRET_KEY_PATTERN = /mlid_sk_(live|test)_/;111112/** Throws when a value looks like a secret API key: those must never reach browser code. */113export function assertNoSecretKey(value: unknown): void {114 if (typeof value === "string" && SECRET_KEY_PATTERN.test(value)) {115 throw new Error(116 "[maclustr-identity] A secret API key (mlid_sk_…) was passed to browser code. Secret keys must stay on your server: " +117 "rotate this key now, create the session server-side and pass only its `url` to the browser.",118 );119 }120}121122export interface ParsedVerificationUrl {123 href: string;124 origin: string;125 sessionId: string | null;126}127128/** Validates a session URL: absolute http(s), https outside localhost, no credentials, no secret key. */129export function parseVerificationUrl(url: string): ParsedVerificationUrl {130 assertNoSecretKey(url);131 let u: URL;132 try {133 u = new URL(url);134 } catch {135 throw new Error("[maclustr-identity] `url` must be the absolute session URL returned by your server.");136 }137 const local = u.hostname === "localhost" || u.hostname === "127.0.0.1" || u.hostname === "[::1]";138 if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) {139 throw new Error("[maclustr-identity] The verification URL must use https (http is accepted for localhost only).");140 }141 if (u.username || u.password) throw new Error("[maclustr-identity] The verification URL must not contain credentials.");142 const m = /\/verify\/([^/?#]+)/.exec(u.pathname);143 return { href: u.href, origin: u.origin, sessionId: m ? decodeURIComponent(m[1] as string) : null };144}145146/**147 * Returns the message when the event really comes from the hosted page of this session, otherwise null.148 * Checks: exact origin of the session URL, `source === "maclustr-identity"`, known type, matching session id,149 * and (when the expected window is known) that the message was sent by that window.150 */151export function acceptMessage(152 event: Pick<MessageEvent, "origin" | "data" | "source">,153 expected: { origin: string; sessionId: string | null; sourceWindow?: unknown },154): VerificationMessage | null {155 if (event.origin !== expected.origin) return null;156 const d = event.data as Partial<VerificationMessage> | null;157 if (!d || typeof d !== "object" || d.source !== SOURCE) return null;158 if (typeof d.type !== "string" || !TYPES.has(d.type)) return null;159 if (expected.sessionId && d.session_id !== undefined && d.session_id !== expected.sessionId) return null;160 if (expected.sourceWindow && event.source && event.source !== expected.sourceWindow) return null;161 return d as VerificationMessage;162}163164interface Flow {165 finished: boolean;166 ready: boolean;167 dispose: Array<() => void>;168}169170/** Opens the hosted verification page. See `OpenVerificationOptions`. */171export function openVerification(options: OpenVerificationOptions): VerificationHandle {172 if (typeof window === "undefined" || typeof document === "undefined") {173 throw new Error("[maclustr-identity] openVerification() must be called in a browser.");174 }175 for (const v of Object.values(options)) assertNoSecretKey(v);176 const target = parseVerificationUrl(options.url);177 const mode: VerificationMode = options.mode ?? "modal";178 if (mode === "redirect") return redirect(target);179 if (mode === "popup") return popup(target, options);180 if (mode === "modal") return modal(target, options);181 throw new Error(`[maclustr-identity] Unknown mode: ${String(mode)}`);182}183184/** @internal Indirection so tests can observe navigations and popups. */185export const _internals = {186 navigate(href: string): void {187 window.location.assign(href);188 },189 openWindow(href: string, name: string, features: string): Window | null {190 return window.open(href, name, features);191 },192};193194function redirect(target: ParsedVerificationUrl): VerificationHandle {195 _internals.navigate(target.href);196 return { mode: "redirect", sessionId: target.sessionId, closed: true, close() {} };197}198199function safely(fn: (() => void) | undefined): void {200 try {201 fn?.();202 } catch (e) {203 // A failing application callback must not break the flow teardown.204 setTimeout(() => {205 throw e;206 }, 0);207 }208}209210function listen(211 target: ParsedVerificationUrl,212 options: OpenVerificationOptions,213 flow: Flow,214 getSourceWindow: () => unknown,215 close: () => void,216): void {217 const onMessage = (event: MessageEvent) => {218 if (flow.finished) return;219 const msg = acceptMessage(event, { origin: target.origin, sessionId: target.sessionId, sourceWindow: getSourceWindow() });220 if (!msg) return;221 const sessionId = msg.session_id ?? target.sessionId;222 if (msg.type === "ready") {223 flow.ready = true;224 safely(() => options.onReady?.({ sessionId }));225 return;226 }227 if (msg.type === "error") {228 // The page stays open: the person may retry inside it.229 safely(() => options.onError?.({ sessionId, code: msg.status ?? "page_error", message: "The verification page reported an error." }));230 return;231 }232 flow.finished = true;233 if (options.autoClose !== false) close();234 if (msg.type === "completed") safely(() => options.onComplete?.({ sessionId, status: msg.status ?? null }));235 else safely(() => options.onCancel?.({ sessionId, reason: "page" }));236 };237 window.addEventListener("message", onMessage);238 flow.dispose.push(() => window.removeEventListener("message", onMessage));239}240241function popup(target: ParsedVerificationUrl, options: OpenVerificationOptions): VerificationHandle {242 const w = 480;243 const h = 760;244 const left = Math.max(0, Math.round((window.screenX || 0) + ((window.outerWidth || w) - w) / 2));245 const top = Math.max(0, Math.round((window.screenY || 0) + ((window.outerHeight || h) - h) / 2));246 let win: Window | null = null;247 try {248 win = _internals.openWindow(target.href, "maclustr-identity-verify", `popup=yes,width=${w},height=${h},left=${left},top=${top}`);249 } catch {250 win = null;251 }252 if (!win) return redirect(target); // popup blocked: continue in the same tab253 const flow: Flow = { finished: false, ready: false, dispose: [] };254 let closed = false;255 const close = () => {256 if (closed) return;257 closed = true;258 for (const d of flow.dispose.splice(0)) d();259 try {260 win?.close();261 } catch {262 /* already gone */263 }264 };265 listen(target, options, flow, () => win, close);266 const timer = setInterval(() => {267 let gone = true;268 try {269 gone = !win || win.closed;270 } catch {271 gone = true;272 }273 if (!gone || closed) return;274 const wasReady = flow.ready;275 const wasFinished = flow.finished;276 flow.finished = true;277 close();278 if (wasFinished) return;279 if (wasReady) safely(() => options.onCancel?.({ sessionId: target.sessionId, reason: "dismissed" }));280 else {281 // Either the person closed the popup before the page loaded, or the page isolates itself from its opener282 // (Cross-Origin-Opener-Policy), in which case no message can ever arrive. The server is the source of truth.283 safely(() =>284 options.onError?.({285 sessionId: target.sessionId,286 code: "popup_channel_lost",287 message: "The popup closed or became unreachable before reporting a result. Check the verification status on your server.",288 }),289 );290 }291 }, 500);292 flow.dispose.push(() => clearInterval(timer));293 return {294 mode: "popup",295 sessionId: target.sessionId,296 get closed() {297 return closed;298 },299 close,300 };301}302303let modalCounter = 0;304305function modal(target: ParsedVerificationUrl, options: OpenVerificationOptions): VerificationHandle {306 const container = options.container ?? document.body;307 const title = options.title ?? "Identity verification";308 const previouslyFocused = document.activeElement as HTMLElement | null;309 const id = `mlid-modal-${++modalCounter}`;310311 const overlay = document.createElement("div");312 overlay.id = id;313 overlay.setAttribute("role", "dialog");314 overlay.setAttribute("aria-modal", "true");315 overlay.setAttribute("aria-labelledby", `${id}-title`);316 overlay.setAttribute("data-maclustr-identity", "modal");317 overlay.style.cssText =318 "position:fixed;inset:0;z-index:2147483000;display:flex;flex-direction:column;background:#ffffff;color:#111111;" +319 "font:15px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;";320321 const sentinel = (): HTMLElement => {322 const s = document.createElement("div");323 s.tabIndex = 0;324 s.setAttribute("data-mlid-sentinel", "");325 s.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);";326 return s;327 };328 const first = sentinel();329 const last = sentinel();330331 const bar = document.createElement("div");332 bar.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 14px;border-bottom:1px solid #d9d9d9;flex:0 0 auto;";333 const heading = document.createElement("h2");334 heading.id = `${id}-title`;335 heading.textContent = title;336 heading.style.cssText = "margin:0;font-size:15px;font-weight:600;";337 const closeBtn = document.createElement("button");338 closeBtn.type = "button";339 closeBtn.textContent = options.closeLabel ?? "Close";340 closeBtn.setAttribute("data-mlid-close", "");341 closeBtn.style.cssText = "font:inherit;padding:6px 12px;border:1px solid #767676;border-radius:6px;background:#ffffff;color:#111111;cursor:pointer;";342 bar.append(heading, closeBtn);343344 const frame = document.createElement("iframe");345 frame.src = target.href;346 frame.title = title;347 // Camera access is delegated to the verification origin only; nothing else is granted.348 frame.setAttribute("allow", "camera");349 frame.setAttribute("referrerpolicy", "no-referrer");350 frame.style.cssText = "flex:1 1 auto;width:100%;border:0;background:#ffffff;";351352 overlay.append(first, bar, frame, last);353354 const flow: Flow = { finished: false, ready: false, dispose: [] };355 let closed = false;356357 // Everything outside the dialog becomes inert while it is open.358 const inerted: Array<{ el: HTMLElement; inert: boolean; hidden: string | null }> = [];359 if (container === document.body) {360 for (const el of Array.from(document.body.children) as HTMLElement[]) {361 inerted.push({ el, inert: Boolean((el as { inert?: boolean }).inert), hidden: el.getAttribute("aria-hidden") });362 (el as { inert?: boolean }).inert = true;363 el.setAttribute("aria-hidden", "true");364 }365 }366 const previousOverflow = document.body.style.overflow;367 document.body.style.overflow = "hidden";368 container.appendChild(overlay);369370 const close = () => {371 if (closed) return;372 closed = true;373 for (const d of flow.dispose.splice(0)) d();374 overlay.remove();375 for (const { el, inert, hidden } of inerted) {376 (el as { inert?: boolean }).inert = inert;377 if (hidden === null) el.removeAttribute("aria-hidden");378 else el.setAttribute("aria-hidden", hidden);379 }380 document.body.style.overflow = previousOverflow;381 if (previouslyFocused && typeof previouslyFocused.focus === "function" && document.contains(previouslyFocused)) previouslyFocused.focus();382 };383 const dismiss = () => {384 if (closed) return;385 const wasFinished = flow.finished;386 flow.finished = true;387 close();388 if (!wasFinished) safely(() => options.onCancel?.({ sessionId: target.sessionId, reason: "dismissed" }));389 };390391 // Focus trap: Tab cycles between the close button and the iframe; the sentinels catch focus leaving either end.392 const onFirst = () => frame.focus();393 const onLast = () => closeBtn.focus();394 first.addEventListener("focus", onFirst);395 last.addEventListener("focus", onLast);396 const onKeydown = (e: KeyboardEvent) => {397 if (e.key === "Escape") {398 e.preventDefault();399 e.stopPropagation();400 dismiss();401 } else if (e.key === "Tab" && document.activeElement === closeBtn && e.shiftKey) {402 e.preventDefault();403 frame.focus();404 }405 };406 document.addEventListener("keydown", onKeydown, true);407 const onFocusIn = (e: FocusEvent) => {408 if (!overlay.contains(e.target as Node)) closeBtn.focus();409 };410 document.addEventListener("focusin", onFocusIn);411 closeBtn.addEventListener("click", dismiss);412 flow.dispose.push(() => {413 document.removeEventListener("keydown", onKeydown, true);414 document.removeEventListener("focusin", onFocusIn);415 });416417 listen(target, options, flow, () => frame.contentWindow, close);418 closeBtn.focus();419420 return {421 mode: "modal",422 sessionId: target.sessionId,423 get closed() {424 return closed;425 },426 close,427 };428}429430export interface CameraSupport {431 /** True when a camera capture can be attempted from this page. */432 supported: boolean;433 /** Camera APIs require https (or localhost). */434 secureContext: boolean;435 hasMediaDevices: boolean;436 /** Whether at least one camera is listed; null when the browser does not say. */437 hasCamera: boolean | null;438 /** Permission state for this origin; `unknown` when the Permissions API cannot answer. */439 permission: "granted" | "denied" | "prompt" | "unknown";440 /** Why `supported` is false. */441 reason?: "not_a_browser" | "insecure_context" | "no_media_devices" | "no_camera" | "permission_denied";442}443444/**445 * Pre-check before opening the flow. It never triggers a permission prompt and never opens the camera.446 * A person without a usable camera can still be offered another device (open the session URL on a phone).447 * Note: in modal mode the camera permission that matters is the one of the verification origin inside the iframe;448 * this check describes the embedding page and the device.449 */450export async function checkCameraSupport(): Promise<CameraSupport> {451 if (typeof window === "undefined" || typeof navigator === "undefined") {452 return { supported: false, secureContext: false, hasMediaDevices: false, hasCamera: null, permission: "unknown", reason: "not_a_browser" };453 }454 const secureContext = window.isSecureContext !== false;455 const md = navigator.mediaDevices;456 const hasMediaDevices = Boolean(md && typeof md.getUserMedia === "function");457 let hasCamera: boolean | null = null;458 if (md && typeof md.enumerateDevices === "function") {459 try {460 hasCamera = (await md.enumerateDevices()).some((d) => d.kind === "videoinput");461 } catch {462 hasCamera = null;463 }464 }465 let permission: CameraSupport["permission"] = "unknown";466 try {467 const perms = (navigator as { permissions?: { query(d: { name: string }): Promise<{ state: string }> } }).permissions;468 if (perms) {469 const state = (await perms.query({ name: "camera" })).state;470 if (state === "granted" || state === "denied" || state === "prompt") permission = state;471 }472 } catch {473 permission = "unknown"; // some browsers do not know the "camera" permission name474 }475 let reason: CameraSupport["reason"];476 if (!secureContext) reason = "insecure_context";477 else if (!hasMediaDevices) reason = "no_media_devices";478 else if (hasCamera === false) reason = "no_camera";479 else if (permission === "denied") reason = "permission_denied";480 return { supported: reason === undefined, secureContext, hasMediaDevices, hasCamera, permission, ...(reason ? { reason } : {}) };481}482