mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-31 20:58:04 +00:00
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.
This commit is contained in:
@@ -0,0 +1,127 @@
|
||||
import { useState } from 'react';
|
||||
import { useAuth } from '@/context/AuthContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
|
||||
export function MfaChallenge({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentPropsWithoutRef<'div'>) {
|
||||
const { submitMfa, cancelMfa } = useAuth();
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [useBackup, setUseBackup] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setIsLoading(true);
|
||||
const result = await submitMfa(code, { isBackupCode: useBackup });
|
||||
if (!result.success) {
|
||||
const retryNote = result.retryAfter ? ` (try again in ${Math.ceil(result.retryAfter / 60)} min)` : '';
|
||||
setError((result.error || 'Verification failed') + retryNote);
|
||||
setCode('');
|
||||
}
|
||||
setIsLoading(false);
|
||||
};
|
||||
|
||||
const handleToggleBackup = () => {
|
||||
setUseBackup((v) => !v);
|
||||
setCode('');
|
||||
setError('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn('grid min-h-svh md:grid-cols-2', className)} {...props}>
|
||||
{/* Branding panel (matches Login layout) */}
|
||||
<div className="relative hidden md:flex flex-col items-center justify-center bg-zinc-950 overflow-hidden">
|
||||
<div
|
||||
className="absolute inset-0 opacity-[0.15]"
|
||||
style={{
|
||||
backgroundImage: 'radial-gradient(circle, rgba(255,255,255,0.7) 1px, transparent 1px)',
|
||||
backgroundSize: '24px 24px',
|
||||
}}
|
||||
/>
|
||||
<div className="relative z-10 flex flex-col items-center gap-6 px-12">
|
||||
<img
|
||||
src="/sencho-logo-dark.png"
|
||||
alt="Sencho"
|
||||
className="w-28 h-28"
|
||||
draggable={false}
|
||||
/>
|
||||
<div className="text-center">
|
||||
<h1 className="text-4xl font-medium text-foreground tracking-tight">Sencho</h1>
|
||||
<p className="text-base text-zinc-400 mt-2">Docker Compose Management</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="absolute bottom-0 left-0 right-0 h-px bg-brand" />
|
||||
</div>
|
||||
|
||||
{/* Form panel */}
|
||||
<div className="flex flex-col items-center justify-center bg-background px-6 py-12">
|
||||
<div className="flex items-center gap-2.5 mb-10 md:hidden">
|
||||
<img src="/sencho-logo-light.png" alt="Sencho" className="w-8 h-8 dark:hidden" draggable={false} />
|
||||
<img src="/sencho-logo-dark.png" alt="Sencho" className="w-8 h-8 hidden dark:block" draggable={false} />
|
||||
<span className="text-lg font-semibold tracking-tight">Sencho</span>
|
||||
</div>
|
||||
|
||||
<div className="w-full max-w-sm">
|
||||
<div className="mb-8">
|
||||
<h2 className="text-2xl font-bold tracking-tight">Two-factor authentication</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{useBackup
|
||||
? 'Enter one of your saved backup codes to continue.'
|
||||
: 'Open your authenticator app and enter the 6-digit code.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="flex flex-col gap-5">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="mfa-code">{useBackup ? 'Backup code' : 'Verification code'}</Label>
|
||||
<Input
|
||||
id="mfa-code"
|
||||
type="text"
|
||||
inputMode={useBackup ? 'text' : 'numeric'}
|
||||
autoComplete="one-time-code"
|
||||
autoFocus
|
||||
required
|
||||
maxLength={useBackup ? 12 : 6}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
className="font-mono tabular-nums tracking-widest text-center"
|
||||
placeholder={useBackup ? 'ABCDE-FGHIJ' : '123456'}
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="text-sm text-destructive text-center">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" className="w-full" disabled={isLoading || !code}>
|
||||
{isLoading ? 'Verifying...' : 'Verify and sign in'}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-sm text-muted-foreground hover:text-foreground text-center transition-colors"
|
||||
onClick={handleToggleBackup}
|
||||
>
|
||||
{useBackup ? 'Use your authenticator app instead' : 'Use a backup code instead'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-sm text-muted-foreground/70 hover:text-foreground text-center transition-colors"
|
||||
onClick={cancelMfa}
|
||||
>
|
||||
Cancel and sign out
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user