axm0121 commited on
Commit
ec56d47
·
verified ·
1 Parent(s): 065f39c

Preserve legacy proxy URL compatibility on current source runtime

Browse files

Normalize existing colon-four-part proxy URLs in memory while retaining latest proxy transport, per-account pools and TLS verification. Do not rewrite stored proxies or existing database records. REST migration and backups remain intact.

Files changed (2) hide show
  1. Dockerfile +2 -1
  2. patches/proxy-helper-compatible.js +397 -0
Dockerfile CHANGED
@@ -14,8 +14,9 @@ COPY --from=build /app/node_modules ./node_modules
14
  COPY --from=build /app/package.json ./package.json
15
  COPY --from=build /app/src ./src
16
  COPY --from=build /app/public/dist ./public/dist
17
- # Keep the current upstream chat/CLI/proxy code; restore Upstash REST persistence only.
18
  COPY patches/redis-rest.js /app/src/utils/redis.js
 
19
  COPY patches/rest-preflight.cjs /app/scripts/rest-preflight.cjs
20
  EXPOSE 3000
21
  CMD ["sh", "-c", "bun --no-env-file scripts/rest-preflight.cjs && exec bun --no-env-file src/server.js"]
 
14
  COPY --from=build /app/package.json ./package.json
15
  COPY --from=build /app/src ./src
16
  COPY --from=build /app/public/dist ./public/dist
17
+ # Keep current upstream chat/CLI code; restore REST and normalize legacy proxy URLs.
18
  COPY patches/redis-rest.js /app/src/utils/redis.js
19
+ COPY patches/proxy-helper-compatible.js /app/src/utils/proxy-helper.js
20
  COPY patches/rest-preflight.cjs /app/scripts/rest-preflight.cjs
21
  EXPOSE 3000
22
  CMD ["sh", "-c", "bun --no-env-file scripts/rest-preflight.cjs && exec bun --no-env-file src/server.js"]
