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): activate Premium through Chromium when Node's fetch can't reach the license service (#1592)

Tashfeen5d801ce73799
diff --git a/client/src/lib/api.test.ts b/client/src/lib/api.test.ts
index c456595b..3fa90bda 100644
--- a/client/src/lib/api.test.ts
+++ b/client/src/lib/api.test.ts
@@ -77,3 +77,38 @@ describe('apiFetch 401 handling', () => {
expect(events).toHaveLength(0)
})
})
+
+describe('apiFetch error messages', () => {
+ beforeEach(() => {
+ vi.stubGlobal('localStorage', makeStorage())
+ vi.stubGlobal('window', { dispatchEvent: () => true })
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('shows a plain-string error body instead of the bare status (Premium activation)', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse(502, {
+ error: 'Could not reach the license service. Check your connection and try again.',
+ })))
+ const { apiFetch } = await import('./api')
+ await expect(apiFetch('/api/premium/key', { method: 'POST', body: '{}' })).rejects.toMatchObject({
+ status: 502,
+ message: 'Could not reach the license service. Check your connection and try again.',
+ })
+ })
+
+ it('still reads { error: { message } } bodies', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse(400, { error: { message: 'Bad input', type: 'invalid_request_error' } })))
+ const { apiFetch } = await import('./api')
+ await expect(apiFetch('/api/keys')).rejects.toMatchObject({ status: 400, message: 'Bad input', code: 'invalid_request_error' })
+ })
+
+ it('falls back to the HTTP status when the body has no message', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse(500, {})))
+ const { apiFetch } = await import('./api')
+ await expect(apiFetch('/api/keys')).rejects.toMatchObject({ status: 500, message: 'HTTP 500' })
+ })
+})
diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts
index 6036b25f..38084038 100644
--- a/client/src/lib/api.ts
+++ b/client/src/lib/api.ts
@@ -54,7 +54,11 @@ export async function apiFetch<T>(path: string, options?: RequestInit): Promise<
// Surface the HTTP status and the machine-readable error type on the thrown
// Error so callers can branch on them (e.g. the setup form reveals a code
// field on a `setup_code_required` 403). `.message` behaviour is unchanged.
- const err = new Error(body.error?.message ?? `HTTP ${res.status}`) as ApiError;
+ // Most routes send { error: { message, type } }; some (e.g. /api/premium)
+ // send { error: '...' }. Without the string case those users only saw
+ // "HTTP 502".
+ const message = typeof body.error === 'string' ? body.error : body.error?.message;
+ const err = new Error(message || `HTTP ${res.status}`) as ApiError;
err.status = res.status;
err.code = body.error?.type;
throw err;
diff --git a/desktop/src/main.ts b/desktop/src/main.ts
index 4be37570..c3b51bc7 100644
--- a/desktop/src/main.ts
+++ b/desktop/src/main.ts
@@ -1,7 +1,7 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { app, dialog, ipcMain, clipboard, nativeTheme, screen, shell, type Tray } from 'electron';
-import { startServer, ensureSessionToken, getUnifiedApiKey, isAutoUpdateCheckEnabled, backupBeforeUpdate, outboundProxyUrl } from './server.mjs';
+import { app, dialog, ipcMain, clipboard, nativeTheme, net, screen, shell, type Tray } from 'electron';
+import { startServer, ensureSessionToken, getUnifiedApiKey, isAutoUpdateCheckEnabled, backupBeforeUpdate, outboundProxyUrl, setCatalogFallbackFetch } from './server.mjs';
import { loadConfig, saveConfig } from './config.js';
import { installFileLogger } from './logger.js';
import { buildTray, refreshTrayLocale } from './tray.js';
@@ -287,6 +287,11 @@ if (!app.requestSingleInstanceLock()) {
getLocale: () => locale,
});
+ // License activation and catalog sync retry through Chromium's network
+ // stack (OS certificate store + system proxy) when Node's fetch can't
+ // reach api.freellmapi.co, which some Windows PCs hit as "HTTP 502".
+ setCatalogFallbackFetch((input, init) => net.fetch(String(input), init));
+
try {
const { port } = await startServer({
dbPath,
diff --git a/desktop/src/server-host.ts b/desktop/src/server-host.ts
index 01768a4f..735a159b 100644
--- a/desktop/src/server-host.ts
+++ b/desktop/src/server-host.ts
@@ -49,6 +49,9 @@ export interface StartOptions {
preferredPort: number;
}
+// main.ts registers Electron's net.fetch here (see setCatalogFallbackFetch).
+export { setCatalogFallbackFetch } from '../../server/src/services/catalog-sync.js';
+
export interface ServerHandle {
server: Server;
port: number;
diff --git a/desktop/src/server.d.mts b/desktop/src/server.d.mts
index 6da0e775..d6c1e292 100644
--- a/desktop/src/server.d.mts
+++ b/desktop/src/server.d.mts
@@ -23,3 +23,6 @@ export function getUnifiedApiKey(): string;
export function isAutoUpdateCheckEnabled(): boolean;
export function backupBeforeUpdate(): string;
export function outboundProxyUrl(): string;
+export function setCatalogFallbackFetch(
+ fn: ((input: string | URL, init?: RequestInit) => Promise<Response>) | null,
+): void;
diff --git a/server/src/__tests__/services/catalog-fallback-fetch.test.ts b/server/src/__tests__/services/catalog-fallback-fetch.test.ts
new file mode 100644
index 00000000..f696a5c0
--- /dev/null
+++ b/server/src/__tests__/services/catalog-fallback-fetch.test.ts
@@ -0,0 +1,85 @@
+import { describe, it, expect, afterEach, vi } from 'vitest';
+import { catalogFetch, setCatalogFallbackFetch, validateLicenseKey } from '../../services/catalog-sync.js';
+
+// Node's fetch failing the TLS handshake surfaces as TypeError('fetch failed')
+// with the real reason on .cause — what Windows desktop users hit.
+function tlsFailure(): TypeError {
+ const err = new TypeError('fetch failed');
+ (err as { cause?: unknown }).cause = Object.assign(new Error('unable to get local issuer certificate'), {
+ code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
+ });
+ return err;
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+}
+
+afterEach(() => {
+ setCatalogFallbackFetch(null);
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+describe('catalogFetch', () => {
+ it('uses Node fetch and never the fallback when Node fetch works', async () => {
+ const nodeFetch = vi.fn(async () => json({ ok: true }));
+ const fallback = vi.fn(async () => json({ ok: 'fallback' }));
+ vi.stubGlobal('fetch', nodeFetch);
+ setCatalogFallbackFetch(fallback);
+
+ const res = await catalogFetch('https://catalog.test/v1/latest');
+ expect(await res.json()).toEqual({ ok: true });
+ expect(fallback).not.toHaveBeenCalled();
+ });
+
+ it('retries once through the fallback when Node fetch fails at the network level', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn(async () => { throw tlsFailure(); }));
+ const fallback = vi.fn(async () => json({ ok: 'fallback' }));
+ setCatalogFallbackFetch(fallback);
+
+ const init = { method: 'POST', body: '{}' };
+ const res = await catalogFetch('https://catalog.test/v1/license/activate', init);
+ expect(await res.json()).toEqual({ ok: 'fallback' });
+ expect(fallback).toHaveBeenCalledTimes(1);
+ expect(fallback).toHaveBeenCalledWith('https://catalog.test/v1/license/activate', init);
+ expect(String((console.warn as unknown as { mock: { calls: unknown[][] } }).mock.calls[0][0]))
+ .toContain('UNABLE_TO_GET_ISSUER_CERT_LOCALLY');
+ });
+
+ it('rethrows without a fallback registered (server and Docker installs)', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => { throw tlsFailure(); }));
+ await expect(catalogFetch('https://catalog.test/v1/latest')).rejects.toThrow('fetch failed');
+ });
+
+ it('does not retry a request that timed out', async () => {
+ const controller = new AbortController();
+ controller.abort(new DOMException('timed out', 'TimeoutError'));
+ vi.stubGlobal('fetch', vi.fn(async () => { throw new DOMException('timed out', 'TimeoutError'); }));
+ const fallback = vi.fn(async () => json({}));
+ setCatalogFallbackFetch(fallback);
+
+ await expect(catalogFetch('https://catalog.test/v1/latest', { signal: controller.signal })).rejects.toThrow();
+ expect(fallback).not.toHaveBeenCalled();
+ });
+});
+
+describe('validateLicenseKey', () => {
+ it('activates through the fallback when Node fetch cannot reach the service', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn(async () => { throw tlsFailure(); }));
+ setCatalogFallbackFetch(async () => json({ valid: true, plan: 'lifetime', status: 'active' }));
+
+ await expect(validateLicenseKey('fla_TESTKEY')).resolves.toMatchObject({ valid: true, plan: 'lifetime' });
+ });
+
+ it('returns null (unreachable) and logs the cause when both stacks fail', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn(async () => { throw tlsFailure(); }));
+ setCatalogFallbackFetch(async () => { throw new Error('net::ERR_CONNECTION_REFUSED'); });
+
+ await expect(validateLicenseKey('fla_TESTKEY')).resolves.toBeNull();
+ expect(warn.mock.calls.some(c => String(c[0]).includes('license activation unreachable: net::ERR_CONNECTION_REFUSED'))).toBe(true);
+ });
+});
diff --git a/server/src/routes/premium.ts b/server/src/routes/premium.ts
index 3fcea410..c0a978b4 100644
--- a/server/src/routes/premium.ts
+++ b/server/src/routes/premium.ts
@@ -5,6 +5,7 @@ import {
SETTING_LICENSE_KEY,
SETTING_LICENSE_STATUS,
catalogBaseUrl,
+ catalogFetch,
getCachedLicenseStatus,
getSyncState,
refreshLicenseStatus,
@@ -101,7 +102,7 @@ premiumRouter.post('/portal', async (_req: Request, res: Response) => {
return;
}
try {
- const r = await fetch(`${catalogBaseUrl()}/v1/portal`, {
+ const r = await catalogFetch(`${catalogBaseUrl()}/v1/portal`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }),
diff --git a/server/src/services/catalog-sync.ts b/server/src/services/catalog-sync.ts
index 4a06b6c4..f463ddca 100644
--- a/server/src/services/catalog-sync.ts
+++ b/server/src/services/catalog-sync.ts
@@ -70,6 +70,43 @@ export function catalogBaseUrl(): string {
return (process.env.CATALOG_BASE_URL ?? DEFAULT_BASE_URL).replace(/\/$/, '');
}
+type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
+
+let fallbackFetch: FetchLike | null = null;
+
+/**
+ * Register a second network stack for calls to the catalog service. The
+ * desktop app passes Electron's net.fetch (Chromium: the OS certificate
+ * verifier and system proxy, same as a browser). On some Windows PCs Node's
+ * fetch could not complete the TLS handshake to api.freellmapi.co, so license
+ * activation always showed "HTTP 502" while the same URL opened fine in a
+ * browser. Server and Docker installs never set this.
+ */
+export function setCatalogFallbackFetch(fn: FetchLike | null): void {
+ fallbackFetch = fn;
+}
+
+function describeFetchError(err: unknown): string {
+ const e = err as { message?: string; cause?: { code?: string; message?: string } } | undefined;
+ const cause = e?.cause?.code ?? e?.cause?.message;
+ return cause ? `${e?.message ?? 'fetch failed'} (${cause})` : String(e?.message ?? err);
+}
+
+/**
+ * fetch() for catalog-service calls. Tries Node's fetch first; when that
+ * fails at the network level (not a timeout) and a fallback is registered,
+ * retries once through it.
+ */
+export async function catalogFetch(input: string | URL, init?: RequestInit): Promise<Response> {
+ try {
+ return await fetch(input, init);
+ } catch (err) {
+ if (!fallbackFetch || init?.signal?.aborted) throw err;
+ console.warn(`[catalog-sync] ${describeFetchError(err)}; retrying through the desktop network stack`);
+ return fallbackFetch(input, init);
+ }
+}
+
function catalogPublicKey(): crypto.KeyObject {
const pem = process.env.CATALOG_PUBKEY ? process.env.CATALOG_PUBKEY.replace(/\\n/g, '\n') : PINNED_CATALOG_PUBKEY;
return crypto.createPublicKey({ key: pem, format: 'pem' });
@@ -1029,7 +1066,7 @@ export async function syncCatalog(force = false): Promise<SyncResult> {
const url = new URL(`${catalogBaseUrl()}/v1/latest`);
if (applied && !force) url.searchParams.set('since', applied);
- const res = await fetch(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
+ const res = await catalogFetch(url, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
if (res.status === 304) {
setSetting(SETTING_LAST_SYNC_MS, String(Date.now()));
@@ -1111,14 +1148,15 @@ export interface LicenseActivation {
*/
export async function validateLicenseKey(key: string, timeoutMs = FETCH_TIMEOUT_MS): Promise<LicenseActivation | null> {
try {
- const res = await fetch(`${catalogBaseUrl()}/v1/license/activate`, {
+ const res = await catalogFetch(`${catalogBaseUrl()}/v1/license/activate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }),
signal: AbortSignal.timeout(timeoutMs),
});
return (await res.json()) as LicenseActivation;
- } catch {
+ } catch (err) {
+ console.warn(`[catalog-sync] license activation unreachable: ${describeFetchError(err)}`);
return null;
}
}
@@ -1128,7 +1166,7 @@ export async function refreshLicenseStatus(): Promise<LicenseStatus | null> {
const key = getSetting(SETTING_LICENSE_KEY);
if (!key) return null;
try {
- const res = await fetch(`${catalogBaseUrl()}/v1/license/check`, {
+ const res = await catalogFetch(`${catalogBaseUrl()}/v1/license/check`, {
headers: { Authorization: `Bearer ${key}` },
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
});