7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
fix(auth): sign in after a password reset and log the account email (#1477) (#1486)
Tashfeen986b2118226f
diff --git a/client/src/components/auth-gate.reset-signs-in.test.tsx b/client/src/components/auth-gate.reset-signs-in.test.tsxnew file mode 100644index 00000000..13d40cec--- /dev/null+++ b/client/src/components/auth-gate.reset-signs-in.test.tsx@@ -0,0 +1,124 @@+// @vitest-environment jsdom+//+// A password reset used to end on "Please sign in", but the login form needs+// the account email, which an operator who forgot the password may not+// remember either (#1477). The server now signs them in after a valid reset+// code; the form must store that session and open the dashboard.+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { I18nProvider } from '@/i18n'+import { AuthGate } from './auth-gate'+import { getToken } from '@/lib/api'++let root: Root+let container: HTMLDivElement+let authenticated: boolean+let resetResponse: { status: number; body: unknown }+let posts: { url: string; body: Record<string, string> | null }[]++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } })+}++async function flush() {+ for (let i = 0; i < 6; i++) {+ await act(async () => { await new Promise(r => setTimeout(r, 0)) })+ }+}++function mount() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ act(() => {+ root.render(+ <QueryClientProvider client={client}>+ <I18nProvider initialLocale="en">+ <AuthGate><div data-testid="app">dashboard</div></AuthGate>+ </I18nProvider>+ </QueryClientProvider>,+ )+ })+}++function type(selector: string, value: string) {+ const input = container.querySelector<HTMLInputElement>(selector)!+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!+ act(() => {+ setter.call(input, value)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+}++async function clickButton(label: string) {+ const button = [...container.querySelectorAll('button')].find(b => b.textContent === label)!+ act(() => { button.click() })+ await flush()+}++async function resetWithCode() {+ mount()+ await flush()+ await clickButton('Forgot password?')+ await clickButton('Send reset code')+ type('#reset-code', 'ABCDEFGHIJ')+ type('#reset-new-password', 'brand-new-password')+ const form = container.querySelector('form')!+ act(() => { form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) })+ await flush()+}++beforeAll(() => {+ ;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true+})++beforeEach(() => {+ container = document.createElement('div')+ document.body.appendChild(container)+ root = createRoot(container)+ authenticated = false+ posts = []+ resetResponse = { status: 200, body: { success: true, token: 'session-after-reset', email: '[email protected]' } }+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input)+ if (url.endsWith('/api/auth/status')) {+ return json({ needsSetup: false, authenticated, email: authenticated ? '[email protected]' : null })+ }+ if (init?.method === 'POST') {+ posts.push({ url, body: init.body ? JSON.parse(String(init.body)) : null })+ if (url.endsWith('/api/auth/forgot-password')) return json({ success: true })+ if (url.endsWith('/api/auth/reset-password')) {+ if (resetResponse.status === 200) authenticated = true+ return json(resetResponse.body, resetResponse.status)+ }+ }+ return json({ error: { message: `unexpected ${url}` } }, 404)+ }))+})++afterEach(() => {+ act(() => root.unmount())+ container.remove()+ localStorage.clear()+ vi.unstubAllGlobals()+})++describe('AuthGate password reset', () => {+ it('signs in with the session the reset returns instead of asking for the email', async () => {+ await resetWithCode()++ expect(posts.map(p => p.url.replace(/^.*\/api/, '/api'))).toEqual(['/api/auth/forgot-password', '/api/auth/reset-password'])+ expect(posts[1].body).toEqual({ resetCode: 'ABCDEFGHIJ', newPassword: 'brand-new-password' })+ expect(getToken()).toBe('session-after-reset')+ expect(container.querySelector('[data-testid="app"]')).not.toBeNull()+ })++ it('stays on the reset form with the error when the code is wrong', async () => {+ resetResponse = { status: 403, body: { error: { message: 'Invalid or expired reset code' } } }+ await resetWithCode()++ expect(getToken()).toBeNull()+ expect(container.querySelector('[data-testid="app"]')).toBeNull()+ expect(container.textContent).toContain('Invalid or expired reset code')+ })+})diff --git a/client/src/components/auth-gate.tsx b/client/src/components/auth-gate.tsxindex 78767c20..d7f01e36 100644--- a/client/src/components/auth-gate.tsx+++ b/client/src/components/auth-gate.tsx@@ -113,7 +113,7 @@ function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () =>}if (showForgot && !isSetup) {- return <ForgotPasswordForm onBack={() => setShowForgot(false)} />+ return <ForgotPasswordForm onBack={() => setShowForgot(false)} onAuthed={onAuthed} />}return (@@ -204,7 +204,7 @@ function AuthForm({ mode, onAuthed }: { mode: 'setup' | 'login'; onAuthed: () =>type ForgotStep = 'request' | 'reset' | 'done'-function ForgotPasswordForm({ onBack }: { onBack: () => void }) {+function ForgotPasswordForm({ onBack, onAuthed }: { onBack: () => void; onAuthed: () => void }) {const { t } = useI18n()const [step, setStep] = useState<ForgotStep>('request')const [resetCode, setResetCode] = useState('')@@ -242,10 +242,17 @@ function ForgotPasswordForm({ onBack }: { onBack: () => void }) {setBusy(true)setError('')try {- await apiFetch('/api/auth/reset-password', {+ const res = await apiFetch<{ token?: string }>('/api/auth/reset-password', {method: 'POST',body: JSON.stringify({ resetCode: resetCode.trim(), newPassword }),})+ // The server signs the operator in after a reset, so nobody has to+ // remember which email the account uses (#1477).+ if (res.token) {+ setToken(res.token)+ onAuthed()+ return+ }setStep('done')} catch (err) {setError((err as Error).message)diff --git a/server/src/__tests__/routes/auth-reset-password.test.ts b/server/src/__tests__/routes/auth-reset-password.test.tsindex eca8d8f0..7ceb81ca 100644--- a/server/src/__tests__/routes/auth-reset-password.test.ts+++ b/server/src/__tests__/routes/auth-reset-password.test.ts@@ -48,6 +48,16 @@ async function post(app: Express, path: string, body?: unknown) {return { status: res.status, body: data };}+async function get(app: Express, path: string, token: string) {+ const server = app.listen(0, '127.0.0.1');+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, { headers: { Authorization: `Bearer ${token}` } });+ const data = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: data };+}+/** Step past the cooldown first, so a test never fails for a reason it isn't about. */async function forgot(app: Express) {jump(COOLDOWN_MS + 1_000);@@ -121,6 +131,40 @@ describe('password reset by log code', () => {expect((await post(app, '/api/auth/login', { email: EMAIL, password: PASSWORD })).status).toBe(401);});+ it('signs the operator in and names the account, so a forgotten email is no dead end (#1477)', async () => {+ await forgot(app);+ const code = getResetCode() as string;+ const reset = await post(app, '/api/auth/reset-password', { resetCode: code, newPassword: 'brand-new-password' });++ expect(reset.status).toBe(200);+ expect(reset.body.email).toBe(EMAIL);+ expect(typeof reset.body.token).toBe('string');+ const me = await get(app, '/api/auth/me', reset.body.token);+ expect(me.status).toBe(200);+ expect(me.body.email).toBe(EMAIL);+ });++ it('returns no session for a wrong code', async () => {+ await forgot(app);+ const bad = await post(app, '/api/auth/reset-password', { resetCode: 'NOTTHECODE', newPassword: 'attacker-chosen-pw' });+ expect(bad.status).toBe(403);+ expect(bad.body.token).toBeUndefined();+ expect(bad.body.email).toBeUndefined();+ });++ it('logs the account email beside the reset code, never over HTTP', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});+ try {+ const { body } = await forgot(app);+ const printed = log.mock.calls.map(c => String(c[0])).join('\n');+ expect(printed).toContain(`Password-reset code: ${getResetCode()}`);+ expect(printed).toContain(`Account email: ${EMAIL}`);+ expect(JSON.stringify(body)).not.toContain(EMAIL);+ } finally {+ log.mockRestore();+ }+ });+it('burns the code after one use', async () => {await forgot(app);const code = getResetCode() as string;diff --git a/server/src/lib/reset-code.ts b/server/src/lib/reset-code.tsindex 7ff02249..4e3cc789 100644--- a/server/src/lib/reset-code.ts+++ b/server/src/lib/reset-code.ts@@ -11,12 +11,16 @@ const _code = createOneTimeCode();const RESET_CODE_TTL_MS = 15 * 60 * 1000; // 15 minuteslet mintedAtMs = 0;-// Mint a fresh reset code and log it prominently. Returns the code.-export function generateResetCode(): string {+// Mint a fresh reset code and log it prominently, with the account email: the+// operator who forgot the password may have forgotten which email signs in+// too (#1477), and whoever can read this log can already reset the account.+// Returns the code.+export function generateResetCode(accountEmail?: string | null): string {const code = _code.generate();mintedAtMs = Date.now();console.log('');console.log(' Password-reset code: ' + code);+ if (accountEmail) console.log(' Account email: ' + accountEmail);console.log(' Enter this code on the reset form to set a new password.');console.log('');return code;diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.tsindex 238a15f5..a093b67f 100644--- a/server/src/routes/auth.ts+++ b/server/src/routes/auth.ts@@ -11,6 +11,7 @@ import {updateEmail,updatePassword,resetUserPassword,+ accountEmail,normalizeEmail,} from '../services/auth.js';import { setupCodeMatches, clearSetupCode } from '../lib/setup-code.js';@@ -311,7 +312,7 @@ authRouter.post('/forgot-password', (_req: Request, res: Response) => {return;}lastResetCodeAt = now;- generateResetCode();+ generateResetCode(accountEmail());res.json({ success: true });});@@ -331,11 +332,15 @@ authRouter.post('/reset-password', (req: Request, res: Response) => {res.status(403).json({ error: { message: 'Invalid or expired reset code', type: 'authentication_error' } });return;}- const ok = resetUserPassword(parsed.data.newPassword);- if (!ok) {+ const user = resetUserPassword(parsed.data.newPassword);+ if (!user) {res.status(404).json({ error: { message: 'No account found', type: 'not_found' } });return;}clearResetCode();- res.json({ success: true });+ // Sign the operator straight in: the code already proved they control the+ // install, and sending them back to a login form that needs an email they+ // may not remember left them locked out after a successful reset (#1477).+ const token = createSession(user.userId);+ res.json({ success: true, token, email: user.email });});diff --git a/server/src/services/auth.ts b/server/src/services/auth.tsindex d0a74ea0..6c48ef79 100644--- a/server/src/services/auth.ts+++ b/server/src/services/auth.ts@@ -117,16 +117,22 @@ export function updatePassword(userId: number, currentPassword: string, newPasswreturn true;}+/** The single account's email, or null before first-run setup. */+export function accountEmail(): string | null {+ const row = getDb().prepare('SELECT email FROM users LIMIT 1').get() as { email: string } | undefined;+ return row?.email ?? null;+}+/*** Reset the password for the single existing user and invalidate all* sessions.- * Returns false if no user exists.+ * Returns the user, or null if no user exists.*/-export function resetUserPassword(newPassword: string): boolean {+export function resetUserPassword(newPassword: string): SessionUser | null {const db = getDb();- const row = db.prepare('SELECT id FROM users LIMIT 1').get() as { id: number } | undefined;- if (!row) return false;+ const row = db.prepare('SELECT id, email FROM users LIMIT 1').get() as { id: number; email: string } | undefined;+ if (!row) return null;db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(hashPassword(newPassword), row.id);db.prepare('DELETE FROM sessions WHERE user_id = ?').run(row.id);- return true;+ return { userId: row.id, email: row.email };}