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

feat(proxy): accept socks5h/socks4a and honour standard proxy env vars (#643)

Tashfeen2e24718fa124
diff --git a/.env.example b/.env.example
index 819d0ec7..82483f1a 100644
--- a/.env.example
+++ b/.env.example
@@ -33,6 +33,22 @@ PORT=3001
# to disable proxy rate limiting.
# PROXY_RATE_LIMIT_RPM=120
+# Outbound proxy for provider requests. Normally set in the dashboard
+# (Keys → Outbound proxy); these env vars are for headless installs.
+# Schemes: http, https, socks4, socks4a, socks5, socks5h. The `h`/`a` variants
+# resolve DNS at the proxy, which is what you want on a DNS-poisoned network.
+# Precedence: PROXY_URL → dashboard setting → ALL_PROXY → HTTPS_PROXY →
+# HTTP_PROXY. The standard vars are also read in their lower-case spellings.
+# PROXY_URL=socks5h://127.0.0.1:1080
+# ALL_PROXY=socks5h://127.0.0.1:1080
+# HTTPS_PROXY=http://proxy.corp.com:8080
+# HTTP_PROXY=http://proxy.corp.com:8080
+
+# Hosts that must be reached directly, bypassing the proxy above. Comma-
+# separated; a bare domain also covers its subdomains, and `*` disables the
+# proxy entirely.
+# NO_PROXY=localhost,127.0.0.1,.internal.corp
+
# Per-provider daily request cap, named PROVIDER_DAILY_REQUEST_CAP_<PLATFORM>
# (platform name upper-cased). Overrides the built-in default for that provider;
# set to 0 to disable the cap. Example — cap OpenRouter at 50 requests/day:
diff --git a/client/src/components/keys/proxy-settings-section.tsx b/client/src/components/keys/proxy-settings-section.tsx
index 55190450..f3f8a0c8 100644
--- a/client/src/components/keys/proxy-settings-section.tsx
+++ b/client/src/components/keys/proxy-settings-section.tsx
@@ -97,6 +97,7 @@ export function ProxySettingsSection() {
</p>
<ul className="list-disc list-inside mt-1 space-y-0.5">
<li><code className="font-mono">socks5://127.0.0.1:1080</code></li>
+ <li><code className="font-mono">socks5h://127.0.0.1:1080</code></li>
<li><code className="font-mono">http://proxy.corp.com:8080</code></li>
<li><code className="font-mono">socks5://user:pass@proxy:1080</code></li>
</ul>
diff --git a/server/src/__tests__/lib/proxy.test.ts b/server/src/__tests__/lib/proxy.test.ts
index 4a8583e5..1fbedcc9 100644
--- a/server/src/__tests__/lib/proxy.test.ts
+++ b/server/src/__tests__/lib/proxy.test.ts
@@ -1,4 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { EventEmitter } from 'events';
+import https from 'https';
import {
applyProxyUrl,
applyProxyEnabled,
@@ -6,15 +8,30 @@ import {
getProxyUrl,
isProxyEnabled,
getProxyBypassPlatforms,
+ getNoProxyRules,
isProxyActive,
+ isSocksProxyUrl,
+ PROXY_SCHEMES,
proxyFetch,
describeAbort,
} from '../../lib/proxy.js';
+// Every env var the proxy config reads, in both the upper- and lower-case
+// spellings the convention allows. Cleared around each test so a developer
+// machine that genuinely sits behind a corporate proxy doesn't fail the suite.
+const PROXY_ENV_VARS = ['PROXY_URL', 'ALL_PROXY', 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY'];
+
+function clearProxyEnv(): void {
+ for (const name of PROXY_ENV_VARS) {
+ delete process.env[name];
+ delete process.env[name.toLowerCase()];
+ }
+}
+
// Reset module-level proxy state before each test so cases don't bleed into
// each other (the lib keeps a process-wide config + a short dispatcher cache).
beforeEach(() => {
- delete process.env.PROXY_URL;
+ clearProxyEnv();
applyProxyEnabled(true);
applyProxyBypass('');
applyProxyUrl(''); // clears the URL and the dispatcher cache
@@ -22,7 +39,7 @@ beforeEach(() => {
afterEach(() => {
vi.restoreAllMocks();
- delete process.env.PROXY_URL;
+ clearProxyEnv();
});
const okResponse = () => ({ ok: true, status: 200 }) as Response;
@@ -61,6 +78,254 @@ describe('proxy config accessors', () => {
});
});
+// #630: `socks5h://` (and its SOCKS4 sibling `socks4a://`) ask the proxy to
+// resolve DNS, which is the whole point for users on DNS-poisoned networks.
+// Scheme detection used to be `startsWith('socks5:') || startsWith('socks4:')`,
+// so socks5h fell through to the undici ProxyAgent — which has no idea what
+// SOCKS is — and every request failed. socks-proxy-agent has understood both
+// schemes natively all along.
+describe('SOCKS scheme detection (#630)', () => {
+ it('recognises every SOCKS scheme socks-proxy-agent supports', () => {
+ expect(isSocksProxyUrl('socks5://127.0.0.1:1080')).toBe(true);
+ expect(isSocksProxyUrl('socks5h://127.0.0.1:1080')).toBe(true);
+ expect(isSocksProxyUrl('socks4://127.0.0.1:1080')).toBe(true);
+ expect(isSocksProxyUrl('socks4a://127.0.0.1:1080')).toBe(true);
+ });
+
+ it('is case-insensitive about the scheme', () => {
+ expect(isSocksProxyUrl('SOCKS5H://127.0.0.1:1080')).toBe(true);
+ });
+
+ it('does not treat HTTP proxies as SOCKS', () => {
+ expect(isSocksProxyUrl('http://proxy:8080')).toBe(false);
+ expect(isSocksProxyUrl('https://proxy:8443')).toBe(false);
+ expect(isSocksProxyUrl('')).toBe(false);
+ });
+
+ it('exposes the accepted scheme list for the settings validator', () => {
+ expect(PROXY_SCHEMES).toEqual(
+ expect.arrayContaining(['http:', 'https:', 'socks4:', 'socks4a:', 'socks5:', 'socks5h:']),
+ );
+ });
+});
+
+// SOCKS requests never go through global fetch() — they ride http/https.request
+// with a SocksProxyAgent. Stubbing https.request lets us assert *which* agent
+// the dispatcher picked (and that socks5h parsed into a real SOCKS5 agent)
+// without opening a socket.
+function stubHttpsRequest() {
+ return vi.spyOn(https, 'request').mockImplementation(((_opts: any, cb: any) => {
+ const req = new EventEmitter() as any;
+ req.write = () => {};
+ req.destroy = () => {};
+ req.end = () => {
+ const res = new EventEmitter() as any;
+ res.statusCode = 200;
+ res.statusMessage = 'OK';
+ res.headers = {};
+ res.destroy = () => {};
+ cb(res);
+ setImmediate(() => res.emit('end'));
+ };
+ return req;
+ }) as any);
+}
+
+describe('proxyFetch dispatcher selection for SOCKS schemes (#630)', () => {
+ const cases: Array<[string, number]> = [
+ ['socks5://127.0.0.1:1080', 5],
+ ['socks5h://127.0.0.1:1080', 5],
+ ['socks4://127.0.0.1:1080', 4],
+ ['socks4a://127.0.0.1:1080', 4],
+ ];
+
+ for (const [url, socksType] of cases) {
+ it(`routes ${url} through a SocksProxyAgent, not undici`, async () => {
+ applyProxyUrl(url);
+ const fetchSpy = vi.spyOn(global, 'fetch');
+ const reqSpy = stubHttpsRequest();
+
+ const res = await proxyFetch('https://api.example.com/v1', { method: 'POST' }, 'groq');
+
+ expect(res.status).toBe(200);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ const agent = (reqSpy.mock.calls[0][0] as any).agent;
+ expect(agent?.proxy?.type).toBe(socksType);
+ expect(agent?.proxy?.port).toBe(1080);
+ });
+ }
+});
+
+// #353: HTTPS_PROXY / HTTP_PROXY / ALL_PROXY / NO_PROXY are the de-facto
+// standard for every other CLI on the box. Honouring them means a user who
+// already exported them for curl/git gets a working app with no extra config —
+// but an explicitly configured dashboard proxy must still win over ambient env.
+describe('standard proxy env vars (#353)', () => {
+ it('PROXY_URL wins over everything, including the dashboard value', () => {
+ process.env.PROXY_URL = 'http://explicit:8080';
+ process.env.ALL_PROXY = 'socks5://all:1080';
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ applyProxyUrl('http://db-proxy:3128');
+ expect(getProxyUrl()).toBe('http://explicit:8080');
+ });
+
+ it('a dashboard-configured proxy beats the ambient standard vars', () => {
+ process.env.ALL_PROXY = 'socks5://all:1080';
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ process.env.HTTP_PROXY = 'http://http-proxy:3128';
+ applyProxyUrl('socks5h://db-proxy:1080');
+ expect(getProxyUrl()).toBe('socks5h://db-proxy:1080');
+ });
+
+ it('falls back to ALL_PROXY when nothing is configured', () => {
+ process.env.ALL_PROXY = 'socks5://all:1080';
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ process.env.HTTP_PROXY = 'http://http-proxy:3128';
+ applyProxyUrl('');
+ expect(getProxyUrl()).toBe('socks5://all:1080');
+ });
+
+ it('prefers HTTPS_PROXY over HTTP_PROXY', () => {
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ process.env.HTTP_PROXY = 'http://http-proxy:3128';
+ applyProxyUrl('');
+ expect(getProxyUrl()).toBe('http://https-proxy:3128');
+ });
+
+ it('falls back to HTTP_PROXY last', () => {
+ process.env.HTTP_PROXY = 'http://http-proxy:3128';
+ applyProxyUrl('');
+ expect(getProxyUrl()).toBe('http://http-proxy:3128');
+ });
+
+ it('accepts the lower-case spellings the convention allows', () => {
+ process.env.https_proxy = 'http://lower:3128';
+ applyProxyUrl('');
+ expect(getProxyUrl()).toBe('http://lower:3128');
+ });
+
+ it('ignores blank env values', () => {
+ process.env.ALL_PROXY = ' ';
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ applyProxyUrl('');
+ expect(getProxyUrl()).toBe('http://https-proxy:3128');
+ });
+});
+
+describe('proxy source logging (#353)', () => {
+ it('names the source that won', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ applyProxyUrl('');
+ expect(log.mock.calls.flat().join(' ')).toContain('HTTPS_PROXY');
+ });
+
+ it('names the dashboard as the source when the DB value wins', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ process.env.HTTPS_PROXY = 'http://https-proxy:3128';
+ applyProxyUrl('http://db-proxy:3128');
+ expect(log.mock.calls.flat().join(' ')).toContain('dashboard');
+ });
+
+ it('never logs credentials embedded in the proxy URL', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+ process.env.ALL_PROXY = 'socks5h://alice:[email protected]:1080';
+ applyProxyUrl('');
+ const logged = log.mock.calls.flat().join(' ');
+ expect(logged).not.toContain('hunter2');
+ expect(logged).not.toContain('alice');
+ expect(logged).toContain('***@proxy.internal:1080');
+ });
+
+ it('redacts credentials in the dispatcher-failure log too', async () => {
+ const err = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ // A failed dispatcher falls back to a direct fetch — stub it so the test
+ // never touches the network.
+ vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+ // A port outside the valid range makes SocksProxyAgent throw on construction.
+ applyProxyUrl('socks5h://alice:[email protected]:not-a-port');
+ await proxyFetch('https://api.example.com/v1', undefined, 'groq');
+ const logged = err.mock.calls.flat().join(' ');
+ expect(logged).not.toContain('hunter2');
+ });
+});
+
+describe('NO_PROXY bypass (#353)', () => {
+ const dispatcherFor = async (url: string) => {
+ const spy = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
+ await proxyFetch(url, { method: 'POST' }, 'groq');
+ return (spy.mock.calls[0][1] as any)?.dispatcher;
+ };
+
+ it('parses a comma-separated list, lower-cased', () => {
+ process.env.NO_PROXY = 'localhost, .Internal.Corp ,, 10.0.0.1';
+ applyProxyUrl('http://proxy:8080');
+ expect(getNoProxyRules()).toEqual(['localhost', '.internal.corp', '10.0.0.1']);
+ });
+
+ it('bypasses an exact host match', async () => {
+ process.env.NO_PROXY = 'api.example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('still proxies hosts that do not match', async () => {
+ process.env.NO_PROXY = 'api.example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.groq.com/v1')).toBeDefined();
+ });
+
+ it('treats a bare domain as a suffix match on its subdomains', async () => {
+ process.env.NO_PROXY = 'example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('does not let a suffix rule match an unrelated host that merely ends with it', async () => {
+ process.env.NO_PROXY = 'example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://notexample.com/v1')).toBeDefined();
+ });
+
+ it('supports the leading-dot spelling', async () => {
+ process.env.NO_PROXY = '.example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('matches case-insensitively', async () => {
+ process.env.NO_PROXY = 'API.EXAMPLE.COM';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('ignores a port qualifier on the rule', async () => {
+ process.env.NO_PROXY = 'api.example.com:443';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('"*" bypasses every host', async () => {
+ process.env.NO_PROXY = '*';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.groq.com/v1')).toBeUndefined();
+ });
+
+ it('accepts the lower-case spelling', async () => {
+ process.env.no_proxy = 'api.example.com';
+ applyProxyUrl('http://proxy:8080');
+ expect(await dispatcherFor('https://api.example.com/v1')).toBeUndefined();
+ });
+
+ it('leaves the per-platform bypass list untouched', () => {
+ process.env.NO_PROXY = 'api.example.com';
+ applyProxyBypass('groq');
+ applyProxyUrl('http://proxy:8080');
+ expect(getProxyBypassPlatforms()).toEqual(['groq']);
+ });
+});
+
describe('proxyFetch routing', () => {
it('passes straight through to fetch when no proxy is configured (default for all users)', async () => {
const spy = vi.spyOn(global, 'fetch').mockResolvedValue(okResponse());
diff --git a/server/src/__tests__/routes/settings-proxy.test.ts b/server/src/__tests__/routes/settings-proxy.test.ts
new file mode 100644
index 00000000..18cde34a
--- /dev/null
+++ b/server/src/__tests__/routes/settings-proxy.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import type { Express } from 'express';
+import { createApp } from '../../app.js';
+import { initDb } from '../../db/index.js';
+import { mintDashboardToken } from '../helpers/auth.js';
+import { applyProxyUrl } from '../../lib/proxy.js';
+
+async function request(app: Express, method: string, path: string, body: any, token: string) {
+ const server = app.listen(0);
+ const addr = server.address() as any;
+ const res = await fetch(`http://127.0.0.1:${addr.port}${path}`, {
+ method,
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: JSON.stringify(body),
+ });
+ const raw = await res.text();
+ server.close();
+ let json: any = null;
+ try { json = JSON.parse(raw); } catch {}
+ return { status: res.status, body: json };
+}
+
+// PUT /api/settings/proxy is the only place a proxy URL is validated, so the
+// scheme allow-list here is what actually decides whether a user can save
+// `socks5h://` from the dashboard (#630).
+describe('PUT /api/settings/proxy scheme validation', () => {
+ let app: Express;
+ let token: string;
+
+ beforeAll(() => {
+ process.env.ENCRYPTION_KEY = '0'.repeat(64);
+ delete process.env.PROXY_URL;
+ initDb(':memory:');
+ app = createApp();
+ token = mintDashboardToken();
+ });
+
+ afterAll(() => {
+ applyProxyUrl('');
+ });
+
+ const accepted = [
+ 'http://proxy.corp.com:8080',
+ 'https://proxy.corp.com:8443',
+ 'socks5://127.0.0.1:1080',
+ 'socks5h://127.0.0.1:1080',
+ 'socks4://127.0.0.1:1080',
+ 'socks4a://127.0.0.1:1080',
+ ];
+
+ for (const proxyUrl of accepted) {
+ it(`accepts ${proxyUrl}`, async () => {
+ const { status, body } = await request(app, 'PUT', '/api/settings/proxy', { proxyUrl }, token);
+ expect(status).toBe(200);
+ expect(body.proxyUrl).toBe(proxyUrl);
+ });
+ }
+
+ it('accepts socks5h with credentials', async () => {
+ const proxyUrl = 'socks5h://user:[email protected]:1080';
+ const { status, body } = await request(app, 'PUT', '/api/settings/proxy', { proxyUrl }, token);
+ expect(status).toBe(200);
+ expect(body.proxyUrl).toBe(proxyUrl);
+ });
+
+ it('rejects an unsupported scheme', async () => {
+ const { status, body } = await request(app, 'PUT', '/api/settings/proxy', { proxyUrl: 'ftp://proxy:21' }, token);
+ expect(status).toBe(400);
+ expect(body.error.message).toMatch(/socks5h/);
+ });
+
+ it('rejects a malformed URL', async () => {
+ const { status, body } = await request(app, 'PUT', '/api/settings/proxy', { proxyUrl: 'not a url' }, token);
+ expect(status).toBe(400);
+ expect(body.error.type).toBe('invalid_request_error');
+ });
+
+ it('clears the proxy on an empty string', async () => {
+ const { status, body } = await request(app, 'PUT', '/api/settings/proxy', { proxyUrl: '' }, token);
+ expect(status).toBe(200);
+ expect(body.proxyUrl).toBe('');
+ });
+});
diff --git a/server/src/lib/proxy.ts b/server/src/lib/proxy.ts
index 73387018..716ced16 100644
--- a/server/src/lib/proxy.ts
+++ b/server/src/lib/proxy.ts
@@ -22,10 +22,101 @@ async function loadSocksAgent(): Promise<Ctor<unknown>> {
return _socksAgentCtor;
}
+// SOCKS schemes socks-proxy-agent understands. `socks5h`/`socks4a` are the
+// "resolve DNS at the proxy" variants (#630) — the ones that matter on
+// DNS-poisoned networks, where resolving the upstream hostname locally is
+// exactly what fails. They are ordinary SOCKS URLs to the agent; only our
+// scheme detection ever needed teaching.
+const SOCKS_SCHEMES = ['socks5:', 'socks5h:', 'socks4:', 'socks4a:'] as const;
+
+/** Every proxy scheme the app accepts. Shared with the settings validator. */
+export const PROXY_SCHEMES: readonly string[] = ['http:', 'https:', ...SOCKS_SCHEMES];
+
+/** True when the URL names a SOCKS scheme (so it needs SocksProxyAgent, not undici). */
+export function isSocksProxyUrl(url: string): boolean {
+ const colon = url.indexOf(':');
+ if (colon < 0) return false;
+ return (SOCKS_SCHEMES as readonly string[]).includes(url.slice(0, colon + 1).toLowerCase());
+}
+
+/** Strip any `user:pass@` userinfo so a proxy URL is safe to log. */
+function redactProxyUrl(url: string): string {
+ return url.replace(/\/\/[^@/]*@/, '//***@');
+}
+
+// Standard proxy env vars, in the order they are consulted. PROXY_URL is the
+// app's own knob and outranks the dashboard; the rest are ambient system
+// settings (#353) that only apply when nothing is configured in the dashboard.
+const ENV_PROXY_FALLBACKS = ['ALL_PROXY', 'HTTPS_PROXY', 'HTTP_PROXY'] as const;
+
+/** Read an env var in either the upper- or lower-case spelling. */
+function readEnv(name: string): string {
+ return (process.env[name] ?? process.env[name.toLowerCase()] ?? '').trim();
+}
+
+/**
+ * Decide which proxy URL wins, and say where it came from.
+ *
+ * PROXY_URL → dashboard setting → ALL_PROXY → HTTPS_PROXY → HTTP_PROXY.
+ *
+ * PROXY_URL stays on top because it has always documented itself as taking
+ * precedence (the dashboard hint says so). The standard vars sit *below* the
+ * dashboard: they're usually exported machine-wide for curl/git, so a proxy a
+ * user deliberately typed into the UI must not be silently overridden by them.
+ */
+function resolveProxySource(dbValue: string): { url: string; source: string } {
+ const explicit = readEnv('PROXY_URL');
+ if (explicit) return { url: explicit, source: 'PROXY_URL' };
+
+ const db = dbValue.trim();
+ if (db) return { url: db, source: 'dashboard' };
+
+ for (const name of ENV_PROXY_FALLBACKS) {
+ const value = readEnv(name);
+ if (value) return { url: value, source: name };
+ }
+ return { url: '', source: 'none' };
+}
+
+/**
+ * Parse a NO_PROXY list into match rules. Entries are hosts or suffixes,
+ * comma-separated: `localhost,.internal.corp,example.com,*`. A bare domain
+ * also covers its subdomains, matching curl/git behaviour.
+ */
+function parseNoProxy(value: string): string[] {
+ return value
+ .split(',')
+ .map(s => s.trim().toLowerCase())
+ .filter(Boolean)
+ .map(s => (s.startsWith('*.') ? s.slice(1) : s));
+}
+
+/** True when NO_PROXY says this hostname must be reached directly. */
+function noProxyMatches(hostname: string): boolean {
+ if (_noProxyRules.length === 0) return false;
+ // Trailing dot (FQDN form) and IPv6 brackets are noise for matching.
+ const host = hostname.toLowerCase().replace(/\.$/, '').replace(/^\[|\]$/g, '');
+
+ for (const rule of _noProxyRules) {
+ if (rule === '*') return true;
+ // A `host:port` qualifier narrows the rule to one port; we match on host,
+ // so compare the host half. Guarded so bare IPv6 rules aren't mangled.
+ const bare = /^[^:]+:\d+$/.test(rule) ? rule.slice(0, rule.lastIndexOf(':')) : rule;
+ if (!bare) continue;
+ if (bare.startsWith('.')) {
+ if (host === bare.slice(1) || host.endsWith(bare)) return true;
+ } else if (host === bare || host.endsWith(`.${bare}`)) {
+ return true;
+ }
+ }
+ return false;
+}
+
// Module-level proxy URL.
let _proxyUrl = '';
let _proxyEnabled = true;
let _bypassPlatforms = new Set<string>();
+let _noProxyRules: string[] = [];
let _initialized = false;
// Cache.
@@ -39,16 +130,15 @@ const CACHE_TTL_MS = 30_000;
/** Called once at startup (after initDb) and on PUT /api/settings/proxy. */
export function applyProxyUrl(dbValue: string): void {
- const envUrl = process.env.PROXY_URL?.trim();
- if (envUrl) {
- _proxyUrl = envUrl;
- } else {
- _proxyUrl = dbValue.trim();
- }
+ const { url, source } = resolveProxySource(dbValue);
+ _proxyUrl = url;
+ _noProxyRules = parseNoProxy(readEnv('NO_PROXY'));
cached = null;
if (_proxyUrl) {
- const masked = _proxyUrl.replace(/\/\/[^@]*@/, '//***@');
- console.log(`[proxy] Configured → ${masked}`);
+ console.log(`[proxy] Configured → ${redactProxyUrl(_proxyUrl)} (source: ${source})`);
+ if (_noProxyRules.length > 0) {
+ console.log(`[proxy] NO_PROXY direct for: ${_noProxyRules.join(', ')}`);
+ }
} else {
console.log('[proxy] Not configured — outbound requests go direct.');
}
@@ -86,13 +176,26 @@ export function getProxyBypassPlatforms(): string[] {
return [..._bypassPlatforms];
}
+/** The NO_PROXY rules currently in effect (parsed from the env at apply time). */
+export function getNoProxyRules(): string[] {
+ return [..._noProxyRules];
+}
+
/**
- * Returns true when a platform should NOT use the proxy.
- * True when: proxy is disabled globally, or the platform is in the bypass list.
+ * Returns true when a request should NOT use the proxy.
+ * True when: proxy is disabled globally, the platform is in the bypass list,
+ * or the upstream host is covered by NO_PROXY.
*/
-function shouldBypassProxy(platform?: string): boolean {
+function shouldBypassProxy(url: string, platform?: string): boolean {
if (!_proxyEnabled) return true;
if (platform && _bypassPlatforms.has(platform.toLowerCase())) return true;
+ if (_noProxyRules.length > 0) {
+ try {
+ if (noProxyMatches(new URL(url).hostname)) return true;
+ } catch {
+ // Unparseable URL — leave the routing decision to the caller/fetch.
+ }
+ }
return false;
}
@@ -115,7 +218,7 @@ async function resolveDispatcher(): Promise<{ dispatcher: unknown; isSocks: bool
}
try {
- const isSocks = _proxyUrl.startsWith('socks5:') || _proxyUrl.startsWith('socks4:');
+ const isSocks = isSocksProxyUrl(_proxyUrl);
if (isSocks) {
const SocksAgent = await loadSocksAgent();
@@ -129,8 +232,7 @@ async function resolveDispatcher(): Promise<{ dispatcher: unknown; isSocks: bool
cached = { dispatcher, proxyUrl: _proxyUrl, isSocks: false, ts: now };
return { dispatcher, isSocks: false };
} catch (err: any) {
- const masked = _proxyUrl.replace(/\/\/[^@]*@/, '//***@');
- console.error(`[proxy] Failed to create dispatcher for "${masked}": ${err.message}`);
+ console.error(`[proxy] Failed to create dispatcher for "${redactProxyUrl(_proxyUrl)}": ${err.message}`);
cached = { dispatcher: undefined, proxyUrl: _proxyUrl, isSocks: false, ts: now };
return undefined;
}
@@ -379,8 +481,9 @@ async function dispatchFetch(
requestType: ProxyRequestType,
timeoutMs: number | undefined,
): Promise<Response> {
- // Bypass check: disabled globally, or this platform is exempt.
- if (shouldBypassProxy(platform)) {
+ // Bypass check: disabled globally, this platform is exempt, or the upstream
+ // host is listed in NO_PROXY.
+ if (shouldBypassProxy(url, platform)) {
return fetch(url, init);
}
diff --git a/server/src/routes/settings.ts b/server/src/routes/settings.ts
index d398e8b8..436156fa 100644
--- a/server/src/routes/settings.ts
+++ b/server/src/routes/settings.ts
@@ -1,7 +1,7 @@
import { Router } from 'express';
import type { Request, Response } from 'express';
import { getUnifiedApiKey, regenerateUnifiedKey, getSetting, setSetting } from '../db/index.js';
-import { applyProxyUrl, applyProxyEnabled, applyProxyBypass, isProxyActive, getProxyUrl, isProxyEnabled, getProxyBypassPlatforms } from '../lib/proxy.js';
+import { applyProxyUrl, applyProxyEnabled, applyProxyBypass, isProxyActive, getProxyUrl, isProxyEnabled, getProxyBypassPlatforms, PROXY_SCHEMES } from '../lib/proxy.js';
import { getSavedFusionConfig, setSavedFusionConfig, savedFusionConfigSchema, getFusionMaxK } from '../services/fusion.js';
import { isUnifyEnabled, setUnifyEnabled, getUnifyOverrides, setUnifyOverrides, unifyOverridesSchema } from '../services/model-groups.js';
import { getClaudeModelMap, setClaudeModelMap } from '../services/anthropic-map.js';
@@ -250,9 +250,12 @@ settingsRouter.put('/proxy', (req: Request, res: Response) => {
if (trimmed) {
try {
const u = new URL(trimmed);
- if (!['http:', 'https:', 'socks5:', 'socks4:'].includes(u.protocol)) {
+ if (!PROXY_SCHEMES.includes(u.protocol)) {
res.status(400).json({
- error: { message: 'Proxy URL must use http, https, socks5, or socks4 scheme', type: 'invalid_request_error' },
+ error: {
+ message: 'Proxy URL must use http, https, socks5, socks5h, socks4, or socks4a scheme',
+ type: 'invalid_request_error',
+ },
});
return;
}