SPB Git

Repository Public

Passkey.tsx 2.8 KB 48 lines tsx

1"use client";2import { WebAuthnError, startAuthentication, startRegistration } from "@simplewebauthn/browser";3import { useState } from "react";4import { ApiClientError, api, go } from "./client";56interface Opts<T> { challengeId: string; options: T }78function message(e: unknown): string {9  if (e instanceof WebAuthnError || (e instanceof Error && e.name === "NotAllowedError")) {10    const code = e instanceof WebAuthnError ? e.code : "";11    if (code === "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED") return "Cet appareil possède déjà une clé d’accès pour ce studio.";12    if (code === "ERROR_INVALID_DOMAIN" || code === "ERROR_INVALID_RP_ID") return "Les clés d’accès ne fonctionnent qu’à l’adresse officielle du site, en HTTPS.";13    return "La vérification a été annulée ou a expiré. Touch ID, Face ID ou le code de l’appareil est requis ; réessayez.";14  }15  if (e instanceof ApiClientError) {16    if (e.code === "locked_out" || e.code === "rate_limited") return "Trop de tentatives. Patientez avant de réessayer.";17    if (e.code === "login_failed") return "Accès refusé : cette clé d’accès n’est pas reconnue.";18    return e.message;19  }20  return "Une erreur inattendue s’est produite.";21}22const deviceName = () => { const ua = navigator.userAgent; return /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Macintosh/.test(ua) ? "Mac" : "Clé d’accès"; };2324export function PasskeyButton({ mode, token }: { mode: "login" | "enrol"; token?: string }) {25  const [busy, setBusy] = useState(false), [error, setError] = useState("");26  const run = async () => {27    setBusy(true); setError("");28    try {29      if (mode === "login") {30        const { challengeId, options } = await api<Opts<Parameters<typeof startAuthentication>[0]["optionsJSON"]>>("auth/login/options", { body: {} });31        await api("auth/login/verify", { body: { challengeId, response: await startAuthentication({ optionsJSON: options }) } });32      } else {33        const { challengeId, options } = await api<Opts<Parameters<typeof startRegistration>[0]["optionsJSON"]>>("auth/register/options", { body: { token } });34        await api("auth/register/verify", { body: { challengeId, token, name: deviceName(), response: await startRegistration({ optionsJSON: options }) } });35      }36      go("/admin");37    } catch (e) { setError(message(e)); setBusy(false); }38  };39  return (40    <div>41      <button type="button" className="btn btn-primary w-full" disabled={busy} onClick={run} data-testid={`passkey-${mode}`}>42        {busy ? "En attente de votre appareil…" : mode === "login" ? "Ouvrir avec une clé d’accès" : "Créer une clé d’accès sur cet appareil"}43      </button>44      {error && <p role="alert" className="mt-4 rounded-lg bg-coral-soft p-3 text-sm text-coral" data-testid="passkey-error">{error}</p>}45    </div>46  );47}48
Files main
Menu

Theme