Sign-in lockout with console unlock, and forgotten-password reset
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s
- Wrong passwords in a row are counted across every device and kept in the database. The first 3 are free; from the 3rd the next attempt waits 15 s, 30 s, 1, 2, 5, 15 and 30 minutes; the 10th locks sign-in until the unlock code printed to the server log (and saved to unlock-code.txt) is entered. Signed-in devices keep working. Only one password check runs at a time, so parallel guesses cannot skip a wait. - "Forgot password?" prints a reset code to the log (reset-code.txt), valid once for 15 minutes. It sets a new password, signs out every device, lifts any lockout and signs in. Asking again while a code is valid prints nothing new. - Codes are stored hashed; wrong codes count toward the per-address limit. RESET_ADMIN_PASSWORD also lifts a lockout. - Sign-in page: a live countdown during a wait, an unlock step and a reset step. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
fe94dbf876
commit
917954d12d
7 changed files with 522 additions and 18 deletions
|
|
@ -1,7 +1,7 @@
|
|||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { KeyRound, LockKeyhole } from 'lucide-react';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { api, errorMessage } from '@/lib/api';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { KeyRound, LockKeyhole, LockKeyholeOpen, Timer } from 'lucide-react';
|
||||
import { useEffect, useState, type FormEvent } from 'react';
|
||||
import { api, ApiError, errorMessage } from '@/lib/api';
|
||||
import { qk } from '@/lib/queries';
|
||||
import { useDocumentTitle } from '@/lib/util';
|
||||
import { Button, Callout, Field, Input } from '@/ui';
|
||||
|
|
@ -32,40 +32,215 @@ function AuthFrame({ title, subtitle, children }: { title: string; subtitle: str
|
|||
);
|
||||
}
|
||||
|
||||
/** Seconds left until `until` (a timestamp), ticking every second; 0 once it has passed. */
|
||||
function useCountdown(until: number): number {
|
||||
const [, tick] = useState(0);
|
||||
const left = Math.max(0, Math.ceil((until - Date.now()) / 1000));
|
||||
useEffect(() => {
|
||||
if (left <= 0) return;
|
||||
const id = window.setInterval(() => tick((n) => n + 1), 1000);
|
||||
return () => window.clearInterval(id);
|
||||
}, [left > 0]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
return left;
|
||||
}
|
||||
|
||||
const clockText = (s: number) => (s < 60 ? `${s}s` : `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`);
|
||||
|
||||
/** Retry-after seconds the server attached to an error, if any. */
|
||||
function retryAfterOf(err: unknown): number {
|
||||
const details = err instanceof ApiError ? (err.details as { retryAfter?: unknown } | undefined) : undefined;
|
||||
return typeof details?.retryAfter === 'number' ? details.retryAfter : 0;
|
||||
}
|
||||
|
||||
/** Brings the gate through after a successful sign-in or reset, dropping anything cached from a previous session. */
|
||||
function useSignedIn() {
|
||||
const qc = useQueryClient();
|
||||
return () => {
|
||||
qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'auth' });
|
||||
qc.setQueryData(qk.auth, { configured: true, authenticated: true });
|
||||
};
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
useDocumentTitle('Sign in');
|
||||
const qc = useQueryClient();
|
||||
const signedIn = useSignedIn();
|
||||
// Whether sign-in is locked or waiting, so the page opens on the right step after a reload.
|
||||
const guard = useQuery({ queryKey: ['auth', 'guard'], queryFn: () => api.get<{ locked?: boolean; retryAfter?: number }>('/api/auth/status'), staleTime: 0 });
|
||||
const [step, setStep] = useState<'password' | 'unlock' | 'reset'>('password');
|
||||
const [notice, setNotice] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [waitUntil, setWaitUntil] = useState(0);
|
||||
const wait = useCountdown(waitUntil);
|
||||
|
||||
useEffect(() => {
|
||||
if (guard.data?.locked) setStep('unlock');
|
||||
else if (guard.data?.retryAfter) setWaitUntil(Date.now() + guard.data.retryAfter * 1000);
|
||||
}, [guard.data]);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!password) return;
|
||||
if (!password || wait > 0) return;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setNotice('');
|
||||
try {
|
||||
await api.post('/api/auth/login', { password });
|
||||
// Drop anything cached from a previous session, then let the gate through.
|
||||
qc.removeQueries({ predicate: (q) => q.queryKey[0] !== 'auth' });
|
||||
qc.setQueryData(qk.auth, { configured: true, authenticated: true });
|
||||
signedIn();
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
if (err instanceof ApiError && err.code === 'locked') {
|
||||
setStep('unlock');
|
||||
} else {
|
||||
setError(errorMessage(err));
|
||||
const retry = retryAfterOf(err);
|
||||
if (retry > 0) setWaitUntil(Date.now() + retry * 1000);
|
||||
}
|
||||
setPassword('');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (step === 'unlock') return <UnlockStep onUnlocked={() => { void guard.refetch(); setStep('password'); setError(''); setWaitUntil(0); setNotice('Sign-in is unlocked. Enter your password.'); }} onForgot={() => setStep('reset')} />;
|
||||
if (step === 'reset') return <ResetStep onBack={() => setStep(guard.data?.locked ? 'unlock' : 'password')} onDone={signedIn} />;
|
||||
|
||||
return (
|
||||
<AuthFrame title="Welcome back" subtitle="Enter your password to open your study desk.">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
{notice && (
|
||||
<Callout tone="good" className="py-2.5">
|
||||
{notice}
|
||||
</Callout>
|
||||
)}
|
||||
<Field label="Password" error={error || undefined}>
|
||||
<Input type="password" autoFocus autoComplete="current-password" value={password} onChange={(e) => setPassword(e.target.value)} aria-invalid={Boolean(error)} />
|
||||
</Field>
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy} icon={<LockKeyhole />}>
|
||||
Sign in
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy} disabled={wait > 0} icon={wait > 0 ? <Timer /> : <LockKeyhole />}>
|
||||
{wait > 0 ? `Try again in ${clockText(wait)}` : 'Sign in'}
|
||||
</Button>
|
||||
<button type="button" onClick={() => setStep('reset')} className="mx-auto block rounded text-sm text-ink-2 underline-offset-4 hover:text-ink hover:underline">
|
||||
Forgot password?
|
||||
</button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function UnlockStep({ onUnlocked, onForgot }: { onUnlocked: () => void; onForgot: () => void }) {
|
||||
useDocumentTitle('Sign-in locked');
|
||||
const [code, setCode] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/unlock', { code });
|
||||
onUnlocked();
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<AuthFrame title="Sign-in is locked" subtitle="There were 10 incorrect passwords in a row, so signing in is paused until you unlock it from the server.">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<Callout tone="accent" icon={<KeyRound />}>
|
||||
Find the <strong>unlock code</strong> in the container log, or in <code className="num text-[12px]">unlock-code.txt</code> inside the data folder.
|
||||
</Callout>
|
||||
<Field label="Unlock code" error={error || undefined}>
|
||||
<Input autoFocus value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required aria-invalid={Boolean(error)} />
|
||||
</Field>
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy} icon={<LockKeyholeOpen />}>
|
||||
Unlock sign-in
|
||||
</Button>
|
||||
<button type="button" onClick={onForgot} className="mx-auto block rounded text-sm text-ink-2 underline-offset-4 hover:text-ink hover:underline">
|
||||
Forgot your password too? Reset it instead
|
||||
</button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetStep({ onBack, onDone }: { onBack: () => void; onDone: () => void }) {
|
||||
useDocumentTitle('Reset password');
|
||||
const [code, setCode] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [requested, setRequested] = useState<'pending' | 'sent' | 'failed'>('pending');
|
||||
const mismatch = confirm.length > 0 && password !== confirm;
|
||||
|
||||
const request = async () => {
|
||||
setRequested('pending');
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/reset/request', {});
|
||||
setRequested('sent');
|
||||
} catch (err) {
|
||||
setRequested('failed');
|
||||
setError(errorMessage(err));
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
void request();
|
||||
}, []);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (password.length < 8) return setError('Use at least 8 characters.');
|
||||
if (password !== confirm) return setError('The passwords do not match.');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
await api.post('/api/auth/reset', { code, password });
|
||||
onDone();
|
||||
} catch (err) {
|
||||
setError(errorMessage(err));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame title="Reset your password" subtitle="A reset code was printed to the server console. Enter it with a new password.">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<Callout tone="accent" icon={<KeyRound />}>
|
||||
{requested === 'pending' ? 'Asking the server for a reset code…' : requested === 'failed' ? 'The server could not create a reset code.' : (
|
||||
<>
|
||||
Find the <strong>reset code</strong> in the container log, or in <code className="num text-[12px]">reset-code.txt</code> inside the data folder. It works for 15 minutes. Resetting signs out every device.
|
||||
</>
|
||||
)}
|
||||
</Callout>
|
||||
<Field label="Reset code">
|
||||
<Input autoFocus value={code} onChange={(e) => setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required />
|
||||
</Field>
|
||||
<Field label="New password" hint="At least 8 characters. A short sentence works well.">
|
||||
<Input type="password" autoComplete="new-password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
|
||||
</Field>
|
||||
<Field label="Confirm new password" error={mismatch ? 'The passwords do not match.' : undefined}>
|
||||
<Input type="password" autoComplete="new-password" value={confirm} onChange={(e) => setConfirm(e.target.value)} required aria-invalid={mismatch} />
|
||||
</Field>
|
||||
{error && (
|
||||
<Callout tone="bad" className="py-2.5">
|
||||
{error}
|
||||
{/expired/i.test(error) && (
|
||||
<button type="button" onClick={() => void request()} className="ml-1 font-medium underline underline-offset-2">
|
||||
Get a new code
|
||||
</button>
|
||||
)}
|
||||
</Callout>
|
||||
)}
|
||||
<Button type="submit" variant="primary" size="lg" block loading={busy}>
|
||||
Set new password and sign in
|
||||
</Button>
|
||||
<button type="button" onClick={onBack} className="mx-auto block rounded text-sm text-ink-2 underline-offset-4 hover:text-ink hover:underline">
|
||||
Back
|
||||
</button>
|
||||
</form>
|
||||
</AuthFrame>
|
||||
);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue