SPB Git

Repository Public

auth-forms.tsx 9.8 KB 131 lines tsx

1"use client";2import { useEffect, useState } from "react";3import { useLocale } from "@/i18n/client";4import { dict } from "@/i18n/dict";5import { api, setCsrf } from "@/lib/client-api";6import { Wordmark } from "@/components/brand";7import { deviceName, enrol, passkeyMessage, passkeysSupported, signIn } from "./passkey";89const T = dict({10  signInTitle: ["Studio", "Studio"], signInLead: ["Connexion par clé d’accès : Face ID, Touch ID ou clé de sécurité.", "Sign in with a passkey: Face ID, Touch ID or a security key."],11  signIn: ["Se connecter avec une clé d’accès", "Sign in with a passkey"], working: ["Vérification…", "Verifying…"],12  unsupported: ["Ce navigateur ne prend pas en charge les clés d’accès. Utilisez Safari, Chrome ou Firefox à jour, en HTTPS.", "This browser does not support passkeys. Use an up-to-date Safari, Chrome or Firefox, over HTTPS."],13  lost: ["Appareil perdu ? Utiliser un code de récupération", "Lost your device? Use a recovery code"], code: ["Code de récupération", "Recovery code"], useCode: ["Continuer", "Continue"],14  codeHelp: ["Un code ne sert qu’une fois. Il ouvre une session limitée qui permet seulement d’enregistrer une nouvelle clé d’accès ; les anciennes sont alors révoquées.", "A code works once. It opens a limited session that can only enrol a new passkey; the old ones are then revoked."],15  noBio: ["Aucune donnée biométrique ne quitte votre appareil : le serveur ne reçoit qu’une signature.", "No biometric data leaves your device: the server only receives a signature."],16  setupTitle: ["Enregistrer une clé d’accès", "Enrol a passkey"], setupFirst: ["Première configuration de l’administrateur {name}.", "First setup of the administrator {name}."],17  setupRecovery: ["Récupération du compte {name} : les clés existantes seront révoquées et toutes les sessions fermées.", "Recovery of the account {name}: existing passkeys will be revoked and every session closed."],18  setupLimited: ["Session de récupération : enregistrez une nouvelle clé d’accès pour retrouver l’accès. Les anciennes clés seront révoquées.", "Recovery session: enrol a new passkey to regain access. The old passkeys will be revoked."],19  name: ["Nom de cet appareil", "Name of this device"], create: ["Créer la clé d’accès", "Create the passkey"],20  invalid: ["Ce lien d’inscription est invalide, expiré ou déjà utilisé. Un nouveau lien se génère depuis le serveur (voir docs/SECURITY.md).", "This enrolment link is invalid, expired or already used. A new link is issued from the server (see docs/SECURITY.md)."],21  none: ["Aucune inscription n’est en attente. La configuration initiale est fermée.", "No enrolment is pending. Initial setup is closed."],22  codesTitle: ["Codes de récupération", "Recovery codes"], codesLead: ["Notez-les maintenant et rangez-les hors ligne : ils ne seront plus jamais affichés. Chacun ne sert qu’une fois.", "Write them down now and keep them offline: they will never be shown again. Each works once."],23  copy: ["Copier", "Copy"], copied: ["Copié", "Copied"], saved: ["Je les ai notés, ouvrir le studio", "I saved them, open the studio"], back: ["Retour à la connexion", "Back to sign-in"],24});2526function Frame({ children }: { children: React.ReactNode }) {27  return (28    <main className="mx-auto flex min-h-dvh max-w-md flex-col justify-center px-5 py-10" style={{ paddingBottom: "max(2.5rem, env(safe-area-inset-bottom))" }}>29      <a href="/" className="mb-8 self-start rounded-lg"><Wordmark /></a>30      {children}31    </main>32  );33}34const Alert = ({ text }: { text: string }) => <p role="alert" className="mt-4 rounded-xl border border-bad/40 bg-bad/10 px-4 py-3 text-sm">{text}</p>;3536export function LoginForm({ next }: { next: string }) {37  const locale = useLocale(), fr = locale === "fr", t = T(locale);38  const [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [supported, setSupported] = useState(true);39  const [recovery, setRecovery] = useState(false), [code, setCode] = useState("");40  useEffect(() => { setSupported(passkeysSupported()); }, []);41  const go = async () => {42    setBusy(true); setError(null);43    try { await signIn(); window.location.assign(next); } catch (e) { setError(passkeyMessage(e, fr)); setBusy(false); }44  };45  const useCode = async (ev: React.FormEvent) => {46    ev.preventDefault(); setBusy(true); setError(null);47    try { await api("/api/auth/recovery", { body: { code } }); window.location.assign("/admin/setup"); } catch (e) { setError(passkeyMessage(e, fr)); setBusy(false); }48  };49  return (50    <Frame>51      <h1 className="font-display text-4xl font-semibold tracking-tight">{t.signInTitle}</h1>52      <p className="mt-3 text-muted">{t.signInLead}</p>53      {!supported && <Alert text={t.unsupported} />}54      <button type="button" className="btn btn-primary mt-7 !min-h-14 w-full text-base" onClick={go} disabled={busy || !supported} autoFocus>55        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><circle cx="8" cy="14" r="4" /><path d="m11 11 9-9M16 6l3 3M14 8l2 2" /></svg>56        {busy && !recovery ? t.working : t.signIn}57      </button>58      {error && <Alert text={error} />}59      <p className="mt-4 text-sm text-faint">{t.noBio}</p>60      <div className="mt-8 border-t border-line pt-4">61        {!recovery ? <button type="button" className="min-h-11 text-sm font-semibold text-accent" onClick={() => setRecovery(true)}>{t.lost}</button> : (62          <form onSubmit={useCode} className="grid gap-3">63            <label className="grid gap-1 text-sm font-medium" htmlFor="rc">{t.code}64              <input id="rc" className="field font-mono" value={code} onChange={(e) => setCode(e.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} placeholder="xxxx-xxxx-xxxx-xxxx" required minLength={8} /></label>65            <p className="text-sm text-faint">{t.codeHelp}</p>66            <button className="btn" disabled={busy}>{t.useCode}</button>67          </form>68        )}69      </div>70    </Frame>71  );72}7374/** First setup and recovery. The token travels in the URL fragment, which browsers never send to servers or logs. */75export function SetupForm({ limitedSession, pending }: { limitedSession: boolean; pending: boolean }) {76  const locale = useLocale(), fr = locale === "fr", t = T(locale);77  const [token, setToken] = useState<string | null>(null);78  const [info, setInfo] = useState<{ purpose: "setup" | "recovery"; displayName: string } | null>(null);79  const [state, setState] = useState<"loading" | "ready" | "invalid" | "none">("loading");80  const [name, setName] = useState("Passkey"), [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null);81  const [codes, setCodes] = useState<string[] | null>(null), [copied, setCopied] = useState(false);8283  useEffect(() => {84    setName(deviceName());85    const raw = window.location.hash.slice(1);86    if (limitedSession && !raw) { void api<{ csrfToken?: string }>("/api/auth/session").then((s) => { setCsrf(s.csrfToken ?? null); setState("ready"); }); return; }87    if (!raw) { setState(pending ? "invalid" : "none"); return; }88    setToken(raw);89    // The address bar no longer shows the token once it has been read.90    window.history.replaceState(null, "", window.location.pathname);91    api<{ purpose: "setup" | "recovery"; displayName: string }>("/api/auth/setup/info", { body: { setupToken: raw } }).then((i) => { setInfo(i); setState("ready"); }).catch(() => setState("invalid"));92  }, [limitedSession, pending]);9394  const create = async (ev: React.FormEvent) => {95    ev.preventDefault(); setBusy(true); setError(null);96    try { const r = await enrol({ setupToken: token ?? undefined, name }); if (r.recoveryCodes) setCodes(r.recoveryCodes); else window.location.assign("/admin"); }97    catch (e) { setError(passkeyMessage(e, fr)); }98    setBusy(false);99  };100101  if (codes) return (102    <Frame>103      <h1 className="font-display text-3xl font-semibold tracking-tight">{t.codesTitle}</h1>104      <p className="mt-3 text-muted">{t.codesLead}</p>105      <ol className="mt-5 grid grid-cols-1 gap-2 rounded-xl border border-line bg-surface p-4 font-mono text-[0.9375rem] xs:grid-cols-2" data-testid="recovery-codes">{codes.map((c) => <li key={c}>{c}</li>)}</ol>106      <div className="mt-4 flex flex-wrap gap-3">107        <button type="button" className="btn" onClick={() => { void navigator.clipboard.writeText(codes.join("\n")).then(() => setCopied(true)); }}>{copied ? t.copied : t.copy}</button>108        <button type="button" className="btn btn-primary" onClick={() => window.location.assign("/admin")}>{t.saved}</button>109      </div>110    </Frame>111  );112  return (113    <Frame>114      <h1 className="font-display text-3xl font-semibold tracking-tight">{t.setupTitle}</h1>115      {state === "loading" && <p className="mt-4 text-muted" aria-busy="true">…</p>}116      {(state === "invalid" || state === "none") && <><Alert text={state === "invalid" ? t.invalid : t.none} /><a className="btn mt-5" href="/admin/login">{t.back}</a></>}117      {state === "ready" && (118        <form onSubmit={create} className="mt-4 grid gap-4">119          <p className="text-muted">{limitedSession && !info ? t.setupLimited : (info?.purpose === "recovery" ? t.setupRecovery : t.setupFirst).replace("{name}", info?.displayName ?? "")}</p>120          <label className="grid gap-1 text-sm font-medium" htmlFor="pk-name">{t.name}121            <input id="pk-name" className="field" value={name} onChange={(e) => setName(e.target.value)} maxLength={60} required /></label>122          <button className="btn btn-primary !min-h-14 text-base" disabled={busy || !passkeysSupported()}>{busy ? t.working : t.create}</button>123          {!passkeysSupported() && <Alert text={t.unsupported} />}124          {error && <Alert text={error} />}125          <p className="text-sm text-faint">{t.noBio}</p>126        </form>127      )}128    </Frame>129  );130}131
Files main
Menu

Theme