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(keys): allow copying a full key on the desktop build without password re-verification (#786) (#810)
suantea (asuan_suan)ae08693b38ec
diff --git a/client/src/components/keys/copy-key-dialog.tsx b/client/src/components/keys/copy-key-dialog.tsxindex 41f89b42..201ddc70 100644--- a/client/src/components/keys/copy-key-dialog.tsx+++ b/client/src/components/keys/copy-key-dialog.tsx@@ -10,6 +10,16 @@ import { copyText } from '@/lib/clipboard'import { useI18n } from '@/i18n'import { toast } from '@/lib/toast'+// #786: the desktop build has no user-set password (its machine user's+// password is random and never shown), so the re-verification dialog would+// lock desktop users out of copying a full key. The desktop server skips+// re-auth (FREEAPI_DESKTOP) for local requests, so here we just hide the+// password field. Only the Electron preload sets this flag, so a browser+// reaching the same desktop server over LAN still gets the field — and the+// server still demands the password from it.+const isDesktopApp = typeof window !== 'undefined'+ && (window as Window & { __FREEAPI_DESKTOP__?: boolean }).__FREEAPI_DESKTOP__ === true+// #705: the list only ever shows a masked key, and the sole way to read one// back was to export every key to a file. This narrows that to one key, behind// the same password re-verification the export uses: a live session is not@@ -41,7 +51,9 @@ export function CopyKeyDialog({try {const { key } = await apiFetch<{ key: string }>(`/api/keys/${keyId}/reveal`, {method: 'POST',- headers: { 'x-reauth-password': password },+ // The desktop server skips re-auth for this local request (#786); the+ // web build still needs it.+ headers: isDesktopApp ? undefined : { 'x-reauth-password': password },})// A plain-HTTP LAN origin has no Clipboard API at all, so this falls back// to execCommand rather than throwing (#734). If even that fails the key@@ -75,25 +87,28 @@ export function CopyKeyDialog({</code><form onSubmit={submit} className="mt-4 space-y-4">- <div className="space-y-1.5">- <Label className="text-xs" htmlFor="reveal-password">{t('auth.password')}</Label>- <Input- id="reveal-password"- type="password"- autoFocus- autoComplete="current-password"- value={password}- onChange={e => setPassword(e.target.value)}- aria-invalid={!!error}- />- <FieldError error={error} />- </div>+ {!isDesktopApp && (+ <div className="space-y-1.5">+ <Label className="text-xs" htmlFor="reveal-password">{t('auth.password')}</Label>+ <Input+ id="reveal-password"+ type="password"+ autoFocus+ autoComplete="current-password"+ value={password}+ onChange={e => setPassword(e.target.value)}+ aria-invalid={!!error}+ />+ <FieldError error={error} />+ </div>+ )}+ {isDesktopApp && error && <FieldError error={error} />}<div className="flex items-center justify-end gap-2"><Button type="button" variant="outline" size="sm" onClick={() => onOpenChange(false)}>{t('common.cancel')}</Button>- <Button type="submit" size="sm" disabled={!password || busy}>+ <Button type="submit" size="sm" disabled={(!isDesktopApp && !password) || busy}><Copy className="size-3.5" />{t('keys.copyKey')}</Button>diff --git a/client/src/components/keys/export-keys-dialog.tsx b/client/src/components/keys/export-keys-dialog.tsxindex ebf10c26..fa52923a 100644--- a/client/src/components/keys/export-keys-dialog.tsx+++ b/client/src/components/keys/export-keys-dialog.tsx@@ -25,6 +25,13 @@ const FORMAT_OPTIONS: { value: ExportFormat; label: string; ext: string }[] = [const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');+// #786: the desktop build has no user-set password to re-enter, and its server+// skips re-auth for local requests, so the password step is skipped here too.+// Only the Electron preload sets this flag: a browser reaching the same desktop+// server over LAN still walks through the step, and the server still checks it.+const isDesktopApp = typeof window !== 'undefined'+ && (window as Window & { __FREEAPI_DESKTOP__?: boolean }).__FREEAPI_DESKTOP__ === true+async function downloadExport(format: ExportFormat, healthyOnly: boolean, password: string) {const token = getToken()const params = new URLSearchParams({ format })@@ -76,8 +83,8 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen? exportableKeys.filter(k => k.status === 'healthy').length: exportableKeys.length- async function handleExport(e: FormEvent) {- e.preventDefault()+ async function handleExport(e?: FormEvent) {+ e?.preventDefault()setExporting(true)setError(null)try {@@ -191,12 +198,13 @@ export function ExportKeysDialog({ open, onOpenChange }: { open: boolean; onOpen<Buttontype="button"className="w-full"- onClick={() => setStep('password')}- disabled={exportCount === 0}+ onClick={() => (isDesktopApp ? handleExport() : setStep('password'))}+ disabled={exportCount === 0 || exporting}><Download className="size-3.5" />- {t('keys.exportDownload')}+ {exporting ? t('keys.exporting') : t('keys.exportDownload')}</Button>+ {isDesktopApp && error && <FieldError error={error} />}</div>)}</DialogPopup>diff --git a/desktop/src/server-host.ts b/desktop/src/server-host.tsindex b9c0b366..85a66cf2 100644--- a/desktop/src/server-host.ts+++ b/desktop/src/server-host.ts@@ -32,6 +32,13 @@ export interface ServerHandle {export async function startServer(opts: StartOptions): Promise<ServerHandle> {process.env.CLIENT_DIST = opts.clientDist;+ // #786: the desktop build has no user-set password (the machine user's+ // password is random and never shown), so password re-verification for+ // key reveal / export would lock the user out. Mark the process as the+ // desktop embedder; the server then skips re-auth for those two endpoints,+ // and only for requests arriving over loopback — with LAN access on we bind+ // 0.0.0.0, and a remote viewer must still enter the password.+ process.env.FREEAPI_DESKTOP = '1';initDb(opts.dbPath);const app = createApp();const { server, port } = await listenWithScan(app, opts.host, opts.preferredPort);diff --git a/server/src/__tests__/routes/keys-desktop-reauth.test.ts b/server/src/__tests__/routes/keys-desktop-reauth.test.tsnew file mode 100644index 00000000..1854b0f4--- /dev/null+++ b/server/src/__tests__/routes/keys-desktop-reauth.test.ts@@ -0,0 +1,144 @@+import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest';+import express, { type Express } from 'express';+import { keysRouter } from '../../routes/keys.js';+import { requireAuth } from '../../middleware/requireAuth.js';+import { initDb, getDb } from '../../db/index.js';+import { mintDashboardToken } from '../helpers/auth.js';++// #786: the desktop build has no user-set password, so reveal/export skip the+// re-verification there — but only for a caller on the machine itself. The+// desktop app can bind 0.0.0.0 (its LAN-access toggle), and a LAN client of that+// server must still re-enter the password or the second factor is gone for the+// whole network. The real connection here is always loopback, so a middleware+// overrides req.socket with the address under test (the route reads+// req.socket.remoteAddress, never req.ip or X-Forwarded-For).++let token: string;++function appWithRemote(remoteAddr: string): Express {+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ Object.defineProperty(req, 'socket', { value: { remoteAddress: remoteAddr }, configurable: true });+ next();+ });+ app.use('/api/keys', requireAuth, keysRouter);+ return app;+}++async function call(app: Express, path: string, method: 'GET' | 'POST') {+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {+ method,+ headers: { Authorization: `Bearer ${token}` },+ });+ const body = await res.json().catch(() => null);+ server.close();+ return { status: res.status, body: body as any };+}++async function addKey(): Promise<number> {+ const app = appWithRemote('127.0.0.1');+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },+ body: JSON.stringify({ platform: 'groq', key: 'gsk_the_real_secret' }),+ });+ const body = await res.json() as { id: number };+ server.close();+ return body.id;+}++describe('Desktop re-auth bypass is loopback-only (#786)', () => {+ beforeAll(() => {+ process.env.ENCRYPTION_KEY = '0'.repeat(64);+ initDb(':memory:');+ token = mintDashboardToken();+ });++ beforeEach(() => {+ getDb().prepare('DELETE FROM api_keys').run();+ delete process.env.FREEAPI_DESKTOP;+ });++ afterAll(() => {+ delete process.env.FREEAPI_DESKTOP;+ });++ describe('reveal', () => {+ it('reveals without a password for a loopback caller on the desktop build', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ const id = await addKey();+ const { status, body } = await call(appWithRemote('127.0.0.1'), `/api/keys/${id}/reveal`, 'POST');+ expect(status).toBe(200);+ expect(body.key).toBe('gsk_the_real_secret');+ });++ it('accepts IPv6 and IPv4-mapped loopback forms', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ const id = await addKey();+ for (const addr of ['::1', '::ffff:127.0.0.1', '127.0.0.53']) {+ const { status } = await call(appWithRemote(addr), `/api/keys/${id}/reveal`, 'POST');+ expect(status, addr).toBe(200);+ }+ });++ it('still demands the password from a LAN caller on the desktop build', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ const id = await addKey();+ const { status, body } = await call(appWithRemote('192.168.1.42'), `/api/keys/${id}/reveal`, 'POST');+ expect(status).toBe(403);+ expect(body.error.type).toBe('authentication_error');+ expect(body.key).toBeUndefined();+ });++ it('demands the password from a loopback caller when the env is unset', async () => {+ const id = await addKey();+ const { status, body } = await call(appWithRemote('127.0.0.1'), `/api/keys/${id}/reveal`, 'POST');+ expect(status).toBe(403);+ expect(body.key).toBeUndefined();+ });+ });++ describe('export', () => {+ it('exports without a password for a loopback caller on the desktop build', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ await addKey();+ const { status, body } = await call(appWithRemote('127.0.0.1'), '/api/keys/export?format=json', 'GET');+ expect(status).toBe(200);+ expect(body.keys.length).toBe(1);+ });++ it('still demands the password from a LAN caller on the desktop build', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ await addKey();+ const { status, body } = await call(appWithRemote('192.168.1.42'), '/api/keys/export?format=json', 'GET');+ expect(status).toBe(403);+ expect(body.error.type).toBe('authentication_error');+ expect(body.keys).toBeUndefined();+ });++ it('demands the password from a loopback caller when the env is unset', async () => {+ await addKey();+ const { status } = await call(appWithRemote('127.0.0.1'), '/api/keys/export?format=json', 'GET');+ expect(status).toBe(403);+ });+ });++ it('does not take X-Forwarded-For as proof of being local', async () => {+ process.env.FREEAPI_DESKTOP = '1';+ const id = await addKey();+ const app = appWithRemote('192.168.1.42');+ const server = app.listen(0);+ const addr = server.address() as { port: number };+ const res = await fetch(`http://127.0.0.1:${addr.port}/api/keys/${id}/reveal`, {+ method: 'POST',+ headers: { Authorization: `Bearer ${token}`, 'X-Forwarded-For': '127.0.0.1' },+ });+ server.close();+ expect(res.status).toBe(403);+ });+});diff --git a/server/src/routes/keys.ts b/server/src/routes/keys.tsindex bc9887f9..8e9539d3 100644--- a/server/src/routes/keys.ts+++ b/server/src/routes/keys.ts@@ -345,16 +345,41 @@ keysRouter.delete('/:id/cooldowns', (req: Request, res: Response) => {res.json({ cleared });});+// Is the caller connecting from this machine? Read from the real socket peer+// address, NOT req.ip or X-Forwarded-For: those are caller-controlled, so+// trusting them here would let a remote caller claim to be local.+function isLoopbackRemote(req: Request): boolean {+ let addr = req.socket?.remoteAddress ?? '';+ // Node reports IPv4 loopback over a dual-stack socket as "::ffff:127.0.0.1".+ if (addr.startsWith('::ffff:')) addr = addr.slice(7);+ if (addr === '::1') return true;+ return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(addr);+}++// #786: the desktop build has no user-set password (its machine user's password+// is random and never shown), so re-verification would lock desktop users out of+// reading their own keys. The embedder marks the process+// (desktop/src/server-host.ts) and the two plaintext-key endpoints below skip+// re-auth for it — but ONLY for a request from this machine. The desktop app can+// bind 0.0.0.0 through its LAN-access toggle, and a remote viewer on that LAN+// still has to prove the password before it can lift a key.+function skipsReauth(req: Request): boolean {+ return process.env.FREEAPI_DESKTOP === '1' && isLoopbackRemote(req);+}+// Export keys — returns plaintext keys in the requested format.// GET /api/keys/export?format=json|env|csv&healthy=true// The response is the raw file download (Content-Type varies by format).-// Password re-verification via x-reauth-password header is required.+// Password re-verification via x-reauth-password header is required, except for+// a local request on the desktop build (see skipsReauth).keysRouter.get('/export', (req: Request, res: Response) => {const user = (req as any).user;- const password = req.headers['x-reauth-password'] as string | undefined;- if (!password || !verifyCredentials(user.email, password)) {- res.status(403).json({ error: { message: 'Password verification required to export keys', type: 'authentication_error' } });- return;+ if (!skipsReauth(req)) {+ const password = req.headers['x-reauth-password'] as string | undefined;+ if (!password || !verifyCredentials(user.email, password)) {+ res.status(403).json({ error: { message: 'Password verification required to export keys', type: 'authentication_error' } });+ return;+ }}const db = getDb();const format = (req.query.format as string) ?? 'json';@@ -465,13 +490,17 @@ keysRouter.get('/export', (req: Request, res: Response) => {// credential it otherwise only ever shows masked (#705). Exporting every key to// a file was the only way to read one back, which is a poor trade for "what is// the key on this row again?". Gated exactly like the export it narrows: the-// session alone is not enough, the password has to be re-entered.+// session alone is not enough, the password has to be re-entered — except for a+// local request on the desktop build, which has no password to re-enter (see+// skipsReauth; a LAN client of that same desktop server still needs one).keysRouter.post('/:id/reveal', (req: Request, res: Response) => {const user = (req as any).user;- const password = req.headers['x-reauth-password'] as string | undefined;- if (!password || !verifyCredentials(user.email, password)) {- res.status(403).json({ error: { message: 'Password verification required to reveal a key', type: 'authentication_error' } });- return;+ if (!skipsReauth(req)) {+ const password = req.headers['x-reauth-password'] as string | undefined;+ if (!password || !verifyCredentials(user.email, password)) {+ res.status(403).json({ error: { message: 'Password verification required to reveal a key', type: 'authentication_error' } });+ return;+ }}const id = parseInt(req.params.id as string, 10);