Files
sencho/frontend/src/components/mfa/MfaEnrollDialog.tsx
T
Anso 7d78c9fe22 feat(auth): add TOTP two-factor authentication with backup codes (#615)
* feat(auth): add TOTP two-factor authentication with backup codes

Adds RFC 6238 time-based one-time password support to every tier,
integrated with the existing password and SSO login paths.

Backend:
- New MfaService wrapping otplib with a plus or minus 1 step tolerance,
  base32 secret generation, and hashed single-use backup codes (bcrypt).
- user_mfa and mfa_used_tokens tables in DatabaseService. The second
  table is a DB-backed replay blacklist, purged on a 60s interval.
- authMiddleware now recognizes an mfa_pending scope. A token carrying
  that scope is rejected on every route except the MFA challenge and
  logout, so no API surface is reachable before the second factor
  clears.
- /api/auth/login issues only a short-lived mfa_pending cookie when the
  user has MFA enrolled. /api/auth/login/mfa consumes that cookie,
  verifies the code (or backup code), and swaps in a real session.
- /api/auth/mfa/* routes for status, enrol/start, enrol/confirm,
  disable, backup-code regenerate, and SSO-bypass opt-in.
- Admin recovery path: POST /api/users/:id/mfa/reset clears the target's
  MFA state, bumps token_version, and writes an audit log entry.
- CLI emergency fallback: backend/src/cli/resetMfa.ts is wired via
  `npm run reset-mfa <username>` and also exported for tests.
- SSO flows (LDAP and OIDC) gate on user_mfa.sso_enforce_mfa before
  issuing a session; default behaviour keeps the SSO path frictionless.
- Per-user lockout after 5 consecutive failed codes (15 min).

Frontend:
- AppStatus gains an mfa-challenge branch driven by /api/auth/status.
- New MfaChallenge screen, MfaEnrollDialog (QR plus manual secret plus
  backup codes), MfaDisableDialog, MfaBackupCodesDialog.
- Account section shows a Two-factor authentication card with enrol,
  regenerate, disable, and the SSO-enforce toggle (shown only when SSO
  providers are configured).
- Users section gains a Reset 2FA action for admins.

Docs:
- New user guide at features/two-factor-authentication.mdx.
- New admin guide at operations/two-factor-admin.mdx.
- SSO page cross-links to the 2FA doc.

* fix(mfa): drop unused TEST_PASSWORD import and stale eslint disable

* fix(mfa): simplify e2e openAccountSettings helper to match working pattern

* fix(mfa): make e2e suite self-contained and always clean up

Test #2 called loginAs() before the MFA challenge step, which waited for
the dashboard indicator that never appears once the previous test enrolled
the user. That timeout skipped the rest of the serial block, including
the disable step, leaving MFA enabled and breaking every later spec.

Two fixes:

- Tests #2 and #3 now navigate directly to the login page instead of
  piggybacking on loginAs, which only handles the password-only path.
- A new afterAll hook unconditionally disables MFA via the API using two
  unused backup codes, so the DB is reset even if a test fails midway.

* fix(e2e): use backup code for mfa recovery to avoid totp replay race

The final recovery step in the backup-code replay test previously
generated a fresh TOTP to sign back in. When the timing landed inside
the same 30-second window that test #2 consumed, the server's replay
blacklist correctly rejected it, producing a ~50% flake rate. Backup
codes are single-use and sidestep the replay window, so the recovery
becomes deterministic.

* fix(e2e): drive mfa disable test through the challenge screen

Test #4 called loginAs after test #3 left MFA enabled, but loginAs
waits for the dashboard indicator and does not handle the challenge
screen, so it timed out. Drive the login manually, satisfy the
challenge with a backup code, and use a backup code for the disable
step too to avoid any TOTP replay-window race against earlier tests
in the serial block.
2026-04-15 18:45:51 -04:00

251 lines
9.2 KiB
TypeScript

import { useEffect, useState } from 'react';
import { QRCodeSVG } from 'qrcode.react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Copy, Download, ChevronDown, ChevronRight } from 'lucide-react';
import { toast } from '@/components/ui/toast-store';
import { apiFetch } from '@/lib/api';
interface MfaEnrollDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
onEnrolled: () => void;
}
type Step = 'qr' | 'confirm' | 'backup';
/**
* Format a raw base32 secret as groups of 4 characters so it is easier for
* users typing it into authenticator apps manually.
*/
function formatSecret(secret: string): string {
return secret.replace(/(.{4})/g, '$1 ').trim();
}
export function MfaEnrollDialog({ open, onOpenChange, onEnrolled }: MfaEnrollDialogProps) {
const [step, setStep] = useState<Step>('qr');
const [loading, setLoading] = useState(false);
const [otpauthUri, setOtpauthUri] = useState('');
const [secret, setSecret] = useState('');
const [showSecret, setShowSecret] = useState(false);
const [code, setCode] = useState('');
const [error, setError] = useState('');
const [backupCodes, setBackupCodes] = useState<string[]>([]);
// When the dialog opens, start enrolment so the QR is ready immediately.
useEffect(() => {
if (!open) return;
let cancelled = false;
setStep('qr');
setCode('');
setError('');
setBackupCodes([]);
setShowSecret(false);
setLoading(true);
apiFetch('/auth/mfa/enroll/start', { method: 'POST', localOnly: true })
.then(async (r) => {
const data = await r.json().catch(() => ({}));
if (cancelled) return;
if (!r.ok) {
toast.error(data?.error || 'Failed to start enrolment');
onOpenChange(false);
return;
}
setOtpauthUri(data.otpauthUri);
setSecret(data.secret);
})
.catch((e) => {
if (cancelled) return;
toast.error(e?.message || 'Failed to start enrolment');
onOpenChange(false);
})
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [open, onOpenChange]);
const handleConfirm = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
const res = await apiFetch('/auth/mfa/enroll/confirm', {
method: 'POST',
localOnly: true,
body: JSON.stringify({ code }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
setError(data?.error || 'Verification failed');
return;
}
setBackupCodes(data.backupCodes || []);
setStep('backup');
} catch (err) {
setError((err as Error)?.message || 'Verification failed');
} finally {
setLoading(false);
}
};
const handleCopySecret = async () => {
try {
await navigator.clipboard.writeText(secret);
toast.success('Secret copied to clipboard');
} catch {
toast.error('Could not copy to clipboard');
}
};
const handleCopyBackupCodes = async () => {
try {
await navigator.clipboard.writeText(backupCodes.join('\n'));
toast.success('Backup codes copied');
} catch {
toast.error('Could not copy to clipboard');
}
};
const handleDownloadBackupCodes = () => {
const blob = new Blob([
'Sencho backup codes\n',
'Each code can be used once. Keep this file somewhere safe.\n\n',
backupCodes.join('\n'),
'\n',
], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'sencho-backup-codes.txt';
a.click();
URL.revokeObjectURL(url);
};
const handleFinish = () => {
onOpenChange(false);
onEnrolled();
};
return (
<Dialog
open={open}
onOpenChange={(next) => {
// Once backup codes have been shown, a close is equivalent to
// finishing, so the parent can refresh the status card.
if (!next && step === 'backup') onEnrolled();
onOpenChange(next);
}}
>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{step === 'qr' && 'Set up two-factor authentication'}
{step === 'confirm' && 'Confirm your authenticator'}
{step === 'backup' && 'Save your backup codes'}
</DialogTitle>
<DialogDescription className="sr-only">
Enrol a time-based one-time password (TOTP) authenticator and save
single-use backup codes.
</DialogDescription>
</DialogHeader>
{step === 'qr' && (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
Scan the QR code with an authenticator app such as 1Password, Bitwarden, or Google Authenticator.
</p>
<div className="flex justify-center rounded-md border border-card-border bg-card p-4 shadow-card-bevel">
{otpauthUri
? <QRCodeSVG value={otpauthUri} size={176} />
: <div className="h-[176px] w-[176px] bg-muted/20 animate-pulse rounded" />
}
</div>
<button
type="button"
onClick={() => setShowSecret((v) => !v)}
className="flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
{showSecret ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
Can&apos;t scan? Show secret key
</button>
{showSecret && (
<div className="flex items-center gap-2">
<code className="flex-1 rounded-md border border-card-border bg-card px-3 py-2 font-mono text-xs tracking-wider break-all shadow-card-bevel">
{formatSecret(secret) || '...'}
</code>
<Button type="button" size="icon" variant="outline" onClick={handleCopySecret} disabled={!secret}>
<Copy className="w-4 h-4" strokeWidth={1.5} />
</Button>
</div>
)}
<DialogFooter className="gap-2 sm:gap-2">
<Button type="button" variant="ghost" onClick={() => onOpenChange(false)}>Cancel</Button>
<Button type="button" onClick={() => setStep('confirm')} disabled={!otpauthUri || loading}>
Next
</Button>
</DialogFooter>
</div>
)}
{step === 'confirm' && (
<form onSubmit={handleConfirm} className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
Enter the 6-digit code shown in your authenticator app to confirm enrolment.
</p>
<div className="grid gap-2">
<Label htmlFor="mfa-confirm-code">Verification code</Label>
<Input
id="mfa-confirm-code"
type="text"
inputMode="numeric"
autoComplete="one-time-code"
autoFocus
required
maxLength={6}
value={code}
onChange={(e) => setCode(e.target.value)}
className="font-mono tabular-nums tracking-widest text-center"
placeholder="123456"
/>
</div>
{error && <div className="text-sm text-destructive">{error}</div>}
<DialogFooter className="gap-2 sm:gap-2">
<Button type="button" variant="ghost" onClick={() => setStep('qr')} disabled={loading}>Back</Button>
<Button type="submit" disabled={loading || code.length !== 6}>
{loading ? 'Verifying...' : 'Verify'}
</Button>
</DialogFooter>
</form>
)}
{step === 'backup' && (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">
Each code can be used once if your authenticator is unavailable. Store them somewhere safe; they will not be shown again.
</p>
<div className="grid grid-cols-2 gap-2 rounded-md border border-card-border bg-card p-4 font-mono text-sm tabular-nums tracking-wider shadow-card-bevel">
{backupCodes.map((c) => (
<div key={c} className="text-center">{c}</div>
))}
</div>
<div className="flex gap-2">
<Button type="button" variant="outline" className="flex-1" onClick={handleCopyBackupCodes}>
<Copy className="w-4 h-4 mr-2" strokeWidth={1.5} />
Copy all
</Button>
<Button type="button" variant="outline" className="flex-1" onClick={handleDownloadBackupCodes}>
<Download className="w-4 h-4 mr-2" strokeWidth={1.5} />
Download
</Button>
</div>
<DialogFooter>
<Button type="button" onClick={handleFinish}>I&apos;ve saved these</Button>
</DialogFooter>
</div>
)}
</DialogContent>
</Dialog>
);
}