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/proxy fail closed upstream v015 (#1539)

Vladislav7069f8c82d82
diff --git a/.env.example b/.env.example
index 22530225..f8b108a9 100644
--- a/.env.example
+++ b/.env.example
@@ -96,6 +96,14 @@ PORT=3001
# proxy entirely.
# NO_PROXY=localhost,127.0.0.1,.internal.corp
+# Optional fail-closed outbound policy. These platform IDs MUST use a proxy:
+# if the proxy is missing, disabled, bypassed, or its agent cannot be built,
+# return an explicit error instead of silently connecting directly.
+# Non-listed platforms keep the normal routing behavior. This controls NETWORK
+# transport only; it does not disable model/provider failover in auto routing.
+# Example: require Gemini to use your configured SOCKS5 tunnel.
+# PROXY_REQUIRED_PLATFORMS=google
+
# Local and LAN destinations (localhost, 127.0.0.0/8, ::1, 0.0.0.0, RFC1918 /
# ULA / CGNAT addresses) always bypass the proxy — a remote proxy has no route
# back to your own machine, and an IP literal makes Tor log "giving Tor only an
diff --git a/server/src/__tests__/lib/proxy.test.ts b/server/src/__tests__/lib/proxy.test.ts
index 4e9a3156..f3839244 100644
--- a/server/src/__tests__/lib/proxy.test.ts
+++ b/server/src/__tests__/lib/proxy.test.ts
@@ -53,6 +53,7 @@ const PROXY_ENV_VARS = [
'HTTPS_PROXY',
'HTTP_PROXY',
'NO_PROXY',
+ 'PROXY_REQUIRED_PLATFORMS',
'FREEAPI_PROXY_LOCAL_DESTINATIONS',
'FREEAPI_BLOCK_PRIVATE_PROVIDER_URLS',
];
@@ -537,6 +538,99 @@ describe('proxyFetch routing', () => {
});
});
+
+describe('opt-in required proxy transport (fail closed)', () => {
+ const googleUrl = 'https://generativelanguage.googleapis.com/v1beta/models';
+
+ it('rejects Google without any proxy instead of fetching directly', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toMatchObject({ code: 'PROXY_REQUIRED_UNAVAILABLE' });
+ expect(direct).not.toHaveBeenCalled();
+ });
+
+ it('rejects a globally disabled proxy without direct Google egress', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ applyProxyUrl('socks5h://127.0.0.1:1080');
+ applyProxyEnabled(false);
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toThrow('proxy routing disabled or bypassed');
+ expect(direct).not.toHaveBeenCalled();
+ });
+
+ it('rejects a Google platform bypass and NO_PROXY without direct egress', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'GOOGLE';
+ applyProxyUrl('socks5h://127.0.0.1:1080');
+ applyProxyBypass('google');
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toMatchObject({ code: 'PROXY_REQUIRED_UNAVAILABLE' });
+ expect(direct).not.toHaveBeenCalled();
+
+ applyProxyBypass('');
+ process.env.NO_PROXY = 'generativelanguage.googleapis.com';
+ applyProxyUrl('socks5h://127.0.0.1:1080');
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toMatchObject({ code: 'PROXY_REQUIRED_UNAVAILABLE' });
+ expect(direct).not.toHaveBeenCalled();
+ });
+
+ it('does not silently use direct fetch when the global SOCKS agent fails to construct', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ applyProxyUrl('socks5h://127.0.0.1:not-a-port');
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toThrow('proxy not configured or proxy agent unavailable');
+ // The negative agent cache must also be fail-closed on the next request.
+ await expect(proxyFetch(googleUrl, undefined, 'google'))
+ .rejects.toMatchObject({ code: 'PROXY_REQUIRED_UNAVAILABLE' });
+ expect(direct).not.toHaveBeenCalled();
+ });
+
+ it('does not switch from a broken per-key proxy to a working global proxy', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ applyProxyUrl('http://127.0.0.1:8080');
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await expect(withKeyProxy('socks5h://127.0.0.1:not-a-port', () =>
+ proxyFetch(googleUrl, undefined, 'google'),
+ )).rejects.toThrow('per-key proxy agent unavailable');
+ // No proxy dispatcher may be supplied to global fetch in this case either.
+ expect(direct).not.toHaveBeenCalled();
+ });
+
+ it('still permits explicitly direct non-Google platforms', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ applyProxyUrl('socks5h://127.0.0.1:1080');
+ applyProxyBypass('mistral');
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+
+ await proxyFetch('https://api.mistral.ai/v1/chat/completions', undefined, 'mistral');
+ expect(direct).toHaveBeenCalledTimes(1);
+ expect((direct.mock.calls[0][1] as any)?.dispatcher).toBeUndefined();
+ });
+
+ it('uses the SOCKS agent for Google when available, without direct fetch', async () => {
+ process.env.PROXY_REQUIRED_PLATFORMS = 'google';
+ applyProxyUrl('socks5h://127.0.0.1:1080');
+ const direct = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+ const proxied = stubHttpsRequest();
+
+ const response = await proxyFetch(googleUrl, { method: 'GET' }, 'google');
+ expect(response.status).toBe(200);
+ expect(proxied).toHaveBeenCalledTimes(1);
+ expect(direct).not.toHaveBeenCalled();
+ });
+});
+
// #951: a local destination — Ollama/llama.cpp/LM Studio on 127.0.0.1, or on
// the LAN at 192.168.1.20 — is unreachable through a remote proxy, and because
// an IP literal must go on the wire as ATYP 0x01 (an IP) regardless of the
diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.ts
index 2d459aa4..11e2e797 100644
--- a/server/src/lib/proxy.ts
+++ b/server/src/lib/proxy.ts
@@ -867,6 +867,27 @@ export async function proxyFetch(
}
}
+/**
+ * Opt-in no-direct-egress policy for sensitive platforms.
+ *
+ * PROXY_REQUIRED_PLATFORMS=google means that any Google provider request
+ * without a working proxy transport must fail rather than silently go direct.
+ * This is independent of model failover (which the request router controls).
+ */
+function requiresOutboundProxy(platform?: string): boolean {
+ if (!platform) return false;
+ return readEnv('PROXY_REQUIRED_PLATFORMS')
+ .split(',')
+ .some(value => value.trim().toLowerCase() === platform.toLowerCase());
+}
+
+function proxyRequiredError(platform: string | undefined, reason: string): Error {
+ return Object.assign(
+ new Error(`Outbound proxy required for ${platform ?? 'unknown'}: ${reason}`),
+ { code: 'PROXY_REQUIRED_UNAVAILABLE' },
+ );
+}
+
/** Route the request through the configured proxy (or straight to fetch). */
async function dispatchFetch(
url: string,
@@ -879,6 +900,7 @@ async function dispatchFetch(
// call) takes precedence over the global proxy for THIS request. Empty
// string (the store default) means "fall back to global".
const perKeyUrl = perKeyProxyStore.getStore() ?? '';
+ const proxyRequired = requiresOutboundProxy(platform);
if (perKeyUrl) {
// Every bypass still applies, unchanged: the global on/off switch, the
// per-platform bypass list, NO_PROXY, and local/LAN destinations. A
@@ -893,14 +915,20 @@ async function dispatchFetch(
}
return fetch(url, { ...init, dispatcher: resolved.dispatcher } as unknown as RequestInit);
}
+ if (proxyRequired) {
+ throw proxyRequiredError(platform, 'per-key proxy agent unavailable');
+ }
}
- // Per-key proxy failed to build → fall through to the global/direct path.
+ // Non-required platforms keep their historical global/direct fallback.
}
// Bypass check: disabled globally, this platform is exempt, the upstream
// host is listed in NO_PROXY, or it is a local/LAN destination no proxy can
// reach (#951).
if (shouldBypassProxy(url, platform)) {
+ if (proxyRequired) {
+ throw proxyRequiredError(platform, 'proxy routing disabled or bypassed');
+ }
return fetch(url, init);
}
@@ -910,8 +938,12 @@ async function dispatchFetch(
const resolved = await resolveDispatcher();
- // No dispatcher (no proxy URL configured, or it failed to build) → direct
+ // For required platforms, a missing/failed proxy agent is never a
+ // reason to attempt direct egress (including cached constructor failures).
if (!resolved) {
+ if (proxyRequired) {
+ throw proxyRequiredError(platform, 'proxy not configured or proxy agent unavailable');
+ }
return fetch(url, init);
}