Repository Public
1"use client";2import { browserSupportsWebAuthn, startAuthentication, startRegistration } from "@simplewebauthn/browser";3import { useEffect, useState } from "react";4import { api, ApiClientError, setCsrf } from "@/lib/client-api";5import { I18nProvider, useT, type Locale } from "@/i18n";6import type { Key } from "@/i18n/messages";7import { IAlert, ICheck, IKey, ILogo, ISpinner } from "./icons";89/** Suggested name for a new passkey, from the device the browser reports. Editable before saving. */10export function deviceName(): string {11 const ua = navigator.userAgent;12 if (/iPhone/.test(ua)) return "iPhone";13 if (/iPad/.test(ua)) return "iPad";14 if (/Macintosh/.test(ua)) return navigator.maxTouchPoints > 1 ? "iPad" : "Mac";15 if (/Android/.test(ua)) return "Android";16 if (/Windows/.test(ua)) return "Windows";17 return "Passkey";18}1920/** Maps a WebAuthn / API failure to a sentence. A cancelled system prompt is not an error worth shouting about. */21export function authErrorKey(e: unknown): Key {22 if (e instanceof ApiClientError) {23 if (e.code === "network") return "err.network";24 if (e.code === "rate_limited") return "err.rate_limited";25 if (e.code === "invalid_setup_token") return "auth.err.token";26 if (e.code === "challenge_expired") return "auth.err.challenge";27 if (e.code === "login_failed") return "auth.err.login";28 return "auth.err.generic";29 }30 const name = (e as { name?: string })?.name;31 if (name === "NotAllowedError" || name === "AbortError") return "auth.err.cancelled";32 if (name === "InvalidStateError") return "auth.err.exists";33 if (name === "SecurityError") return "auth.err.security";34 return "auth.err.generic";35}3637function Frame({ children, title, subtitle }: { children: React.ReactNode; title: string; subtitle?: string }) {38 return (39 <main className="relative flex min-h-dvh items-center justify-center px-5 py-10">40 <div className="pointer-events-none absolute inset-0 opacity-50" aria-hidden style={{ background: "radial-gradient(90% 55% at 50% 0%, color-mix(in srgb, var(--accent) 30%, transparent), transparent 70%)" }} />41 <div className="fade-up relative w-full max-w-sm">42 <div className="mb-7 flex flex-col items-center text-center">43 <ILogo size={64} />44 <p className="mt-4 text-2xl font-extrabold tracking-tight">Music <span className="brand-text">SP</span></p>45 <h1 className="mt-5 text-lg font-bold">{title}</h1>46 {subtitle && <p className="mt-1.5 text-sm leading-relaxed text-muted">{subtitle}</p>}47 </div>48 {children}49 </div>50 </main>51 );52}5354function Unsupported() {55 const t = useT();56 const insecure = typeof window !== "undefined" && !window.isSecureContext;57 return (58 <div className="card p-4 text-sm leading-relaxed" role="alert">59 <p className="flex items-center gap-2 font-bold text-warn"><IAlert size={18} />{t("auth.unsupportedTitle")}</p>60 <p className="mt-2 text-muted">{t(insecure ? "auth.unsupportedInsecure" : "auth.unsupportedBrowser")}</p>61 </div>62 );63}6465function LoginInner({ next }: { next: string }) {66 const t = useT();67 const [busy, setBusy] = useState(false);68 const [err, setErr] = useState<Key | null>(null);69 const [supported, setSupported] = useState<boolean | null>(null);70 const [recovery, setRecovery] = useState(false);71 const [code, setCode] = useState("");72 useEffect(() => setSupported(browserSupportsWebAuthn()), []);7374 const signIn = async () => {75 setBusy(true); setErr(null);76 try {77 const { challengeId, options } = await api<{ challengeId: string; options: never }>("/api/v1/auth/login/options", { method: "POST", body: {} });78 // The browser shows the system dialog here (Face ID, Touch ID, device code or a nearby phone).79 const response = await startAuthentication({ optionsJSON: options });80 await api("/api/v1/auth/login/verify", { body: { challengeId, response } });81 window.location.assign(next);82 } catch (e) { setErr(authErrorKey(e)); setBusy(false); }83 };84 const submitCode = async () => {85 setBusy(true); setErr(null);86 try { await api("/api/v1/auth/recovery", { body: { code } }); window.location.assign("/compte?recovered=1"); }87 catch (e) { setErr(e instanceof ApiClientError && e.code === "login_failed" ? "auth.err.code" : authErrorKey(e)); setBusy(false); }88 };8990 return (91 <Frame title={t("auth.loginTitle")} subtitle={t("auth.loginSubtitle")}>92 {supported === false ? <Unsupported /> : (93 <button className="btn btn-primary w-full !min-h-12 !text-base" onClick={signIn} disabled={busy || supported === null}>{busy && !recovery ? <ISpinner size={18} /> : <IKey size={18} />}{t("auth.signIn")}</button>94 )}95 {err && <p className="mt-3 flex items-start gap-2 rounded-xl border border-[#6b2428] bg-[#2a1214] p-3 text-sm text-[#ffb4b4]" role="alert"><IAlert size={16} className="mt-0.5 flex-none" />{t(err)}</p>}96 <div className="mt-6 text-center">97 {!recovery ? <button className="text-sm font-semibold text-muted underline-offset-4 hover:text-ink hover:underline" onClick={() => setRecovery(true)}>{t("auth.noPasskey")}</button> : (98 <div className="card p-4 text-left">99 <p className="text-sm font-bold">{t("auth.recoveryTitle")}</p>100 <p className="mt-1 text-sm leading-relaxed text-muted">{t("auth.recoveryBody")}</p>101 <form className="mt-3 flex gap-2" onSubmit={(e) => { e.preventDefault(); void submitCode(); }}>102 <label htmlFor="code" className="sr-only">{t("auth.recoveryCode")}</label>103 <input id="code" className="input font-mono" placeholder="xxxx-xxxx-xxxx" autoComplete="one-time-code" autoCapitalize="none" spellCheck={false} value={code} onChange={(e) => setCode(e.target.value)} />104 <button className="btn" disabled={busy || code.trim().length < 8}>{t("auth.useCode")}</button>105 </form>106 <p className="mt-3 text-xs leading-relaxed text-faint">{t("auth.recoveryShell")}</p>107 </div>108 )}109 </div>110 <p className="mt-8 text-center text-xs leading-relaxed text-faint">{t("auth.privateNote")}</p>111 </Frame>112 );113}114115function SetupInner() {116 const t = useT();117 const [token, setToken] = useState<string | null>(null);118 const [info, setInfo] = useState<{ purpose: "setup" | "recovery" | "invite"; displayName: string; role: string } | null>(null);119 const [phase, setPhase] = useState<"loading" | "invalid" | "ready" | "done">("loading");120 const [name, setName] = useState("");121 const [busy, setBusy] = useState(false);122 const [err, setErr] = useState<Key | null>(null);123 const [codes, setCodes] = useState<string[] | null>(null);124 const [saved, setSaved] = useState(false);125 const [supported, setSupported] = useState(true);126127 useEffect(() => {128 // The token travels in the URL fragment: it is never sent in a request line, a Referer header or a proxy log.129 const raw = window.location.hash.slice(1);130 setSupported(browserSupportsWebAuthn()); setName(deviceName());131 if (!raw) { setPhase("invalid"); return; }132 setToken(raw);133 api<{ purpose: "setup" | "recovery" | "invite"; displayName: string; role: string }>("/api/v1/auth/setup/info", { body: { setupToken: raw } })134 .then((i) => { setInfo(i); setPhase("ready"); }).catch(() => setPhase("invalid"));135 }, []);136137 const enrol = async () => {138 if (!token) return;139 setBusy(true); setErr(null);140 try {141 const { challengeId, options } = await api<{ challengeId: string; options: never }>("/api/v1/auth/register/options", { body: { setupToken: token } });142 const response = await startRegistration({ optionsJSON: options });143 const r = await api<{ recoveryCodes: string[] | null }>("/api/v1/auth/register/verify", { body: { challengeId, response, name: name.trim() || deviceName(), setupToken: token } });144 history.replaceState(null, "", "/setup");145 setCodes(r.recoveryCodes); setPhase("done");146 } catch (e) { const k = authErrorKey(e); setErr(k); if (k === "auth.err.token") setPhase("invalid"); } finally { setBusy(false); }147 };148149 if (phase === "loading") return <Frame title={t("auth.setupTitle")}><div className="flex justify-center text-muted"><ISpinner /></div></Frame>;150 if (phase === "invalid") return (151 <Frame title={t("auth.linkInvalidTitle")} subtitle={t("auth.linkInvalidBody")}>152 <a href="/login" className="btn w-full">{t("auth.backToLogin")}</a>153 </Frame>154 );155 if (phase === "done") return (156 <Frame title={t("auth.doneTitle")} subtitle={t("auth.doneBody")}>157 {codes && (158 <div className="card p-4">159 <p className="flex items-center gap-2 text-sm font-bold text-warn"><IAlert size={16} />{t("auth.codesTitle")}</p>160 <p className="mt-1 text-sm leading-relaxed text-muted">{t("auth.codesBody")}</p>161 <ul className="mt-3 grid grid-cols-2 gap-2 font-mono text-sm" aria-label={t("auth.codesTitle")}>{codes.map((c) => <li key={c} className="rounded-lg bg-raised px-2 py-1.5 text-center tracking-wide">{c}</li>)}</ul>162 <button className="btn btn-sm mt-3 w-full" onClick={() => navigator.clipboard?.writeText(codes.join("\n")).catch(() => {})}>{t("auth.copyCodes")}</button>163 <label className="mt-4 flex items-start gap-2.5 text-sm"><input type="checkbox" className="mt-0.5 h-4 w-4 accent-[var(--accent)]" checked={saved} onChange={(e) => setSaved(e.target.checked)} /><span>{t("auth.codesSaved")}</span></label>164 </div>165 )}166 <button className="btn btn-primary mt-4 w-full !min-h-12" disabled={!!codes && !saved} onClick={() => window.location.assign("/")}><ICheck size={18} />{t("auth.enter")}</button>167 </Frame>168 );169 return (170 <Frame title={t(info?.purpose === "recovery" ? "auth.recoverTitle" : info?.purpose === "invite" ? "auth.inviteTitle" : "auth.setupTitle")}171 subtitle={t(info?.purpose === "recovery" ? "auth.recoverBody" : "auth.setupBody", { name: info?.displayName ?? "" })}>172 {!supported ? <Unsupported /> : (173 <form onSubmit={(e) => { e.preventDefault(); void enrol(); }}>174 <label className="label" htmlFor="pk-name">{t("auth.passkeyName")}</label>175 <input id="pk-name" className="input" value={name} maxLength={60} onChange={(e) => setName(e.target.value)} />176 <p className="mt-1.5 text-xs text-faint">{t("auth.passkeyNameHint")}</p>177 <button className="btn btn-primary mt-4 w-full !min-h-12 !text-base" disabled={busy}>{busy ? <ISpinner size={18} /> : <IKey size={18} />}{t("auth.createPasskey")}</button>178 </form>179 )}180 {err && <p className="mt-3 flex items-start gap-2 rounded-xl border border-[#6b2428] bg-[#2a1214] p-3 text-sm text-[#ffb4b4]" role="alert"><IAlert size={16} className="mt-0.5 flex-none" />{t(err)}</p>}181 <p className="mt-6 text-center text-xs leading-relaxed text-faint">{t("auth.biometricNote")}</p>182 </Frame>183 );184}185186/** Approval of a native app's pairing code by the signed-in account (see src/lib/auth.ts, device linking). */187function DeviceInner({ code: initial, csrfToken, displayName }: { code: string; csrfToken: string; displayName: string }) {188 const t = useT();189 const [code, setCode] = useState(initial);190 const [info, setInfo] = useState<{ deviceName: string; ip: string | null } | null>(null);191 const [phase, setPhase] = useState<"enter" | "confirm" | "approved" | "denied">("enter");192 const [busy, setBusy] = useState(false);193 const [err, setErr] = useState<Key | null>(null);194 const fail = (e: unknown) => setErr(e instanceof ApiClientError && e.code === "unknown_code" ? "device.err.code" : authErrorKey(e));195196 const lookup = async (c: string) => {197 setBusy(true); setErr(null);198 try { setCsrf(csrfToken); setInfo(await api("/api/v1/auth/device/info", { body: { userCode: c } })); setPhase("confirm"); }199 catch (e) { fail(e); } finally { setBusy(false); }200 };201 // The app opens this page with its code in the address: show what is being approved straight away.202 useEffect(() => { if (initial.replace(/-/g, "").length === 8) void lookup(initial); }, []); // eslint-disable-line react-hooks/exhaustive-deps203 const decide = async (approve: boolean) => {204 setBusy(true); setErr(null);205 try { setCsrf(csrfToken); await api("/api/v1/auth/device/decide", { body: { userCode: code, approve } }); setPhase(approve ? "approved" : "denied"); }206 catch (e) { fail(e); setPhase("enter"); } finally { setBusy(false); }207 };208 const error = err && <p className="mt-3 flex items-start gap-2 rounded-xl border border-[#6b2428] bg-[#2a1214] p-3 text-sm text-[#ffb4b4]" role="alert"><IAlert size={16} className="mt-0.5 flex-none" />{t(err)}</p>;209210 if (phase === "approved") return <Frame title={t("device.approvedTitle")} subtitle={t("device.approvedBody")}><a href="/" className="btn w-full"><ICheck size={18} />{t("device.backToPlayer")}</a></Frame>;211 if (phase === "denied") return <Frame title={t("device.deniedTitle")} subtitle={t("device.deniedBody")}><a href="/" className="btn w-full">{t("device.backToPlayer")}</a></Frame>;212 if (phase === "confirm" && info) return (213 <Frame title={t("device.confirmTitle")} subtitle={t("device.confirmBody", { name: displayName })}>214 <div className="card p-4 text-center">215 <p className="text-base font-bold">{info.deviceName || t("device.unnamed")}</p>216 <p className="mt-2 font-mono text-2xl font-bold tracking-widest">{code}</p>217 <p className="mt-2 text-xs leading-relaxed text-faint">{t("device.sameCode")}</p>218 </div>219 <button className="btn btn-primary mt-4 w-full !min-h-12 !text-base" disabled={busy} onClick={() => void decide(true)}>{busy ? <ISpinner size={18} /> : <ICheck size={18} />}{t("device.approve")}</button>220 <button className="btn mt-2 w-full" disabled={busy} onClick={() => void decide(false)}>{t("device.deny")}</button>221 {error}222 <p className="mt-6 text-center text-xs leading-relaxed text-faint">{t("device.note")}</p>223 </Frame>224 );225 return (226 <Frame title={t("device.enterTitle")} subtitle={t("device.enterBody")}>227 <form onSubmit={(e) => { e.preventDefault(); void lookup(code); }}>228 <label className="label" htmlFor="device-code">{t("device.code")}</label>229 <input id="device-code" className="input text-center font-mono text-lg tracking-widest" placeholder="XXXX-XXXX" autoCapitalize="characters" autoComplete="off" spellCheck={false} maxLength={9} value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} />230 <button className="btn btn-primary mt-4 w-full !min-h-12" disabled={busy || code.replace(/[^A-Z0-9]/g, "").length !== 8}>{busy ? <ISpinner size={18} /> : <IKey size={18} />}{t("device.continue")}</button>231 </form>232 {error}233 </Frame>234 );235}236237export const LoginForm = ({ locale, next = "/" }: { locale: Locale; next?: string }) => <I18nProvider locale={locale}><LoginInner next={next} /></I18nProvider>;238export const DeviceLinkForm = ({ locale, code, csrfToken, displayName }: { locale: Locale; code: string; csrfToken: string; displayName: string }) => <I18nProvider locale={locale}><DeviceInner code={code} csrfToken={csrfToken} displayName={displayName} /></I18nProvider>;239export const SetupForm = ({ locale }: { locale: Locale }) => <I18nProvider locale={locale}><SetupInner /></I18nProvider>;240