"use client"; import React, { useState } from "react"; import QRCode from "qrcode"; import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui"; import { useBranding } from "@/components/BrandingProvider"; import { call, type ApiError } from "@/lib/api"; import { useExternalEffect } from "@/lib/hooks"; type State = { uid: string; stage: "password" | "verify_email" | "two_factor" | "setup_two_factor" | "notice" | "news" | "done"; product: string; signupEnabled: boolean; loginHint?: string | null; screen?: "signin" | "signup"; name?: string; email?: string; sentTo?: string; method?: "totp" | "email" | "whatsapp"; methods?: string[]; why?: "admin" | "product"; notice?: { version: number; title: string; body: string }; updated?: boolean; redirectTo?: string; recoveryCodes?: string[]; }; /** * One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). The backend says which step comes next; * when it's done, the browser goes back to the product it came from. */ export function SignIn({ uid }: { uid: string }) { const branding = useBranding(); const [state, setState] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(false); const [mode, setMode] = useState<"signin" | "signup">("signin"); const [codes, setCodes] = useState<{ codes: string[]; next: State } | null>(null); const [opened, setOpened] = useState(false); // New recovery codes (2FA just set up, or moved in from Cross Events without them) are shown // first, whatever comes next. const go = (s: State) => { if (s.stage === "done" && s.redirectTo) { window.location.assign(s.redirectTo); return; } setState(s); }; const apply = (s: State) => { if (!opened) { setOpened(true); if (s.screen === "signup" && s.signupEnabled) setMode("signup"); } if (s.recoveryCodes?.length) { setCodes({ codes: s.recoveryCodes, next: s }); return; } go(s); }; useExternalEffect(() => { let alive = true; call("GET", `/interaction/${encodeURIComponent(uid)}/state`).then((r) => { if (!alive) return; if (r.ok) apply(r.data); else setError(r.error); }); return () => { alive = false; }; }, [uid]); const submit = async (path: string, body: unknown) => { setBusy(true); setError(null); const r = await call("POST", `/interaction/${encodeURIComponent(uid)}${path}`, body); setBusy(false); if (r.ok) apply(r.data); else setError(r.error); return r; }; const frame = (children: React.ReactNode) => {children}; if (codes) { return frame( { const next = codes.next; setCodes(null); go(next); }} />); } if (!state) { return frame(error ? ( <> We couldn't continue {error.message} ) :

Loading…

); } const err = error ? {error.message} : null; const fieldError = (name: string) => error?.fields?.[name] ?? null; switch (state.stage) { case "password": return frame(mode === "signin" ? submit("/password", b)} onSignUp={() => { setError(null); setMode("signup"); }} /> : submit("/signup", b)} onBack={() => { setError(null); setMode("signin"); }} />); case "verify_email": return frame(We sent a 6-digit code to {state.sentTo}. Enter it to confirm your email address.} busy={busy} err={err} onSubmit={(code) => submit("/verify-email", { code })} onResend={() => submit("/resend", {})} />); case "two_factor": return frame( submit("/two-factor", b)} onResend={() => submit("/resend", {})} />); case "setup_two_factor": return frame( submit("/two-factor/setup/confirm", b)} />); case "notice": return frame( submit("/notice", { version: state.notice!.version })} />); case "news": return frame( submit("/news", b)} />); default: return frame(

Taking you back…

); } } function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onSignUp: () => void }) { const branding = useBranding(); return (
{ e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}> Sign in to {branding.name} {err}
Forgot your password? {state.signupEnabled && }
); } function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean; err: React.ReactNode; fieldError: (n: string) => string | null; onSubmit: (b: object) => void; onBack: () => void }) { const branding = useBranding(); const [phone, setPhone] = useState(""); return (
{ e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true }); }}> Create your account {err} setPhone(e.target.value)} error={fieldError("phone")} hint="For WhatsApp messages, if you'd like them." /> {phone && } I've read the privacy notice} hint={fieldError("acceptNotice") ?? undefined} />

); } function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) { return (
{ e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}> {title} {err} {onResend &&

} ); } function TwoFactorStep({ state, busy, err, onSubmit, onResend }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onResend: () => void }) { const [recovery, setRecovery] = useState(false); if (recovery) { return (
{ e.preventDefault(); onSubmit({ recoveryCode: new FormData(e.currentTarget).get("recoveryCode") }); }}> Use a recovery code {err}

); } const sub = state.method === "totp" ? "Enter the 6-digit code from your authenticator app." : <>We sent a 6-digit code to {state.sentTo}.; return ( <> onSubmit({ code })} onResend={state.method === "totp" ? undefined : onResend} />

); } function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string; state: State; busy: boolean; err: React.ReactNode; setError: (e: ApiError | null) => void; onConfirm: (b: object) => void }) { const [started, setStarted] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string } | null>(null); const [qr, setQr] = useState(null); const start = async (method: string) => { setError(null); const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", `/interaction/${encodeURIComponent(uid)}/two-factor/setup`, { method }); if (!r.ok) return setError(r.error); setStarted(r.data); if (r.data.otpauthUrl) setQr(await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 })); }; const why = state.why === "admin" ? "Admins must use a second step when they sign in." : `${state.product} asks for a second step when you sign in.`; if (!started) { const labels: Record = { totp: ["An authenticator app", "Google Authenticator, Microsoft Authenticator, 1Password… Most secure, works without signal."], email: ["A code by email", `Sent to ${state.email}.`], whatsapp: ["A code on WhatsApp", "Sent to your mobile number."], }; return ( <> Set up two-step sign-in {err}
{(state.methods ?? []).map((m) => ( ))}
); } return (
{ e.preventDefault(); onConfirm({ method: started.method, code: new FormData(e.currentTarget).get("code") }); }}> We sent a code to {started.sentTo}.}> {started.method === "totp" ? "Scan the QR code" : "Enter the code"} {err} {qr && QR code for your authenticator app} {started.secret &&

Or type this key: {started.secret}

} ); } function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void }) { const text = codes.join("\n"); return ( <> Save your recovery codes
{text}
Download
); } function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) { return ( <> {state.notice!.title} {err}
{state.notice!.body}
); } function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void }) { const branding = useBranding(); return (
{ e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}> Would you like news from {branding.name}? {err} ); }