Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOURCE FILE4 * =============================================================================5 * Project : MacLustr LLM API6 * File : web/assets/webauthn.js7 * Author : Simon-Pierre Boucher | https://spboucher.ai8 * Contact : admin@spboucher.ai9 * Copyright : (c) 2026 Simon-Pierre Boucher10 * License : None specified (no license file in this repository)11 * =============================================================================12 * END OF SP BOUCHER SOURCE HEADER13 * =============================================================================14 */1516// Aides WebAuthn partagées (activation, connexion, ré-authentification, ajout d'une clé d'accès).17// Conversion JSON ⇄ ArrayBuffer : API natives quand elles existent, repli manuel en base64url sinon.1819export function b64urlToBuffer(value) {20 const s = String(value).replace(/-/g, "+").replace(/_/g, "/");21 const bin = atob(s + "=".repeat((4 - (s.length % 4)) % 4));22 const out = new Uint8Array(bin.length);23 for (let i = 0; i < bin.length; i += 1) out[i] = bin.charCodeAt(i);24 return out.buffer;25}2627export function bufferToB64url(buffer) {28 const bytes = buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);29 let bin = "";30 for (let i = 0; i < bytes.length; i += 1) bin += String.fromCharCode(bytes[i]);31 return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");32}3334export function isSupported() {35 return typeof window.PublicKeyCredential === "function" && !!navigator.credentials && window.isSecureContext;36}3738/** true / false, ou null si le navigateur ne sait pas répondre. */39export async function platformAuthenticatorAvailable() {40 try {41 if (!isSupported() || typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable !== "function") return null;42 return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();43 } catch {44 return null;45 }46}4748function descriptors(list) {49 return (list || []).map((d) => ({ ...d, id: b64urlToBuffer(d.id) }));50}5152function creationOptions(json) {53 if (typeof PublicKeyCredential.parseCreationOptionsFromJSON === "function") {54 try { return PublicKeyCredential.parseCreationOptionsFromJSON(json); } catch { /* repli manuel */ }55 }56 return {57 ...json,58 challenge: b64urlToBuffer(json.challenge),59 user: { ...json.user, id: b64urlToBuffer(json.user.id) },60 excludeCredentials: descriptors(json.excludeCredentials),61 };62}6364function requestOptions(json) {65 if (typeof PublicKeyCredential.parseRequestOptionsFromJSON === "function") {66 try { return PublicKeyCredential.parseRequestOptionsFromJSON(json); } catch { /* repli manuel */ }67 }68 return { ...json, challenge: b64urlToBuffer(json.challenge), allowCredentials: descriptors(json.allowCredentials) };69}7071function serialize(cred) {72 if (typeof cred.toJSON === "function") {73 try {74 const json = cred.toJSON();75 if (json && json.response && json.rawId) return json;76 } catch { /* certaines extensions cassent toJSON : repli manuel */ }77 }78 const r = cred.response;79 const response = { clientDataJSON: bufferToB64url(r.clientDataJSON) };80 if (r.attestationObject) {81 response.attestationObject = bufferToB64url(r.attestationObject);82 response.transports = typeof r.getTransports === "function" ? r.getTransports() : [];83 } else {84 response.authenticatorData = bufferToB64url(r.authenticatorData);85 response.signature = bufferToB64url(r.signature);86 if (r.userHandle && r.userHandle.byteLength) response.userHandle = bufferToB64url(r.userHandle);87 }88 return {89 id: cred.id,90 rawId: bufferToB64url(cred.rawId),91 type: cred.type,92 response,93 authenticatorAttachment: cred.authenticatorAttachment ?? undefined,94 clientExtensionResults: typeof cred.getClientExtensionResults === "function" ? cred.getClientExtensionResults() : {},95 };96}9798function unsupported() {99 const err = new Error("WebAuthn indisponible");100 err.name = "NotSupportedError";101 return err;102}103104/** Crée une clé d'accès à partir des options JSON du serveur ; retourne la réponse sérialisée en JSON. */105export async function createCredential(publicKeyJSON, { signal } = {}) {106 if (!isSupported()) throw unsupported();107 const cred = await navigator.credentials.create({ publicKey: creationOptions(publicKeyJSON), signal });108 if (!cred) throw unsupported();109 return serialize(cred);110}111112/** Demande une signature (connexion / ré-authentification) ; retourne la réponse sérialisée en JSON. */113export async function getCredential(publicKeyJSON, { signal } = {}) {114 if (!isSupported()) throw unsupported();115 const cred = await navigator.credentials.get({ publicKey: requestOptions(publicKeyJSON), signal });116 if (!cred) throw unsupported();117 return serialize(cred);118}119120/** Message humain pour une erreur levée par navigator.credentials.*. `mode` : "create" ou "get". */121export function describeWebAuthnError(err, mode = "get") {122 const name = err && err.name;123 if (name === "NotAllowedError" || name === "AbortError") {124 return mode === "create"125 ? "La création a été annulée ou le délai est dépassé. Rien n'a été enregistré : vous pouvez réessayer."126 : "La vérification a été annulée ou le délai est dépassé. Vous pouvez réessayer.";127 }128 if (name === "InvalidStateError") {129 return mode === "create"130 ? "Cet appareil possède déjà une clé d'accès pour ce compte. Utilisez-la pour vous connecter."131 : "Cette clé d'accès ne peut pas être utilisée ici.";132 }133 if (name === "NotSupportedError") {134 return "Ce navigateur ou cet appareil ne prend pas en charge les clés d'accès. Utilisez Safari ou Chrome à jour, sur un appareil doté de Touch ID, Face ID ou d'un code de verrouillage.";135 }136 if (name === "SecurityError") {137 return "Le navigateur a refusé l'opération pour ce domaine. Ouvrez la page à son adresse officielle, en HTTPS.";138 }139 if (name === "ConstraintError") {140 return "Cet appareil ne peut pas vérifier votre identité (aucune biométrie ni code configuré).";141 }142 return "L'opération n'a pas abouti sur cet appareil. Réessayez dans un instant.";143}144145/** Nom par défaut d'une clé d'accès selon l'appareil : « iPhone », « iPad », « Mac »… */146export function defaultPasskeyName() {147 const ua = navigator.userAgent || "";148 const platform = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || "";149 if (/iPhone|iPod/.test(ua)) return "iPhone";150 if (/iPad/.test(ua) || (/Mac/.test(platform) && navigator.maxTouchPoints > 1)) return "iPad";151 if (/Mac/i.test(platform) || /Macintosh/.test(ua)) return "Mac";152 if (/Android/i.test(ua)) return "Android";153 if (/Win/i.test(platform)) return "PC Windows";154 if (/CrOS/.test(ua)) return "Chromebook";155 if (/Linux/i.test(platform)) return "Linux";156 return "Clé d'accès";157}158