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 (
Study Desk
);
}
function AuthFrame({ title, subtitle, children }: { title: string; subtitle: string; children: React.ReactNode }) {
return (
{title}
{subtitle}
{children}
);
}
/** 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 { void guard.refetch(); setStep('password'); setError(''); setWaitUntil(0); setNotice('Sign-in is unlocked. Enter your password.'); }} onForgot={() => setStep('reset')} />;
if (step === 'reset') return setStep(guard.data?.locked ? 'unlock' : 'password')} onDone={signedIn} />;
return (
);
}
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 (
);
}
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 (
);
}
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 (
);
}