@zllf/pi-provider-proxy 0.1.0 → 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 +5 -7
- package/package.json +43 -11
- package/src/oauth-diagnostics.js +73 -0
- package/src/oauth-worker.js +10 -13
- package/src/transport.js +28 -15
package/README.md
CHANGED
|
@@ -2,21 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
用 `/proxy` 为 Pi 的每个模型服务商单独设置 HTTP、HTTPS 或 SOCKS5 代理。例如,让 ChatGPT 订阅账号走 SOCKS5,保留本地 Ollama 直连。菜单自动跟随设备语言,支持中文和英文。
|
|
4
4
|
|
|
5
|
-
##
|
|
6
|
-
|
|
7
|
-
从 GitHub 安装已发布的 `v0.1.0` 版本。
|
|
5
|
+
## 安装与更新
|
|
8
6
|
|
|
9
7
|
```sh
|
|
10
|
-
pi install
|
|
8
|
+
pi install npm:@zllf/pi-provider-proxy
|
|
11
9
|
```
|
|
12
10
|
|
|
13
|
-
|
|
11
|
+
已通过 npm 安装的用户可以单独更新此扩展。
|
|
14
12
|
|
|
15
13
|
```sh
|
|
16
|
-
pi
|
|
14
|
+
pi update npm:@zllf/pi-provider-proxy
|
|
17
15
|
```
|
|
18
16
|
|
|
19
|
-
在已打开的 Pi 会话中运行 `/reload`,然后输入 `/proxy
|
|
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 验证。
|
|
20
18
|
|
|
21
19
|
## 配置代理
|
|
22
20
|
|
package/package.json
CHANGED
|
@@ -1,16 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zllf/pi-provider-proxy",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"description": "Per-provider HTTP and SOCKS routes for the Pi terminal",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"repository": {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
"
|
|
15
|
-
|
|
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
|
+
}
|
|
16
48
|
}
|
|
@@ -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
|
+
}
|
package/src/oauth-worker.js
CHANGED
|
@@ -4,6 +4,10 @@ import { registerHooks } from 'node:module';
|
|
|
4
4
|
import { pathToFileURL } from 'node:url';
|
|
5
5
|
import { MessageChannel, parentPort, workerData } from 'node:worker_threads';
|
|
6
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());
|
|
7
11
|
|
|
8
12
|
const providerSpecifier = '@earendil-works/pi-ai/providers/openai-codex';
|
|
9
13
|
const missingPeer = 'Scoped Codex OAuth requires a physical @earendil-works/pi-ai installation accessible from the extension or the Pi CLI';
|
|
@@ -37,6 +41,7 @@ async function prompt({ signal: promptSignal, ...prompt }) {
|
|
|
37
41
|
parentPort.postMessage({ type: 'prompt', prompt, reply: port2 }, [port2]);
|
|
38
42
|
const [answer] = await once(port1, 'message', { signal });
|
|
39
43
|
if (answer.cancelled) throw new Error('Login cancelled');
|
|
44
|
+
if (prompt.type === 'select' && answer.value === 'browser') diagnostics.setStage('browser');
|
|
40
45
|
return answer.value;
|
|
41
46
|
} finally {
|
|
42
47
|
// If Pi's callback listener wins, closing the port aborts the pending UI prompt.
|
|
@@ -47,12 +52,13 @@ async function prompt({ signal: promptSignal, ...prompt }) {
|
|
|
47
52
|
async function run() {
|
|
48
53
|
const { operation, route, input, signal } = workerData;
|
|
49
54
|
const { openaiCodexProvider } = await import(resolveProvider(workerData.hostEntry));
|
|
50
|
-
const transport = createTransport(route);
|
|
55
|
+
const transport = createTransport(route, { retrySocksHandshake: true });
|
|
51
56
|
try {
|
|
52
57
|
// Pi 1.7.0's Codex OAuth uses global fetch for every token/device request.
|
|
53
58
|
// This worker is private to the operation, including its global object.
|
|
54
|
-
globalThis.fetch = transport.fetch;
|
|
59
|
+
globalThis.fetch = diagnostics.observe(transport.fetch);
|
|
55
60
|
const oauth = openaiCodexProvider().auth.oauth;
|
|
61
|
+
diagnostics.setStage(operation === 'refresh' ? 'refresh' : 'method');
|
|
56
62
|
if (operation === 'refresh') return await oauth.refresh(input, signal);
|
|
57
63
|
const notify = event => parentPort.postMessage({ type: 'notify', event });
|
|
58
64
|
return await oauth.login({ prompt, notify, signal }, input);
|
|
@@ -61,18 +67,9 @@ async function run() {
|
|
|
61
67
|
}
|
|
62
68
|
}
|
|
63
69
|
|
|
64
|
-
function publicError(error) {
|
|
65
|
-
// Some native errors include entire token responses. Keep known diagnostics and HTTP status.
|
|
66
|
-
const message = error instanceof Error ? error.message : '';
|
|
67
|
-
if (message === missingPeer) return message;
|
|
68
|
-
if (['Login cancelled', 'State mismatch', 'Missing authorization code', 'Failed to extract accountId from token', 'Device flow timed out'].includes(message)) return message;
|
|
69
|
-
const status = message.match(/^OpenAI Codex (?:token (?:exchange|refresh) failed \((\d{3})\)|device (?:code request|auth) failed with status (\d{3}))/);
|
|
70
|
-
if (status) return `Codex OAuth ${workerData.operation} failed (HTTP ${status[1] ?? status[2]})`;
|
|
71
|
-
return `Codex OAuth ${workerData.operation} failed`;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
70
|
try {
|
|
75
71
|
parentPort.postMessage({ type: 'result', credential: await run() });
|
|
76
72
|
} catch (error) {
|
|
77
|
-
|
|
73
|
+
const message = error?.message === missingPeer ? missingPeer : diagnostics.error(error);
|
|
74
|
+
parentPort.postMessage({ type: 'error', message });
|
|
78
75
|
}
|
package/src/transport.js
CHANGED
|
@@ -31,7 +31,17 @@ export function validateProxyUrl(value) {
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
function
|
|
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) {
|
|
35
45
|
const proxy = {
|
|
36
46
|
type: 5,
|
|
37
47
|
host: url.hostname.replace(/^\[|\]$/g, ''),
|
|
@@ -45,16 +55,19 @@ function socksAgent(url) {
|
|
|
45
55
|
let host = hostname;
|
|
46
56
|
if (url.protocol === 'socks5:' && !isIP(host)) host = (await lookup(host)).address;
|
|
47
57
|
if (Buffer.byteLength(host) > 255) throw new Error('SOCKS destination name is too long.');
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
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
|
+
}
|
|
58
71
|
}
|
|
59
72
|
}
|
|
60
73
|
|
|
@@ -69,10 +82,10 @@ function socksAgent(url) {
|
|
|
69
82
|
});
|
|
70
83
|
}
|
|
71
84
|
|
|
72
|
-
function dispatcherFor(route) {
|
|
85
|
+
function dispatcherFor(route, retryHandshake) {
|
|
73
86
|
if (route === 'direct') return new Agent({ connect: { rejectUnauthorized: true } });
|
|
74
87
|
const url = new URL(validateProxyUrl(route));
|
|
75
|
-
if (url.protocol.startsWith('socks')) return socksAgent(url);
|
|
88
|
+
if (url.protocol.startsWith('socks')) return socksAgent(url, retryHandshake);
|
|
76
89
|
|
|
77
90
|
let token;
|
|
78
91
|
if (url.username || url.password) {
|
|
@@ -91,8 +104,8 @@ function dispatcherFor(route) {
|
|
|
91
104
|
}
|
|
92
105
|
|
|
93
106
|
/** Owns one dispatcher. Call close() on retirement to terminate outstanding requests. */
|
|
94
|
-
export function createTransport(route) {
|
|
95
|
-
const dispatcher = dispatcherFor(route);
|
|
107
|
+
export function createTransport(route, { retrySocksHandshake = false } = {}) {
|
|
108
|
+
const dispatcher = dispatcherFor(route, retrySocksHandshake);
|
|
96
109
|
let closing;
|
|
97
110
|
return {
|
|
98
111
|
async fetch(input, init) {
|