Repository Public
1"use client";2import { startAuthentication, startRegistration, WebAuthnError } from "@simplewebauthn/browser";3import { api, ApiClientError } from "@/lib/client-api";45type Opts<T> = { challengeId: string; options: T };67/** Why a ceremony did not complete, in words for the person holding the device. */8export function passkeyMessage(e: unknown, fr: boolean): 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 fr ? "Cet appareil a déjà une clé d’accès pour Sheet." : "This device already has a passkey for Sheet.";12 if (code === "ERROR_INVALID_DOMAIN" || code === "ERROR_INVALID_RP_ID") return fr ? "Les clés d’accès ne fonctionnent que sur l’adresse officielle du site, en HTTPS." : "Passkeys only work on the site’s official address, over HTTPS.";13 return fr ? "La vérification a été annulée ou a expiré. Touch ID, Face ID ou le code de l’appareil est requis ; réessayez." : "The verification was cancelled or timed out. Touch ID, Face ID or the device passcode is required; try again.";14 }15 if (e instanceof ApiClientError) {16 if (e.code === "locked_out" || e.code === "rate_limited") return fr ? "Trop de tentatives. Patientez avant de réessayer." : "Too many attempts. Wait before trying again.";17 if (e.code === "login_failed") return fr ? "Connexion refusée : cette clé d’accès n’est pas reconnue ou a été révoquée." : "Sign-in refused: this passkey is not recognised or was revoked.";18 if (e.code === "invalid_setup_token") return fr ? "Ce lien d’inscription est invalide, expiré ou déjà utilisé." : "This enrolment link is invalid, expired or already used.";19 if (e.code === "challenge_expired") return fr ? "La demande a expiré. Recommencez." : "The request expired. Start again.";20 if (e.code === "network") return fr ? "Connexion au serveur impossible." : "Cannot reach the server.";21 return e.message;22 }23 return fr ? "Une erreur inattendue est survenue." : "An unexpected error occurred.";24}2526export const passkeysSupported = () => typeof window !== "undefined" && typeof window.PublicKeyCredential === "function";2728export async function signIn(): Promise<void> {29 const { challengeId, options } = await api<Opts<Parameters<typeof startAuthentication>[0]["optionsJSON"]>>("/api/auth/login/options", { method: "POST", body: {} });30 const response = await startAuthentication({ optionsJSON: options });31 await api("/api/auth/login/verify", { body: { challengeId, response } });32}3334export async function enrol(input: { setupToken?: string; name: string }): Promise<{ recoveryCodes: string[] | null }> {35 const { challengeId, options } = await api<Opts<Parameters<typeof startRegistration>[0]["optionsJSON"]>>("/api/auth/register/options", { body: { setupToken: input.setupToken } });36 const response = await startRegistration({ optionsJSON: options });37 return api("/api/auth/register/verify", { body: { challengeId, response, name: input.name, setupToken: input.setupToken } });38}3940/** Strong re-verification before a sensitive action (valid a few minutes). */41export async function reauthenticate(): Promise<void> {42 const { challengeId, options } = await api<Opts<Parameters<typeof startAuthentication>[0]["optionsJSON"]>>("/api/auth/reauth/options", { method: "POST", body: {} });43 const response = await startAuthentication({ optionsJSON: options });44 await api("/api/auth/reauth/verify", { body: { challengeId, response } });45}4647/** Runs an action; if the server asks for a fresh verification, performs it and retries once. */48export async function withReauth<T>(action: () => Promise<T>): Promise<T> {49 try { return await action(); }50 catch (e) { if (!(e instanceof ApiClientError) || e.code !== "reauth_required") throw e; await reauthenticate(); return action(); }51}5253export function deviceName(): string {54 const ua = navigator.userAgent;55 return /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Macintosh/.test(ua) ? "Mac" : /Android/.test(ua) ? "Android" : /Windows/.test(ua) ? "Windows" : "Passkey";56}57