@zllf/pi-provider-proxy 0.0.0-stage → 0.1.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 +38 -2
- package/package.json +46 -4
- package/src/config.js +122 -0
- package/src/extension.js +148 -0
- package/src/i18n.js +111 -0
- package/src/menu.js +206 -0
- package/src/oauth-diagnostics.js +73 -0
- package/src/oauth-worker.js +75 -0
- package/src/oauth.js +80 -0
- package/src/routing.js +51 -0
- package/src/secret-input.js +71 -0
- package/src/transport.js +130 -0
package/README.md
CHANGED
|
@@ -1,3 +1,39 @@
|
|
|
1
|
-
#
|
|
1
|
+
# pi-provider-proxy
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
用 `/proxy` 为 Pi 的每个模型服务商单独设置 HTTP、HTTPS 或 SOCKS5 代理。例如,让 ChatGPT 订阅账号走 SOCKS5,保留本地 Ollama 直连。菜单自动跟随设备语言,支持中文和英文。
|
|
4
|
+
|
|
5
|
+
## 安装与更新
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pi install npm:@zllf/pi-provider-proxy
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
已通过 npm 安装的用户可以单独更新此扩展。
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
pi update npm:@zllf/pi-provider-proxy
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy`。也可以用 `pi install git:github.com/Zllf/pi-provider-proxy@v0.1.1` 固定 GitHub 版本。要求 Node.js 22.19 或更高版本,已在 Pi 1.7.0 验证。
|
|
18
|
+
|
|
19
|
+
## 配置代理
|
|
20
|
+
|
|
21
|
+
1. 在 `/proxy` 中选择「共享代理配置」→「添加配置」,起个简称,再粘贴完整地址,例如 `socks5h://127.0.0.1:1080`。`socks5h` 由代理解析目标域名,`socks5` 在本机解析。
|
|
22
|
+
2. 在「选择服务商」中选中目标,再用「更改服务商路由」选择代理、直连或继承 Pi 设置。修改从下一次请求生效。
|
|
23
|
+
3. 用「测试路由」检查能否连到服务商。收到 `401` 表示已收到目标站点的响应,账号权限可通过实际对话验证。
|
|
24
|
+
|
|
25
|
+
**带密码的代理**可以直接粘贴 `socks5://用户名:密码@主机:端口`。输入时显示星号,完整地址以明文保存在 `~/.pi/agent/provider-proxy.json`,macOS 和 Linux 文件权限为 `0600`。也可以用 `$NAME` 引用保存完整地址的环境变量。
|
|
26
|
+
|
|
27
|
+
## 支持范围
|
|
28
|
+
|
|
29
|
+
- **模型对话**支持 `openai-codex`、`openai`、`anthropic`、`deepseek` 和 `openrouter`。`models.json` 自定义服务商可使用 `openai-completions`、`openai-responses` 或 `anthropic-messages`,同一服务商下的模型须使用同一种协议。
|
|
30
|
+
- **ChatGPT 订阅**选择 `openai-codex`,即可复用 `/login` 的已有凭据。指定路由后,对话使用 SSE,Pi 端登录换票和令牌续期也走该路由。浏览器授权页面使用浏览器的网络设置。
|
|
31
|
+
- **其他请求**沿用各自的网络设置,包括其他服务商的登录、模型目录刷新和 Pi 工具调用。
|
|
32
|
+
|
|
33
|
+
## 本地开发
|
|
34
|
+
|
|
35
|
+
```sh
|
|
36
|
+
npm ci
|
|
37
|
+
npm test
|
|
38
|
+
pi -e .
|
|
39
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zllf/pi-provider-proxy",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Per-provider HTTP and SOCKS routes for the Pi terminal",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/Zllf/pi-provider-proxy.git"
|
|
9
|
+
},
|
|
10
|
+
"publishConfig": {
|
|
11
|
+
"access": "public",
|
|
12
|
+
"registry": "https://registry.npmjs.org/"
|
|
13
|
+
},
|
|
14
|
+
"keywords": [
|
|
15
|
+
"pi-package",
|
|
16
|
+
"pi-extension",
|
|
17
|
+
"proxy",
|
|
18
|
+
"socks5"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.19.0"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"src",
|
|
25
|
+
"README.md"
|
|
26
|
+
],
|
|
27
|
+
"pi": {
|
|
28
|
+
"extensions": [
|
|
29
|
+
"./src/extension.js"
|
|
30
|
+
]
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"test": "node --test test/*.test.js"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@earendil-works/pi-ai": "*",
|
|
37
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
38
|
+
"@earendil-works/pi-tui": "*"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
42
|
+
"@earendil-works/pi-coding-agent": "1.7.0"
|
|
43
|
+
},
|
|
44
|
+
"dependencies": {
|
|
45
|
+
"socks": "2.8.11",
|
|
46
|
+
"undici": "7.30.2"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, openSync, closeSync, readFileSync, writeFileSync, renameSync, rmSync } from 'node:fs';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { validateProxyUrl } from './transport.js';
|
|
5
|
+
import { localizeError } from './i18n.js';
|
|
6
|
+
|
|
7
|
+
export function problem(code) {
|
|
8
|
+
return Object.assign(new Error(localizeError({ code })), { code });
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function isRecord(value) {
|
|
12
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const envReference = /^\$([A-Za-z_][A-Za-z0-9_]*)$/;
|
|
16
|
+
function proxyUrl(value) {
|
|
17
|
+
try { return validateProxyUrl(value); } catch { throw problem('INVALID_URL'); }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const urlInName = /[a-z][a-z\d+.-]*:\/\//i;
|
|
21
|
+
|
|
22
|
+
export function validProfileName(name) {
|
|
23
|
+
return typeof name === 'string' && name.length > 0 && name.length <= 80 && name.trim() === name &&
|
|
24
|
+
!/[\p{Cc}\p{Cf}]/u.test(name) && !urlInName.test(name) &&
|
|
25
|
+
!Object.hasOwn(Object.prototype, name) && name !== 'direct' && name !== 'prototype';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function validateConfig(config, isSupported = () => true) {
|
|
29
|
+
if (!isRecord(config) || !isRecord(config.profiles) || !isRecord(config.bindings)) throw problem('CONFIG_INVALID');
|
|
30
|
+
for (const [name, source] of Object.entries(config.profiles)) {
|
|
31
|
+
if (!validProfileName(name)) throw problem('INVALID_NAME');
|
|
32
|
+
if (typeof source !== 'string') throw problem('INVALID_URL');
|
|
33
|
+
if (!envReference.test(source)) proxyUrl(source);
|
|
34
|
+
}
|
|
35
|
+
for (const [id, name] of Object.entries(config.bindings)) {
|
|
36
|
+
if (!isSupported(id)) throw problem('UNKNOWN_PROVIDER');
|
|
37
|
+
if (typeof name !== 'string' || (name !== 'direct' && !Object.hasOwn(config.profiles, name))) throw problem('UNKNOWN_PROFILE');
|
|
38
|
+
}
|
|
39
|
+
return { profiles: { ...config.profiles }, bindings: { ...config.bindings } };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function routeFor(config, provider, env = process.env) {
|
|
43
|
+
if (!Object.hasOwn(config.bindings, provider)) return undefined;
|
|
44
|
+
const name = config.bindings[provider];
|
|
45
|
+
if (name === 'direct') return name;
|
|
46
|
+
const source = config.profiles[name];
|
|
47
|
+
const match = envReference.exec(source);
|
|
48
|
+
if (!match) return proxyUrl(source);
|
|
49
|
+
const resolved = env[match[1]];
|
|
50
|
+
if (!resolved) throw problem('ENV_MISSING');
|
|
51
|
+
return proxyUrl(resolved);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Older releases accepted URLs as display names. Rename only those keys in
|
|
55
|
+
// the private read snapshot and preserve all routes. The next save persists it.
|
|
56
|
+
function migrateLegacyNames(config) {
|
|
57
|
+
if (!isRecord(config?.profiles) || !isRecord(config.bindings)) return config;
|
|
58
|
+
const renames = new Map();
|
|
59
|
+
let sequence = 0;
|
|
60
|
+
for (const name of Object.keys(config.profiles)) {
|
|
61
|
+
if (!urlInName.test(name)) continue;
|
|
62
|
+
let safeName;
|
|
63
|
+
do { safeName = `proxy-${++sequence}`; } while (Object.hasOwn(config.profiles, safeName));
|
|
64
|
+
renames.set(name, safeName);
|
|
65
|
+
config.profiles[safeName] = config.profiles[name];
|
|
66
|
+
delete config.profiles[name];
|
|
67
|
+
}
|
|
68
|
+
for (const [id, name] of Object.entries(config.bindings)) {
|
|
69
|
+
if (renames.has(name)) config.bindings[id] = renames.get(name);
|
|
70
|
+
}
|
|
71
|
+
return config;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function readText(file) {
|
|
75
|
+
try { return readFileSync(file, 'utf8'); }
|
|
76
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw problem('CONFIG_IO'); }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// A session uses one snapshot. On a conflicting external edit, require /reload
|
|
80
|
+
// instead of replacing the other session's choices or adopting half an update.
|
|
81
|
+
export function openConfig(file, isSupported) {
|
|
82
|
+
const parse = text => {
|
|
83
|
+
if (text === null) return { profiles: {}, bindings: {} };
|
|
84
|
+
let parsed;
|
|
85
|
+
try { parsed = JSON.parse(text); } catch { throw problem('CONFIG_INVALID'); }
|
|
86
|
+
// Keep persisted bindings even if a provider's protocol has changed. The
|
|
87
|
+
// extension installs a request guard for those IDs until the user unbinds.
|
|
88
|
+
return validateConfig(migrateLegacyNames(parsed));
|
|
89
|
+
};
|
|
90
|
+
let disk = readText(file);
|
|
91
|
+
let current = parse(disk);
|
|
92
|
+
return {
|
|
93
|
+
read: () => structuredClone(current),
|
|
94
|
+
route: id => routeFor(current, id),
|
|
95
|
+
save(next) {
|
|
96
|
+
const config = validateConfig(next, id => isSupported(id) ||
|
|
97
|
+
(Object.hasOwn(current.bindings, id) && next.bindings[id] === current.bindings[id]));
|
|
98
|
+
const text = JSON.stringify(config, null, 2) + '\n';
|
|
99
|
+
const lock = `${file}.lock`;
|
|
100
|
+
const tmp = `${file}.${randomUUID()}.tmp`;
|
|
101
|
+
let descriptor;
|
|
102
|
+
try {
|
|
103
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
104
|
+
descriptor = openSync(lock, 'wx', 0o600);
|
|
105
|
+
if (readText(file) !== disk) throw problem('CONFIG_CHANGED');
|
|
106
|
+
writeFileSync(tmp, text, { mode: 0o600, flag: 'wx' });
|
|
107
|
+
renameSync(tmp, file);
|
|
108
|
+
disk = text;
|
|
109
|
+
current = config;
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error.code === 'CONFIG_CHANGED' || error.code === 'EEXIST') throw problem('CONFIG_CHANGED');
|
|
112
|
+
throw problem('CONFIG_IO');
|
|
113
|
+
} finally {
|
|
114
|
+
if (descriptor !== undefined) {
|
|
115
|
+
closeSync(descriptor);
|
|
116
|
+
rmSync(lock, { force: true });
|
|
117
|
+
rmSync(tmp, { force: true });
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
package/src/extension.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
|
|
4
|
+
import { getApiProvider } from '@earendil-works/pi-ai/compat';
|
|
5
|
+
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
6
|
+
import { openConfig, problem } from './config.js';
|
|
7
|
+
import { registerMenu } from './menu.js';
|
|
8
|
+
import { wrapCodexAuth } from './oauth.js';
|
|
9
|
+
import { probeEndpoint, routedStream } from './routing.js';
|
|
10
|
+
|
|
11
|
+
const nativeIds = new Set(['openai-codex', 'anthropic', 'openai', 'deepseek', 'openrouter']);
|
|
12
|
+
const compatibleApis = new Set(['openai-completions', 'openai-responses', 'anthropic-messages']);
|
|
13
|
+
|
|
14
|
+
// Pi composes models.json over native providers. An API override can bypass a
|
|
15
|
+
// native stream wrapper, so expose only IDs whose entire chat catalog uses a
|
|
16
|
+
// supported protocol. Reload Pi after changing the protocol of an endpoint.
|
|
17
|
+
function supportedCatalog(agentDir, builtins) {
|
|
18
|
+
const entries = new Map(builtins.filter(p => nativeIds.has(p.id)).map(p => [p.id, { native: p }]));
|
|
19
|
+
let modelsFile;
|
|
20
|
+
try { modelsFile = JSON.parse(readFileSync(join(agentDir, 'models.json'), 'utf8')); }
|
|
21
|
+
catch { return entries; } // Pi itself reports models.json errors.
|
|
22
|
+
const builtinIds = new Set(builtins.map(p => p.id));
|
|
23
|
+
for (const [id, definition] of Object.entries(modelsFile?.providers ?? {})) {
|
|
24
|
+
if (!definition || typeof definition !== 'object') continue;
|
|
25
|
+
const native = entries.get(id)?.native;
|
|
26
|
+
const nativeApis = new Set(native?.getModels().map(model => model.api));
|
|
27
|
+
const models = Array.isArray(definition.models) ? definition.models : [];
|
|
28
|
+
const apis = new Set(models.map(model => model?.api ?? definition.api));
|
|
29
|
+
if (native) {
|
|
30
|
+
if ([...apis].some(api => api && !nativeApis.has(api))) entries.delete(id);
|
|
31
|
+
} else if (!builtinIds.has(id) && apis.size === 1 && !definition.oauth) {
|
|
32
|
+
const [api] = apis;
|
|
33
|
+
if (compatibleApis.has(api)) entries.set(id, { api });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return entries;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Every Pi operation resolves provider auth before choosing a model-specific
|
|
40
|
+
// protocol. Blocking here also covers APIs added by a models.json overlay.
|
|
41
|
+
function blockedProvider(id, native, error) {
|
|
42
|
+
const deny = () => { throw error; };
|
|
43
|
+
return {
|
|
44
|
+
id, name: native?.name ?? id,
|
|
45
|
+
getModels: () => native?.getModels() ?? [],
|
|
46
|
+
getAllModels: () => native?.getAllModels?.() ?? native?.getModels() ?? [],
|
|
47
|
+
auth: {
|
|
48
|
+
apiKey: { name: 'API key', check: async () => undefined, resolve: deny, login: deny },
|
|
49
|
+
...(native?.auth.oauth && { oauth: { ...native.auth.oauth, login: deny, refresh: deny, toAuth: deny } }),
|
|
50
|
+
},
|
|
51
|
+
stream: deny, streamSimple: deny,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export default function providerProxy(pi) {
|
|
56
|
+
const dir = getAgentDir();
|
|
57
|
+
const builtins = builtinProviders();
|
|
58
|
+
const catalog = supportedCatalog(dir, builtins);
|
|
59
|
+
let store, loadError;
|
|
60
|
+
try { store = openConfig(join(dir, 'provider-proxy.json'), id => catalog.has(id)); }
|
|
61
|
+
catch (error) { loadError = error; }
|
|
62
|
+
const checked = () => {
|
|
63
|
+
if (loadError) throw loadError;
|
|
64
|
+
return store;
|
|
65
|
+
};
|
|
66
|
+
const installed = new Set();
|
|
67
|
+
const blocked = new Set();
|
|
68
|
+
function block(id, error) {
|
|
69
|
+
if (blocked.has(id)) return;
|
|
70
|
+
pi.registerProvider(blockedProvider(id, builtins.find(p => p.id === id), error));
|
|
71
|
+
blocked.add(id);
|
|
72
|
+
}
|
|
73
|
+
function activate(id) {
|
|
74
|
+
if (installed.has(id)) return;
|
|
75
|
+
const { native, api } = catalog.get(id);
|
|
76
|
+
const route = () => checked().route(id);
|
|
77
|
+
if (native) {
|
|
78
|
+
pi.registerProvider({
|
|
79
|
+
...native,
|
|
80
|
+
auth: id === 'openai-codex' ? wrapCodexAuth(native.auth, route) : native.auth,
|
|
81
|
+
stream: routedStream(native.stream, route),
|
|
82
|
+
streamSimple: routedStream(native.streamSimple, route),
|
|
83
|
+
});
|
|
84
|
+
} else {
|
|
85
|
+
// Omit the model list so Pi retains its models.json catalog and auth.
|
|
86
|
+
pi.registerProvider(id, { api, streamSimple: routedStream(getApiProvider(api).streamSimple, route) });
|
|
87
|
+
}
|
|
88
|
+
installed.add(id);
|
|
89
|
+
}
|
|
90
|
+
for (const id of loadError ? catalog.keys() : Object.keys(store.read().bindings)) {
|
|
91
|
+
if (loadError || !catalog.has(id)) block(id, loadError ?? problem('STALE_BINDING'));
|
|
92
|
+
else activate(id);
|
|
93
|
+
}
|
|
94
|
+
// /model can refresh models.json without reloading extensions. Check Pi's
|
|
95
|
+
// effective chat models both on selection and before dispatching a new turn.
|
|
96
|
+
function checkLiveBindings(ctx) {
|
|
97
|
+
if (!installed.size || !store) return;
|
|
98
|
+
const bindings = store.read().bindings;
|
|
99
|
+
const models = ctx.modelRegistry.getAll();
|
|
100
|
+
for (const id of installed) {
|
|
101
|
+
if (!Object.hasOwn(bindings, id) || blocked.has(id)) continue;
|
|
102
|
+
const { native, api } = catalog.get(id);
|
|
103
|
+
const accepted = new Set(native ? native.getModels().map(model => model.api) : [api]);
|
|
104
|
+
if (models.some(model => model.provider === id && !accepted.has(model.api))) {
|
|
105
|
+
block(id, problem('STALE_BINDING'));
|
|
106
|
+
catalog.delete(id);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
pi.on('model_select', (_event, ctx) => checkLiveBindings(ctx));
|
|
111
|
+
pi.on('before_agent_start', (_event, ctx) => checkLiveBindings(ctx));
|
|
112
|
+
pi.on('session_start', (_event, ctx) => {
|
|
113
|
+
checkLiveBindings(ctx);
|
|
114
|
+
if (loadError) ctx.ui.notify(loadError.message, 'error');
|
|
115
|
+
else if (blocked.size) ctx.ui.notify(`${[...blocked].join(', ')} — ${problem('STALE_BINDING').message}`, 'warning');
|
|
116
|
+
});
|
|
117
|
+
registerMenu(pi, {
|
|
118
|
+
read: () => checked().read(),
|
|
119
|
+
save: next => {
|
|
120
|
+
// Register before publishing. Until save succeeds, each wrapper still reads the old snapshot.
|
|
121
|
+
for (const id of Object.keys(next.bindings)) {
|
|
122
|
+
if (blocked.has(id)) {
|
|
123
|
+
if (next.bindings[id] !== checked().read().bindings[id]) throw problem('STALE_BINDING');
|
|
124
|
+
} else {
|
|
125
|
+
if (!catalog.has(id)) throw problem('UNKNOWN_PROVIDER');
|
|
126
|
+
activate(id);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
checked().save(next);
|
|
130
|
+
for (const id of blocked) {
|
|
131
|
+
if (Object.hasOwn(next.bindings, id)) continue;
|
|
132
|
+
pi.unregisterProvider(id);
|
|
133
|
+
installed.delete(id);
|
|
134
|
+
blocked.delete(id);
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
providers: ctx => {
|
|
138
|
+
checkLiveBindings(ctx);
|
|
139
|
+
return [...new Set([...catalog.keys(), ...blocked])];
|
|
140
|
+
},
|
|
141
|
+
isBlocked: id => blocked.has(id),
|
|
142
|
+
probe: (id, ctx) => {
|
|
143
|
+
if (blocked.has(id)) throw problem('STALE_BINDING');
|
|
144
|
+
const model = ctx.model?.provider === id ? ctx.model : ctx.modelRegistry.getAll().find(m => m.provider === id);
|
|
145
|
+
return probeEndpoint(model?.baseUrl, checked().route(id));
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
}
|
package/src/i18n.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { win32 } from 'node:path';
|
|
3
|
+
|
|
4
|
+
function preferredDeviceLocale(platform, env, run) {
|
|
5
|
+
const options = { encoding: 'utf8', timeout: 800, maxBuffer: 16_384, windowsHide: true,
|
|
6
|
+
stdio: ['ignore', 'pipe', 'ignore'], shell: false, killSignal: 'SIGKILL' };
|
|
7
|
+
try {
|
|
8
|
+
if (platform === 'darwin') {
|
|
9
|
+
const output = run('/usr/bin/defaults', ['read', '-g', 'AppleLanguages'], options);
|
|
10
|
+
return /^\s*\(\s*["']?([\w-]+)/.exec(output)?.[1];
|
|
11
|
+
}
|
|
12
|
+
if (platform === 'win32') {
|
|
13
|
+
const powershell = win32.join(env.SystemRoot || 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
14
|
+
const output = run(powershell, ['-NoProfile', '-NonInteractive', '-Command', '(Get-UICulture).Name'], options);
|
|
15
|
+
return output.trim();
|
|
16
|
+
}
|
|
17
|
+
} catch { /* Headless hosts can lack platform preferences or the system utility. */ }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function detectLanguage({ platform = process.platform, env = process.env, run = execFileSync,
|
|
21
|
+
intlLocale = () => Intl.DateTimeFormat().resolvedOptions().locale } = {}) {
|
|
22
|
+
const device = preferredDeviceLocale(platform, env, run);
|
|
23
|
+
const locale = [device, env.LC_ALL, env.LC_MESSAGES, env.LANGUAGE?.split(':')[0], env.LANG]
|
|
24
|
+
.find(value => value?.trim()) ?? intlLocale();
|
|
25
|
+
return /^zh(?:$|[-_.@])/i.test(locale?.trim() ?? '') ? 'zh' : 'en';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
let cachedLanguage;
|
|
29
|
+
export function deviceLanguage() {
|
|
30
|
+
return cachedLanguage ??= detectLanguage();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const en = {
|
|
34
|
+
title: 'Provider proxy', provider: 'Provider', none: 'None available', active: 'active model',
|
|
35
|
+
chooseProvider: 'Select provider', bind: 'Change provider route', test: 'Test route',
|
|
36
|
+
inherit: 'Inherit (Pi default)', direct: 'Direct (bypass proxy)', profile: 'Profile',
|
|
37
|
+
codex: 'Codex uses SSE on managed routes.',
|
|
38
|
+
profiles: 'Shared proxy profiles', add: 'Add profile', edit: 'Edit proxy', remove: 'Remove profile',
|
|
39
|
+
name: 'New profile name', invalidName: 'Use a short label such as “office” (1–80 characters). URLs and reserved names are invalid.',
|
|
40
|
+
secureInputUnavailable: 'Open /proxy in the Pi terminal to enter this value securely.',
|
|
41
|
+
blockedRoute: 'Requests are blocked because the provider protocol changed. Restore the protocol and reload, or select Inherit to release the binding.',
|
|
42
|
+
duplicate: 'A profile with that name already exists.',
|
|
43
|
+
source: 'Proxy source', enter: 'Paste proxy URL', env: 'Choose environment variable',
|
|
44
|
+
variable: 'Environment variable holding the full proxy URL', custom: 'Enter another variable name',
|
|
45
|
+
enterVariable: 'Environment variable name', invalidVar: 'Use a variable name such as MY_PROXY.',
|
|
46
|
+
proxyPrompt: 'Paste the full proxy URL. Credentials are saved locally in plain text.',
|
|
47
|
+
invalidUrl: 'Enter an HTTP, HTTPS, SOCKS5 or SOCKS5H proxy address (host and optional port), or a reference such as $MY_PROXY.',
|
|
48
|
+
affected: providers => `Changing this profile changes the route for ${providers}. Continue?`,
|
|
49
|
+
inUse: providers => `Unbind this profile before removing it. Used by ${providers}.`,
|
|
50
|
+
confirmRemove: name => `Remove the shared profile “${name}”?`,
|
|
51
|
+
saved: 'Proxy settings saved.', stale: 'Settings changed while the menu was open. Review the current settings and retry.',
|
|
52
|
+
diskChanged: 'Another session changed the proxy settings. Run /reload to read the current settings.',
|
|
53
|
+
readFailed: 'Could not read proxy settings.', saveFailed: 'Could not apply and save proxy settings.',
|
|
54
|
+
unavailable: 'Could not list supported providers.', probing: 'Testing route', probeFailed: 'Route test failed before an HTTP response was available.',
|
|
55
|
+
reachable: 'Route reachable.', auth: 'Route reachable. The endpoint requires authentication or denied access.',
|
|
56
|
+
proxyAuth: 'The proxy requires authentication. Endpoint connectivity is unverified.',
|
|
57
|
+
httpError: 'Route reachable. The endpoint returned an HTTP error.',
|
|
58
|
+
invalidConfig: 'Proxy configuration is invalid.', envMissing: 'The proxy environment variable is unset or empty.',
|
|
59
|
+
unsupported: 'This provider does not support managed routes.', timeout: 'Route test timed out.',
|
|
60
|
+
network: 'Could not connect. Check the route, endpoint and proxy settings.',
|
|
61
|
+
configIO: 'Could not access the proxy settings file.', unknownProfile: 'The selected profile does not exist.',
|
|
62
|
+
noEndpoint: 'No HTTP endpoint is available for this provider.', failed: 'Proxy operation failed.',
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const zh = {
|
|
66
|
+
title: '服务商代理', provider: '服务商', none: '无可用服务商', active: '当前模型',
|
|
67
|
+
chooseProvider: '选择服务商', bind: '更改服务商路由', test: '测试路由',
|
|
68
|
+
inherit: '继承(Pi 默认设置)', direct: '直连(绕过代理)', profile: '配置',
|
|
69
|
+
codex: 'Codex 在指定路由时使用 SSE。',
|
|
70
|
+
profiles: '共享代理配置', add: '添加配置', edit: '编辑代理', remove: '删除配置',
|
|
71
|
+
name: '新配置名称', invalidName: '请输入 1 到 80 个字符的简称,例如“办公室”。名称不能包含网址,也不能使用保留名称。',
|
|
72
|
+
secureInputUnavailable: '请在 Pi 终端打开 /proxy,以遮蔽方式输入。',
|
|
73
|
+
blockedRoute: '服务商协议已变更,请求已拦截。可恢复原协议并执行 /reload,或选择“继承”解除绑定。',
|
|
74
|
+
duplicate: '同名配置已存在。',
|
|
75
|
+
source: '代理地址来源', enter: '粘贴代理地址', env: '选择环境变量',
|
|
76
|
+
variable: '选择保存完整代理地址的环境变量', custom: '输入其他变量名',
|
|
77
|
+
enterVariable: '环境变量名称', invalidVar: '请输入有效的变量名,例如 MY_PROXY。',
|
|
78
|
+
proxyPrompt: '粘贴完整代理地址。内含的用户名和密码将以明文保存在本机。',
|
|
79
|
+
invalidUrl: '请输入 HTTP、HTTPS、SOCKS5 或 SOCKS5H 代理地址(主机和可选端口),或输入 $MY_PROXY 这样的环境变量引用。',
|
|
80
|
+
affected: providers => `修改此配置将更改以下服务商的路由:${providers}。是否继续?`,
|
|
81
|
+
inUse: providers => `请先解除绑定再删除此配置。使用中的服务商:${providers}。`,
|
|
82
|
+
confirmRemove: name => `删除共享配置“${name}”?`,
|
|
83
|
+
saved: '代理设置已保存。', stale: '操作期间设置已发生变化,请检查当前设置后重试。',
|
|
84
|
+
diskChanged: '其他会话更改了代理设置,请运行 /reload 重新读取设置。',
|
|
85
|
+
readFailed: '无法读取代理设置。', saveFailed: '无法应用并保存代理设置。',
|
|
86
|
+
unavailable: '无法获取支持的服务商。', probing: '正在测试路由', probeFailed: '路由测试失败,未收到 HTTP 响应。',
|
|
87
|
+
reachable: '路由可达。', auth: '路由可达。目标服务要求身份验证或拒绝访问。',
|
|
88
|
+
proxyAuth: '代理要求身份验证,尚未确认目标服务是否可达。',
|
|
89
|
+
httpError: '路由可达。目标服务返回了 HTTP 错误。',
|
|
90
|
+
invalidConfig: '代理配置无效。', envMissing: '代理环境变量未设置或为空。',
|
|
91
|
+
unsupported: '此服务商不支持指定路由。', timeout: '路由测试超时。',
|
|
92
|
+
network: '连接失败。请检查路由、目标服务和代理设置。',
|
|
93
|
+
configIO: '无法访问代理配置文件。', unknownProfile: '所选配置不存在。',
|
|
94
|
+
noEndpoint: '此服务商没有可用的 HTTP 测试地址。', failed: '代理操作失败。',
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
export function messages(language = deviceLanguage()) {
|
|
98
|
+
return language === 'zh' ? zh : en;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Only translate known codes. Exceptions and unknown codes can contain proxy credentials.
|
|
102
|
+
const errorKeys = new Map(Object.entries({
|
|
103
|
+
CONFIG_INVALID: 'invalidConfig', CONFIG_IO: 'configIO', CONFIG_CHANGED: 'diskChanged', INVALID_NAME: 'invalidName',
|
|
104
|
+
INVALID_URL: 'invalidUrl', UNKNOWN_PROVIDER: 'unsupported',
|
|
105
|
+
UNKNOWN_PROFILE: 'unknownProfile', ENV_MISSING: 'envMissing', PROBE_FAILED: 'network',
|
|
106
|
+
PROBE_TIMEOUT: 'timeout', NO_ENDPOINT: 'noEndpoint', STALE_BINDING: 'blockedRoute',
|
|
107
|
+
}));
|
|
108
|
+
|
|
109
|
+
export function localizeError(error, language = deviceLanguage(), fallback = 'failed') {
|
|
110
|
+
return messages(language)[errorKeys.get(error?.code) ?? fallback];
|
|
111
|
+
}
|
package/src/menu.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { validProfileName } from './config.js';
|
|
3
|
+
import { readSecret, SecureInputUnavailable } from './secret-input.js';
|
|
4
|
+
import { validateProxyUrl } from './transport.js';
|
|
5
|
+
import { deviceLanguage, localizeError, messages } from './i18n.js';
|
|
6
|
+
|
|
7
|
+
const envRef = /^\$[A-Za-z_][A-Za-z0-9_]*$/;
|
|
8
|
+
const commonEnv = ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'all_proxy'];
|
|
9
|
+
|
|
10
|
+
// Pi returns the selected display string. Keep config keys separate from translated labels.
|
|
11
|
+
async function choose(ui, title, entries) {
|
|
12
|
+
const label = await ui.select(title, entries.map(entry => entry[1]));
|
|
13
|
+
return entries.find(entry => entry[1] === label)?.[0];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function safeAuthority(value, allowedProtocols) {
|
|
17
|
+
try {
|
|
18
|
+
const url = new URL(value);
|
|
19
|
+
if (url.hostname && allowedProtocols.includes(url.protocol)) return `${url.protocol}//${url.host}`;
|
|
20
|
+
} catch { /* Never echo malformed URLs or credentials into the terminal. */ }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const proxyProtocols = ['http:', 'https:', 'socks5:', 'socks5h:'];
|
|
24
|
+
|
|
25
|
+
function profileLabel(text, config, name) {
|
|
26
|
+
const value = config.profiles[name];
|
|
27
|
+
const address = envRef.test(value) ? value : safeAuthority(value, proxyProtocols);
|
|
28
|
+
return `${text.profile} ${name}${address ? ` (${address})` : ''}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function route(text, config, provider) {
|
|
32
|
+
if (!Object.hasOwn(config.bindings, provider)) return text.inherit;
|
|
33
|
+
const name = config.bindings[provider];
|
|
34
|
+
return name === 'direct' ? text.direct : profileLabel(text, config, name);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function pickRoute(ui, text, config, provider, blocked) {
|
|
38
|
+
const inherit = Symbol('inherit');
|
|
39
|
+
const entries = [[inherit, text.inherit]];
|
|
40
|
+
if (!blocked) entries.push(['direct', text.direct],
|
|
41
|
+
...Object.keys(config.profiles).sort().map(name => [name, profileLabel(text, config, name)]));
|
|
42
|
+
const choice = await choose(ui, `${provider} — ${blocked ? text.blockedRoute : route(text, config, provider)}`, entries);
|
|
43
|
+
if (choice === undefined) return;
|
|
44
|
+
const bindings = { ...config.bindings, [provider]: choice };
|
|
45
|
+
if (choice === inherit) delete bindings[provider];
|
|
46
|
+
return { ...config, bindings };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function enterProxy(ctx, text) {
|
|
50
|
+
const { ui } = ctx;
|
|
51
|
+
const source = await choose(ui, text.source, [['enter', text.enter], ['env', text.env]]);
|
|
52
|
+
if (!source) return;
|
|
53
|
+
if (source === 'env') {
|
|
54
|
+
const selected = await ui.select(text.variable, [...commonEnv, text.custom]);
|
|
55
|
+
if (selected === undefined) return;
|
|
56
|
+
const name = selected === text.custom ? await readSecret(ctx, text.enterVariable) : selected;
|
|
57
|
+
if (name === undefined) return;
|
|
58
|
+
const ref = '$' + name.trim().replace(/^\$/, '');
|
|
59
|
+
if (envRef.test(ref)) return ref;
|
|
60
|
+
ui.notify(text.invalidVar, 'error');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const value = (await readSecret(ctx, text.proxyPrompt))?.trim();
|
|
64
|
+
if (value === undefined || envRef.test(value)) return value;
|
|
65
|
+
try {
|
|
66
|
+
validateProxyUrl(value);
|
|
67
|
+
return value;
|
|
68
|
+
} catch {
|
|
69
|
+
ui.notify(text.invalidUrl, 'error');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async function manageProfiles(ctx, text, config) {
|
|
74
|
+
const { ui } = ctx;
|
|
75
|
+
const add = Symbol('add');
|
|
76
|
+
const profile = await choose(ui, text.profiles, [
|
|
77
|
+
[add, text.add], ...Object.keys(config.profiles).sort().map(name => [name, profileLabel(text, config, name)]),
|
|
78
|
+
]);
|
|
79
|
+
if (profile === undefined) return;
|
|
80
|
+
if (profile === add) {
|
|
81
|
+
const name = (await readSecret(ctx, text.name))?.trim();
|
|
82
|
+
if (name === undefined) return;
|
|
83
|
+
if (!validProfileName(name)) {
|
|
84
|
+
ui.notify(text.invalidName, 'error');
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (Object.hasOwn(config.profiles, name)) {
|
|
88
|
+
ui.notify(text.duplicate, 'error');
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
const value = await enterProxy(ctx, text);
|
|
92
|
+
if (value !== undefined) return { ...config, profiles: { ...config.profiles, [name]: value } };
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const action = await choose(ui, profileLabel(text, config, profile), [['edit', text.edit], ['remove', text.remove]]);
|
|
97
|
+
if (!action) return;
|
|
98
|
+
const users = Object.keys(config.bindings).filter(id => config.bindings[id] === profile).sort().join(', ');
|
|
99
|
+
const profiles = { ...config.profiles };
|
|
100
|
+
if (action === 'remove') {
|
|
101
|
+
if (users) {
|
|
102
|
+
ui.notify(text.inUse(users), 'warning');
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (!await ui.confirm(text.remove, text.confirmRemove(profile))) return;
|
|
106
|
+
delete profiles[profile];
|
|
107
|
+
} else {
|
|
108
|
+
const value = await enterProxy(ctx, text);
|
|
109
|
+
if (value === undefined || value === profiles[profile]) return;
|
|
110
|
+
if (users && !await ui.confirm(text.edit, text.affected(users))) return;
|
|
111
|
+
profiles[profile] = value;
|
|
112
|
+
}
|
|
113
|
+
return { ...config, profiles };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function testRoute(services, ctx, provider, language) {
|
|
117
|
+
const text = messages(language);
|
|
118
|
+
ctx.ui.notify(`${text.probing} — ${provider}`, 'info');
|
|
119
|
+
try {
|
|
120
|
+
const { origin: target, status, elapsedMs } = await services.probe(provider, ctx);
|
|
121
|
+
const endpoint = safeAuthority(target, ['http:', 'https:']);
|
|
122
|
+
if (!endpoint || !Number.isInteger(status) || !Number.isFinite(elapsedMs)) throw new Error();
|
|
123
|
+
let outcome = text.reachable;
|
|
124
|
+
if (status === 407) outcome = text.proxyAuth;
|
|
125
|
+
else if (status === 401 || status === 403) outcome = text.auth;
|
|
126
|
+
else if (status >= 400) outcome = text.httpError;
|
|
127
|
+
ctx.ui.notify(`${provider} — ${endpoint} — HTTP ${status} (${Math.round(elapsedMs)} ms)\n${outcome}`, status >= 400 ? 'warning' : 'info');
|
|
128
|
+
} catch (error) {
|
|
129
|
+
ctx.ui.notify(localizeError(error, language, 'probeFailed'), 'error');
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function registerMenu(pi, services, detect = deviceLanguage) {
|
|
134
|
+
const language = detect();
|
|
135
|
+
const text = messages(language);
|
|
136
|
+
pi.registerCommand('proxy', {
|
|
137
|
+
description: text.title,
|
|
138
|
+
async handler(_args, ctx) {
|
|
139
|
+
if (!ctx.hasUI) return;
|
|
140
|
+
const { ui } = ctx;
|
|
141
|
+
let provider = ctx.model?.provider;
|
|
142
|
+
while (true) {
|
|
143
|
+
let ids;
|
|
144
|
+
try {
|
|
145
|
+
ids = [...new Set(services.providers(ctx))];
|
|
146
|
+
} catch (error) {
|
|
147
|
+
ui.notify(localizeError(error, language, 'unavailable'), 'error');
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (!ids.includes(provider)) provider = ids.includes(ctx.model?.provider) ? ctx.model.provider : ids[0];
|
|
151
|
+
const blocked = provider && services.isBlocked?.(provider);
|
|
152
|
+
let config;
|
|
153
|
+
try {
|
|
154
|
+
config = structuredClone(services.read());
|
|
155
|
+
} catch (error) {
|
|
156
|
+
ui.notify(localizeError(error, language, 'readFailed'), 'error');
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const entries = [];
|
|
160
|
+
let title = `${text.title}\n${text.provider}: ${provider ?? text.none}`;
|
|
161
|
+
if (provider) {
|
|
162
|
+
if (provider === ctx.model?.provider) title += ` (${text.active})`;
|
|
163
|
+
title += ` — ${blocked ? text.blockedRoute : route(text, config, provider)}`;
|
|
164
|
+
entries.push(['bind', text.bind]);
|
|
165
|
+
if (!blocked) {
|
|
166
|
+
if (provider === 'openai-codex') title += `\n${text.codex}`;
|
|
167
|
+
entries.push(['test', text.test]);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (ids.length > 1) entries.push(['provider', text.chooseProvider]);
|
|
171
|
+
entries.push(['profiles', text.profiles]);
|
|
172
|
+
const action = await choose(ui, title, entries);
|
|
173
|
+
if (!action) return;
|
|
174
|
+
if (action === 'test') {
|
|
175
|
+
await testRoute(services, ctx, provider, language);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (action === 'provider') {
|
|
179
|
+
const selected = await choose(ui, text.chooseProvider, ids.map(id => [id, `${id} — ${services.isBlocked?.(id) ? text.blockedRoute : route(text, config, id)}`]));
|
|
180
|
+
if (selected) provider = selected;
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
let next;
|
|
184
|
+
try {
|
|
185
|
+
next = action === 'bind' ? await pickRoute(ui, text, config, provider, blocked) : await manageProfiles(ctx, text, config);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
if (!(error instanceof SecureInputUnavailable)) throw error;
|
|
188
|
+
ui.notify(text.secureInputUnavailable, 'error');
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (!next || isDeepStrictEqual(next, config)) continue;
|
|
192
|
+
try {
|
|
193
|
+
// A dialog can outlive another command's save. Recheck before replacing a snapshot.
|
|
194
|
+
if (!isDeepStrictEqual(config, structuredClone(services.read()))) {
|
|
195
|
+
ui.notify(text.stale, 'warning');
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
services.save(next);
|
|
199
|
+
ui.notify(text.saved, 'info');
|
|
200
|
+
} catch (error) {
|
|
201
|
+
ui.notify(localizeError(error, language, 'saveFailed'), 'error');
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Each worker handles one OAuth operation. Keep only fixed stage names, HTTP
|
|
2
|
+
// status and allowlisted error codes. Native errors may include token bodies.
|
|
3
|
+
const labels = {
|
|
4
|
+
en: { setup: 'initializing provider', method: 'selecting login method', browser: 'browser authorization and callback',
|
|
5
|
+
device: 'requesting device code', poll: 'waiting for device authorization', exchange: 'exchanging authorization code', refresh: 'refreshing token',
|
|
6
|
+
request: 'authorization request', network: 'network request failed', callback: 'browser authorization was declined or failed',
|
|
7
|
+
invalid: 'unexpected authorization response', unavailable: 'device code login is unavailable; choose Browser login' },
|
|
8
|
+
zh: { setup: '初始化服务商', method: '选择登录方式', browser: '浏览器授权和本机回调',
|
|
9
|
+
device: '申请设备码', poll: '查询设备授权结果', exchange: '用授权码换取令牌', refresh: '刷新令牌',
|
|
10
|
+
request: '授权请求', network: '网络请求失败', callback: '浏览器授权未通过',
|
|
11
|
+
invalid: '授权服务返回了无法识别的响应', unavailable: '设备码登录不可用,请选择浏览器登录' },
|
|
12
|
+
};
|
|
13
|
+
const networkCodes = new Set(['SOCKS_AUTH', 'SOCKS_CONNECT', 'SOCKS_RESET', 'SOCKS_TIMEOUT', 'ECONNRESET', 'ECONNREFUSED',
|
|
14
|
+
'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_SOCKET',
|
|
15
|
+
'ERR_TLS_CERT_ALTNAME_INVALID', 'CERT_HAS_EXPIRED', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', 'SELF_SIGNED_CERT_IN_CHAIN']);
|
|
16
|
+
const tokenErrors = new Set(['invalid_grant', 'invalid_client', 'invalid_request', 'access_denied']);
|
|
17
|
+
|
|
18
|
+
function networkDetail(error, fallback) {
|
|
19
|
+
for (let cause = error; cause; cause = cause.cause) {
|
|
20
|
+
if (networkCodes.has(cause.code)) return cause.code;
|
|
21
|
+
if (cause.code === 'UND_ERR_ABORTED') {
|
|
22
|
+
const status = /^Proxy response \((\d{3})\)/.exec(cause.message);
|
|
23
|
+
if (status) return `HTTP CONNECT ${status[1]}`;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return fallback;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function oauthDiagnostics(operation, language) {
|
|
30
|
+
const words = labels[language] ?? labels.en;
|
|
31
|
+
let stage = 'setup', status, network;
|
|
32
|
+
return {
|
|
33
|
+
setStage(value) { stage = value; },
|
|
34
|
+
observe(fetch) {
|
|
35
|
+
return async (input, init) => {
|
|
36
|
+
const path = new URL(input?.url ?? input).pathname;
|
|
37
|
+
stage = ({ '/api/accounts/deviceauth/usercode': 'device', '/api/accounts/deviceauth/token': 'poll',
|
|
38
|
+
'/oauth/token': operation === 'refresh' ? 'refresh' : 'exchange' })[path] ?? 'request';
|
|
39
|
+
status = undefined;
|
|
40
|
+
network = undefined;
|
|
41
|
+
try {
|
|
42
|
+
const response = await fetch(input, init);
|
|
43
|
+
status = response.status;
|
|
44
|
+
return response;
|
|
45
|
+
} catch (error) {
|
|
46
|
+
network = networkDetail(error, words.network);
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
},
|
|
51
|
+
error(error) {
|
|
52
|
+
const message = error instanceof Error ? error.message : '';
|
|
53
|
+
// Pi recognizes this exact string to return to the provider picker.
|
|
54
|
+
if (message === 'Login cancelled') return message;
|
|
55
|
+
const details = [];
|
|
56
|
+
if (Number.isInteger(status)) details.push(`HTTP ${status}`);
|
|
57
|
+
if (network) details.push(network);
|
|
58
|
+
if (stage === 'device' && status === 404) details.push(words.unavailable);
|
|
59
|
+
else if (message.startsWith('OpenAI authorization failed:')) details.push(words.callback);
|
|
60
|
+
else if (['State mismatch', 'Missing authorization code', 'Failed to extract accountId from token', 'Device flow timed out'].includes(message)) details.push(message);
|
|
61
|
+
else if (error instanceof SyntaxError || status >= 200 && status < 300) details.push(words.invalid);
|
|
62
|
+
else if ((stage === 'exchange' || stage === 'refresh') && status >= 400) {
|
|
63
|
+
try {
|
|
64
|
+
const body = JSON.parse(message.slice(message.indexOf('): ') + 3));
|
|
65
|
+
const reason = typeof body?.error === 'string' ? body.error : body?.error?.code;
|
|
66
|
+
if (tokenErrors.has(reason)) details.push(reason);
|
|
67
|
+
} catch { /* HTML and freeform provider responses stay private. */ }
|
|
68
|
+
}
|
|
69
|
+
const title = language === 'zh' ? `Codex OAuth ${operation === 'refresh' ? '续期' : '登录'}失败` : `Codex OAuth ${operation} failed`;
|
|
70
|
+
return `${title} (${[words[stage], ...details].join(', ')})`;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { once } from 'node:events';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import { registerHooks } from 'node:module';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { MessageChannel, parentPort, workerData } from 'node:worker_threads';
|
|
6
|
+
import { createTransport } from './transport.js';
|
|
7
|
+
import { deviceLanguage } from './i18n.js';
|
|
8
|
+
import { oauthDiagnostics } from './oauth-diagnostics.js';
|
|
9
|
+
|
|
10
|
+
const diagnostics = oauthDiagnostics(workerData.operation, deviceLanguage());
|
|
11
|
+
|
|
12
|
+
const providerSpecifier = '@earendil-works/pi-ai/providers/openai-codex';
|
|
13
|
+
const missingPeer = 'Scoped Codex OAuth requires a physical @earendil-works/pi-ai installation accessible from the extension or the Pi CLI';
|
|
14
|
+
|
|
15
|
+
function resolveProvider(hostEntry) {
|
|
16
|
+
try {
|
|
17
|
+
return import.meta.resolve(providerSpecifier);
|
|
18
|
+
} catch (error) {
|
|
19
|
+
if (error.code !== 'ERR_MODULE_NOT_FOUND') throw error;
|
|
20
|
+
}
|
|
21
|
+
// Managed installs supply Pi peers via the host loader. Resolve the public ESM
|
|
22
|
+
// export relative to the physical CLI in this worker (the CLI may be a symlink).
|
|
23
|
+
try {
|
|
24
|
+
const parentURL = pathToFileURL(realpathSync(hostEntry)).href;
|
|
25
|
+
const hook = registerHooks({ resolve: (id, context, next) => next(id, { ...context, parentURL }) });
|
|
26
|
+
try {
|
|
27
|
+
return import.meta.resolve(providerSpecifier);
|
|
28
|
+
} finally {
|
|
29
|
+
hook.deregister();
|
|
30
|
+
}
|
|
31
|
+
} catch {
|
|
32
|
+
throw new Error(missingPeer);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function prompt({ signal: promptSignal, ...prompt }) {
|
|
37
|
+
const { port1, port2 } = new MessageChannel();
|
|
38
|
+
try {
|
|
39
|
+
const signal = promptSignal ? AbortSignal.any([promptSignal, workerData.signal]) : workerData.signal;
|
|
40
|
+
signal.throwIfAborted();
|
|
41
|
+
parentPort.postMessage({ type: 'prompt', prompt, reply: port2 }, [port2]);
|
|
42
|
+
const [answer] = await once(port1, 'message', { signal });
|
|
43
|
+
if (answer.cancelled) throw new Error('Login cancelled');
|
|
44
|
+
if (prompt.type === 'select' && answer.value === 'browser') diagnostics.setStage('browser');
|
|
45
|
+
return answer.value;
|
|
46
|
+
} finally {
|
|
47
|
+
// If Pi's callback listener wins, closing the port aborts the pending UI prompt.
|
|
48
|
+
port1.close();
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function run() {
|
|
53
|
+
const { operation, route, input, signal } = workerData;
|
|
54
|
+
const { openaiCodexProvider } = await import(resolveProvider(workerData.hostEntry));
|
|
55
|
+
const transport = createTransport(route, { retrySocksHandshake: true });
|
|
56
|
+
try {
|
|
57
|
+
// Pi 1.7.0's Codex OAuth uses global fetch for every token/device request.
|
|
58
|
+
// This worker is private to the operation, including its global object.
|
|
59
|
+
globalThis.fetch = diagnostics.observe(transport.fetch);
|
|
60
|
+
const oauth = openaiCodexProvider().auth.oauth;
|
|
61
|
+
diagnostics.setStage(operation === 'refresh' ? 'refresh' : 'method');
|
|
62
|
+
if (operation === 'refresh') return await oauth.refresh(input, signal);
|
|
63
|
+
const notify = event => parentPort.postMessage({ type: 'notify', event });
|
|
64
|
+
return await oauth.login({ prompt, notify, signal }, input);
|
|
65
|
+
} finally {
|
|
66
|
+
await transport.close();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
try {
|
|
71
|
+
parentPort.postMessage({ type: 'result', credential: await run() });
|
|
72
|
+
} catch (error) {
|
|
73
|
+
const message = error?.message === missingPeer ? missingPeer : diagnostics.error(error);
|
|
74
|
+
parentPort.postMessage({ type: 'error', message });
|
|
75
|
+
}
|
package/src/oauth.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { transferableAbortController } from 'node:util';
|
|
3
|
+
|
|
4
|
+
// A separate reply port lets the browser callback dismiss just its own manual-code prompt.
|
|
5
|
+
async function answerPrompt(interaction, { prompt, reply }, operationSignal) {
|
|
6
|
+
const dismissed = new AbortController();
|
|
7
|
+
reply.once('close', () => dismissed.abort());
|
|
8
|
+
const signal = AbortSignal.any([dismissed.signal, operationSignal]);
|
|
9
|
+
try {
|
|
10
|
+
const value = await interaction.prompt({ ...prompt, signal });
|
|
11
|
+
if (!signal.aborted) reply.postMessage({ value });
|
|
12
|
+
} catch {
|
|
13
|
+
if (!signal.aborted) reply.postMessage({ cancelled: true });
|
|
14
|
+
} finally {
|
|
15
|
+
reply.close();
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function runScoped(operation, route, input, signal, interaction) {
|
|
20
|
+
signal?.throwIfAborted();
|
|
21
|
+
const scope = transferableAbortController();
|
|
22
|
+
const worker = new Worker(new URL('./oauth-worker.js', import.meta.url), {
|
|
23
|
+
workerData: { operation, route, input, signal: scope.signal, hostEntry: process.argv[1] },
|
|
24
|
+
transferList: [scope.signal],
|
|
25
|
+
execArgv: [],
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
let onAbort;
|
|
29
|
+
try {
|
|
30
|
+
return await new Promise((resolve, reject) => {
|
|
31
|
+
onAbort = () => {
|
|
32
|
+
scope.abort();
|
|
33
|
+
reject(signal.reason);
|
|
34
|
+
};
|
|
35
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
36
|
+
worker.once('error', reject);
|
|
37
|
+
worker.once('exit', code => reject(new Error(`Codex OAuth worker exited before completion (${code})`)));
|
|
38
|
+
worker.on('message', message => {
|
|
39
|
+
if (scope.signal.aborted) return;
|
|
40
|
+
switch (message.type) {
|
|
41
|
+
case 'prompt':
|
|
42
|
+
answerPrompt(interaction, message, scope.signal).catch(reject);
|
|
43
|
+
break;
|
|
44
|
+
case 'notify':
|
|
45
|
+
try { interaction.notify(message.event); } catch (error) { reject(error); }
|
|
46
|
+
break;
|
|
47
|
+
case 'result': resolve(message.credential); break;
|
|
48
|
+
case 'error': reject(new Error(message.message)); break;
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
} finally {
|
|
53
|
+
signal?.removeEventListener('abort', onAbort);
|
|
54
|
+
scope.abort();
|
|
55
|
+
// Also releases a loopback listener or stalled socket when cancellation wins the race.
|
|
56
|
+
await worker.terminate();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Wrap a native Codex ProviderAuth. Resolve the route once per login or refresh. */
|
|
61
|
+
export function wrapCodexAuth(auth, getRoute) {
|
|
62
|
+
const oauth = auth.oauth;
|
|
63
|
+
return {
|
|
64
|
+
...auth,
|
|
65
|
+
oauth: {
|
|
66
|
+
...oauth,
|
|
67
|
+
login(interaction, options) {
|
|
68
|
+
const route = getRoute();
|
|
69
|
+
if (route === undefined) return oauth.login(interaction, options);
|
|
70
|
+
// agentName is the only LoginOptions field used by Codex. getDeviceId is a callback.
|
|
71
|
+
return runScoped('login', route, { agentName: options?.agentName }, interaction.signal, interaction);
|
|
72
|
+
},
|
|
73
|
+
refresh(credential, signal) {
|
|
74
|
+
const route = getRoute();
|
|
75
|
+
if (route === undefined) return oauth.refresh(credential, signal);
|
|
76
|
+
return runScoped('refresh', route, credential, signal);
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
}
|
package/src/routing.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { createTransport } from './transport.js';
|
|
2
|
+
import { problem } from './config.js';
|
|
3
|
+
|
|
4
|
+
// Each logical stream owns its connections through retries and body consumption.
|
|
5
|
+
// Editing/deleting a profile can therefore never disrupt an existing stream.
|
|
6
|
+
export function routedStream(delegate, getRoute) {
|
|
7
|
+
return (model, transcript, options) => {
|
|
8
|
+
const route = getRoute();
|
|
9
|
+
if (route === undefined) return delegate(model, transcript, options);
|
|
10
|
+
const transport = createTransport(route);
|
|
11
|
+
try {
|
|
12
|
+
const stream = delegate(model, transcript, {
|
|
13
|
+
...options, fetch: transport.fetch,
|
|
14
|
+
...(model.api === 'openai-codex-responses' ? { transport: 'sse' } : {}),
|
|
15
|
+
});
|
|
16
|
+
const retire = () => transport.close().catch(() => {});
|
|
17
|
+
stream.result().then(retire, retire);
|
|
18
|
+
return stream;
|
|
19
|
+
} catch (error) {
|
|
20
|
+
void transport.close().catch(() => {});
|
|
21
|
+
throw error;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function probeEndpoint(endpoint, route) {
|
|
27
|
+
let origin;
|
|
28
|
+
try {
|
|
29
|
+
const url = new URL(endpoint);
|
|
30
|
+
if (!['https:', 'http:'].includes(url.protocol)) throw new Error();
|
|
31
|
+
origin = url.origin;
|
|
32
|
+
} catch { throw problem('NO_ENDPOINT'); }
|
|
33
|
+
const transport = route === undefined ? undefined : createTransport(route);
|
|
34
|
+
const signal = AbortSignal.timeout(6000);
|
|
35
|
+
const start = performance.now();
|
|
36
|
+
try {
|
|
37
|
+
const response = await (transport?.fetch ?? globalThis.fetch)(origin, {
|
|
38
|
+
method: 'HEAD', redirect: 'manual', signal,
|
|
39
|
+
});
|
|
40
|
+
await response.body?.cancel();
|
|
41
|
+
return { origin, status: response.status, elapsedMs: Math.round(performance.now() - start) };
|
|
42
|
+
} catch (error) {
|
|
43
|
+
if (signal.aborted) throw problem('PROBE_TIMEOUT');
|
|
44
|
+
for (let cause = error; cause; cause = cause.cause) {
|
|
45
|
+
if (cause.code === 'UND_ERR_ABORTED' && /^Proxy response \(407\)/.test(cause.message)) {
|
|
46
|
+
return { origin, status: 407, elapsedMs: Math.round(performance.now() - start) };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
throw problem('PROBE_FAILED');
|
|
50
|
+
} finally { await transport?.close(); }
|
|
51
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { CURSOR_MARKER, decodeKittyPrintable, renderFakeCursor, StdinBuffer, truncateToWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
2
|
+
|
|
3
|
+
const graphemes = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
|
|
4
|
+
|
|
5
|
+
// Only this closure owns the field value. Rendering and terminal selection see masks from the first frame.
|
|
6
|
+
function maskedField(title, tui, keys, done) {
|
|
7
|
+
let value = '';
|
|
8
|
+
let closed = false;
|
|
9
|
+
const input = new StdinBuffer();
|
|
10
|
+
|
|
11
|
+
function dispose() {
|
|
12
|
+
closed = true;
|
|
13
|
+
value = '';
|
|
14
|
+
input.destroy();
|
|
15
|
+
input.removeAllListeners();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function finish(result) {
|
|
19
|
+
dispose();
|
|
20
|
+
done(result);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
input.on('paste', text => {
|
|
24
|
+
// Keep paste literal (including Enter/Escape) until the menu validates the submitted field.
|
|
25
|
+
value += text;
|
|
26
|
+
tui.requestRender();
|
|
27
|
+
});
|
|
28
|
+
input.on('data', data => {
|
|
29
|
+
if (keys.matches(data, 'tui.select.cancel')) return finish(undefined);
|
|
30
|
+
if (keys.matches(data, 'tui.input.submit') || data === '\n') return finish(value);
|
|
31
|
+
if (keys.matches(data, 'tui.editor.deleteCharBackward')) {
|
|
32
|
+
const last = graphemes.segment(value).containing(value.length - 1);
|
|
33
|
+
if (last) value = value.slice(0, last.index);
|
|
34
|
+
} else {
|
|
35
|
+
const text = decodeKittyPrintable(data) ?? data;
|
|
36
|
+
if (!text || /\p{Cc}/u.test(text)) return;
|
|
37
|
+
value += text;
|
|
38
|
+
}
|
|
39
|
+
tui.requestRender();
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
focused: false,
|
|
44
|
+
handleInput(data) { if (!closed) input.process(data); },
|
|
45
|
+
render(width) {
|
|
46
|
+
if (width < 1) return [];
|
|
47
|
+
const mask = '*'.repeat(Math.min(value.length, width - 1));
|
|
48
|
+
const cursor = (this.focused ? CURSOR_MARKER : '') + renderFakeCursor(' ');
|
|
49
|
+
return [...wrapTextWithAnsi(title, width).map(line => truncateToWidth(line, width, '')), mask + cursor];
|
|
50
|
+
},
|
|
51
|
+
invalidate() {},
|
|
52
|
+
dispose,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class SecureInputUnavailable extends Error {}
|
|
57
|
+
|
|
58
|
+
export async function readSecret(ctx, title) {
|
|
59
|
+
// RPC supports ordinary input but has no masked-input protocol or custom component host.
|
|
60
|
+
if (ctx.mode !== 'tui' || typeof ctx.ui.custom !== 'function') throw new SecureInputUnavailable();
|
|
61
|
+
let field;
|
|
62
|
+
try {
|
|
63
|
+
const result = await ctx.ui.custom((tui, _theme, keys, done) => {
|
|
64
|
+
field = maskedField(title, tui, keys, done);
|
|
65
|
+
return field;
|
|
66
|
+
}, { blocked: { kind: 'question', message: title } });
|
|
67
|
+
if (field) return result;
|
|
68
|
+
} catch { /* Never report a UI exception that may contain input. */ }
|
|
69
|
+
finally { field?.dispose(); }
|
|
70
|
+
throw new SecureInputUnavailable();
|
|
71
|
+
}
|
package/src/transport.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { lookup } from 'node:dns/promises';
|
|
2
|
+
import { isIP } from 'node:net';
|
|
3
|
+
import { domainToASCII } from 'node:url';
|
|
4
|
+
import { Agent, Pool, ProxyAgent, Request as UndiciRequest, buildConnector, fetch as dispatchFetch } from 'undici';
|
|
5
|
+
import { SocksClient } from 'socks';
|
|
6
|
+
|
|
7
|
+
function invalidProxy() {
|
|
8
|
+
return new TypeError('Invalid proxy URL (expected an HTTP, HTTPS, SOCKS5, or SOCKS5H proxy authority).');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Return a normalized URL. The return value can contain credentials and is private. */
|
|
12
|
+
export function validateProxyUrl(value) {
|
|
13
|
+
const text = value instanceof URL ? value.href : value;
|
|
14
|
+
if (typeof text !== 'string' || /[\s\x00-\x1f\x7f\\]/u.test(text) ||
|
|
15
|
+
!/^(?:https?|socks5h?):\/\/[^/?#]+\/?$/i.test(text)) {
|
|
16
|
+
throw invalidProxy();
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
const url = new URL(text);
|
|
20
|
+
const hostname = domainToASCII(url.hostname);
|
|
21
|
+
if (!hostname || url.port === '0') throw invalidProxy();
|
|
22
|
+
url.hostname = hostname;
|
|
23
|
+
const credentials = [url.username, url.password].map(decodeURIComponent);
|
|
24
|
+
if (url.protocol.startsWith('socks') && credentials.some(s => Buffer.byteLength(s) > 255)) {
|
|
25
|
+
throw invalidProxy();
|
|
26
|
+
}
|
|
27
|
+
return url.href;
|
|
28
|
+
} catch {
|
|
29
|
+
// URL parser errors can retain the entire input, including the password.
|
|
30
|
+
throw invalidProxy();
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function socksFailure(error) {
|
|
35
|
+
// SocksClientError also holds the plaintext proxy credentials. Copy only a code.
|
|
36
|
+
const msg = error?.message ?? '';
|
|
37
|
+
let code = 'SOCKS_CONNECT';
|
|
38
|
+
if (msg === 'Proxy connection timed out' || /\bETIMEDOUT\b/.test(msg)) code = 'SOCKS_TIMEOUT';
|
|
39
|
+
else if (msg === 'Socket closed' || /\bECONNRESET\b/.test(msg)) code = 'SOCKS_RESET';
|
|
40
|
+
else if (/Authentication failed|authentication type/i.test(msg)) code = 'SOCKS_AUTH';
|
|
41
|
+
return Object.assign(new Error('SOCKS proxy connection failed.'), { code });
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function socksAgent(url, retryHandshake) {
|
|
45
|
+
const proxy = {
|
|
46
|
+
type: 5,
|
|
47
|
+
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
48
|
+
port: Number(url.port || 1080),
|
|
49
|
+
userId: decodeURIComponent(url.username),
|
|
50
|
+
password: decodeURIComponent(url.password),
|
|
51
|
+
};
|
|
52
|
+
const tlsConnect = buildConnector({ rejectUnauthorized: true });
|
|
53
|
+
|
|
54
|
+
async function tunnel({ hostname, port, protocol }) {
|
|
55
|
+
let host = hostname;
|
|
56
|
+
if (url.protocol === 'socks5:' && !isIP(host)) host = (await lookup(host)).address;
|
|
57
|
+
if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
|
|
58
|
+
const secured = protocol === 'https:';
|
|
59
|
+
const options = {
|
|
60
|
+
command: 'connect', proxy, destination: { host, port: Number(port || (secured ? 443 : 80)) },
|
|
61
|
+
timeout: 10_000, set_tcp_nodelay: true,
|
|
62
|
+
};
|
|
63
|
+
for (let attempt = 0; ; attempt++) {
|
|
64
|
+
try {
|
|
65
|
+
return (await SocksClient.createConnection(options)).socket;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const failure = socksFailure(error);
|
|
68
|
+
// Only establish a tunnel again. No OAuth POST has been sent at this point.
|
|
69
|
+
if (!retryHandshake || attempt > 0 || !['SOCKS_TIMEOUT', 'SOCKS_RESET'].includes(failure.code)) throw failure;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return new Agent({
|
|
75
|
+
connect(options, callback) {
|
|
76
|
+
tunnel(options).then(socket => {
|
|
77
|
+
if (options.protocol !== 'https:') return callback(null, socket);
|
|
78
|
+
// Verify against the original destination hostname, even after local DNS lookup.
|
|
79
|
+
tlsConnect({ ...options, httpSocket: socket }, callback);
|
|
80
|
+
}, callback);
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function dispatcherFor(route, retryHandshake) {
|
|
86
|
+
if (route === 'direct') return new Agent({ connect: { rejectUnauthorized: true } });
|
|
87
|
+
const url = new URL(validateProxyUrl(route));
|
|
88
|
+
if (url.protocol.startsWith('socks')) return socksAgent(url, retryHandshake);
|
|
89
|
+
|
|
90
|
+
let token;
|
|
91
|
+
if (url.username || url.password) {
|
|
92
|
+
const basic = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;
|
|
93
|
+
token = `Basic ${Buffer.from(basic).toString('base64')}`;
|
|
94
|
+
}
|
|
95
|
+
return new ProxyAgent({
|
|
96
|
+
uri: url.origin, token, proxyTunnel: true,
|
|
97
|
+
// ProxyAgent passes even an IP literal as SNI. Let the connector derive SNI
|
|
98
|
+
// from the proxy host, omitting it for IPs while TLS still verifies their SAN.
|
|
99
|
+
clientFactory: (origin, { connect }) => new Pool(origin, {
|
|
100
|
+
connect: (options, callback) => connect({ ...options, servername: undefined }, callback),
|
|
101
|
+
}),
|
|
102
|
+
proxyTls: { rejectUnauthorized: true }, requestTls: { rejectUnauthorized: true },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
|
|
107
|
+
export function createTransport(route, { retrySocksHandshake = false } = {}) {
|
|
108
|
+
const dispatcher = dispatcherFor(route, retrySocksHandshake);
|
|
109
|
+
let closing;
|
|
110
|
+
return {
|
|
111
|
+
async fetch(input, init) {
|
|
112
|
+
if (closing) throw new TypeError('Transport is closed.');
|
|
113
|
+
// Node and the installed undici have separately branded Fetch classes.
|
|
114
|
+
let request;
|
|
115
|
+
if (input instanceof Request && !(input instanceof UndiciRequest)) {
|
|
116
|
+
const native = new Request(input, init);
|
|
117
|
+
request = new UndiciRequest(native.url, native);
|
|
118
|
+
} else {
|
|
119
|
+
request = new UndiciRequest(input, init);
|
|
120
|
+
}
|
|
121
|
+
if (request.headers.has('proxy-authorization')) {
|
|
122
|
+
throw new TypeError('Set proxy credentials on the proxy URL.');
|
|
123
|
+
}
|
|
124
|
+
return dispatchFetch(request, { dispatcher });
|
|
125
|
+
},
|
|
126
|
+
close() {
|
|
127
|
+
return closing ??= dispatcher.destroy();
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|