@zllf/pi-provider-proxy 0.1.1 → 0.2.1
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 +4 -3
- package/package.json +2 -2
- package/src/config.js +3 -2
- package/src/entry.cjs +6 -0
- package/src/extension.js +55 -8
- package/src/i18n.js +2 -0
- package/src/local-target.js +16 -0
- package/src/menu.js +10 -4
- package/src/model-events.js +39 -0
- package/src/session-http.js +142 -0
- package/src/session-network.js +152 -0
- package/src/transport.js +2 -2
package/README.md
CHANGED
|
@@ -14,13 +14,14 @@ 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.
|
|
17
|
+
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.2.1` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
|
|
18
18
|
|
|
19
19
|
## 配置代理
|
|
20
20
|
|
|
21
21
|
1. 在 `/proxy` 中选择「共享代理配置」→「添加配置」,起个简称,再粘贴完整地址,例如 `socks5h://127.0.0.1:1080`。`socks5h` 由代理解析目标域名,`socks5` 在本机解析。
|
|
22
22
|
2. 在「选择服务商」中选中目标,再用「更改服务商路由」选择代理、直连或继承 Pi 设置。修改从下一次请求生效。
|
|
23
|
-
3.
|
|
23
|
+
3. 如果希望额度查询、自动命名等扩展也走当前模型的出口,在 `/proxy` 打开「Pi 网络跟随当前模型」。切换模型或更改绑定时,新请求立即使用新的出口。开关默认关闭。
|
|
24
|
+
4. 用「测试路由」检查能否连到服务商。收到 `401` 表示已收到目标站点的响应,账号权限可通过实际对话验证。
|
|
24
25
|
|
|
25
26
|
**带密码的代理**可以直接粘贴 `socks5://用户名:密码@主机:端口`。输入时显示星号,完整地址以明文保存在 `~/.pi/agent/provider-proxy.json`,macOS 和 Linux 文件权限为 `0600`。也可以用 `$NAME` 引用保存完整地址的环境变量。
|
|
26
27
|
|
|
@@ -28,7 +29,7 @@ pi update npm:@zllf/pi-provider-proxy
|
|
|
28
29
|
|
|
29
30
|
- **模型对话**支持 `openai-codex`、`openai`、`anthropic`、`deepseek` 和 `openrouter`。`models.json` 自定义服务商可使用 `openai-completions`、`openai-responses` 或 `anthropic-messages`,同一服务商下的模型须使用同一种协议。
|
|
30
31
|
- **ChatGPT 订阅**选择 `openai-codex`,即可复用 `/login` 的已有凭据。指定路由后,对话使用 SSE,Pi 端登录换票和令牌续期也走该路由。浏览器授权页面使用浏览器的网络设置。
|
|
31
|
-
-
|
|
32
|
+
- **Pi 网络跟随当前模型**覆盖会话中使用默认 `fetch`、Undici、WebSocket 和 Node `http` / `https` 客户端的请求。当前模型选择「继承」或关闭开关时,恢复 Pi 原有网络设置。回环地址沿用原有连接方式,适用于本地 Ollama 和 OAuth 回调。显式指定连接代理的客户端、独立进程(如 `git`、`npm`、`curl`)和系统浏览器使用各自的网络设置。
|
|
32
33
|
|
|
33
34
|
## 本地开发
|
|
34
35
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zllf/pi-provider-proxy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Per-provider HTTP and SOCKS routes for the Pi terminal",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
],
|
|
27
27
|
"pi": {
|
|
28
28
|
"extensions": [
|
|
29
|
-
"./src/
|
|
29
|
+
"./src/entry.cjs"
|
|
30
30
|
]
|
|
31
31
|
},
|
|
32
32
|
"scripts": {
|
package/src/config.js
CHANGED
|
@@ -26,7 +26,8 @@ export function validProfileName(name) {
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
export function validateConfig(config, isSupported = () => true) {
|
|
29
|
-
if (!isRecord(config) || !isRecord(config.profiles) || !isRecord(config.bindings)
|
|
29
|
+
if (!isRecord(config) || !isRecord(config.profiles) || !isRecord(config.bindings) ||
|
|
30
|
+
(Object.hasOwn(config, 'followModel') && typeof config.followModel !== 'boolean')) throw problem('CONFIG_INVALID');
|
|
30
31
|
for (const [name, source] of Object.entries(config.profiles)) {
|
|
31
32
|
if (!validProfileName(name)) throw problem('INVALID_NAME');
|
|
32
33
|
if (typeof source !== 'string') throw problem('INVALID_URL');
|
|
@@ -36,7 +37,7 @@ export function validateConfig(config, isSupported = () => true) {
|
|
|
36
37
|
if (!isSupported(id)) throw problem('UNKNOWN_PROVIDER');
|
|
37
38
|
if (typeof name !== 'string' || (name !== 'direct' && !Object.hasOwn(config.profiles, name))) throw problem('UNKNOWN_PROFILE');
|
|
38
39
|
}
|
|
39
|
-
return { profiles: { ...config.profiles }, bindings: { ...config.bindings } };
|
|
40
|
+
return { profiles: { ...config.profiles }, bindings: { ...config.bindings }, ...(config.followModel && { followModel: true }) };
|
|
40
41
|
}
|
|
41
42
|
|
|
42
43
|
export function routeFor(config, provider, env = process.env) {
|
package/src/entry.cjs
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Resolve Pi's runner through the extension loader. A native ESM import in a
|
|
2
|
+
// source checkout can instead resolve the separate development SDK instance.
|
|
3
|
+
const { ExtensionRunner } = require('@earendil-works/pi-coding-agent');
|
|
4
|
+
const providerProxy = require('./extension.js').default;
|
|
5
|
+
|
|
6
|
+
module.exports = pi => providerProxy(pi, ExtensionRunner);
|
package/src/extension.js
CHANGED
|
@@ -2,10 +2,13 @@ import { join } from 'node:path';
|
|
|
2
2
|
import { readFileSync } from 'node:fs';
|
|
3
3
|
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
4
4
|
import { getApiProvider } from '@earendil-works/pi-ai/compat';
|
|
5
|
-
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { ExtensionRunner, getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
6
6
|
import { openConfig, problem } from './config.js';
|
|
7
7
|
import { registerMenu } from './menu.js';
|
|
8
8
|
import { wrapCodexAuth } from './oauth.js';
|
|
9
|
+
import { createSessionNetwork } from './session-network.js';
|
|
10
|
+
import { createSessionHttp } from './session-http.js';
|
|
11
|
+
import { beforeModelListeners } from './model-events.js';
|
|
9
12
|
import { probeEndpoint, routedStream } from './routing.js';
|
|
10
13
|
|
|
11
14
|
const nativeIds = new Set(['openai-codex', 'anthropic', 'openai', 'deepseek', 'openrouter']);
|
|
@@ -52,7 +55,7 @@ function blockedProvider(id, native, error) {
|
|
|
52
55
|
};
|
|
53
56
|
}
|
|
54
57
|
|
|
55
|
-
export default function providerProxy(pi) {
|
|
58
|
+
export default function providerProxy(pi, HostRunner = ExtensionRunner) {
|
|
56
59
|
const dir = getAgentDir();
|
|
57
60
|
const builtins = builtinProviders();
|
|
58
61
|
const catalog = supportedCatalog(dir, builtins);
|
|
@@ -65,6 +68,25 @@ export default function providerProxy(pi) {
|
|
|
65
68
|
};
|
|
66
69
|
const installed = new Set();
|
|
67
70
|
const blocked = new Set();
|
|
71
|
+
const sessionNetwork = createSessionNetwork();
|
|
72
|
+
const sessionHttp = createSessionHttp();
|
|
73
|
+
let activeProvider;
|
|
74
|
+
function applySessionRoute() {
|
|
75
|
+
let route;
|
|
76
|
+
if (activeProvider && store?.read().followModel) {
|
|
77
|
+
try {
|
|
78
|
+
if (blocked.has(activeProvider)) throw problem('STALE_BINDING');
|
|
79
|
+
route = store.route(activeProvider);
|
|
80
|
+
} catch (error) { route = error; }
|
|
81
|
+
}
|
|
82
|
+
sessionNetwork.set(route);
|
|
83
|
+
sessionHttp.set(route);
|
|
84
|
+
}
|
|
85
|
+
function selectProvider(id, ctx) {
|
|
86
|
+
activeProvider = id;
|
|
87
|
+
checkLiveBindings(ctx);
|
|
88
|
+
applySessionRoute();
|
|
89
|
+
}
|
|
68
90
|
function block(id, error) {
|
|
69
91
|
if (blocked.has(id)) return;
|
|
70
92
|
pi.registerProvider(blockedProvider(id, builtins.find(p => p.id === id), error));
|
|
@@ -107,14 +129,36 @@ export default function providerProxy(pi) {
|
|
|
107
129
|
}
|
|
108
130
|
}
|
|
109
131
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
132
|
+
const prepared = new WeakSet();
|
|
133
|
+
let releaseEarlyListener;
|
|
134
|
+
function prepareModel(event, ctx) {
|
|
135
|
+
if (prepared.has(event)) return;
|
|
136
|
+
selectProvider((event.type === 'model_select' ? event.model : ctx.model)?.provider, ctx);
|
|
137
|
+
prepared.add(event);
|
|
138
|
+
}
|
|
139
|
+
function configureEarlyListener() {
|
|
140
|
+
if (store?.read().followModel) {
|
|
141
|
+
releaseEarlyListener ??= beforeModelListeners(HostRunner.prototype, commandHandler, prepareModel);
|
|
142
|
+
} else {
|
|
143
|
+
releaseEarlyListener?.();
|
|
144
|
+
releaseEarlyListener = undefined;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
pi.on('model_select', prepareModel);
|
|
148
|
+
pi.on('before_agent_start', (_event, ctx) => selectProvider(ctx.model?.provider, ctx));
|
|
149
|
+
pi.on('session_shutdown', () => {
|
|
150
|
+
releaseEarlyListener?.();
|
|
151
|
+
releaseEarlyListener = undefined;
|
|
152
|
+
activeProvider = undefined;
|
|
153
|
+
sessionNetwork.dispose();
|
|
154
|
+
sessionHttp.dispose();
|
|
155
|
+
});
|
|
156
|
+
pi.on('session_start', (event, ctx) => {
|
|
157
|
+
prepareModel(event, ctx);
|
|
114
158
|
if (loadError) ctx.ui.notify(loadError.message, 'error');
|
|
115
159
|
else if (blocked.size) ctx.ui.notify(`${[...blocked].join(', ')} — ${problem('STALE_BINDING').message}`, 'warning');
|
|
116
160
|
});
|
|
117
|
-
registerMenu(pi, {
|
|
161
|
+
const commandHandler = registerMenu(pi, {
|
|
118
162
|
read: () => checked().read(),
|
|
119
163
|
save: next => {
|
|
120
164
|
// Register before publishing. Until save succeeds, each wrapper still reads the old snapshot.
|
|
@@ -133,9 +177,11 @@ export default function providerProxy(pi) {
|
|
|
133
177
|
installed.delete(id);
|
|
134
178
|
blocked.delete(id);
|
|
135
179
|
}
|
|
180
|
+
configureEarlyListener();
|
|
181
|
+
applySessionRoute();
|
|
136
182
|
},
|
|
137
183
|
providers: ctx => {
|
|
138
|
-
|
|
184
|
+
selectProvider(ctx.model?.provider, ctx);
|
|
139
185
|
return [...new Set([...catalog.keys(), ...blocked])];
|
|
140
186
|
},
|
|
141
187
|
isBlocked: id => blocked.has(id),
|
|
@@ -145,4 +191,5 @@ export default function providerProxy(pi) {
|
|
|
145
191
|
return probeEndpoint(model?.baseUrl, checked().route(id));
|
|
146
192
|
},
|
|
147
193
|
});
|
|
194
|
+
configureEarlyListener();
|
|
148
195
|
}
|
package/src/i18n.js
CHANGED
|
@@ -32,6 +32,7 @@ export function deviceLanguage() {
|
|
|
32
32
|
|
|
33
33
|
const en = {
|
|
34
34
|
title: 'Provider proxy', provider: 'Provider', none: 'None available', active: 'active model',
|
|
35
|
+
sessionOnly: 'Pi network follows active model: off', sessionFollow: 'Pi network follows active model: on',
|
|
35
36
|
chooseProvider: 'Select provider', bind: 'Change provider route', test: 'Test route',
|
|
36
37
|
inherit: 'Inherit (Pi default)', direct: 'Direct (bypass proxy)', profile: 'Profile',
|
|
37
38
|
codex: 'Codex uses SSE on managed routes.',
|
|
@@ -64,6 +65,7 @@ const en = {
|
|
|
64
65
|
|
|
65
66
|
const zh = {
|
|
66
67
|
title: '服务商代理', provider: '服务商', none: '无可用服务商', active: '当前模型',
|
|
68
|
+
sessionOnly: 'Pi 网络跟随当前模型:关', sessionFollow: 'Pi 网络跟随当前模型:开',
|
|
67
69
|
chooseProvider: '选择服务商', bind: '更改服务商路由', test: '测试路由',
|
|
68
70
|
inherit: '继承(Pi 默认设置)', direct: '直连(绕过代理)', profile: '配置',
|
|
69
71
|
codex: 'Codex 在指定路由时使用 SSE。',
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { isIP } from 'node:net';
|
|
2
|
+
|
|
3
|
+
// Keep local services and OAuth callbacks on the host. Normalize the URL forms
|
|
4
|
+
// Node accepts, including 127.1 and IPv4-mapped IPv6 addresses.
|
|
5
|
+
export function isLoopbackHost(hostname) {
|
|
6
|
+
if (typeof hostname !== 'string' || !hostname) return false;
|
|
7
|
+
const host = hostname.toLowerCase().replace(/\.$/, '');
|
|
8
|
+
if (host === 'localhost' || host.endsWith('.localhost')) return true;
|
|
9
|
+
if (!/^[\da-fx.:\[\]]+$/i.test(host)) return false;
|
|
10
|
+
try {
|
|
11
|
+
const authority = isIP(host) === 6 ? `[${host}]` : host;
|
|
12
|
+
const canonical = new URL(`http://${authority}`).hostname;
|
|
13
|
+
return canonical === '0.0.0.0' || (isIP(canonical) === 4 && canonical.startsWith('127.')) ||
|
|
14
|
+
canonical === '[::1]' || canonical === '[::]' || /^\[::ffff:7f[\da-f]{2}:[\da-f]{1,4}\]$/.test(canonical);
|
|
15
|
+
} catch { return false; }
|
|
16
|
+
}
|
package/src/menu.js
CHANGED
|
@@ -133,7 +133,7 @@ async function testRoute(services, ctx, provider, language) {
|
|
|
133
133
|
export function registerMenu(pi, services, detect = deviceLanguage) {
|
|
134
134
|
const language = detect();
|
|
135
135
|
const text = messages(language);
|
|
136
|
-
|
|
136
|
+
const command = {
|
|
137
137
|
description: text.title,
|
|
138
138
|
async handler(_args, ctx) {
|
|
139
139
|
if (!ctx.hasUI) return;
|
|
@@ -168,7 +168,7 @@ export function registerMenu(pi, services, detect = deviceLanguage) {
|
|
|
168
168
|
}
|
|
169
169
|
}
|
|
170
170
|
if (ids.length > 1) entries.push(['provider', text.chooseProvider]);
|
|
171
|
-
entries.push(['profiles', text.profiles]);
|
|
171
|
+
entries.push(['profiles', text.profiles], ['scope', config.followModel ? text.sessionFollow : text.sessionOnly]);
|
|
172
172
|
const action = await choose(ui, title, entries);
|
|
173
173
|
if (!action) return;
|
|
174
174
|
if (action === 'test') {
|
|
@@ -182,7 +182,11 @@ export function registerMenu(pi, services, detect = deviceLanguage) {
|
|
|
182
182
|
}
|
|
183
183
|
let next;
|
|
184
184
|
try {
|
|
185
|
-
|
|
185
|
+
if (action === 'scope') {
|
|
186
|
+
next = { ...config, followModel: !config.followModel };
|
|
187
|
+
} else {
|
|
188
|
+
next = action === 'bind' ? await pickRoute(ui, text, config, provider, blocked) : await manageProfiles(ctx, text, config);
|
|
189
|
+
}
|
|
186
190
|
} catch (error) {
|
|
187
191
|
if (!(error instanceof SecureInputUnavailable)) throw error;
|
|
188
192
|
ui.notify(text.secureInputUnavailable, 'error');
|
|
@@ -202,5 +206,7 @@ export function registerMenu(pi, services, detect = deviceLanguage) {
|
|
|
202
206
|
}
|
|
203
207
|
}
|
|
204
208
|
},
|
|
205
|
-
}
|
|
209
|
+
};
|
|
210
|
+
pi.registerCommand('proxy', command);
|
|
211
|
+
return command.handler;
|
|
206
212
|
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Pi 1.7 awaits extension listeners in install order. These two events need
|
|
2
|
+
// the model's route before *any* listener can issue or await its first request.
|
|
3
|
+
// Match on the owning command function (unique per factory/session), using the
|
|
4
|
+
// host-exported runner so this also works with Pi's bundled CLI.
|
|
5
|
+
const bridgeKey = Symbol.for('@zllf/pi-provider-proxy.model-events.v1');
|
|
6
|
+
|
|
7
|
+
function installBridge(prototype) {
|
|
8
|
+
const original = prototype.emit;
|
|
9
|
+
const owners = new WeakMap();
|
|
10
|
+
const bridge = { owners, count: 0, dispose };
|
|
11
|
+
function emit(event, ...args) {
|
|
12
|
+
if (event.type === 'session_start' || event.type === 'model_select') {
|
|
13
|
+
const command = this.getCommand('proxy');
|
|
14
|
+
// Pi namespaces commands with duplicate names, e.g. /proxy:1.
|
|
15
|
+
const commands = command ? [command] : this.getRegisteredCommands().filter(c => c.name === 'proxy');
|
|
16
|
+
for (const { handler } of commands) {
|
|
17
|
+
const prepare = owners.get(handler);
|
|
18
|
+
if (prepare) prepare(event, this.createContext());
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return original.call(this, event, ...args);
|
|
22
|
+
}
|
|
23
|
+
function dispose() {
|
|
24
|
+
if (bridge.count === 0 && prototype.emit === emit) prototype.emit = original;
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(emit, bridgeKey, { value: bridge });
|
|
27
|
+
prototype.emit = emit;
|
|
28
|
+
return bridge;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function beforeModelListeners(prototype, commandHandler, prepare) {
|
|
32
|
+
const bridge = prototype.emit[bridgeKey] ?? installBridge(prototype);
|
|
33
|
+
bridge.owners.set(commandHandler, prepare);
|
|
34
|
+
bridge.count++;
|
|
35
|
+
return () => {
|
|
36
|
+
if (bridge.owners.delete(commandHandler)) bridge.count--;
|
|
37
|
+
bridge.dispose();
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import dns from 'node:dns';
|
|
2
|
+
import http from 'node:http';
|
|
3
|
+
import https from 'node:https';
|
|
4
|
+
import { isIP } from 'node:net';
|
|
5
|
+
import { buildConnector, Client } from 'undici';
|
|
6
|
+
import { SocksClient } from 'socks';
|
|
7
|
+
import { isLoopbackHost } from './local-target.js';
|
|
8
|
+
import { validateProxyUrl } from './transport.js';
|
|
9
|
+
|
|
10
|
+
const handshakeTimeout = 10_000;
|
|
11
|
+
|
|
12
|
+
function httpTunnel(proxy) {
|
|
13
|
+
const headers = {};
|
|
14
|
+
if (proxy.username || proxy.password) {
|
|
15
|
+
const basic = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
|
|
16
|
+
headers['proxy-authorization'] = `Basic ${Buffer.from(basic).toString('base64')}`;
|
|
17
|
+
}
|
|
18
|
+
// The CONNECT Host header names the destination. Verify outer TLS against the proxy.
|
|
19
|
+
const connect = buildConnector({ rejectUnauthorized: true });
|
|
20
|
+
return async ({ host, port }) => {
|
|
21
|
+
const authority = `${isIP(host) === 6 ? `[${host}]` : host}:${port}`;
|
|
22
|
+
// A successful CONNECT detaches the socket from this one-use client.
|
|
23
|
+
const client = new Client(proxy.origin, {
|
|
24
|
+
connect: (options, callback) => connect({ ...options, servername: undefined }, callback),
|
|
25
|
+
});
|
|
26
|
+
try {
|
|
27
|
+
const { socket, statusCode } = await client.connect({
|
|
28
|
+
path: authority, headers: { ...headers, host: authority }, signal: AbortSignal.timeout(handshakeTimeout),
|
|
29
|
+
});
|
|
30
|
+
if (statusCode === 200) return socket;
|
|
31
|
+
socket.destroy();
|
|
32
|
+
throw new Error('Proxy refused CONNECT.');
|
|
33
|
+
} finally {
|
|
34
|
+
await client.destroy();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function socksTunnel(url) {
|
|
40
|
+
const proxy = {
|
|
41
|
+
type: 5, host: url.hostname.replace(/^\[|\]$/g, ''), port: Number(url.port || 1080),
|
|
42
|
+
userId: decodeURIComponent(url.username), password: decodeURIComponent(url.password),
|
|
43
|
+
};
|
|
44
|
+
return async ({ host, port, lookup = dns.lookup, family = 0 }) => {
|
|
45
|
+
if (url.protocol === 'socks5:' && !isIP(host)) {
|
|
46
|
+
host = await new Promise((resolve, reject) => {
|
|
47
|
+
lookup(host, { family }, (error, address) => error ? reject(error) : resolve(address));
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
|
|
51
|
+
const { socket } = await SocksClient.createConnection({
|
|
52
|
+
command: 'connect', proxy, destination: { host, port: Number(port) }, timeout: handshakeTimeout,
|
|
53
|
+
});
|
|
54
|
+
return socket;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function remoteAgent(core, tunnel) {
|
|
59
|
+
// One-use sockets let an old route drain naturally, including upgrades and streams.
|
|
60
|
+
const agent = new core.Agent();
|
|
61
|
+
if (!tunnel) return agent;
|
|
62
|
+
const secureConnection = agent.createConnection.bind(agent);
|
|
63
|
+
agent.createConnection = (options, callback) => {
|
|
64
|
+
tunnel(options).then(socket => {
|
|
65
|
+
if (core === https) {
|
|
66
|
+
try {
|
|
67
|
+
socket = secureConnection({ ...options, socket });
|
|
68
|
+
} catch (error) {
|
|
69
|
+
socket.destroy();
|
|
70
|
+
return callback(error);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
callback(null, socket);
|
|
74
|
+
}, () => {
|
|
75
|
+
// Both proxy response details and SocksClientError.options can contain credentials.
|
|
76
|
+
callback(new Error('Session proxy connection failed.'));
|
|
77
|
+
});
|
|
78
|
+
};
|
|
79
|
+
return agent;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function hasProxyAuthorization(req, headers) {
|
|
83
|
+
if (req.hasHeader('proxy-authorization')) return true;
|
|
84
|
+
if (!Array.isArray(headers)) return false;
|
|
85
|
+
// Core also accepts headers as pairs or a flat array. These bypass req's header map.
|
|
86
|
+
const names = Array.isArray(headers[0]) ? headers.map(([name]) => name) : headers.filter((_, i) => i % 2 === 0);
|
|
87
|
+
return names.some(name => String(name).toLowerCase() === 'proxy-authorization');
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function install(core) {
|
|
91
|
+
const original = core.globalAgent;
|
|
92
|
+
// Core uses defaultAgent.constructor for the explicit { agent: false } case.
|
|
93
|
+
const router = new core.Agent();
|
|
94
|
+
let remote;
|
|
95
|
+
let active = true;
|
|
96
|
+
router.addRequest = (req, options) => {
|
|
97
|
+
const local = options.socketPath || isLoopbackHost(options.host);
|
|
98
|
+
const delegate = active && !local ? remote : original;
|
|
99
|
+
if (!delegate) return req.onSocket(null, new Error('Session HTTP route is unavailable.'));
|
|
100
|
+
if (active && !local && hasProxyAuthorization(req, options.headers)) {
|
|
101
|
+
return req.onSocket(null, new Error('Set proxy credentials on the proxy URL.'));
|
|
102
|
+
}
|
|
103
|
+
req.agent = delegate;
|
|
104
|
+
delegate.addRequest(req, options);
|
|
105
|
+
};
|
|
106
|
+
core.globalAgent = router;
|
|
107
|
+
return {
|
|
108
|
+
configure(blocked, tunnel) { remote = blocked ? undefined : remoteAgent(core, tunnel); },
|
|
109
|
+
restore() {
|
|
110
|
+
active = false;
|
|
111
|
+
remote = undefined;
|
|
112
|
+
if (core.globalAgent === router) core.globalAgent = original;
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Route requests that use the process defaults until the session is disabled or disposed. */
|
|
118
|
+
export function createSessionHttp() {
|
|
119
|
+
let installed;
|
|
120
|
+
function restore() {
|
|
121
|
+
for (const binding of installed ?? []) binding.restore();
|
|
122
|
+
installed = undefined;
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
set(route) {
|
|
126
|
+
if (route === undefined) return restore();
|
|
127
|
+
let tunnel;
|
|
128
|
+
let blocked = route instanceof Error;
|
|
129
|
+
if (!blocked && route !== 'direct') {
|
|
130
|
+
try {
|
|
131
|
+
const url = new URL(validateProxyUrl(route));
|
|
132
|
+
tunnel = url.protocol.startsWith('socks') ? socksTunnel(url) : httpTunnel(url);
|
|
133
|
+
} catch {
|
|
134
|
+
blocked = true;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
installed ??= [install(http), install(https)];
|
|
138
|
+
for (const binding of installed) binding.configure(blocked, tunnel);
|
|
139
|
+
},
|
|
140
|
+
dispose: restore,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { Dispatcher } from 'undici';
|
|
2
|
+
import WrapHandler from 'undici/lib/handler/wrap-handler.js';
|
|
3
|
+
import UnwrapHandler from 'undici/lib/handler/unwrap-handler.js';
|
|
4
|
+
import { isLoopbackHost } from './local-target.js';
|
|
5
|
+
import { createRouteDispatcher } from './transport.js';
|
|
6
|
+
|
|
7
|
+
// Undici 7.30 reads .1 and sets both slots. Undici 8 reads .2 and sets
|
|
8
|
+
// .1 to a separate legacy adapter. Calling either setter would overwrite both.
|
|
9
|
+
const legacy = Symbol.for('undici.globalDispatcher.1');
|
|
10
|
+
const modern = Symbol.for('undici.globalDispatcher.2');
|
|
11
|
+
|
|
12
|
+
function rejectDispatch(handler, error) {
|
|
13
|
+
if (typeof handler.onResponseError === 'function') handler.onResponseError(undefined, error);
|
|
14
|
+
else if (typeof handler.onError === 'function') handler.onError(error);
|
|
15
|
+
else throw error;
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function dispatchRoute(route, options, handler) {
|
|
20
|
+
if (route.error) return rejectDispatch(handler, route.error);
|
|
21
|
+
// Our pinned 7.30 dispatcher accepts both legacy and modern handlers.
|
|
22
|
+
return route.dispatcher.dispatch(options, handler);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
class SessionDispatcher extends Dispatcher {
|
|
26
|
+
#original;
|
|
27
|
+
#adapt;
|
|
28
|
+
#state;
|
|
29
|
+
|
|
30
|
+
constructor(original, adapt, state) {
|
|
31
|
+
super();
|
|
32
|
+
this.#original = original;
|
|
33
|
+
this.#adapt = adapt;
|
|
34
|
+
this.#state = state;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
get webSocketOptions() { return this.#original.webSocketOptions; }
|
|
38
|
+
get eventSourceOptions() { return this.#original.eventSourceOptions; }
|
|
39
|
+
|
|
40
|
+
dispatch(options, handler) {
|
|
41
|
+
const route = this.#state.route;
|
|
42
|
+
if (route && !isLoopbackHost(new URL(options.origin).hostname)) return dispatchRoute(route, options, handler);
|
|
43
|
+
return this.#original.dispatch(options, this.#adapt(handler));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function restore(hooks) {
|
|
48
|
+
for (const { target, key, descriptor, installed } of hooks) {
|
|
49
|
+
if (Object.getOwnPropertyDescriptor(target, key)?.value !== installed) continue;
|
|
50
|
+
if (descriptor) Object.defineProperty(target, key, descriptor);
|
|
51
|
+
else delete target[key];
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Pi 1.7 replaces BOTH non-configurable data slots after session_start and on
|
|
56
|
+
// idle-timeout changes. Its .1 adapter calls .2.dispatch on the host agent.
|
|
57
|
+
// Take the prototype from the running host (Pi can have its own Undici copy).
|
|
58
|
+
// Shadow dispatch on that class only, and delegate every other instance.
|
|
59
|
+
function installPiDispatcher(state, host, adapter) {
|
|
60
|
+
const target = host && Object.getPrototypeOf(host);
|
|
61
|
+
const adapterType = adapter && Object.getPrototypeOf(adapter)?.constructor;
|
|
62
|
+
// Pi 1.7's CLI bundle emits EnvHttpProxyAgent2 and _Dispatcher1Wrapper.
|
|
63
|
+
if (!/^EnvHttpProxyAgent\d*$/.test(target?.constructor?.name) || !/^_?Dispatcher1Wrapper\d*$/.test(adapterType?.name)) return;
|
|
64
|
+
// Only shadow the inherited method on a stock, extensible class prototype.
|
|
65
|
+
// Respect instance/class overrides and fall back to the slot facades there.
|
|
66
|
+
if (Object.hasOwn(host, 'dispatch') || Object.hasOwn(target, 'dispatch') || !Object.isExtensible(target)) return;
|
|
67
|
+
const dispatch = target.dispatch;
|
|
68
|
+
function installed(options, handler) {
|
|
69
|
+
if (this === globalThis[modern] && state.route && !isLoopbackHost(new URL(options.origin).hostname)) {
|
|
70
|
+
return dispatchRoute(state.route, options, handler);
|
|
71
|
+
}
|
|
72
|
+
return dispatch.call(this, options, handler);
|
|
73
|
+
}
|
|
74
|
+
Object.defineProperty(target, 'dispatch', { configurable: true, writable: true, value: installed });
|
|
75
|
+
return { target, key: 'dispatch', installed };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function install(state) {
|
|
79
|
+
const previous = { [legacy]: globalThis[legacy], [modern]: globalThis[modern] };
|
|
80
|
+
const piHook = installPiDispatcher(state, previous[modern], previous[legacy]);
|
|
81
|
+
if (piHook) return [piHook];
|
|
82
|
+
const hooks = [];
|
|
83
|
+
try {
|
|
84
|
+
for (const key of [legacy, modern]) {
|
|
85
|
+
// Node 22's bundled Undici may have initialized only the legacy slot.
|
|
86
|
+
// Use the pinned ABI adapters when delegating across the slot boundary.
|
|
87
|
+
const other = key === legacy ? modern : legacy;
|
|
88
|
+
const originalKey = previous[key] ? key : other;
|
|
89
|
+
const original = previous[originalKey];
|
|
90
|
+
if (typeof original?.dispatch !== 'function') throw new Error('No default Undici dispatcher is available.');
|
|
91
|
+
const adapt = originalKey === modern ? WrapHandler.wrap : UnwrapHandler.unwrap;
|
|
92
|
+
const installed = new SessionDispatcher(original, adapt, state);
|
|
93
|
+
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
|
|
94
|
+
Object.defineProperty(globalThis, key, descriptor ? { value: installed } : {
|
|
95
|
+
value: installed, configurable: true, writable: true,
|
|
96
|
+
});
|
|
97
|
+
hooks.push({ target: globalThis, key, descriptor, installed });
|
|
98
|
+
}
|
|
99
|
+
return hooks;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
restore(hooks);
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function resolve(route) {
|
|
107
|
+
if (route instanceof Error) return { error: route };
|
|
108
|
+
try {
|
|
109
|
+
return { dispatcher: createRouteDispatcher(route) };
|
|
110
|
+
} catch (error) {
|
|
111
|
+
// Invalid configuration must replace the previous route even if its agent
|
|
112
|
+
// could not be constructed. The transport validator redacts credentials.
|
|
113
|
+
return { error };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function createSessionNetwork() {
|
|
118
|
+
let state, hooks, current;
|
|
119
|
+
const retiring = new Set();
|
|
120
|
+
|
|
121
|
+
function retire(dispatcher) {
|
|
122
|
+
if (!dispatcher) return;
|
|
123
|
+
const closed = dispatcher.close().catch(() => dispatcher.destroy());
|
|
124
|
+
retiring.add(closed);
|
|
125
|
+
closed.then(() => retiring.delete(closed), () => retiring.delete(closed));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function set(route) {
|
|
129
|
+
if (current === route) return;
|
|
130
|
+
if (!hooks) {
|
|
131
|
+
state = {};
|
|
132
|
+
hooks = install(state);
|
|
133
|
+
}
|
|
134
|
+
const previous = state.route;
|
|
135
|
+
state.route = route === undefined ? undefined : resolve(route);
|
|
136
|
+
current = route;
|
|
137
|
+
if (route === undefined) {
|
|
138
|
+
restore(hooks);
|
|
139
|
+
state = undefined;
|
|
140
|
+
hooks = undefined;
|
|
141
|
+
}
|
|
142
|
+
retire(previous?.dispatcher);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
set,
|
|
147
|
+
dispose() {
|
|
148
|
+
set(undefined);
|
|
149
|
+
return Promise.allSettled(retiring);
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
package/src/transport.js
CHANGED
|
@@ -82,7 +82,7 @@ function socksAgent(url, retryHandshake) {
|
|
|
82
82
|
});
|
|
83
83
|
}
|
|
84
84
|
|
|
85
|
-
function
|
|
85
|
+
export function createRouteDispatcher(route, retryHandshake = false) {
|
|
86
86
|
if (route === 'direct') return new Agent({ connect: { rejectUnauthorized: true } });
|
|
87
87
|
const url = new URL(validateProxyUrl(route));
|
|
88
88
|
if (url.protocol.startsWith('socks')) return socksAgent(url, retryHandshake);
|
|
@@ -105,7 +105,7 @@ function dispatcherFor(route, retryHandshake) {
|
|
|
105
105
|
|
|
106
106
|
/** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
|
|
107
107
|
export function createTransport(route, { retrySocksHandshake = false } = {}) {
|
|
108
|
-
const dispatcher =
|
|
108
|
+
const dispatcher = createRouteDispatcher(route, retrySocksHandshake);
|
|
109
109
|
let closing;
|
|
110
110
|
return {
|
|
111
111
|
async fetch(input, init) {
|