diff --git a/PROGRESS.md b/PROGRESS.md index 3bddee9..6208165 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -219,7 +219,7 @@ stored DeepSeek connection still holding the old key; it was updated from `.env` ## Verification status Baseline: 162 tests passed, TypeScript passed and production web/server builds passed. -Added six regression tests. Full `npm run check` passes: **293 tests** (exam formatting tidy and natural openers, 2026-11-16; 291 after exam-style questions; 290 after V1 importer removed; 291 after full-backup restore; 289 after rationale layout; 285 after varied openers; 281 after generation steps; 280 after the check loop and second review; 274 after the fifth revision; 261 after share-link generation, 2026-11-15; 257 after the fourth revision; 247 after the third, 208 after the second, 181 on 2026-11-12), TypeScript +Added six regression tests. Full `npm run check` passes: **298 tests** (sign-in lockout and console-code reset, 2026-11-16; 293 after exam formatting tidy and natural openers; 291 after exam-style questions; 290 after V1 importer removed; 291 after full-backup restore; 289 after rationale layout; 285 after varied openers; 281 after generation steps; 280 after the check loop and second review; 274 after the fifth revision; 261 after share-link generation, 2026-11-15; 257 after the fourth revision; 247 after the third, 208 after the second, 181 on 2026-11-12), TypeScript and both production builds. The Docker `test` stage runs the same 181 tests on Node 24. Tests were run with loopback access for the mock provider. The earlier agent manually exercised quiz completion/results, flashcards, streak effects, diff --git a/README.md b/README.md index d319079..52f456a 100644 --- a/README.md +++ b/README.md @@ -26,6 +26,10 @@ Open http://localhost:3726. On a fresh install, enter the setup code from the se `ADMIN_PASSWORD` for first startup. An optional `.env` file is loaded by the server; see [.env.example](.env.example). Existing environment variables take precedence. +Ten wrong passwords in a row lock sign-in until the unlock code from the server log is entered, +with growing waits after the third. "Forgot password?" prints a reset code to the log instead. See +[sign-in lockout and password reset](docs/DEPLOYMENT.md#sign-in-lockout-and-password-reset). + **This checkout already has an ignored `.env` pointing at `.data/` from development.** Do not delete it or run reset/seed commands against content you want to keep. The demo seeder is an opt-in development tool, never part of startup. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index 9996912..e5ef696 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -51,6 +51,26 @@ when an existing V2 schema needs upgrading. A database from a newer app version The first visit asks for the setup code from the container log or `/data/setup-code.txt`. After setup, the password is stored as a salted scrypt hash. No registration exists. +## Sign-in lockout and password reset + +Wrong passwords are counted in a row across every device, and the count is kept in the +database, so restarting does not clear it. The first 3 are free. From the 3rd, the next +attempt must wait 15 s, then 30 s, 1, 2, 5, 15 and 30 minutes. The **10th** wrong password +locks sign-in. Devices that are already signed in keep working. To lift a lockout, enter the +**unlock code** on the sign-in page. It is printed to the container log +(`docker logs `) and saved to `/data/unlock-code.txt`. Lifting the lockout does not +sign you in, and the count starts again. A correct password also starts the count again. + +**Forgot password?** on the sign-in page prints a **reset code** to the log and saves it to +`/data/reset-code.txt`. Asking again while a code is valid prints nothing new. The code works +once, for 15 minutes. It sets a new password, signs out every device, lifts any lockout and +signs you in. Both codes need access to the server, as the setup code does. Wrong codes count +toward the per-address limit (8 in 15 minutes). + +Anyone who can reach the sign-in page can use up the 10 attempts and lock it. A lockout never +reveals or weakens the password, and the console code always gets you back in. +`RESET_ADMIN_PASSWORD` (below) still works too and also lifts a lockout. + ## Reverse proxy Point your proxy to the container's port 3726 (or the host's mapped port). Forward `Host`, diff --git a/server/auth.ts b/server/auth.ts index 8283b84..6427642 100644 --- a/server/auth.ts +++ b/server/auth.ts @@ -54,6 +54,104 @@ export function resetRateLimits(): void { buckets.clear(); } +/* ------------------------------ sign-in lockout ------------------------------ */ + +/** + * Wrong passwords in a row, counted across every device and kept in the database so a restart + * does not clear them. The first three are free; from the third, each one makes the next + * attempt wait longer (seconds, by number of failures: 15 s, 30 s, 1, 2, 5, 15, 30 min); the + * tenth locks sign-in until the unlock code printed to the server console is entered. A correct password, an unlock or a password reset starts the count again. + * Devices that are already signed in are not affected. + */ +export const LOGIN_WAITS = [0, 0, 0, 15, 30, 60, 120, 300, 900, 1800]; +export const LOCKOUT_AFTER = 10; +const GUARD_KEY = 'auth.guard'; +const RESET_KEY = 'auth.reset_code'; +const RESET_MS = 15 * 60_000; + +interface Guard { + failures: number; + waitUntil: number; + locked: boolean; + /** sha256 of the unlock code while locked. */ + unlockHash: string | null; +} + +function readGuard(app: AppContext): Guard { + return { failures: 0, waitUntil: 0, locked: false, unlockHash: null, ...getSetting>(app.db, GUARD_KEY, {}) }; +} + +function clearGuard(app: AppContext): void { + deleteSetting(app.db, GUARD_KEY); + fs.rmSync(consoleCodeFile(app, 'unlock'), { force: true }); +} + +/** Seconds until the next sign-in attempt is allowed (0 when it is). */ +function waitLeft(guard: Guard): number { + return Math.max(0, Math.ceil((guard.waitUntil - now()) / 1000)); +} + +function describeWait(seconds: number): string { + return seconds < 60 ? `${seconds} second${seconds === 1 ? '' : 's'}` : `${Math.ceil(seconds / 60)} minute${seconds > 60 ? 's' : ''}`; +} + +/** A one-time code shown only on the server console, like the first-run setup code: XXXXX-XXXXX. */ +function newConsoleCode(): string { + return crypto.randomBytes(5).toString('hex').toUpperCase().replace(/(.{5})/, '$1-'); +} + +function codeHash(code: string): string { + return sha256(code.trim().toUpperCase().replace(/[\s-]/g, '')); +} + +function consoleCodeFile(app: AppContext, kind: 'unlock' | 'reset'): string { + return path.join(app.config.dataDir, `${kind}-code.txt`); +} + +/** Prints a console code to the server log and saves it in the data folder (readable only by the server's user). */ +function announceCode(app: AppContext, kind: 'unlock' | 'reset', code: string, what: string): void { + const file = consoleCodeFile(app, kind); + try { + fs.writeFileSync(file, `${code}\n`, { mode: 0o600 }); + } catch { + /* the log line below is enough */ + } + app.log('warn', `${what}: ${code} (also saved to ${file})`); +} + +/** Wrong password: count it, and set the next wait or lock sign-in. Returns the message for the client. */ +function recordWrongPassword(app: AppContext): { message: string; retryAfter?: number; locked?: boolean; attemptsLeft: number } { + const guard = readGuard(app); + guard.failures += 1; + const attemptsLeft = Math.max(0, LOCKOUT_AFTER - guard.failures); + if (guard.failures >= LOCKOUT_AFTER) { + const code = newConsoleCode(); + guard.locked = true; + guard.unlockHash = codeHash(code); + setSetting(app.db, GUARD_KEY, guard); + announceCode(app, 'unlock', code, `Sign-in locked after ${LOCKOUT_AFTER} incorrect passwords in a row. Unlock code`); + return { message: `Sign-in is locked after ${LOCKOUT_AFTER} incorrect passwords. Enter the unlock code from the server console.`, locked: true, attemptsLeft: 0 }; + } + const wait = LOGIN_WAITS[guard.failures] ?? LOGIN_WAITS[LOGIN_WAITS.length - 1]!; + guard.waitUntil = now() + wait * 1000; + setSetting(app.db, GUARD_KEY, guard); + const parts = ['Incorrect password.']; + if (wait > 0) parts.push(`Wait ${describeWait(wait)} before trying again.`); + if (attemptsLeft <= 3) parts.push(`${attemptsLeft} more incorrect ${attemptsLeft === 1 ? 'attempt' : 'attempts'} will lock sign-in.`); + return { message: parts.join(' '), retryAfter: wait || undefined, attemptsLeft }; +} + +/** Throws when sign-in is locked or a wait is running. */ +function assertGuardOpen(app: AppContext): void { + const guard = readGuard(app); + if (guard.locked) throw new HttpError(423, 'locked', `Sign-in is locked after ${LOCKOUT_AFTER} incorrect passwords. Enter the unlock code from the server console.`); + const left = waitLeft(guard); + if (left > 0) throw new HttpError(429, 'rate_limited', `Too many incorrect passwords. Try again in ${describeWait(left)}.`, { retryAfter: left }); +} + +/** One password check at a time per server, so parallel guesses cannot slip past a wait. */ +const checking = new WeakSet(); + /* ------------------------------ request helpers ------------------------------ */ export function clientIp(c: Context, trustProxy: boolean): string { @@ -172,6 +270,7 @@ export async function initAuth(app: AppContext): Promise { passwordSchema.parse(config.resetAdminPassword); await storePassword(app, config.resetAdminPassword); db.run('DELETE FROM sessions'); + clearGuard(app); app.log('warn', 'Administrator password was reset from RESET_ADMIN_PASSWORD. Remove that variable and restart.'); return; } @@ -200,7 +299,10 @@ export async function initAuth(app: AppContext): Promise { export function authRoutes(app: AppContext): Hono { const r = new Hono(); - r.get('/status', (c) => c.json({ configured: isConfigured(app), authenticated: isAuthenticated(app, c) })); + r.get('/status', (c) => { + const guard = readGuard(app); + return c.json({ configured: isConfigured(app), authenticated: isAuthenticated(app, c), locked: guard.locked, retryAfter: guard.locked ? 0 : waitLeft(guard) }); + }); r.post('/setup', async (c) => { if (isConfigured(app)) throw new HttpError(409, 'already_configured', 'Study Desk is already set up'); @@ -224,10 +326,75 @@ export function authRoutes(app: AppContext): Hono { const body = await readBody(c, z.object({ password: z.string().max(256) })); const hash = getSetting(app.db, HASH_KEY, null); if (!hash) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet'); - if (!(await verifyPassword(body.password, hash))) { - recordFailure(ip); - throw new HttpError(401, 'bad_password', 'Incorrect password'); + assertGuardOpen(app); + if (checking.has(app)) throw new HttpError(429, 'rate_limited', 'Another sign-in is being checked. Try again in a moment.', { retryAfter: 1 }); + checking.add(app); + let ok: boolean; + try { + ok = await verifyPassword(body.password, hash); + } finally { + checking.delete(app); } + if (!ok) { + // Wrong passwords follow the lockout schedule alone; the per-IP limit is for wrong codes. + const wrong = recordWrongPassword(app); + if (wrong.locked) throw new HttpError(423, 'locked', wrong.message); + throw new HttpError(401, 'bad_password', wrong.message, { retryAfter: wrong.retryAfter, attemptsLeft: wrong.attemptsLeft }); + } + if (readGuard(app).failures > 0) deleteSetting(app.db, GUARD_KEY); + createSession(app, c); + return c.json({ ok: true }); + }); + + /** Lifts a lockout with the code printed to the server console. The password is still needed to sign in. */ + r.post('/unlock', async (c) => { + const ip = clientIp(c, app.config.trustProxy); + assertNotLimited(ip); + const body = await readBody(c, z.object({ code: z.string().max(40) })); + const guard = readGuard(app); + if (!guard.locked) return c.json({ ok: true }); + if (!guard.unlockHash || !safeEqual(codeHash(body.code), guard.unlockHash)) { + recordFailure(ip); + throw new HttpError(403, 'bad_code', 'That unlock code is not correct. Check the server console or unlock-code.txt in the data folder.'); + } + clearGuard(app); + app.log('info', 'Sign-in unlocked with the console code.'); + return c.json({ ok: true }); + }); + + /** + * Forgotten password, step 1: prints a reset code to the server console (valid 15 minutes). + * While a code is still valid, asking again does not print another. + */ + r.post('/reset/request', (c) => { + if (!isConfigured(app)) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet'); + assertNotLimited(clientIp(c, app.config.trustProxy)); + const current = getSetting<{ hash: string; expiresAt: number } | null>(app.db, RESET_KEY, null); + if (current && current.expiresAt > now()) return c.json({ ok: true, expiresAt: current.expiresAt }); + const code = newConsoleCode(); + const expiresAt = now() + RESET_MS; + setSetting(app.db, RESET_KEY, { hash: codeHash(code), expiresAt }); + announceCode(app, 'reset', code, 'Password reset requested. Reset code (valid 15 minutes)'); + return c.json({ ok: true, expiresAt }); + }); + + /** Forgotten password, step 2: the console code sets a new password, signs out every device, lifts any lockout and signs in here. */ + r.post('/reset', async (c) => { + const ip = clientIp(c, app.config.trustProxy); + assertNotLimited(ip); + const body = await readBody(c, z.object({ code: z.string().max(40), password: passwordSchema })); + const current = getSetting<{ hash: string; expiresAt: number } | null>(app.db, RESET_KEY, null); + if (!current || current.expiresAt <= now()) throw new HttpError(410, 'code_expired', 'That reset code has expired. Ask for a new one.'); + if (!safeEqual(codeHash(body.code), current.hash)) { + recordFailure(ip); + throw new HttpError(403, 'bad_code', 'That reset code is not correct. Check the server console or reset-code.txt in the data folder.'); + } + await storePassword(app, body.password); + deleteSetting(app.db, RESET_KEY); + fs.rmSync(consoleCodeFile(app, 'reset'), { force: true }); + clearGuard(app); + app.db.run('DELETE FROM sessions'); + app.log('warn', 'Administrator password was reset with the console code. Every device was signed out.'); createSession(app, c); return c.json({ ok: true }); }); diff --git a/tests/api.test.ts b/tests/api.test.ts index c2b4a9c..680a490 100644 --- a/tests/api.test.ts +++ b/tests/api.test.ts @@ -21,7 +21,7 @@ describe('authentication', () => { it('requires the setup code, then a session, for private routes', async () => { const fresh = await createTestApp({ login: false }); try { - expect((await fresh.api('GET', '/api/auth/status')).body).toEqual({ configured: false, authenticated: false }); + expect((await fresh.api('GET', '/api/auth/status')).body).toEqual({ configured: false, authenticated: false, locked: false, retryAfter: 0 }); expect((await fresh.api('GET', '/api/classes')).status).toBe(401); const bad = await fresh.api('POST', '/api/auth/setup', { code: 'WRONG-CODE', password: PASSWORD }); expect(bad.status).toBe(403); diff --git a/tests/lockout.test.ts b/tests/lockout.test.ts new file mode 100644 index 0000000..7a2923c --- /dev/null +++ b/tests/lockout.test.ts @@ -0,0 +1,138 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { LOGIN_WAITS, LOCKOUT_AFTER } from '../server/auth.ts'; +import { createTestApp, PASSWORD, type TestApp } from './helpers.ts'; + +const apps: TestApp[] = []; +async function newApp(): Promise { + const app = await createTestApp(); + apps.push(app); + return app; +} +afterEach(() => { + vi.restoreAllMocks(); + for (const app of apps.splice(0)) { + app.close(); + fs.rmSync(app.dir, { recursive: true, force: true }); + } +}); + +/** A clock the tests can move forward past each wait. */ +function clock() { + let at = Date.now(); + vi.spyOn(Date, 'now').mockImplementation(() => at); + return { advance: (seconds: number) => (at += seconds * 1000 + 1) }; +} + +const login = (t: TestApp, password: string) => t.api('POST', '/api/auth/login', { password }, { cookie: null }); +const codeFile = (t: TestApp, kind: 'unlock' | 'reset') => path.join(t.ctx.config.dataDir, `${kind}-code.txt`); + +describe('sign-in lockout', () => { + it('allows 3 wrong passwords, then waits longer each time, and locks after 10 until the console code', async () => { + const t = await newApp(); + const time = clock(); + for (let i = 1; i <= 2; i += 1) expect((await login(t, 'wrong')).status).toBe(401); + // The third wrong password starts the first wait; the next attempt is refused without checking. + const third = await login(t, 'wrong'); + expect(third.status).toBe(401); + expect(third.body.error.message).toMatch(/Wait 15 seconds/); + const early = await login(t, PASSWORD); + expect(early.status).toBe(429); + expect(early.headers.get('retry-after')).toBe('15'); + + // Waits grow with each failure. + for (let failures = 3; failures < LOCKOUT_AFTER - 1; failures += 1) { + time.advance(LOGIN_WAITS[failures]!); + const res = await login(t, 'wrong'); + expect(res.status).toBe(401); + expect(res.body.error.details.retryAfter).toBe(LOGIN_WAITS[failures + 1]); + } + expect((await login(t, 'wrong')).status).toBe(429); + time.advance(LOGIN_WAITS[LOCKOUT_AFTER - 1]!); + // The tenth locks sign-in, even for the right password, until the console code is entered. + expect((await login(t, 'wrong')).status).toBe(423); + time.advance(3600); + expect((await login(t, PASSWORD)).status).toBe(423); + expect((await t.api('GET', '/api/auth/status', undefined, { cookie: null })).body.locked).toBe(true); + + const code = fs.readFileSync(codeFile(t, 'unlock'), 'utf8').trim(); + expect(code).toMatch(/^[0-9A-F]{5}-[0-9A-F]{5}$/); + expect((await t.api('POST', '/api/auth/unlock', { code: 'AAAAA-AAAAA' }, { cookie: null })).status).toBe(403); + expect((await t.api('POST', '/api/auth/unlock', { code: code.toLowerCase().replace('-', '') }, { cookie: null })).status).toBe(200); + expect(fs.existsSync(codeFile(t, 'unlock'))).toBe(false); + expect((await login(t, PASSWORD)).status).toBe(200); + }); + + it('starts the count again after a correct password, and keeps it across a restart', async () => { + const t = await newApp(); + clock(); + await login(t, 'wrong'); + await login(t, 'wrong'); + expect((await login(t, PASSWORD)).status).toBe(200); + await login(t, 'wrong'); + await login(t, 'wrong'); + expect((await login(t, 'wrong')).status).toBe(401); + expect((await login(t, 'wrong')).status).toBe(429); + + // Kept in the database: a fresh server on the same data folder still makes the client wait. + const again = await createTestApp({ dir: t.dir, login: false }); + try { + expect((await login(again, PASSWORD)).status).toBe(429); + } finally { + again.close(); + } + }); + + it('keeps devices that are already signed in working while sign-in is locked', async () => { + const t = await newApp(); + const time = clock(); + for (let i = 0; i < LOCKOUT_AFTER; i += 1) { + await login(t, 'wrong'); + time.advance(LOGIN_WAITS[LOGIN_WAITS.length - 1]!); + } + expect((await login(t, PASSWORD)).status).toBe(423); + expect((await t.api('GET', '/api/classes')).status).toBe(200); + }); +}); + +describe('forgotten password reset', () => { + it('sets a new password with the console code, signs out every device and lifts a lockout', async () => { + const t = await newApp(); + const time = clock(); + for (let i = 0; i < LOCKOUT_AFTER; i += 1) { + await login(t, 'wrong'); + time.advance(LOGIN_WAITS[LOGIN_WAITS.length - 1]!); + } + const first = await t.api('POST', '/api/auth/reset/request', {}, { cookie: null }); + expect(first.status).toBe(200); + const code = fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim(); + // Asking again while the code is valid keeps the same code. + await t.api('POST', '/api/auth/reset/request', {}, { cookie: null }); + expect(fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim()).toBe(code); + + expect((await t.api('POST', '/api/auth/reset', { code: 'AAAAA-AAAAA', password: 'a brand new password' }, { cookie: null })).status).toBe(403); + expect((await t.api('POST', '/api/auth/reset', { code, password: 'short' }, { cookie: null })).status).toBe(422); + const done = await t.raw('POST', '/api/auth/reset', { cookie: null, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code, password: 'a brand new password' }) }); + expect(done.status).toBe(200); + expect(done.headers.get('set-cookie')).toMatch(/sd_session=/); + expect(fs.existsSync(codeFile(t, 'reset'))).toBe(false); + + // The old session is gone, the old password no longer works, the lockout is lifted. + expect((await t.api('GET', '/api/classes')).status).toBe(401); + expect((await login(t, PASSWORD)).status).toBe(401); + expect((await login(t, 'a brand new password')).status).toBe(200); + // A used code cannot be used again. + expect((await t.api('POST', '/api/auth/reset', { code, password: 'another new password' }, { cookie: null })).status).toBe(410); + }); + + it('expires the reset code after 15 minutes', async () => { + const t = await newApp(); + const time = clock(); + await t.api('POST', '/api/auth/reset/request', {}, { cookie: null }); + const code = fs.readFileSync(codeFile(t, 'reset'), 'utf8').trim(); + time.advance(15 * 60); + expect((await t.api('POST', '/api/auth/reset', { code, password: 'a brand new password' }, { cookie: null })).status).toBe(410); + expect((await login(t, PASSWORD)).status).toBe(200); + }); +}); diff --git a/web/src/pages/Auth.tsx b/web/src/pages/Auth.tsx index 3a719cf..b408905 100644 --- a/web/src/pages/Auth.tsx +++ b/web/src/pages/Auth.tsx @@ -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 { 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 (
+ {notice && ( + + {notice} + + )} setPassword(e.target.value)} aria-invalid={Boolean(error)} /> - + +
+
+ ); +} + +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 ( + +
+ }> + Find the unlock code in the container log, or in unlock-code.txt inside the data folder. + + + setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required aria-invalid={Boolean(error)} /> + + + +
+
+ ); +} + +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 ( + +
+ }> + {requested === 'pending' ? 'Asking the server for a reset code…' : requested === 'failed' ? 'The server could not create a reset code.' : ( + <> + Find the reset code in the container log, or in reset-code.txt inside the data folder. It works for 15 minutes. Resetting signs out every device. + + )} + + + setCode(e.target.value.toUpperCase())} placeholder="XXXXX-XXXXX" autoComplete="off" spellCheck={false} className="num tracking-widest" required /> + + + setPassword(e.target.value)} required minLength={8} /> + + + setConfirm(e.target.value)} required aria-invalid={mismatch} /> + + {error && ( + + {error} + {/expired/i.test(error) && ( + + )} + + )} + +
);