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>
301 lines
13 KiB
TypeScript
301 lines
13 KiB
TypeScript
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';
|
|
|
|
export function Brand({ size = 'md' }: { size?: 'md' | 'lg' }) {
|
|
return (
|
|
<div className="flex items-center gap-2.5">
|
|
<img src="/icon.svg" alt="" className={size === 'lg' ? 'size-11 rounded-[12px]' : 'size-8 rounded-[9px]'} />
|
|
<span className={size === 'lg' ? 'display text-[28px]' : 'display text-[21px]'}>Study Desk</span>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function AuthFrame({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
|
|
return (
|
|
<main className="grid min-h-dvh place-items-center px-5 py-10">
|
|
<div className="w-full max-w-[400px] animate-in">
|
|
<div className="mb-8 flex justify-center">
|
|
<Brand size="lg" />
|
|
</div>
|
|
<div className="card p-6 sm:p-7">
|
|
<h1 className="display text-2xl">{title}</h1>
|
|
<p className="mt-1.5 mb-6 text-sm text-ink-2">{subtitle}</p>
|
|
{children}
|
|
</div>
|
|
</div>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
/** 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 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 || wait > 0) return;
|
|
setBusy(true);
|
|
setError('');
|
|
setNotice('');
|
|
try {
|
|
await api.post('/api/auth/login', { password });
|
|
signedIn();
|
|
} catch (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} 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>
|
|
);
|
|
}
|
|
|
|
export function SetupPage() {
|
|
useDocumentTitle('Set up');
|
|
const qc = useQueryClient();
|
|
const [code, setCode] = useState('');
|
|
const [password, setPassword] = useState('');
|
|
const [confirm, setConfirm] = useState('');
|
|
const [error, setError] = useState('');
|
|
const [busy, setBusy] = useState(false);
|
|
const mismatch = confirm.length > 0 && password !== confirm;
|
|
|
|
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/setup', { code, password });
|
|
qc.setQueryData(qk.auth, { configured: true, authenticated: true });
|
|
} catch (err) {
|
|
setError(errorMessage(err));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AuthFrame title="Set up Study Desk" subtitle="Create the administrator password. You are the only account on this desk.">
|
|
<form onSubmit={submit} className="space-y-4">
|
|
<Callout tone="accent" icon={<KeyRound />}>
|
|
Find the one-time <strong>setup code</strong> in the container log, or in <code className="num text-[12px]">setup-code.txt</code> inside the data folder.
|
|
</Callout>
|
|
<Field label="Setup 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="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 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}
|
|
</Callout>
|
|
)}
|
|
<Button type="submit" variant="primary" size="lg" block loading={busy}>
|
|
Create password and continue
|
|
</Button>
|
|
</form>
|
|
</AuthFrame>
|
|
);
|
|
}
|