Repository navigation
feat: SPA auth flows: PKCE callbacks, password recovery, TOTP MFA and step-up #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JOY (JOY)
wants to merge
2
commits into
ccr-2d7e26ff-ad5z1y
Choose a base branch
from
feat/spa-auth-flows
base: ccr-2d7e26ff-ad5z1y
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,258 @@ | ||
| import { useQuery } from '@tanstack/react-query'; | ||
| import { useState, type FormEvent } from 'react'; | ||
| import { useTranslations } from 'use-intl'; | ||
| import { auth, authErrorMessage } from '../lib/auth.ts'; | ||
| import { Badge } from '@crove/ui/components/badge'; | ||
| import { Button } from '@crove/ui/components/button'; | ||
| import { Card } from '@crove/ui/components/card'; | ||
| import { Input } from '@crove/ui/components/input'; | ||
| import { Label } from '@crove/ui/components/label'; | ||
| import { ErrorText, Notice, Spinner } from './ui.tsx'; | ||
|
|
||
| interface Enrollment { | ||
| factorId: string; | ||
| qrCode: string; | ||
| secret: string; | ||
| } | ||
|
|
||
| // The signed-in user's Supabase Auth MFA factors; `totp` lists the verified ones. | ||
| export function useFactors() { | ||
| return useQuery({ | ||
| queryKey: ['auth', 'factors'], | ||
| queryFn: async () => { | ||
| const { data, error } = await auth().mfa.listFactors(); | ||
| if (error) throw error; | ||
| return data; | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| // Verifies a code from the user's authenticator app, which raises the session to aal2. | ||
| export function MfaChallengeForm({ onVerified }: { onVerified: () => Promise<void> | void }) { | ||
| const root = useTranslations(); | ||
| const t = useTranslations('twoFactor'); | ||
| const [code, setCode] = useState(''); | ||
| const [busy, setBusy] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
|
|
||
| async function submit(event: FormEvent) { | ||
| event.preventDefault(); | ||
| setBusy(true); | ||
| setError(null); | ||
| try { | ||
| const { data: factors, error: listError } = await auth().mfa.listFactors(); | ||
| if (listError) return setError(authErrorMessage(listError, root)); | ||
| const factor = factors.totp[0]; | ||
| if (!factor) return setError(t('noFactor')); | ||
| const { error: verifyError } = await auth().mfa.challengeAndVerify({ factorId: factor.id, code: code.trim() }); | ||
| if (verifyError) { | ||
| setCode(''); | ||
| return setError(authErrorMessage(verifyError, root)); | ||
| } | ||
| await onVerified(); | ||
| } finally { | ||
| setBusy(false); | ||
| } | ||
| } | ||
|
|
||
| return ( | ||
| <form className="space-y-3" onSubmit={submit}> | ||
| <Label className="flex-col items-stretch gap-1 font-normal"> | ||
| <span className="text-muted-foreground">{t('code')}</span> | ||
| <Input | ||
| required | ||
| autoFocus | ||
| inputMode="numeric" | ||
| autoComplete="one-time-code" | ||
| pattern="[0-9]{6}" | ||
| maxLength={6} | ||
| placeholder={t('codePlaceholder')} | ||
| value={code} | ||
| onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))} | ||
| /> | ||
| </Label> | ||
| {error && <ErrorText>{error}</ErrorText>} | ||
| <Button type="submit" size="lg" className="w-full" disabled={busy}> | ||
| {busy ? t('checking') : t('confirm')} | ||
| </Button> | ||
| </form> | ||
| ); | ||
| } | ||
|
|
||
| // TOTP enrollment for the signed-in user (Supabase Auth MFA). A verified factor makes the next sign-in aal2. | ||
| export function TwoFactorCard({ onEnabled }: { onEnabled?: () => void }) { | ||
| const root = useTranslations(); | ||
| const t = useTranslations('twoFactor'); | ||
| const factors = useFactors(); | ||
| const [enrollment, setEnrollment] = useState<Enrollment | null>(null); | ||
| const [code, setCode] = useState(''); | ||
| const [busy, setBusy] = useState(false); | ||
| const [error, setError] = useState<string | null>(null); | ||
| const [notice, setNotice] = useState<string | null>(null); | ||
| const verified = factors.data?.totp ?? []; | ||
|
|
||
| async function run(action: () => Promise<string | null>) { | ||
| setBusy(true); | ||
| setError(null); | ||
| setNotice(null); | ||
| try { | ||
| setError(await action()); | ||
| } finally { | ||
| setBusy(false); | ||
| await factors.refetch(); | ||
| } | ||
| } | ||
|
|
||
| const start = () => | ||
| run(async () => { | ||
| // An abandoned setup leaves an unverified factor behind; remove it so they do not pile up. | ||
| for (const f of factors.data?.all ?? []) { | ||
| if (f.factor_type === 'totp' && f.status !== 'verified') await auth().mfa.unenroll({ factorId: f.id }); | ||
| } | ||
| const { data, error: e } = await auth().mfa.enroll({ factorType: 'totp', issuer: 'Crove' }); | ||
| if (e) return authErrorMessage(e, root); | ||
| setCode(''); | ||
| setEnrollment({ factorId: data.id, qrCode: data.totp.qr_code, secret: data.totp.secret }); | ||
| return null; | ||
| }); | ||
|
|
||
| const confirm = (event: FormEvent) => { | ||
| event.preventDefault(); | ||
| if (!enrollment) return; | ||
| void run(async () => { | ||
| const { error: e } = await auth().mfa.challengeAndVerify({ factorId: enrollment.factorId, code: code.trim() }); | ||
| if (e) return authErrorMessage(e, root); | ||
| setEnrollment(null); | ||
| setNotice(t('enabled')); | ||
| onEnabled?.(); | ||
| return null; | ||
| }); | ||
| }; | ||
|
|
||
| const cancel = () => | ||
| run(async () => { | ||
| if (enrollment) await auth().mfa.unenroll({ factorId: enrollment.factorId }); | ||
| setEnrollment(null); | ||
| return null; | ||
| }); | ||
|
|
||
| const disable = (factorId: string) => { | ||
| if (!window.confirm(t('confirmDisable'))) return; | ||
| void run(async () => { | ||
| const { error: e } = await auth().mfa.unenroll({ factorId }); | ||
| if (e) return authErrorMessage(e, root); | ||
| setNotice(t('disabled')); | ||
| return null; | ||
| }); | ||
| }; | ||
|
|
||
| return ( | ||
| <Card className="block p-4"> | ||
| <div className="flex items-center justify-between gap-2"> | ||
| <p className="text-xs font-medium tracking-wide uppercase text-subtle-foreground">{t('title')}</p> | ||
| {factors.isSuccess && (verified.length > 0 ? <Badge variant="success">{t('on')}</Badge> : <Badge variant="secondary">{t('off')}</Badge>)} | ||
| </div> | ||
| <p className="mt-2 text-sm text-muted-foreground">{t('intro')}</p> | ||
| <div className="mt-4 space-y-3"> | ||
| {factors.isLoading && <Spinner />} | ||
| {factors.error && <ErrorText>{authErrorMessage(factors.error as { code?: string; message: string }, root)}</ErrorText>} | ||
| {enrollment ? ( | ||
| <form className="space-y-3" onSubmit={confirm}> | ||
| <p className="text-sm text-muted-foreground">{t('scan')}</p> | ||
| {/* The QR code draws black modules on a transparent background: it needs a light backdrop in both themes. */} | ||
| <img src={enrollment.qrCode} alt={t('qrAlt')} className="h-44 w-44 rounded-lg bg-primary-foreground p-2" /> | ||
| <div className="text-xs text-subtle-foreground"> | ||
| {t('manualKey')} | ||
| <code className="mt-1 block break-all font-mono text-sm text-foreground" aria-label={t('setupKey')}> | ||
| {enrollment.secret} | ||
| </code> | ||
| </div> | ||
| <Label className="flex-col items-stretch gap-1 font-normal"> | ||
| <span className="text-muted-foreground">{t('code')}</span> | ||
| <Input | ||
| required | ||
| inputMode="numeric" | ||
| autoComplete="one-time-code" | ||
| pattern="[0-9]{6}" | ||
| maxLength={6} | ||
| placeholder={t('codePlaceholder')} | ||
| value={code} | ||
| onChange={(e) => setCode(e.target.value.replace(/\D/g, ''))} | ||
| /> | ||
| </Label> | ||
| <div className="flex gap-2"> | ||
| <Button type="submit" disabled={busy}> | ||
| {t('confirm')} | ||
| </Button> | ||
| <Button type="button" variant="ghost" disabled={busy} onClick={() => void cancel()}> | ||
| {root('common.cancel')} | ||
| </Button> | ||
| </div> | ||
| </form> | ||
| ) : factors.isSuccess && verified.length > 0 ? ( | ||
| verified.map((f) => ( | ||
| <Button key={f.id} variant="destructive" disabled={busy} onClick={() => disable(f.id)}> | ||
| {t('disable')} | ||
| </Button> | ||
| )) | ||
| ) : ( | ||
| factors.isSuccess && ( | ||
| <Button disabled={busy} onClick={() => void start()}> | ||
| {busy ? <Spinner /> : null} | ||
| {t('enable')} | ||
| </Button> | ||
| ) | ||
| )} | ||
| {error && <ErrorText>{error}</ErrorText>} | ||
| {notice && <Notice>{notice}</Notice>} | ||
| </div> | ||
| </Card> | ||
| ); | ||
| } | ||
|
|
||
| // Shown when the kernel answers STEP_UP_REQUIRED (policy P11): approving and other R3 work need a second factor | ||
| // verified in the last 5 minutes. With a factor, the user enters a fresh code; without one, they enable it here | ||
| // (or, where `enroll` is false, in the two-factor card on the same page). Either way `onVerified` repeats the request | ||
| // that was refused, which `action` names; `onCancel` drops it. | ||
| export function StepUpPrompt({ | ||
| action, | ||
| onVerified, | ||
| onCancel, | ||
| enroll = true, | ||
| }: { | ||
| action: string; | ||
| onVerified: () => void; | ||
| onCancel?: () => void; | ||
| enroll?: boolean; | ||
| }) { | ||
| const root = useTranslations(); | ||
| const t = useTranslations('twoFactor.stepUp'); | ||
| const factors = useFactors(); | ||
| if (factors.isLoading) return <Spinner />; | ||
| if (factors.error) return <ErrorText>{authErrorMessage(factors.error as { code?: string; message: string }, root)}</ErrorText>; | ||
| const pending = <p className="text-sm text-muted-foreground">{t('pending', { action })}</p>; | ||
| const cancel = onCancel && ( | ||
| <Button type="button" variant="ghost" onClick={onCancel}> | ||
| {t('cancel')} | ||
| </Button> | ||
| ); | ||
| if ((factors.data?.totp.length ?? 0) > 0) { | ||
|
JOY marked this conversation as resolved.
|
||
| return ( | ||
| <Card className="block max-w-sm space-y-3 p-4"> | ||
| <p className="text-sm font-medium text-foreground">{t('title')}</p> | ||
| <p className="text-sm text-muted-foreground">{t('recent')}</p> | ||
| {pending} | ||
| <MfaChallengeForm onVerified={onVerified} /> | ||
| {cancel} | ||
| </Card> | ||
| ); | ||
| } | ||
| return ( | ||
| <div className="max-w-md space-y-3"> | ||
| <p className="text-sm text-muted-foreground">{enroll ? t('enrollHere') : t('enrollBeside')}</p> | ||
| {pending} | ||
| {enroll && <TwoFactorCard onEnabled={onVerified} />} | ||
| {cancel} | ||
| </div> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.