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

- 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:
Elijah 2026-11-16 15:46:16 -07:00
parent fe94dbf876
commit 917954d12d
7 changed files with 522 additions and 18 deletions

View file

@ -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,

View file

@ -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.

View file

@ -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 <container>`) 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`,

View file

@ -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<Partial<Guard>>(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<AppContext>();
/* ------------------------------ request helpers ------------------------------ */
export function clientIp(c: Context, trustProxy: boolean): string {
@ -172,6 +270,7 @@ export async function initAuth(app: AppContext): Promise<void> {
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<void> {
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<string | null>(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 });
});

View file

@ -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);

138
tests/lockout.test.ts Normal file
View file

@ -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<TestApp> {
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);
});
});

View file

@ -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>
);