Skip to content

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(desktop): sign the dashboard in from any local browser tab, never show Sign In (#1399) (#1533)

Tashfeen2f030d497fcf
diff --git a/README.md b/README.md
index fd38a06d..2d3df1a4 100644
--- a/README.md
+++ b/README.md
@@ -316,7 +316,7 @@ One request in, the best free model out: the router picks the highest-priority m
## FAQ
-**Do I need a password?** Not for the desktop app — the dashboard signs itself in with a hidden local account, so there is nothing to set up and nothing to forget. Open it from the tray icon → **Open Dashboard**. Server installs (Docker, one-liner, `npm run dev`) do have an email + password account.
+**Do I need a password?** Not for the desktop app — the dashboard signs itself in with a hidden local account, so there is nothing to set up and nothing to forget. Open it from the tray icon → **Open Dashboard**, or in any browser on the same computer (for example http://127.0.0.1:31415); both sign in on their own. Another device reaching the app over LAN access still sees the sign-in form. Server installs (Docker, one-liner, `npm run dev`) do have an email + password account.
**I forgot the password on a server install.** Click **Forgot password?** on the login page. There is no email to send a link to, so the one-time code is printed to the server log — read it with `docker compose logs -f freellmapi` (or in the terminal running the server, or in the desktop log file), then enter it on the reset form. The code lasts 15 minutes.
diff --git a/client/src/components/auth-gate.desktop-browser.test.tsx b/client/src/components/auth-gate.desktop-browser.test.tsx
new file mode 100644
index 00000000..4eb2f254
--- /dev/null
+++ b/client/src/components/auth-gate.desktop-browser.test.tsx
@@ -0,0 +1,93 @@
+// @vitest-environment jsdom
+//
+// #1399: the desktop app's dashboard opened in a normal browser tab has no
+// preload bridge. When the server reports `desktop: true` (a desktop install,
+// a request from this computer) the gate fetches a session from
+// /api/auth/desktop-session and never shows the Sign In form. Without the flag
+// (web and Docker installs) the form stays.
+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'
+
+const MINTED = 'minted-desktop-session'
+
+let root: Root
+let container: HTMLDivElement
+let desktopFlag: boolean
+let sessionCalls: number
+
+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>,
+ )
+ })
+}
+
+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)
+ desktopFlag = true
+ sessionCalls = 0
+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input)
+ if (url.endsWith('/api/auth/desktop-session')) {
+ sessionCalls++
+ return desktopFlag ? json({ token: MINTED }) : json({ error: { message: 'forbidden' } }, 403)
+ }
+ if (url.endsWith('/api/auth/status')) {
+ const ok = new Headers(init?.headers).get('Authorization') === `Bearer ${MINTED}`
+ return json({ needsSetup: false, authenticated: ok, email: ok ? 'desktop@localhost' : null, desktop: desktopFlag })
+ }
+ return json({ error: { message: `unexpected ${url}` } }, 404)
+ }))
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ container.remove()
+ localStorage.clear()
+ vi.unstubAllGlobals()
+})
+
+describe('AuthGate in a browser tab on a desktop install (#1399)', () => {
+ it('signs in through the server and never shows the Sign In form', async () => {
+ mount()
+ await flush()
+ expect(sessionCalls).toBe(1)
+ expect(container.querySelector('[data-testid="app"]')).not.toBeNull()
+ expect(container.querySelector('input[type="password"]')).toBeNull()
+ })
+
+ it('keeps the Sign In form when the server does not report a desktop install', async () => {
+ desktopFlag = false
+ mount()
+ await flush()
+ expect(sessionCalls).toBe(0)
+ expect(container.querySelector('[data-testid="app"]')).toBeNull()
+ expect(container.querySelector('input[type="password"]')).not.toBeNull()
+ })
+})
diff --git a/client/src/components/auth-gate.tsx b/client/src/components/auth-gate.tsx
index d7f01e36..26daf8e2 100644
--- a/client/src/components/auth-gate.tsx
+++ b/client/src/components/auth-gate.tsx
@@ -30,10 +30,20 @@ function desktopSessionBridge(): (() => Promise<string>) | null {
: null
}
+// The same dashboard opened in a normal browser tab on a desktop install has no
+// preload bridge, so the server mints the session instead (#1399). It only
+// does so for a request from this computer, and says so through `desktop` on
+// /api/auth/status; web and Docker installs never set it and keep their login.
+async function browserDesktopSession(): Promise<string> {
+ const res = await apiFetch<{ token: string }>('/api/auth/desktop-session', { method: 'POST' })
+ return res.token
+}
+
interface AuthStatus {
needsSetup: boolean
authenticated: boolean
email: string | null
+ desktop?: boolean
}
function Centered({ children }: { children: ReactNode }) {
@@ -462,7 +472,7 @@ export function AuthGate({ children }: { children: ReactNode }) {
// Desktop self-repair: one attempt at a time, and none after the shell has
// handed back a session the server still rejects — a broken install shows a
// message instead of looping.
- const desktopSession = desktopSessionBridge()
+ const desktopSession = desktopSessionBridge() ?? (data?.desktop ? browserDesktopSession : null)
const desktopNeedsSession = !!desktopSession && !!data && (data.needsSetup || !data.authenticated)
const repairing = useRef(false)
const [repairFailed, setRepairFailed] = useState(false)
diff --git a/desktop/src/server-host.ts b/desktop/src/server-host.ts
index 27ec8d0e..01768a4f 100644
--- a/desktop/src/server-host.ts
+++ b/desktop/src/server-host.ts
@@ -7,7 +7,6 @@
// The server sources live in this same repo (../../server). Keep these
// relative imports in sync with the repo-root default in main.ts.
import '../../server/src/env.js';
-import crypto from 'node:crypto';
import tls from 'node:tls';
import type { Server } from 'node:http';
import { createApp } from '../../server/src/app.js';
@@ -25,7 +24,7 @@ import { loadCacheFromDb } from '../../server/src/services/cache.js';
import { startWakeDetect } from '../../server/src/lib/wake-detect.js';
import { installProcessSafetyNet } from '../../server/src/lib/process-safety-net.js';
import { installLogRedaction } from '../../server/src/lib/log-redaction.js';
-import { userCount, createUser, createSession } from '../../server/src/services/auth.js';
+import { desktopSessionToken } from '../../server/src/services/auth.js';
import { NodeScheduler } from '../../server/src/lib/scheduler.js';
export { getDb, getUnifiedApiKey, isAutoUpdateCheckEnabled };
@@ -177,11 +176,7 @@ export async function startServer(opts: StartOptions): Promise<ServerHandle> {
// The dashboard window authenticates as a hidden machine user. The password
// is random and never shown — sessions are minted directly against the DB.
export function ensureSessionToken(): string {
- if (userCount() === 0) {
- createUser('desktop@localhost', crypto.randomBytes(24).toString('hex'));
- }
- const first = getDb().prepare('SELECT id FROM users ORDER BY id ASC LIMIT 1').get() as { id: number };
- return createSession(first.id);
+ return desktopSessionToken();
}
async function listenWithScan(
diff --git a/docs/en/install/01-install.md b/docs/en/install/01-install.md
index 0716ea29..576c8f40 100644
--- a/docs/en/install/01-install.md
+++ b/docs/en/install/01-install.md
@@ -344,6 +344,9 @@ install. For the server (non-desktop) deployment, the equivalent state is the
**Desktop app — there is no password.** The dashboard signs itself in with a
hidden local account, so there is nothing to remember and nothing to reset. If
you cannot see the dashboard, open it from the tray icon → **Open Dashboard**.
+A browser tab on the same computer (for example http://127.0.0.1:31415) signs in
+the same way. Only another device reaching the app over LAN access is asked to
+sign in.
**Server installs** (Docker, one-liner, `npm run dev`) do have an email +
password account, and there is no email delivery to send a reset link to. The
diff --git a/server/src/__tests__/routes/auth-desktop-session.test.ts b/server/src/__tests__/routes/auth-desktop-session.test.ts
new file mode 100644
index 00000000..abf20205
--- /dev/null
+++ b/server/src/__tests__/routes/auth-desktop-session.test.ts
@@ -0,0 +1,106 @@
+import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';
+import http from 'node:http';
+import express, { type Express } from 'express';
+import { authRouter } from '../../routes/auth.js';
+import { initDb, getDb } from '../../db/index.js';
+import { validateSession, userCount } from '../../services/auth.js';
+
+// #1399: the desktop app's dashboard opened in a normal browser tab must sign
+// in without a form. POST /api/auth/desktop-session mints the install's session,
+// but only for the desktop embedder, over loopback, with a localhost Host
+// header, and never for another site's page. The real connection here is
+// always loopback, so a middleware overrides req.socket for the remote cases.
+
+function app(remoteAddr = '127.0.0.1'): Express {
+ const a = express();
+ a.use(express.json());
+ a.use((req, _res, next) => {
+ Object.defineProperty(req, 'socket', { value: { remoteAddress: remoteAddr }, configurable: true });
+ next();
+ });
+ a.use('/api/auth', authRouter);
+ return a;
+}
+
+// node:http rather than fetch: the Host header is the thing under test, and
+// fetch does not let a caller set it.
+async function call(a: Express, method: 'GET' | 'POST', path: string, headers: Record<string, string> = {}) {
+ const server = a.listen(0, '127.0.0.1');
+ if (!server.listening) await new Promise<void>(resolve => server.once('listening', () => resolve()));
+ const { port } = server.address() as { port: number };
+ try {
+ return await new Promise<{ status: number; body: any }>((resolve, reject) => {
+ const req = http.request({ host: '127.0.0.1', port, method, path, headers: { host: `127.0.0.1:${port}`, ...headers } }, res => {
+ let data = '';
+ res.on('data', c => { data += c; });
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: data ? JSON.parse(data) : null }));
+ });
+ req.on('error', reject);
+ req.end();
+ });
+ } finally {
+ server.close();
+ }
+}
+
+describe('POST /api/auth/desktop-session (#1399)', () => {
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ initDb(':memory:');
+ });
+
+ beforeEach(() => {
+ getDb().prepare('DELETE FROM sessions').run();
+ getDb().prepare('DELETE FROM users').run();
+ process.env.FREEAPI_DESKTOP = '1';
+ });
+
+ afterAll(() => {
+ delete process.env.FREEAPI_DESKTOP;
+ });
+
+ it('mints a working session for a local browser tab and creates the hidden account on first run', async () => {
+ expect(userCount()).toBe(0);
+ const status = await call(app(), 'GET', '/api/auth/status');
+ expect(status.body).toMatchObject({ authenticated: false, desktop: true });
+
+ const res = await call(app(), 'POST', '/api/auth/desktop-session', { 'sec-fetch-site': 'same-origin', origin: 'http://127.0.0.1:31415' });
+ expect(res.status).toBe(200);
+ expect(validateSession(res.body.token)?.email).toBe('desktop@localhost');
+ expect(userCount()).toBe(1);
+ });
+
+ it('accepts localhost and [::1] host names', async () => {
+ for (const host of ['localhost:31415', '[::1]:31415']) {
+ const res = await call(app(), 'POST', '/api/auth/desktop-session', { host });
+ expect(res.status, host).toBe(200);
+ }
+ });
+
+ it('refuses web and Docker installs (no FREEAPI_DESKTOP)', async () => {
+ delete process.env.FREEAPI_DESKTOP;
+ expect((await call(app(), 'GET', '/api/auth/status')).body.desktop).toBe(false);
+ expect((await call(app(), 'POST', '/api/auth/desktop-session')).status).toBe(403);
+ });
+
+ it('refuses a LAN caller when the app binds 0.0.0.0', async () => {
+ expect((await call(app('192.168.1.20'), 'POST', '/api/auth/desktop-session')).status).toBe(403);
+ expect((await call(app('192.168.1.20'), 'GET', '/api/auth/status')).body.desktop).toBe(false);
+ });
+
+ it('refuses a request relayed by a local reverse proxy from a remote client', async () => {
+ const res = await call(app(), 'POST', '/api/auth/desktop-session', { 'x-forwarded-for': '203.0.113.9' });
+ expect(res.status).toBe(403);
+ });
+
+ it('refuses a DNS-rebinding page (non-local Host header)', async () => {
+ const res = await call(app(), 'POST', '/api/auth/desktop-session', { host: 'evil.example:31415' });
+ expect(res.status).toBe(403);
+ });
+
+ it('refuses another site firing a request at localhost', async () => {
+ expect((await call(app(), 'POST', '/api/auth/desktop-session', { 'sec-fetch-site': 'cross-site' })).status).toBe(403);
+ expect((await call(app(), 'POST', '/api/auth/desktop-session', { origin: 'https://evil.example' })).status).toBe(403);
+ expect(userCount()).toBe(0);
+ });
+});
diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts
index a093b67f..508bb792 100644
--- a/server/src/routes/auth.ts
+++ b/server/src/routes/auth.ts
@@ -13,6 +13,7 @@ import {
resetUserPassword,
accountEmail,
normalizeEmail,
+ desktopSessionToken,
} from '../services/auth.js';
import { setupCodeMatches, clearSetupCode } from '../lib/setup-code.js';
import { generateResetCode, resetCodeMatches, clearResetCode } from '../lib/reset-code.js';
@@ -131,16 +132,79 @@ function isLoopbackRemote(req: Request): boolean {
return !firstForwarded || isLoopbackAddress(firstForwarded);
}
+// ── Desktop sign-in (#1399) ───────────────────────────────────────────────
+// The desktop app's account is a hidden machine user with a random password
+// nobody knows. Its own window gets sessions over IPC, but the same dashboard
+// opened in a normal browser tab (the tray's "Open in browser", a bookmark,
+// http://127.0.0.1:31415) used to land on a Sign In form nobody could pass.
+// On a desktop install, a request from this machine gets the session the
+// window would have got, so the form never shows.
+//
+// Guards, all required:
+// - FREEAPI_DESKTOP=1: only the desktop embedder sets it; web/Docker installs
+// keep their login.
+// - Loopback socket with no remote forwarded hop (isLoopbackRemote), so LAN
+// access mode and a local reverse proxy never hand out sessions.
+// - A localhost Host header: a DNS-rebinding page (evil.example resolving to
+// 127.0.0.1) is same-origin to the browser but still sends its own name.
+// - Not cross-site: another site's page can fire a request at 127.0.0.1, and
+// Sec-Fetch-Site / Origin say so.
+const LOCAL_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
+
+function hostnameOf(hostHeader: string | undefined): string | null {
+ if (!hostHeader) return null;
+ try {
+ return new URL(`http://${hostHeader}`).hostname.toLowerCase();
+ } catch {
+ return null;
+ }
+}
+
+function isCrossSite(req: Request): boolean {
+ const site = req.headers['sec-fetch-site'];
+ if (typeof site === 'string' && site !== 'same-origin' && site !== 'none') return true;
+ const origin = req.headers.origin;
+ if (typeof origin === 'string' && origin !== 'null') {
+ let originHost: string;
+ try {
+ originHost = new URL(origin).hostname.toLowerCase();
+ } catch {
+ return true;
+ }
+ if (!LOCAL_HOSTNAMES.has(originHost)) return true;
+ }
+ return false;
+}
+
+export function desktopSignInAllowed(req: Request): boolean {
+ if (process.env.FREEAPI_DESKTOP !== '1') return false;
+ if (!isLoopbackRemote(req)) return false;
+ const host = hostnameOf(req.headers.host);
+ if (!host || !LOCAL_HOSTNAMES.has(host)) return false;
+ return !isCrossSite(req);
+}
+
// Has the dashboard been set up yet, and is this caller authenticated?
+// `desktop` tells the dashboard it can fetch a session instead of showing the
+// sign-in form.
authRouter.get('/status', (req: Request, res: Response) => {
const session = validateSession(bearer(req));
res.json({
needsSetup: userCount() === 0,
authenticated: !!session,
email: session?.email ?? null,
+ desktop: desktopSignInAllowed(req),
});
});
+authRouter.post('/desktop-session', (req: Request, res: Response) => {
+ if (!desktopSignInAllowed(req)) {
+ res.status(403).json({ error: { message: 'Desktop sign-in is only available on this computer.', type: 'desktop_signin_forbidden' } });
+ return;
+ }
+ res.json({ token: desktopSessionToken() });
+});
+
// First-run account creation. Only allowed while there are zero users, so it
// can't be used to add accounts once the dashboard is claimed.
authRouter.post('/setup', (req: Request, res: Response) => {
diff --git a/server/src/services/auth.ts b/server/src/services/auth.ts
index 6c48ef79..7b4f8960 100644
--- a/server/src/services/auth.ts
+++ b/server/src/services/auth.ts
@@ -55,6 +55,18 @@ export function verifyCredentials(email: string, password: string): SessionUser
return { userId: row.id, email: row.email };
}
+/** Desktop app only: a session for the install's account, creating the hidden
+ * machine account (`desktop@localhost`, random password nobody knows) on first
+ * run. The desktop window gets this over IPC; a browser tab on the same
+ * machine gets it from POST /api/auth/desktop-session (routes/auth.ts). */
+export function desktopSessionToken(): string {
+ if (userCount() === 0) {
+ createUser('desktop@localhost', crypto.randomBytes(24).toString('hex'));
+ }
+ const first = getDb().prepare('SELECT id FROM users ORDER BY id ASC LIMIT 1').get() as { id: number };
+ return createSession(first.id);
+}
+
/** Mint a session and return the raw token (only the hash is persisted). */
export function createSession(userId: number): string {
const token = crypto.randomBytes(32).toString('hex');