@zllf/pi-provider-proxy 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/package.json +1 -1
- package/src/connection-demand.js +81 -0
- package/src/connection-retry.js +40 -0
- package/src/session-http.js +93 -29
- package/src/transport.js +52 -26
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ pi install npm:@zllf/pi-provider-proxy
|
|
|
14
14
|
pi update npm:@zllf/pi-provider-proxy
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.
|
|
17
|
+
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.3` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
|
|
18
18
|
|
|
19
19
|
## 配置代理
|
|
20
20
|
|
|
@@ -25,6 +25,8 @@ pi update npm:@zllf/pi-provider-proxy
|
|
|
25
25
|
|
|
26
26
|
同一 Pi 会话内,同一服务商的多轮模型请求会复用代理连接。每个目标站点最多并发使用 4 条连接,空闲连接最长保留 90 秒,实际时长取决于上游。换代理后,新请求使用新路由,已开始的回答继续走原连接。SOCKS5 建连时限为 20 秒,调用方可以设置更短的请求期限。
|
|
27
27
|
|
|
28
|
+
扩展接管的连接在请求发出前遇到重置时,会在同一路由上静默补试,最多 3 次。补试在首次建连后的 5 秒内启动,耗尽后按原有方式报告最后一次错误。调用方发起的新请求有自己的补试次数。
|
|
29
|
+
|
|
28
30
|
**带密码的代理**可以直接粘贴 `socks5://用户名:密码@主机:端口`。输入时显示星号,完整地址以明文保存在 `~/.pi/agent/provider-proxy.json`,macOS 和 Linux 文件权限为 `0600`。也可以用 `$NAME` 引用保存完整地址的环境变量。
|
|
29
31
|
|
|
30
32
|
## 支持范围
|
package/package.json
CHANGED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import UnwrapHandler from 'undici/lib/handler/unwrap-handler.js';
|
|
2
|
+
import { errors } from 'undici';
|
|
3
|
+
|
|
4
|
+
const originalConnectError = Symbol('original connection error');
|
|
5
|
+
const forwardedCallbacks = ['onBodySent', 'onRequestSent', 'onResponseStarted', 'onHeaders', 'onData'];
|
|
6
|
+
|
|
7
|
+
export function terminalConnectError(error) {
|
|
8
|
+
// Undici reconnects for these codes instead of failing the pending request.
|
|
9
|
+
if (error?.code !== 'UND_ERR_SOCKET' && error?.code !== 'UND_ERR_INFO') return error;
|
|
10
|
+
return Object.assign(new Error(error.message), { [originalConnectError]: error });
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function createConnectionDemand() {
|
|
14
|
+
const origins = new Map();
|
|
15
|
+
|
|
16
|
+
function attach(dispatcher) {
|
|
17
|
+
const dispatch = dispatcher.dispatch.bind(dispatcher);
|
|
18
|
+
dispatcher.dispatch = (options, incoming) => {
|
|
19
|
+
const handler = UnwrapHandler.unwrap(incoming);
|
|
20
|
+
if (typeof handler.onConnect !== 'function' || typeof handler.onError !== 'function') {
|
|
21
|
+
return dispatch(options, incoming);
|
|
22
|
+
}
|
|
23
|
+
const origin = new URL(options.origin).origin;
|
|
24
|
+
origins.set(origin, (origins.get(origin) ?? 0) + 1);
|
|
25
|
+
let pending = true;
|
|
26
|
+
let cancelled;
|
|
27
|
+
let abortRequest;
|
|
28
|
+
function release() {
|
|
29
|
+
if (!pending) return;
|
|
30
|
+
pending = false;
|
|
31
|
+
const remaining = origins.get(origin) - 1;
|
|
32
|
+
if (remaining) origins.set(origin, remaining);
|
|
33
|
+
else origins.delete(origin);
|
|
34
|
+
}
|
|
35
|
+
const wrapped = {
|
|
36
|
+
onConnect(abort) {
|
|
37
|
+
release();
|
|
38
|
+
abortRequest = abort;
|
|
39
|
+
// Fail this unwritten request without closing a socket another request can use.
|
|
40
|
+
if (cancelled) throw cancelled;
|
|
41
|
+
},
|
|
42
|
+
onError(error) {
|
|
43
|
+
release();
|
|
44
|
+
return handler.onError(cancelled ?? error?.[originalConnectError] ?? error);
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
for (const name of forwardedCallbacks) {
|
|
48
|
+
if (typeof handler[name] === 'function') wrapped[name] = handler[name].bind(handler);
|
|
49
|
+
}
|
|
50
|
+
for (const name of ['onComplete', 'onUpgrade']) {
|
|
51
|
+
if (typeof handler[name] === 'function') {
|
|
52
|
+
wrapped[name] = (...args) => {
|
|
53
|
+
release();
|
|
54
|
+
return handler[name](...args);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
// Fetch only provides cancellation through this callback, so register it before socket setup.
|
|
60
|
+
handler.onConnect(reason => {
|
|
61
|
+
release();
|
|
62
|
+
cancelled ??= reason ?? new errors.RequestAbortedError();
|
|
63
|
+
abortRequest?.(cancelled);
|
|
64
|
+
});
|
|
65
|
+
} catch (error) {
|
|
66
|
+
release();
|
|
67
|
+
handler.onError(error);
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (cancelled) {
|
|
71
|
+
handler.onError(cancelled);
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
try { return dispatch(options, wrapped); }
|
|
75
|
+
catch (error) { release(); throw error; }
|
|
76
|
+
};
|
|
77
|
+
return dispatcher;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { attach, waiting: origin => origins.has(origin) };
|
|
81
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { errors } from 'undici';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { terminalConnectError } from './connection-demand.js';
|
|
4
|
+
|
|
5
|
+
const resetCodes = new Set(['ECONNRESET', 'SOCKS_RESET', 'UND_ERR_SOCKET']);
|
|
6
|
+
const retryDelays = [100, 200, 400];
|
|
7
|
+
// An individual handshake keeps its protocol timeout. This window limits retry starts.
|
|
8
|
+
const resetWindowMs = 5_000;
|
|
9
|
+
|
|
10
|
+
/** Call only during connection setup, before handing a socket to the request. */
|
|
11
|
+
export async function retryConnection(connect, { signal, active = () => true, retrySocksTimeout = false } = {}) {
|
|
12
|
+
const start = performance.now();
|
|
13
|
+
for (let attempt = 0; ; attempt++) {
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
try { return await connect(); }
|
|
16
|
+
catch (error) {
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
const wait = retryDelays[attempt];
|
|
19
|
+
const earlyReset = resetCodes.has(error.code) && performance.now() - start + wait <= resetWindowMs;
|
|
20
|
+
const oauthTimeout = attempt === 0 && retrySocksTimeout && error.code === 'SOCKS_TIMEOUT';
|
|
21
|
+
if (wait === undefined || !active() || (!earlyReset && !oauthTimeout)) throw error;
|
|
22
|
+
try { await delay(wait, undefined, { signal }); }
|
|
23
|
+
catch { signal?.throwIfAborted(); throw error; }
|
|
24
|
+
if (!active()) throw error;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function retryConnector(connect, { active, retrySocksTimeout }) {
|
|
30
|
+
return (parameters, callback) => {
|
|
31
|
+
if (!active()) return callback(new errors.RequestAbortedError());
|
|
32
|
+
retryConnection(() => new Promise((resolve, reject) => {
|
|
33
|
+
connect(parameters, (error, socket) => error ? reject(error) : resolve(socket));
|
|
34
|
+
}), { active, retrySocksTimeout, signal: parameters.signal }).then(socket => {
|
|
35
|
+
if (active()) return callback(null, socket);
|
|
36
|
+
socket.destroy();
|
|
37
|
+
callback(new errors.RequestAbortedError());
|
|
38
|
+
}, error => callback(active() ? terminalConnectError(error) : new errors.RequestAbortedError()));
|
|
39
|
+
};
|
|
40
|
+
}
|
package/src/session-http.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import dns from 'node:dns';
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
2
3
|
import http from 'node:http';
|
|
3
4
|
import https from 'node:https';
|
|
4
5
|
import { isIP } from 'node:net';
|
|
5
6
|
import { buildConnector, Client } from 'undici';
|
|
6
|
-
import {
|
|
7
|
+
import { retryConnection } from './connection-retry.js';
|
|
7
8
|
import { isLoopbackHost } from './local-target.js';
|
|
8
|
-
import { SOCKS_HANDSHAKE_TIMEOUT_MS, validateProxyUrl } from './transport.js';
|
|
9
|
+
import { openSocks, SOCKS_HANDSHAKE_TIMEOUT_MS, socksFailure, validateProxyUrl } from './transport.js';
|
|
9
10
|
|
|
10
11
|
const handshakeTimeout = 10_000;
|
|
12
|
+
const connectionOptions = Symbol('session connection options');
|
|
11
13
|
|
|
12
14
|
function httpTunnel(proxy) {
|
|
13
15
|
const headers = {};
|
|
@@ -17,7 +19,7 @@ function httpTunnel(proxy) {
|
|
|
17
19
|
}
|
|
18
20
|
// The CONNECT Host header names the destination. Verify outer TLS against the proxy.
|
|
19
21
|
const connect = buildConnector({ rejectUnauthorized: true });
|
|
20
|
-
return async ({ host, port }) => {
|
|
22
|
+
return async ({ host, port }, signal) => {
|
|
21
23
|
const authority = `${isIP(host) === 6 ? `[${host}]` : host}:${port}`;
|
|
22
24
|
// A successful CONNECT detaches the socket from this one-use client.
|
|
23
25
|
const client = new Client(proxy.origin, {
|
|
@@ -25,7 +27,8 @@ function httpTunnel(proxy) {
|
|
|
25
27
|
});
|
|
26
28
|
try {
|
|
27
29
|
const { socket, statusCode } = await client.connect({
|
|
28
|
-
path: authority, headers: { ...headers, host: authority },
|
|
30
|
+
path: authority, headers: { ...headers, host: authority },
|
|
31
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(handshakeTimeout)]),
|
|
29
32
|
});
|
|
30
33
|
if (statusCode === 200) return socket;
|
|
31
34
|
socket.destroy();
|
|
@@ -36,49 +39,102 @@ function httpTunnel(proxy) {
|
|
|
36
39
|
};
|
|
37
40
|
}
|
|
38
41
|
|
|
42
|
+
function lookupDestination(lookup, host, family, signal) {
|
|
43
|
+
signal.throwIfAborted();
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const abort = addAbortListener(signal, () => reject(signal.reason));
|
|
46
|
+
function done(error, address) {
|
|
47
|
+
abort[Symbol.dispose]();
|
|
48
|
+
if (error) reject(error);
|
|
49
|
+
else resolve(address);
|
|
50
|
+
}
|
|
51
|
+
try { lookup(host, { family }, done); }
|
|
52
|
+
catch (error) { done(error); }
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
39
56
|
function socksTunnel(url) {
|
|
40
57
|
const proxy = {
|
|
41
58
|
type: 5, host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 1080),
|
|
42
59
|
userId: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
|
|
43
60
|
};
|
|
44
|
-
return async ({ host, port, lookup = dns.lookup, family = 0 }) => {
|
|
61
|
+
return async ({ host, port, lookup = dns.lookup, family = 0 }, signal) => {
|
|
45
62
|
if (url.protocol === 'socks5:' && !isIP(host)) {
|
|
46
|
-
host = await
|
|
47
|
-
lookup(host, { family }, (error, address) => error ? reject(error) : resolve(address));
|
|
48
|
-
});
|
|
63
|
+
host = await lookupDestination(lookup, host, family, signal);
|
|
49
64
|
}
|
|
50
65
|
if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
66
|
+
signal.throwIfAborted();
|
|
67
|
+
try {
|
|
68
|
+
return await openSocks({
|
|
69
|
+
command: 'connect', proxy, destination: { host, port: Number(port) }, timeout: SOCKS_HANDSHAKE_TIMEOUT_MS,
|
|
70
|
+
}, signal);
|
|
71
|
+
} catch (error) { throw socksFailure(error); }
|
|
55
72
|
};
|
|
56
73
|
}
|
|
57
74
|
|
|
58
|
-
function remoteAgent(core, tunnel) {
|
|
75
|
+
function remoteAgent(core, tunnel, timeout) {
|
|
59
76
|
// One-use sockets let an old route drain naturally, including upgrades and streams.
|
|
60
77
|
const agent = new core.Agent();
|
|
61
|
-
|
|
62
|
-
const
|
|
78
|
+
const open = agent.createConnection.bind(agent);
|
|
79
|
+
const secure = core === https;
|
|
63
80
|
agent.createConnection = (options, callback) => {
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
81
|
+
const request = options[connectionOptions];
|
|
82
|
+
const deadline = AbortSignal.timeout(timeout);
|
|
83
|
+
const signal = AbortSignal.any([request.signal, deadline]);
|
|
84
|
+
let tunnelFailure;
|
|
85
|
+
async function connect() {
|
|
86
|
+
let socket;
|
|
87
|
+
if (tunnel) {
|
|
88
|
+
try { socket = await tunnel(options, signal); }
|
|
89
|
+
catch (error) {
|
|
90
|
+
signal.throwIfAborted();
|
|
91
|
+
tunnelFailure = error;
|
|
92
|
+
throw error;
|
|
71
93
|
}
|
|
94
|
+
if (!secure) return socket;
|
|
72
95
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
96
|
+
try {
|
|
97
|
+
signal.throwIfAborted();
|
|
98
|
+
socket = open(socket ? { ...options, socket } : options);
|
|
99
|
+
await once(socket, secure ? 'secureConnect' : 'connect', { signal });
|
|
100
|
+
return socket;
|
|
101
|
+
} catch (error) { socket?.destroy(); throw error; }
|
|
102
|
+
}
|
|
103
|
+
retryConnection(connect, { signal }).then(socket => callback(null, socket), error => {
|
|
104
|
+
if (error === deadline.reason) {
|
|
105
|
+
callback(Object.assign(new Error('Connection timed out.'), { code: 'ETIMEDOUT' }));
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
// Preserve the existing redaction for errors from proxy negotiation.
|
|
109
|
+
callback(error === tunnelFailure ? new Error('Session proxy connection failed.') : error);
|
|
77
110
|
});
|
|
78
111
|
};
|
|
79
112
|
return agent;
|
|
80
113
|
}
|
|
81
114
|
|
|
115
|
+
function pendingConnection(req) {
|
|
116
|
+
const connection = new AbortController();
|
|
117
|
+
const descriptor = Object.getOwnPropertyDescriptor(req, 'destroy');
|
|
118
|
+
const destroy = req.destroy;
|
|
119
|
+
function cancel(error, ...args) {
|
|
120
|
+
const result = destroy.call(this, error, ...args);
|
|
121
|
+
if (this === req && req.destroyed) connection.abort(error ?? Object.assign(new Error('socket hang up'), { code: 'ECONNRESET' }));
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
function release() {
|
|
125
|
+
req.removeListener('socket', release);
|
|
126
|
+
req.removeListener('close', release);
|
|
127
|
+
if (Object.getOwnPropertyDescriptor(req, 'destroy')?.value !== cancel) return;
|
|
128
|
+
if (descriptor) Object.defineProperty(req, 'destroy', descriptor);
|
|
129
|
+
else delete req.destroy;
|
|
130
|
+
}
|
|
131
|
+
// Node emits close only after the agent's connection callback, so observe destroy while it is pending.
|
|
132
|
+
Object.defineProperty(req, 'destroy', { configurable: true, writable: true, value: cancel });
|
|
133
|
+
req.once('socket', release);
|
|
134
|
+
req.once('close', release);
|
|
135
|
+
return connection;
|
|
136
|
+
}
|
|
137
|
+
|
|
82
138
|
function hasProxyAuthorization(req, headers) {
|
|
83
139
|
if (req.hasHeader('proxy-authorization')) return true;
|
|
84
140
|
if (!Array.isArray(headers)) return false;
|
|
@@ -100,12 +156,16 @@ function install(core) {
|
|
|
100
156
|
if (active && !local && hasProxyAuthorization(req, options.headers)) {
|
|
101
157
|
return req.onSocket(null, new Error('Set proxy credentials on the proxy URL.'));
|
|
102
158
|
}
|
|
159
|
+
if (active && !local) {
|
|
160
|
+
if (req.destroyed) return req.onSocket(null);
|
|
161
|
+
options = { ...options, [connectionOptions]: pendingConnection(req) };
|
|
162
|
+
}
|
|
103
163
|
req.agent = delegate;
|
|
104
164
|
delegate.addRequest(req, options);
|
|
105
165
|
};
|
|
106
166
|
core.globalAgent = router;
|
|
107
167
|
return {
|
|
108
|
-
configure(blocked, tunnel) { remote = blocked ? undefined : remoteAgent(core, tunnel); },
|
|
168
|
+
configure(blocked, tunnel, timeout) { remote = blocked ? undefined : remoteAgent(core, tunnel, timeout); },
|
|
109
169
|
restore() {
|
|
110
170
|
active = false;
|
|
111
171
|
remote = undefined;
|
|
@@ -125,17 +185,21 @@ export function createSessionHttp() {
|
|
|
125
185
|
set(route) {
|
|
126
186
|
if (route === undefined) return restore();
|
|
127
187
|
let tunnel;
|
|
188
|
+
let timeout = handshakeTimeout;
|
|
128
189
|
let blocked = route instanceof Error;
|
|
129
190
|
if (!blocked && route !== 'direct') {
|
|
130
191
|
try {
|
|
131
192
|
const url = new URL(validateProxyUrl(route));
|
|
132
|
-
|
|
193
|
+
if (url.protocol.startsWith('socks')) {
|
|
194
|
+
tunnel = socksTunnel(url);
|
|
195
|
+
timeout = SOCKS_HANDSHAKE_TIMEOUT_MS;
|
|
196
|
+
} else tunnel = httpTunnel(url);
|
|
133
197
|
} catch {
|
|
134
198
|
blocked = true;
|
|
135
199
|
}
|
|
136
200
|
}
|
|
137
201
|
installed ??= [install(http), install(https)];
|
|
138
|
-
for (const binding of installed) binding.configure(blocked, tunnel);
|
|
202
|
+
for (const binding of installed) binding.configure(blocked, tunnel, timeout);
|
|
139
203
|
},
|
|
140
204
|
dispose: restore,
|
|
141
205
|
};
|
package/src/transport.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import { lookup } from 'node:dns/promises';
|
|
2
|
-
import {
|
|
2
|
+
import { addAbortListener, once } from 'node:events';
|
|
3
|
+
import { connect as openTcp, isIP } from 'node:net';
|
|
3
4
|
import { domainToASCII } from 'node:url';
|
|
4
|
-
import { Agent, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
|
|
5
|
+
import { Agent, Client, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
|
|
5
6
|
import { SocksClient } from 'socks';
|
|
7
|
+
import { createConnectionDemand } from './connection-demand.js';
|
|
8
|
+
import { retryConnector } from './connection-retry.js';
|
|
6
9
|
|
|
7
10
|
export const SOCKS_HANDSHAKE_TIMEOUT_MS = 20_000;
|
|
8
11
|
const modelPoolOptions = { connections: 4, keepAliveTimeout: 90_000, keepAliveMaxTimeout: 90_000 };
|
|
9
|
-
const earlyResetWindowMs = 5_000;
|
|
10
12
|
|
|
11
13
|
function invalidProxy() {
|
|
12
14
|
return new TypeError('Invalid proxy URL (expected an HTTP, HTTPS, SOCKS5, or SOCKS5H proxy authority).');
|
|
@@ -35,7 +37,7 @@ export function validateProxyUrl(value) {
|
|
|
35
37
|
}
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
function socksFailure(error) {
|
|
40
|
+
export function socksFailure(error) {
|
|
39
41
|
// SocksClientError also holds the plaintext proxy credentials. Copy only a code.
|
|
40
42
|
const msg = error?.message ?? '';
|
|
41
43
|
let code = 'SOCKS_CONNECT';
|
|
@@ -45,7 +47,28 @@ function socksFailure(error) {
|
|
|
45
47
|
return Object.assign(new Error('SOCKS proxy connection failed.'), { code });
|
|
46
48
|
}
|
|
47
49
|
|
|
48
|
-
function
|
|
50
|
+
export async function openSocks(options, signal) {
|
|
51
|
+
if (!signal) return (await SocksClient.createConnection(options)).socket;
|
|
52
|
+
signal.throwIfAborted();
|
|
53
|
+
const { host, port } = options.proxy;
|
|
54
|
+
const socket = openTcp({ host, port });
|
|
55
|
+
const abort = addAbortListener(signal, () => socket.destroy());
|
|
56
|
+
try {
|
|
57
|
+
await once(socket, 'connect', { signal });
|
|
58
|
+
socket.setNoDelay(true);
|
|
59
|
+
await SocksClient.createConnection({ ...options, existing_socket: socket });
|
|
60
|
+
signal.throwIfAborted();
|
|
61
|
+
return socket;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
socket.destroy();
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
throw error;
|
|
66
|
+
} finally {
|
|
67
|
+
abort[Symbol.dispose]();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function socksConnector(url) {
|
|
49
72
|
const proxy = {
|
|
50
73
|
type: 5,
|
|
51
74
|
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
@@ -78,39 +101,41 @@ function socksAgent(url, retrySocksHandshake, modelPool) {
|
|
|
78
101
|
} catch (error) { socket.destroy(); throw error; }
|
|
79
102
|
}
|
|
80
103
|
|
|
81
|
-
|
|
82
|
-
const start = performance.now();
|
|
83
|
-
try { return await connectOnce(options); }
|
|
84
|
-
catch (error) {
|
|
85
|
-
const retryOAuth = retrySocksHandshake && ['SOCKS_TIMEOUT', 'SOCKS_RESET'].includes(error.code);
|
|
86
|
-
const earlyModelReset = modelPool && performance.now() - start <= earlyResetWindowMs &&
|
|
87
|
-
['SOCKS_RESET', 'ECONNRESET'].includes(error.code);
|
|
88
|
-
if (!retryOAuth && !earlyModelReset) throw error;
|
|
89
|
-
// Undici receives a socket only after connect resolves. No HTTP bytes have been sent.
|
|
90
|
-
return connectOnce(options);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
return new Agent({
|
|
95
|
-
...(modelPool && modelPoolOptions),
|
|
96
|
-
connect(options, callback) { connect(options).then(socket => callback(null, socket), callback); },
|
|
97
|
-
});
|
|
104
|
+
return (options, callback) => { connectOnce(options).then(socket => callback(null, socket), callback); };
|
|
98
105
|
}
|
|
99
106
|
|
|
100
|
-
export function createRouteDispatcher(route,
|
|
107
|
+
export function createRouteDispatcher(route, retrySocksTimeout = false, modelPool = false) {
|
|
101
108
|
const poolOptions = modelPool ? modelPoolOptions : {};
|
|
102
|
-
|
|
109
|
+
const demand = createConnectionDemand();
|
|
110
|
+
let dispatcher;
|
|
111
|
+
function factory(origin, options) {
|
|
112
|
+
const key = new URL(origin).origin;
|
|
113
|
+
const Dispatcher = options.connections === 1 ? Client : Pool;
|
|
114
|
+
const connect = retryConnector(options.connect, {
|
|
115
|
+
active: () => !dispatcher.destroyed && demand.waiting(key), retrySocksTimeout,
|
|
116
|
+
});
|
|
117
|
+
return new Dispatcher(origin, { ...options, connect });
|
|
118
|
+
}
|
|
119
|
+
if (route === 'direct') {
|
|
120
|
+
dispatcher = new Agent({ ...poolOptions, factory, connect: buildConnector({ rejectUnauthorized: true }) });
|
|
121
|
+
return demand.attach(dispatcher);
|
|
122
|
+
}
|
|
103
123
|
const url = new URL(validateProxyUrl(route));
|
|
104
|
-
if (url.protocol.startsWith('socks'))
|
|
124
|
+
if (url.protocol.startsWith('socks')) {
|
|
125
|
+
dispatcher = new Agent({ ...poolOptions, factory, connect: socksConnector(url) });
|
|
126
|
+
return demand.attach(dispatcher);
|
|
127
|
+
}
|
|
105
128
|
|
|
106
129
|
let token;
|
|
107
130
|
if (url.username || url.password) {
|
|
108
131
|
const basic = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
|
|
109
132
|
token = `Basic ${Buffer.from(basic).toString('base64')}`;
|
|
110
133
|
}
|
|
111
|
-
|
|
134
|
+
dispatcher = new ProxyAgent({
|
|
112
135
|
...poolOptions,
|
|
113
136
|
uri: url.origin, token, proxyTunnel: true,
|
|
137
|
+
// Retry the whole CONNECT and origin TLS setup before handing off its socket.
|
|
138
|
+
factory,
|
|
114
139
|
// ProxyAgent passes even an IP literal as SNI. Let the connector derive SNI
|
|
115
140
|
// from the proxy host, omitting it for IPs while TLS still verifies their SAN.
|
|
116
141
|
clientFactory: (origin, { connect }) => new Pool(origin, {
|
|
@@ -118,6 +143,7 @@ export function createRouteDispatcher(route, retryHandshake = false, modelPool =
|
|
|
118
143
|
}),
|
|
119
144
|
proxyTls: { rejectUnauthorized: true }, requestTls: { rejectUnauthorized: true },
|
|
120
145
|
});
|
|
146
|
+
return demand.attach(dispatcher);
|
|
121
147
|
}
|
|
122
148
|
|
|
123
149
|
/** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
|