patches/proxy-helper-compatible.js ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const { once } = require('node:events');
2
+ const { STATUS_CODES } = require('node:http');
3
+ const { isIP } = require('node:net');
4
+ const { PassThrough } = require('node:stream');
5
+ const { checkServerIdentity } = require('node:tls');
6
+ const axios = require('axios');
7
+ const { HttpsProxyAgent } = require('https-proxy-agent');
8
+ const { SocksProxyAgent } = require('socks-proxy-agent');
9
+ // The explicit entry bypasses Bun's built-in undici shim, which ignores custom sockets.
10
+ const { Agent, Pool, ProxyAgent, errors, interceptors, request: proxyRequest } = require('undici/index.js');
11
+
12
+ const config = require('../config/index.js');
13
+ const { logger } = require('./logger');
14
+
15
+ // Per-account agent cache keyed by `${proxyUrl}::${email}`.
16
+ // LRU eviction when cache exceeds MAX_AGENT_CACHE_SIZE.
17
+ const proxyAgents = new Map()
18
+ const MAX_AGENT_CACHE_SIZE = 50
19
+ const PROXY_CONNECT_TIMEOUT_MS = 10_000;
20
+ const proxyUrls = new WeakMap();
21
+ const proxyTransports = new WeakMap();
22
+ // undici transport failures mapped onto the codes request.js already retries / cools down on.
23
+ const UNDICI_ERROR_CODES = {
24
+ UND_ERR_SOCKET: 'ECONNRESET',
25
+ UND_ERR_CONNECT_TIMEOUT: 'ETIMEDOUT',
26
+ UND_ERR_HEADERS_TIMEOUT: 'ECONNABORTED',
27
+ UND_ERR_BODY_TIMEOUT: 'ECONNABORTED',
28
+ UND_ERR_ABORTED: 'ERR_CANCELED'
29
+ };
30
+
31
+ /**
32
+ * Reuse the account's SOCKS/CONNECT implementation with an HTTP client that honors sockets.
33
+ */
34
+ const getProxyTransport = (proxyAgent) => {
35
+ let transport = proxyTransports.get(proxyAgent);
36
+ if (transport) return transport;
37
+
38
+ const dispatcher = proxyAgent instanceof HttpsProxyAgent ? new ProxyAgent({
39
+ uri: proxyAgent.proxy.href,
40
+ token: proxyAgent.proxy.username || proxyAgent.proxy.password
41
+ ? `Basic ${Buffer.from(`${decodeURIComponent(proxyAgent.proxy.username)}:${decodeURIComponent(proxyAgent.proxy.password)}`).toString('base64')}`
42
+ : undefined,
43
+ requestTls: { ...proxyAgent.options, timeout: PROXY_CONNECT_TIMEOUT_MS },
44
+ proxyTls: { ...proxyAgent.connectOpts, timeout: PROXY_CONNECT_TIMEOUT_MS },
45
+ clientFactory: (origin, options) => new Pool(origin, { ...options, headersTimeout: PROXY_CONNECT_TIMEOUT_MS })
46
+ }) : new Agent({
47
+ connect: async (options, callback) => {
48
+ let socket;
49
+ try {
50
+ const secureEndpoint = options.protocol === 'https:';
51
+ const targetHostname = options.servername || options.hostname;
52
+ const connector = new SocksProxyAgent(proxyUrls.get(proxyAgent), { timeout: PROXY_CONNECT_TIMEOUT_MS });
53
+ socket = await connector.connect(new PassThrough(), {
54
+ ...proxyAgent.options,
55
+ ...options,
56
+ host: options.hostname,
57
+ port: Number(options.port || (secureEndpoint ? 443 : 80)),
58
+ secureEndpoint,
59
+ servername: isIP(targetHostname) ? undefined : targetHostname,
60
+ checkServerIdentity: (hostname, certificate) => checkServerIdentity(targetHostname, certificate),
61
+ ALPNProtocols: ['http/1.1']
62
+ });
63
+ if (secureEndpoint) {
64
+ await once(socket, 'secureConnect', { signal: AbortSignal.timeout(PROXY_CONNECT_TIMEOUT_MS) });
65
+ }
66
+ // Bound tunnel setup without imposing the same idle limit on model generation.
67
+ socket.setTimeout(0);
68
+ callback(null, socket);
69
+ } catch (error) {
70
+ socket?.destroy();
71
+ // Undici retries raw hostname errors against alternate SNI values; a proxy must fail closed.
72
+ callback(error.code === 'ERR_TLS_CERT_ALTNAME_INVALID' ? new errors.SecureProxyConnectionError(error) : error, null);
73
+ }
74
+ }
75
+ });
76
+ const requestDispatcher = dispatcher.compose(interceptors.redirect({ maxRedirections: 20 }), interceptors.decompress());
77
+ // Never hand a Readable.toWeb/fromWeb-bridged body to a consumer: under Bun the bridge drops
78
+ // undici's body error on a mid-body close, so the consumer hangs and the rejection escapes as a
79
+ // process crash (qwen-next died 6x in 2.5 h on 2026-09-16; reproduced with a proxy that closes
80
+ // the socket mid-body).
81
+ // Streams are returned as undici's own Node Readable; everything else is buffered right here.
82
+ const fetch = async (url, options) => {
83
+ const request = new globalThis.Request(url, options);
84
+ // Keep buffered upstream payloads replayable across 307/308 redirects.
85
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;
86
+ const response = await proxyRequest(request.url, {
87
+ dispatcher: requestDispatcher,
88
+ method: request.method,
89
+ headers: Object.fromEntries(request.headers),
90
+ body,
91
+ signal: request.signal,
92
+ maxRedirections: request.redirect === 'follow' ? 20 : 0
93
+ });
94
+ const noBody = request.method === 'HEAD' || [204, 205, 304].includes(response.statusCode);
95
+ if (noBody) await response.body.dump();
96
+ const payload = noBody ? null : Buffer.from(await response.body.arrayBuffer());
97
+ return new globalThis.Response(payload, {
98
+ status: response.statusCode,
99
+ statusText: STATUS_CODES[response.statusCode] || '',
100
+ headers: response.headers
101
+ });
102
+ };
103
+ const readResponseData = (response, responseType) => {
104
+ if (responseType === 'stream') return response.body;
105
+ if (responseType === 'arraybuffer') return response.body.arrayBuffer().then((buffer) => Buffer.from(buffer));
106
+ // json/text/undefined: axios' transformResponse parses the text, exactly as with the Node adapter.
107
+ return response.body.text();
108
+ };
109
+ const adapter = async (requestConfig) => {
110
+ let response;
111
+ try {
112
+ response = await proxyRequest(axios.getUri(requestConfig), {
113
+ dispatcher: requestDispatcher,
114
+ method: String(requestConfig.method || 'get').toUpperCase(),
115
+ headers: axios.AxiosHeaders.from(requestConfig.headers).toJSON(),
116
+ body: requestConfig.data,
117
+ signal: requestConfig.signal,
118
+ headersTimeout: requestConfig.timeout || undefined,
119
+ bodyTimeout: requestConfig.timeout || undefined,
120
+ maxRedirections: 20
121
+ });
122
+ } catch (error) {
123
+ throw axios.AxiosError.from(error, UNDICI_ERROR_CODES[error.code] || error.code || axios.AxiosError.ERR_NETWORK, requestConfig);
124
+ }
125
+ const axiosResponse = {
126
+ data: await readResponseData(response, requestConfig.responseType),
127
+ status: response.statusCode,
128
+ statusText: STATUS_CODES[response.statusCode] || '',
129
+ headers: axios.AxiosHeaders.from(response.headers),
130
+ config: requestConfig,
131
+ request: null
132
+ };
133
+ const { validateStatus } = requestConfig;
134
+ if (!validateStatus || validateStatus(axiosResponse.status)) return axiosResponse;
135
+ throw new axios.AxiosError(
136
+ `Request failed with status code ${axiosResponse.status}`,
137
+ axiosResponse.status >= 500 ? axios.AxiosError.ERR_BAD_RESPONSE : axios.AxiosError.ERR_BAD_REQUEST,
138
+ requestConfig,
139
+ null,
140
+ axiosResponse
141
+ );
142
+ };
143
+ transport = { dispatcher, fetch, adapter };
144
+ proxyTransports.set(proxyAgent, transport);
145
+ return transport;
146
+ };
147
+
148
+ const destroyProxyAgent = (agent) => {
149
+ const transport = proxyTransports.get(agent);
150
+ if (transport) {
151
+ transport.dispatcher.destroy().catch(error => {
152
+ logger.warn('关闭代理连接池失败', 'PROXY', '', error.message);
153
+ });
154
+ proxyTransports.delete(agent);
155
+ }
156
+ agent.destroy();
157
+ };
158
+
159
+ // Accept http/https/socks5/socks5h; regex intentionally loose to catch common typos only.
160
+ // socks5:// resolves the target hostname LOCALLY and hands the proxy an IP (socks-proxy-agent
161
+ // sets `lookup = true`), so the DNS query leaves through the host's resolver while the TCP
162
+ // goes through the proxy. socks5h:// delegates resolution to the proxy (curl semantics):
163
+ // DNS and TCP share one egress. Measured on qwen-next 2026-09-16: 76/80 upstream connections
164
+ // reached sing-box as bare IPs under socks5://.
165
+ const PROXY_URL_REGEX = /^(https?|socks5h?):\/\/[^\s]+$/i
166
+
167
+ /**
168
+ * Validate proxy URL format.
169
+ * Null/undefined/empty are valid (means "no account-level proxy").
170
+ * @param {string|null|undefined} url
171
+ * @returns {boolean}
172
+ */
173
+ const isValidProxyUrl = (url) => {
174
+ if (url === null || url === undefined || url === '') return true
175
+ if (typeof url !== 'string') return false
176
+ const trimmed = url.trim()
177
+ if (!trimmed) return true
178
+ return PROXY_URL_REGEX.test(trimmed)
179
+ }
180
+
181
+ /**
182
+ * Resolve the effective proxy URL for an account.
183
+ * Priority: account.proxy > global PROXY_URL > null
184
+ * @param {Object} [account]
185
+ * @returns {string|null}
186
+ */
187
+ const SCHEME_RE = /^([a-z][a-z0-9+.-]*):\/\/(.+)$/i
188
+
189
+ /**
190
+ * 把非标准代理写法规整成 new URL()/HttpsProxyAgent 能解析的标准形式。
191
+ * 这是标准 URL 的“超集”:凡是 new URL() 本就能解析的输入一律原样返回,
192
+ * 只补一种否则会抛 "Invalid URL"、令 HttpsProxyAgent 构造失败的写法:
193
+ * scheme://host:port:user:pass → scheme://user:pass@host:port
194
+ * (IP:端口:用户名:密码 冒号四段式,代理供应商常见导出格式,如 http://3.112.36.241:2080:1234:1234)
195
+ * 其余写法原样返回,交由 isValidProxyUrl / HttpsProxyAgent 处理。
196
+ * @param {string} raw
197
+ * @returns {string}
198
+ */
199
+ const normalizeProxyUrl = (raw) => {
200
+ if (typeof raw !== 'string') return raw
201
+ const trimmed = raw.trim()
202
+ if (!trimmed) return trimmed
203
+
204
+ const schemeMatch = trimmed.match(SCHEME_RE)
205
+ if (!schemeMatch) return trimmed
206
+ const scheme = schemeMatch[1].toLowerCase()
207
+ const rest = schemeMatch[2]
208
+
209
+ // host:port:user:pass —— 无 '@'、非 IPv6、端口为数字、正好四段
210
+ // 合法 URL 不会是这个形状(端口后多出的 ':...' 会让 new URL 抛错),所以此转换安全
211
+ const quad = rest.match(/^([^:@/\\[\]]+):(\d{1,5}):([^:@/\\]+):([^:@/\\]+)$/)
212
+ if (quad) {
213
+ const [, host, port, user, pass] = quad
214
+ return `${scheme}://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${host}:${port}`
215
+ }
216
+
217
+ // 其余(含合法 URL、无法识别的写法)原样返回
218
+ return trimmed
219
+ }
220
+
221
+
222
+ const resolveProxyUrl = (account) => {
223
+ if (account && typeof account.proxy === 'string' && account.proxy.trim()) {
224
+ return normalizeProxyUrl(account.proxy)
225
+ }
226
+ return normalizeProxyUrl(config.proxyUrl) || null
227
+ }
228
+
229
+ /**
230
+ * Egress identity for logs: `protocol//host:port` of the proxy an account's
231
+ * requests leave through, or 'direct' when none applies. Qwen's WAF judges by
232
+ * egress IP, not by account, so parse failures name this instead of the account.
233
+ * Credentials never make it out: the WHATWG parser drops userinfo, and the regex
234
+ * fallback (unparseable URL) masks up to the last `@` of the authority.
235
+ */
236
+ const describeEgress = (account) => {
237
+ const url = resolveProxyUrl(account)
238
+ if (!url) return 'direct'
239
+ try {
240
+ const parsed = new URL(url)
241
+ return `${parsed.protocol}//${parsed.host}`
242
+ } catch {
243
+ return url.replace(/\/\/[^/?#]*@/, '//***@')
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Evict oldest entry from agent cache when over limit.
249
+ * Map iteration order is insertion order, so first key is oldest.
250
+ */
251
+ const evictOldestAgent = () => {
252
+ if (proxyAgents.size <= MAX_AGENT_CACHE_SIZE) return
253
+ const oldestKey = proxyAgents.keys().next().value
254
+ if (oldestKey !== undefined) {
255
+ const agent = proxyAgents.get(oldestKey)
256
+ destroyProxyAgent(agent);
257
+ proxyAgents.delete(oldestKey)
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Build cache key from proxy URL and account email.
263
+ * @param {string|null} url
264
+ * @param {Object} [account]
265
+ * @returns {string}
266
+ */
267
+ const buildAgentCacheKey = (url, account) => {
268
+ const email = account && account.email ? account.email : '__global__'
269
+ return `${url || ''}::${email}`
270
+ }
271
+
272
+ /**
273
+ * Get or create a proxy agent, keyed by proxy URL + account email.
274
+ * Separate TCP pools per account even when sharing the same proxy.
275
+ * @param {string|null} url
276
+ * @param {Object} [account]
277
+ * @returns {HttpsProxyAgent|SocksProxyAgent|undefined}
278
+ */
279
+ const getOrCreateAgent = (url, account) => {
280
+ if (!url) return undefined
281
+ const key = buildAgentCacheKey(url, account)
282
+ let agent = proxyAgents.get(key)
283
+ if (!agent) {
284
+ const proxyUrl = new URL(url);
285
+ switch (proxyUrl.protocol) {
286
+ case 'socks5:':
287
+ case 'socks5h:':
288
+ // The agent reads the scheme itself: socks5h → shouldLookup=false.
289
+ agent = new SocksProxyAgent(proxyUrl);
290
+ break;
291
+ case 'http:':
292
+ case 'https:':
293
+ agent = new HttpsProxyAgent(proxyUrl);
294
+ break;
295
+ default:
296
+ throw new Error(`Unsupported proxy protocol: ${proxyUrl.protocol}`);
297
+ }
298
+ proxyUrls.set(agent, proxyUrl);
299
+ proxyAgents.set(key, agent)
300
+ evictOldestAgent()
301
+ } else {
302
+ // Move to end (most recently used) by deleting and re-inserting
303
+ proxyAgents.delete(key)
304
+ proxyAgents.set(key, agent)
305
+ }
306
+ return agent
307
+ }
308
+
309
+ /**
310
+ * Get proxy agent for an account.
311
+ * @param {Object} [account] - Account object (optional). Falls back to global PROXY_URL
312
+ * @returns {HttpsProxyAgent|SocksProxyAgent|undefined}
313
+ */
314
+ const getProxyAgent = (account) => {
315
+ return getOrCreateAgent(resolveProxyUrl(account), account)
316
+ }
317
+
318
+ /**
319
+ * Invalidate cached agent for a specific proxy URL.
320
+ * Called when an account's proxy is changed or removed.
321
+ * @param {string|null} url
322
+ * @returns {void}
323
+ */
324
+ const invalidateProxyAgent = (url) => {
325
+ url = normalizeProxyUrl(url)
326
+ if (!url) return
327
+ // Delete all entries matching this proxy URL exactly (any account).
328
+ // Cache keys are `${proxyUrl}::${email}`; match only when the URL segment
329
+ // before '::' equals the target url to avoid prefix collisions (e.g. port 8080 vs 80800).
330
+ for (const [key, agent] of proxyAgents.entries()) {
331
+ const sepIdx = key.lastIndexOf('::')
332
+ if (sepIdx !== -1 && key.slice(0, sepIdx) === url) {
333
+ destroyProxyAgent(agent);
334
+ proxyAgents.delete(key)
335
+ }
336
+ }
337
+ }
338
+
339
+ /**
340
+ * Get Chat API base URL.
341
+ * @returns {string}
342
+ */
343
+ const getChatBaseUrl = () => config.qwenChatProxyUrl
344
+
345
+ /**
346
+ * Get CLI API base URL.
347
+ * @returns {string}
348
+ */
349
+ const getCliBaseUrl = () => config.qwenCliProxyUrl
350
+
351
+ /**
352
+ * Apply proxy settings to axios request config.
353
+ * Note: account as second optional param for backward compatibility.
354
+ * @param {Object} [requestConfig]
355
+ * @param {Object} [account]
356
+ * @returns {Object}
357
+ */
358
+ const applyProxyToAxiosConfig = (requestConfig = {}, account) => {
359
+ const proxyAgent = getProxyAgent(account)
360
+ if (proxyAgent) {
361
+ requestConfig.httpAgent = proxyAgent;
362
+ requestConfig.httpsAgent = proxyAgent
363
+ requestConfig.proxy = false
364
+ if (process.versions.bun) {
365
+ requestConfig.adapter = getProxyTransport(proxyAgent).adapter;
366
+ }
367
+ }
368
+ return requestConfig
369
+ }
370
+
371
+ /**
372
+ * Fetch through the account proxy, falling back to the global proxy.
373
+ * @param {string|URL} url
374
+ * @param {Object} [fetchOptions]
375
+ * @param {Object} [account]
376
+ * @returns {Promise<Response>}
377
+ */
378
+ const fetchWithProxy = (url, fetchOptions = {}, account) => {
379
+ const proxyAgent = getProxyAgent(account);
380
+ if (!proxyAgent) return fetch(url, fetchOptions);
381
+
382
+ return getProxyTransport(proxyAgent).fetch(url, fetchOptions);
383
+ };
384
+
385
+ module.exports = {
386
+ normalizeProxyUrl,
387
+ resolveProxyUrl,
388
+ describeEgress,
389
+ getProxyAgent,
390
+ invalidateProxyAgent,
391
+ getChatBaseUrl,
392
+ getCliBaseUrl,
393
+ applyProxyToAxiosConfig,
394
+ getProxyTransport,
395
+ fetchWithProxy,
396
+ isValidProxyUrl
397
+ }