qq-bot-roost 1.0.11 → 1.0.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/package.json +3 -3
- package/src/bot.js +12 -0
- package/src/config.js +777 -759
- package/src/gitee.js +5 -4
- package/src/main.js +3 -0
- package/src/message.js +2 -0
- package/src/mirror.js +8 -2
- package/src/outbound.js +39 -0
- package/src/plugin/loader.js +42 -10
- package/src/plugin/market.js +41 -3
- package/src/plugin/runtime-errors.js +27 -0
- package/src/plugin/snapshot.js +64 -0
- package/src/proxy.js +675 -0
- package/src/runtime.js +18 -0
- package/src/services/config-watch.js +2 -0
- package/src/tarball.js +3 -2
- package/src/updater.js +2 -1
- package/src/web/server.js +3741 -3620
- package/web/app.js +4934 -4701
- package/web/index.html +1337 -1315
package/src/proxy.js
ADDED
|
@@ -0,0 +1,675 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 代理支持
|
|
3
|
+
* ========
|
|
4
|
+
*
|
|
5
|
+
* 为什么需要它:Node 的 `fetch`(undici)**既不读 Windows 的「系统代理」设置,
|
|
6
|
+
* 默认也不读 `HTTPS_PROXY` 环境变量**——它永远是直连。而浏览器走系统代理,
|
|
7
|
+
* 于是出现最让人困惑的一种现象:
|
|
8
|
+
*
|
|
9
|
+
* 浏览器打开 raw.githubusercontent.com 1 秒就出来了,框架却说「连不上 GitHub」。
|
|
10
|
+
*
|
|
11
|
+
* 实测(2026-11-09,作者机器):系统代理 `127.0.0.1:7892` 下 raw 索引 0.75 秒 200;
|
|
12
|
+
* 同一个地址 Node 直连 10~20 秒超时。DNS 是干净的,纯粹是 TCP 连不上。
|
|
13
|
+
* 以前只能靠 `auto` 模式超时后切 Gitee 兜底,代价是**每次冷启动白等十几秒**。
|
|
14
|
+
*
|
|
15
|
+
* 这里补上两条路:
|
|
16
|
+
* - HTTPS 目标:CONNECT 隧道,再在隧道上做 TLS
|
|
17
|
+
* - HTTP 目标:直接给代理发绝对地址(absolute-form),不用隧道
|
|
18
|
+
*
|
|
19
|
+
* 只支持 **http / https 代理**(Clash、v2rayN、Fiddler 这些本地代理都是 http)。
|
|
20
|
+
* SOCKS 不认——写错了会落到「没有代理」,面板会提示,不会静默乱来。
|
|
21
|
+
*
|
|
22
|
+
* 接管范围只有「下载相关」的出站:插件市场索引与包、框架更新、镜像测速、Gitee 拉取。
|
|
23
|
+
* QQ 官方接口、扫码登录、预签名上传仍用原生 `fetch` 直连——那些是国内地址,
|
|
24
|
+
* 套一层本地代理只会更慢,甚至被对端拒掉。
|
|
25
|
+
*/
|
|
26
|
+
import http from 'node:http';
|
|
27
|
+
import https from 'node:https';
|
|
28
|
+
import net from 'node:net';
|
|
29
|
+
import tls from 'node:tls';
|
|
30
|
+
import { execFileSync } from 'node:child_process';
|
|
31
|
+
import { createLogger } from './logger.js';
|
|
32
|
+
|
|
33
|
+
const log = createLogger('proxy');
|
|
34
|
+
|
|
35
|
+
/** CONNECT 握手最多等这么久。真代理建隧道是毫秒级,6 秒还没动静基本就是死的 */
|
|
36
|
+
const CONNECT_TIMEOUT_MS = 6000;
|
|
37
|
+
|
|
38
|
+
/** 判定「这个代理不可用」之后,多久之内不再试它(避免每个请求都白等 6 秒) */
|
|
39
|
+
const DEAD_TTL_MS = 60_000;
|
|
40
|
+
|
|
41
|
+
/** 跟随重定向的上限。原生 fetch 默认 20,我们只下静态文件,5 跳足够 */
|
|
42
|
+
const MAX_REDIRECT = 5;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 当前设置:`auto` 跟随系统 / `off` 直连 / 具体代理地址。
|
|
46
|
+
*
|
|
47
|
+
* 由 configureProxy() 从 `config/bot.json` 的 `network.proxy` 读进来。
|
|
48
|
+
*/
|
|
49
|
+
let setting = 'auto';
|
|
50
|
+
|
|
51
|
+
/** 解析结果的缓存(读注册表要起子进程,不能每次请求都读) */
|
|
52
|
+
let cache = null;
|
|
53
|
+
|
|
54
|
+
/** `raw -> 到期时间`:被判死的代理在一分钟内跳过 */
|
|
55
|
+
const deadUntil = new Map();
|
|
56
|
+
|
|
57
|
+
/** 代理本身不可用(连不上 / 拒绝 CONNECT / 握手超时),可以降级直连 */
|
|
58
|
+
class ProxyError extends Error {
|
|
59
|
+
constructor(message) {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'ProxyError';
|
|
62
|
+
this.proxyFailure = true;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 从全局配置里读代理设置。main / 保存配置 / 配置热加载三处都要调。
|
|
68
|
+
*
|
|
69
|
+
* @param {object} globalCfg config/bot.json 的内容
|
|
70
|
+
*/
|
|
71
|
+
export function configureProxy(globalCfg) {
|
|
72
|
+
const raw = String(globalCfg?.network?.proxy ?? 'auto').trim();
|
|
73
|
+
const next = raw === '' ? 'auto' : raw;
|
|
74
|
+
if (next !== setting) log.info(`代理设置:${next}`);
|
|
75
|
+
setting = next;
|
|
76
|
+
cache = null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 校验并规范化用户填的代理地址。
|
|
81
|
+
*
|
|
82
|
+
* @param {string} raw
|
|
83
|
+
* @returns {{ok: boolean, value?: string, error?: string}}
|
|
84
|
+
*/
|
|
85
|
+
export function normalizeProxySetting(raw) {
|
|
86
|
+
const s = String(raw ?? '').trim();
|
|
87
|
+
if (!s) return { ok: false, error: '代理地址不能为空(不想用代理请选「直连」)' };
|
|
88
|
+
if (s === 'auto' || s === 'off') return { ok: true, value: s };
|
|
89
|
+
// 允许只填 127.0.0.1:7890,自动补 http://
|
|
90
|
+
const withScheme = /^[a-z][\w+.-]*:\/\//i.test(s) ? s : `http://${s}`;
|
|
91
|
+
let u;
|
|
92
|
+
try {
|
|
93
|
+
u = new URL(withScheme);
|
|
94
|
+
} catch {
|
|
95
|
+
return { ok: false, error: `代理地址看不懂:${s}` };
|
|
96
|
+
}
|
|
97
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
error: `只支持 http / https 代理,不支持 ${u.protocol.replace(':', '')}(SOCKS 请用 Clash 之类的混合端口)`,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
if (!u.hostname) return { ok: false, error: `代理地址缺少主机名:${s}` };
|
|
104
|
+
return { ok: true, value: `${u.protocol}//${u.host}${u.pathname.replace(/\/$/, '')}` };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 面板显示用:当前生效的是哪个代理、从哪来的 */
|
|
108
|
+
export function proxyInfo() {
|
|
109
|
+
const c = resolve();
|
|
110
|
+
return {
|
|
111
|
+
mode: setting,
|
|
112
|
+
active: c.primary ? c.primary.raw : '',
|
|
113
|
+
/** config / system / env / none */
|
|
114
|
+
source: c.primary ? c.primary.source : 'none',
|
|
115
|
+
candidates: c.list.map((p) => `${p.raw}(${p.source})`),
|
|
116
|
+
bypass: c.bypass,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/* ------------------------------------------------------------------ */
|
|
121
|
+
/* 解析:配置 → 系统 → 环境变量 */
|
|
122
|
+
/* ------------------------------------------------------------------ */
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* 把「不走代理」的例外列表摊平成 host 数组。
|
|
126
|
+
*
|
|
127
|
+
* 来源有三种:注册表的 `ProxyOverride`(分号)、`NO_PROXY`(逗号或分号)、
|
|
128
|
+
* 以后可能有人传数组。统一在这里切开,别让调用方各自 `split`。
|
|
129
|
+
*
|
|
130
|
+
* **为什么单独成一个函数**:2026-11-09 那次「配了代理还是连不上 GitHub」,
|
|
131
|
+
* 根因就是 `bypass.push(...sys.bypass)` —— 展开字符串把
|
|
132
|
+
* `*zhihu.com;localhost;…` 摊成了一百多个单字符,其中那个 `*` 使
|
|
133
|
+
* `shouldBypass()` 对**任何**域名都返回 true,于是 netFetch 全部退回直连,
|
|
134
|
+
* 日志里连一句「代理不可用」都没有,只剩 `fetch failed`。
|
|
135
|
+
* 这里顺手兜一手:万一又被人摊成字符数组,先拼回去再切。
|
|
136
|
+
*
|
|
137
|
+
* @param {string|Array<string|string[]>} [input]
|
|
138
|
+
* @returns {string[]}
|
|
139
|
+
*/
|
|
140
|
+
export function splitBypass(input) {
|
|
141
|
+
let items = Array.isArray(input) ? input : [input];
|
|
142
|
+
if (items.length > 2 && items.every((s) => typeof s === 'string' && s.length <= 1)) {
|
|
143
|
+
items = [items.join('')];
|
|
144
|
+
}
|
|
145
|
+
return items
|
|
146
|
+
.flatMap((s) => (Array.isArray(s) ? s : [s]))
|
|
147
|
+
.flatMap((s) => String(s ?? '').split(/[,;]/))
|
|
148
|
+
.map((s) => s.trim())
|
|
149
|
+
.filter(Boolean);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function resolve() {
|
|
153
|
+
if (cache) return cache;
|
|
154
|
+
|
|
155
|
+
const bypass = [];
|
|
156
|
+
const list = [];
|
|
157
|
+
|
|
158
|
+
const push = (proxy, source) => {
|
|
159
|
+
if (!proxy) return;
|
|
160
|
+
const src = source ?? proxy.source;
|
|
161
|
+
if (list.some((p) => p.raw === proxy.raw)) return;
|
|
162
|
+
list.push({ ...proxy, source: src });
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
if (setting === 'off') {
|
|
166
|
+
cache = { list: [], primary: null, bypass };
|
|
167
|
+
return cache;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (setting !== 'auto') {
|
|
171
|
+
// 用户明确指定:只用它,不去猜系统设置
|
|
172
|
+
const one = parseProxyUrl(setting);
|
|
173
|
+
if (one) push({ ...one, source: 'config' });
|
|
174
|
+
else log.warn(`network.proxy 不是一个可用的代理地址,已按直连处理:${setting}`);
|
|
175
|
+
cache = { list, primary: list[0] ?? null, bypass };
|
|
176
|
+
return cache;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* auto 的顺序:**系统代理优先,环境变量在后**。
|
|
181
|
+
*
|
|
182
|
+
* 直觉上应该反过来(curl / wget 就是环境变量优先),但这是一个桌面工具:
|
|
183
|
+
* 用户脑子里的等价物是「浏览器能打开,你就该能打开」,而浏览器走的是系统
|
|
184
|
+
* 代理。实测过反例——这台机器上 `HTTPS_PROXY=127.0.0.1:8654` 是个对 raw
|
|
185
|
+
* 完全不通的东西(10 秒失败),而系统代理 7892 是好的;环境变量优先会让
|
|
186
|
+
* 框架一直用一个坏代理。想强制用环境变量,就把配置填成具体地址。
|
|
187
|
+
*/
|
|
188
|
+
const sys = readSystemProxy();
|
|
189
|
+
if (sys) {
|
|
190
|
+
push(sys.proxy, 'system');
|
|
191
|
+
/**
|
|
192
|
+
* **必须是 push 这个字符串本身,不能展开。**
|
|
193
|
+
* `push(...sys.bypass)` 会把 `*zhihu.com;localhost;…` 摊成一百多个单字符,
|
|
194
|
+
* 其中那个 `*` 让 shouldBypass() 对**所有**域名都返回 true —— 代理彻底失效,
|
|
195
|
+
* 日志里只剩一句 `fetch failed`。2026-11-09 踩过,见 splitBypass 的注释。
|
|
196
|
+
*/
|
|
197
|
+
bypass.push(sys.bypass);
|
|
198
|
+
}
|
|
199
|
+
push(parseProxyUrl(process.env.HTTPS_PROXY || process.env.https_proxy), 'env');
|
|
200
|
+
push(parseProxyUrl(process.env.HTTP_PROXY || process.env.http_proxy), 'env');
|
|
201
|
+
bypass.push(process.env.NO_PROXY || process.env.no_proxy || '');
|
|
202
|
+
|
|
203
|
+
cache = {
|
|
204
|
+
list,
|
|
205
|
+
primary: list[0] ?? null,
|
|
206
|
+
bypass: splitBypass(bypass),
|
|
207
|
+
};
|
|
208
|
+
if (cache.primary) log.debug(`代理:${cache.primary.raw}(来自 ${cache.primary.source})`);
|
|
209
|
+
return cache;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 解析一条代理地址。支持 `http://user:pass@host:port`。
|
|
214
|
+
*
|
|
215
|
+
* @param {string} [raw]
|
|
216
|
+
*/
|
|
217
|
+
export function parseProxyUrl(raw) {
|
|
218
|
+
const s = String(raw ?? '').trim();
|
|
219
|
+
if (!s) return null;
|
|
220
|
+
const withScheme = /^[a-z][\w+.-]*:\/\//i.test(s) ? s : `http://${s}`;
|
|
221
|
+
let u;
|
|
222
|
+
try {
|
|
223
|
+
u = new URL(withScheme);
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
|
|
228
|
+
const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
|
|
229
|
+
if (!u.hostname || !Number.isFinite(port) || port <= 0) return null;
|
|
230
|
+
return {
|
|
231
|
+
raw: `${u.protocol}//${u.host}`,
|
|
232
|
+
host: u.hostname,
|
|
233
|
+
port,
|
|
234
|
+
/** 代理本身是 https(少见,但支持) */
|
|
235
|
+
secure: u.protocol === 'https:',
|
|
236
|
+
auth: u.username
|
|
237
|
+
? Buffer.from(
|
|
238
|
+
`${decodeURIComponent(u.username)}:${decodeURIComponent(u.password || '')}`,
|
|
239
|
+
).toString('base64')
|
|
240
|
+
: '',
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 读 Windows 的系统代理(IE / 设置里的那个,Clash 之类的「系统代理」开关改的就是它)。
|
|
246
|
+
*
|
|
247
|
+
* 用 `reg query` 而不是 PowerShell:后者启动要几百毫秒,这里可能被每次请求调用。
|
|
248
|
+
* 结果在 resolve() 里缓存,一个进程只读一次。
|
|
249
|
+
*
|
|
250
|
+
* @returns {{proxy: object, bypass: string} | null}
|
|
251
|
+
*/
|
|
252
|
+
function readSystemProxy() {
|
|
253
|
+
if (process.platform !== 'win32') return null;
|
|
254
|
+
/**
|
|
255
|
+
* 逃生舱:某些环境把 `reg.exe` 拦了(企业策略 / 沙箱),一调就是进程级失败。
|
|
256
|
+
* 设 `ROOST_NO_SYSTEM_PROXY=1` 就完全不读系统设置,只用环境变量或直连。
|
|
257
|
+
*/
|
|
258
|
+
if (process.env.ROOST_NO_SYSTEM_PROXY) return null;
|
|
259
|
+
let out = '';
|
|
260
|
+
try {
|
|
261
|
+
out = execFileSync(
|
|
262
|
+
'reg',
|
|
263
|
+
[
|
|
264
|
+
'query',
|
|
265
|
+
'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
|
|
266
|
+
],
|
|
267
|
+
{ encoding: 'utf8', windowsHide: true, timeout: 3000 },
|
|
268
|
+
);
|
|
269
|
+
} catch {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
return parseWindowsProxyReg(out);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 解析 `reg query` 的输出(抽出来单独测:起子进程的方式在 CI / 沙箱里不一定能跑)。
|
|
277
|
+
*
|
|
278
|
+
* 输出长这样:
|
|
279
|
+
* ProxyEnable REG_DWORD 0x1
|
|
280
|
+
* ProxyServer REG_SZ 127.0.0.1:7892
|
|
281
|
+
* ProxyOverride REG_SZ *zhihu.com;localhost;<local>
|
|
282
|
+
*
|
|
283
|
+
* @param {string} out
|
|
284
|
+
* @returns {{proxy: object, bypass: string} | null}
|
|
285
|
+
*/
|
|
286
|
+
export function parseWindowsProxyReg(out) {
|
|
287
|
+
const val = (name) => {
|
|
288
|
+
const m = new RegExp(`^\\s+${name}\\s+REG_\\w+\\s+(.*)$`, 'm').exec(String(out || ''));
|
|
289
|
+
return m ? m[1].trim() : '';
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
if (val('ProxyEnable') !== '0x1' && val('ProxyEnable') !== '0x00000001') return null;
|
|
293
|
+
|
|
294
|
+
// 可能是 `127.0.0.1:7892`,也可能是 `http=...;https=...` 按协议分开的写法
|
|
295
|
+
let server = val('ProxyServer');
|
|
296
|
+
if (!server) return null;
|
|
297
|
+
if (server.includes('=')) {
|
|
298
|
+
const parts = Object.fromEntries(
|
|
299
|
+
server.split(';').map((kv) => {
|
|
300
|
+
const i = kv.indexOf('=');
|
|
301
|
+
return i < 0 ? [kv, ''] : [kv.slice(0, i).trim(), kv.slice(i + 1).trim()];
|
|
302
|
+
}),
|
|
303
|
+
);
|
|
304
|
+
server = parts.https || parts.http || '';
|
|
305
|
+
}
|
|
306
|
+
const proxy = parseProxyUrl(server);
|
|
307
|
+
if (!proxy) return null;
|
|
308
|
+
return { proxy, bypass: val('ProxyOverride') };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* 这个目标地址该不该走代理(`no_proxy` / Windows 的「例外」列表)。
|
|
313
|
+
*
|
|
314
|
+
* 支持 `*`、`.example.com`、`example.com`、`host:port`,以及 Windows 那种
|
|
315
|
+
* 写在前面的通配(`*zhihu.com`)。不支持 CIDR——写 `10.0.0.0/8` 的人极少数,
|
|
316
|
+
* 而且认错了比不认更危险。
|
|
317
|
+
*/
|
|
318
|
+
export function shouldBypass(host, port, bypass = []) {
|
|
319
|
+
const h = String(host || '').toLowerCase();
|
|
320
|
+
for (const entry of bypass) {
|
|
321
|
+
if (!entry) continue;
|
|
322
|
+
let e = entry.toLowerCase();
|
|
323
|
+
if (e === '<local>') {
|
|
324
|
+
if (!h.includes('.')) return true;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (e === '*') return true;
|
|
328
|
+
|
|
329
|
+
// 端口限定:example.com:8080
|
|
330
|
+
let needPort = null;
|
|
331
|
+
const colon = e.lastIndexOf(':');
|
|
332
|
+
if (colon > 0 && /^\d+$/.test(e.slice(colon + 1))) {
|
|
333
|
+
needPort = Number(e.slice(colon + 1));
|
|
334
|
+
e = e.slice(0, colon);
|
|
335
|
+
}
|
|
336
|
+
if (needPort && Number(port) !== needPort) continue;
|
|
337
|
+
|
|
338
|
+
e = e.replace(/^\*\.?/, '').replace(/^\./, '');
|
|
339
|
+
if (!e) continue;
|
|
340
|
+
// 尾部通配:Windows 例外列表里 `10.*` / `127.*` / `172.16.*` 都是这个意思
|
|
341
|
+
if (e.endsWith('*')) {
|
|
342
|
+
const prefix = e.slice(0, -1);
|
|
343
|
+
if (prefix && h.startsWith(prefix)) return true;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (h === e || h.endsWith(`.${e}`)) return true;
|
|
347
|
+
}
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** 这个地址能用哪些代理(已排掉 no_proxy 与「刚判死」的) */
|
|
352
|
+
function candidatesFor(target) {
|
|
353
|
+
const c = resolve();
|
|
354
|
+
if (!c.list.length) return [];
|
|
355
|
+
if (shouldBypass(target.hostname, target.port, c.bypass)) return [];
|
|
356
|
+
const now = Date.now();
|
|
357
|
+
return c.list.filter((p) => (deadUntil.get(p.raw) ?? 0) <= now);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function markDead(proxy, why) {
|
|
361
|
+
deadUntil.set(proxy.raw, Date.now() + DEAD_TTL_MS);
|
|
362
|
+
log.warn(`代理 ${proxy.raw} 不可用(${why}),${DEAD_TTL_MS / 1000} 秒内改走直连`);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/* ------------------------------------------------------------------ */
|
|
366
|
+
/* 对外的 fetch */
|
|
367
|
+
/* ------------------------------------------------------------------ */
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 和 `fetch` 一样的调用方式,但**有代理就走代理**。
|
|
371
|
+
*
|
|
372
|
+
* 返回的是标准 `Response`(内容已经整块读进内存),所以 `.ok`、`.status`、
|
|
373
|
+
* `.headers`、`.json()`、`.text()`、`.arrayBuffer()` 都能照常用。
|
|
374
|
+
* 唯一不支持的是流式 `res.body`——本项目只下索引和 tarball(几百 KB),
|
|
375
|
+
* 不值得为流式再写一套。
|
|
376
|
+
*
|
|
377
|
+
* 代理挂了会自动降级直连(并记住 60 秒),所以「装了代理又关掉」不会把面板卡死。
|
|
378
|
+
*
|
|
379
|
+
* @param {string} url
|
|
380
|
+
* @param {RequestInit} [init]
|
|
381
|
+
* @returns {Promise<Response>}
|
|
382
|
+
*/
|
|
383
|
+
export async function netFetch(url, init = {}) {
|
|
384
|
+
let target;
|
|
385
|
+
try {
|
|
386
|
+
target = new URL(url);
|
|
387
|
+
} catch {
|
|
388
|
+
return fetch(url, init);
|
|
389
|
+
}
|
|
390
|
+
if (target.protocol !== 'http:' && target.protocol !== 'https:') return fetch(url, init);
|
|
391
|
+
|
|
392
|
+
const candidates = candidatesFor(target);
|
|
393
|
+
if (!candidates.length) return fetch(url, init);
|
|
394
|
+
|
|
395
|
+
for (const proxy of candidates) {
|
|
396
|
+
try {
|
|
397
|
+
return await withProxy(target, init, proxy);
|
|
398
|
+
} catch (e) {
|
|
399
|
+
if (!e?.proxyFailure) throw e; // 目标那边的问题,交给调用方(镜像兜底 / 重试)
|
|
400
|
+
markDead(proxy, e.message);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// 代理全挂了:退回直连,别让面板因为一个配错/已关掉的代理彻底不能下载
|
|
405
|
+
return fetch(url, init);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** 走代理抓一个地址,自己跟随重定向(3xx 也要能拿到,调用方可能在看 Location) */
|
|
409
|
+
async function withProxy(target, init, proxy) {
|
|
410
|
+
let url = target;
|
|
411
|
+
let method = String(init.method || 'GET').toUpperCase();
|
|
412
|
+
let body = normalizeBody(init.body);
|
|
413
|
+
const headers = stripUnsupported(init.headers);
|
|
414
|
+
|
|
415
|
+
for (let hop = 0; hop <= MAX_REDIRECT; hop++) {
|
|
416
|
+
const res = await requestOnce(url, { ...init, method, body, headers }, proxy);
|
|
417
|
+
if (init.redirect === 'manual') return res;
|
|
418
|
+
const loc = res.headers.get('location');
|
|
419
|
+
if (!loc || ![301, 302, 303, 307, 308].includes(res.status)) return res;
|
|
420
|
+
url = new URL(loc, url);
|
|
421
|
+
// 303 一律变 GET;301/302 上的 POST 也按浏览器习惯降级(下载用不到,但别写错)
|
|
422
|
+
if (res.status === 303 || ((res.status === 301 || res.status === 302) && method === 'POST')) {
|
|
423
|
+
method = 'GET';
|
|
424
|
+
body = null;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
throw new Error('重定向次数过多');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 发一次请求(https 先建隧道;http 直接让代理转发绝对地址) */
|
|
431
|
+
async function requestOnce(target, init, proxy) {
|
|
432
|
+
const isHttps = target.protocol === 'https:';
|
|
433
|
+
const port = Number(target.port || (isHttps ? 443 : 80));
|
|
434
|
+
const method = String(init.method || 'GET').toUpperCase();
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* https:隧道和 TLS 都先建好,再交给一个只服务这一次请求的 Agent。
|
|
438
|
+
*
|
|
439
|
+
* **不能**把隧道 socket 直接塞进 `http.request({createConnection})`——试过,
|
|
440
|
+
* 请求写出去了但永远读不到响应(8 秒无数据),而手写 HTTP 帧却是通的。
|
|
441
|
+
* 原因是那条 socket 上还挂着上一次 http 客户端的状态。用 Agent 的
|
|
442
|
+
* `createConnection(options, cb)` 回调形式交出去才是干净的路子。
|
|
443
|
+
*/
|
|
444
|
+
let agent;
|
|
445
|
+
if (isHttps) {
|
|
446
|
+
const raw = await connectTunnel(proxy, target.hostname, port, init.signal);
|
|
447
|
+
const tlsSocket = await startTls(raw, target.hostname);
|
|
448
|
+
agent = new SingleSocketAgent(tlsSocket);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* 明文目标走 absolute-form:直接请求代理,path 写完整 URL。
|
|
453
|
+
* 这种请求连到的是代理,代理本身是 https 时要用 https.request。
|
|
454
|
+
*/
|
|
455
|
+
const mod = isHttps ? https : proxy.secure ? https : http;
|
|
456
|
+
const opts = isHttps
|
|
457
|
+
? {
|
|
458
|
+
host: target.hostname,
|
|
459
|
+
port,
|
|
460
|
+
path: `${target.pathname}${target.search}`,
|
|
461
|
+
method,
|
|
462
|
+
headers: init.headers,
|
|
463
|
+
agent,
|
|
464
|
+
signal: init.signal,
|
|
465
|
+
}
|
|
466
|
+
: {
|
|
467
|
+
host: proxy.host,
|
|
468
|
+
port: proxy.port,
|
|
469
|
+
method,
|
|
470
|
+
path: target.href,
|
|
471
|
+
headers: {
|
|
472
|
+
...init.headers,
|
|
473
|
+
Host: target.host,
|
|
474
|
+
...(proxy.auth ? { 'Proxy-Authorization': `Basic ${proxy.auth}` } : {}),
|
|
475
|
+
},
|
|
476
|
+
agent: false,
|
|
477
|
+
signal: init.signal,
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
return await new Promise((resolve, reject) => {
|
|
481
|
+
let responded = false;
|
|
482
|
+
const req = mod.request(opts, (res) => {
|
|
483
|
+
responded = true;
|
|
484
|
+
const chunks = [];
|
|
485
|
+
res.on('data', (c) => chunks.push(c));
|
|
486
|
+
res.on('end', () => resolve(buildResponse(res, Buffer.concat(chunks))));
|
|
487
|
+
res.on('error', (e) => reject(abortAware(e, init.signal)));
|
|
488
|
+
});
|
|
489
|
+
req.once('error', (e) => {
|
|
490
|
+
const err = abortAware(e, init.signal);
|
|
491
|
+
/**
|
|
492
|
+
* 明文目标连的是**代理**,所以「连不上」在这里指的是代理挂了
|
|
493
|
+
* (端口没开、进程退了),要标成 ProxyError 才能触发直连降级。
|
|
494
|
+
* 已经收到响应之后的错误不算——那是目标或链路的问题。
|
|
495
|
+
*/
|
|
496
|
+
if (!isHttps && !responded && isConnFailure(err)) {
|
|
497
|
+
return reject(new ProxyError(`连不上代理 ${proxy.raw}:${err.message}`));
|
|
498
|
+
}
|
|
499
|
+
reject(err);
|
|
500
|
+
});
|
|
501
|
+
if (init.body) req.write(init.body);
|
|
502
|
+
req.end();
|
|
503
|
+
});
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** 这些错误码说明是「根本没连上」,可以换下一个源 / 降级直连 */
|
|
507
|
+
function isConnFailure(e) {
|
|
508
|
+
return ['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EHOSTUNREACH', 'ENETUNREACH', 'EPIPE', 'ETIMEDOUT'].includes(
|
|
509
|
+
e?.code,
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* 只服务一次请求的 Agent:把已经建好的 TLS socket 交还给 http 客户端。
|
|
515
|
+
*
|
|
516
|
+
* 用它而不是 `createConnection: () => socket`,是因为后者在隧道 socket 上
|
|
517
|
+
* 会卡住(详见 requestOnce 里的注释)。
|
|
518
|
+
*/
|
|
519
|
+
class SingleSocketAgent extends https.Agent {
|
|
520
|
+
constructor(socket) {
|
|
521
|
+
super({ keepAlive: false, maxSockets: 1 });
|
|
522
|
+
this._socket = socket;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
createConnection(options, cb) {
|
|
526
|
+
cb(null, this._socket);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** CONNECT 建隧道,返回一条已经打通的裸连接 */
|
|
531
|
+
function connectTunnel(proxy, host, port, signal) {
|
|
532
|
+
return new Promise((resolve, reject) => {
|
|
533
|
+
if (signal?.aborted) return reject(signal.reason ?? new Error('aborted'));
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* **手写 CONNECT 帧**,不走 `http.request({method:'CONNECT'})`。
|
|
537
|
+
*
|
|
538
|
+
* 走 http.request 的话,拿到的 socket 上还留着那个 ClientRequest 的状态
|
|
539
|
+
* (解析器、`_httpMessage`),后面谁再往这条 socket 上发请求都要么被卡住、
|
|
540
|
+
* 要么数据被旧解析器吞掉。手写三十行,省掉一整类诡异问题。
|
|
541
|
+
*/
|
|
542
|
+
const sock = proxy.secure
|
|
543
|
+
? tls.connect({ host: proxy.host, port: proxy.port, servername: proxy.host })
|
|
544
|
+
: net.connect({ port: proxy.port, host: proxy.host });
|
|
545
|
+
|
|
546
|
+
let settled = false;
|
|
547
|
+
const finish = (fn, arg) => {
|
|
548
|
+
if (settled) return;
|
|
549
|
+
settled = true;
|
|
550
|
+
clearTimeout(timer);
|
|
551
|
+
sock.removeListener('data', onData);
|
|
552
|
+
fn(arg);
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
const timer = setTimeout(() => {
|
|
556
|
+
sock.destroy();
|
|
557
|
+
finish(reject, new ProxyError(`连接代理超时(${CONNECT_TIMEOUT_MS / 1000} 秒没建好隧道)`));
|
|
558
|
+
}, CONNECT_TIMEOUT_MS);
|
|
559
|
+
timer.unref?.();
|
|
560
|
+
|
|
561
|
+
let buf = Buffer.alloc(0);
|
|
562
|
+
const onData = (chunk) => {
|
|
563
|
+
buf = Buffer.concat([buf, chunk]);
|
|
564
|
+
const end = buf.indexOf('\r\n\r\n');
|
|
565
|
+
if (end < 0) return; // 响应头还没收全
|
|
566
|
+
const head = buf.slice(0, end).toString('latin1');
|
|
567
|
+
const rest = buf.slice(end + 4);
|
|
568
|
+
const status = Number(/^HTTP\/1\.[01]\s+(\d{3})/.exec(head)?.[1] || 0);
|
|
569
|
+
if (status !== 200) {
|
|
570
|
+
sock.destroy();
|
|
571
|
+
const why =
|
|
572
|
+
status === 407
|
|
573
|
+
? '代理要求认证(407),请在地址里写上用户名密码'
|
|
574
|
+
: `代理拒绝 CONNECT(HTTP ${status || '未知'})`;
|
|
575
|
+
return finish(reject, new ProxyError(why));
|
|
576
|
+
}
|
|
577
|
+
// 隧道里多出来的字节要还给上层,不能丢
|
|
578
|
+
if (rest.length) sock.unshift(rest);
|
|
579
|
+
finish(resolve, sock);
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
sock.setNoDelay?.(true);
|
|
583
|
+
sock.once(proxy.secure ? 'secureConnect' : 'connect', () => {
|
|
584
|
+
const lines = [
|
|
585
|
+
`CONNECT ${host}:${port} HTTP/1.1`,
|
|
586
|
+
`Host: ${host}:${port}`,
|
|
587
|
+
'Proxy-Connection: keep-alive',
|
|
588
|
+
];
|
|
589
|
+
if (proxy.auth) lines.push(`Proxy-Authorization: Basic ${proxy.auth}`);
|
|
590
|
+
sock.write(`${lines.join('\r\n')}\r\n\r\n`);
|
|
591
|
+
});
|
|
592
|
+
sock.on('data', onData);
|
|
593
|
+
|
|
594
|
+
sock.once('error', (e) => {
|
|
595
|
+
if (signal?.aborted) return finish(reject, signal.reason ?? e);
|
|
596
|
+
finish(reject, new ProxyError(`连不上代理 ${proxy.raw}:${e.message}`));
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
// 调用方超时(AbortSignal.timeout)→ 拆掉隧道,把 TimeoutError 原样抛上去
|
|
600
|
+
if (signal) {
|
|
601
|
+
const onAbort = () => {
|
|
602
|
+
sock.destroy();
|
|
603
|
+
finish(reject, signal.reason instanceof Error ? signal.reason : new Error('aborted'));
|
|
604
|
+
};
|
|
605
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
606
|
+
sock.once('close', () => signal.removeEventListener('abort', onAbort));
|
|
607
|
+
}
|
|
608
|
+
});
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** 在隧道上做 TLS,并对齐 SNI(不然 CDN 会回错证书) */
|
|
612
|
+
function startTls(socket, host) {
|
|
613
|
+
return new Promise((resolve, reject) => {
|
|
614
|
+
const s = tls.connect({ socket, servername: host, ALPNProtocols: ['http/1.1'] });
|
|
615
|
+
const onErr = (e) => reject(new Error(`与 ${host} 建立 TLS 失败:${e.message}`));
|
|
616
|
+
s.once('secureConnect', () => {
|
|
617
|
+
s.removeListener('error', onErr);
|
|
618
|
+
resolve(s);
|
|
619
|
+
});
|
|
620
|
+
s.once('error', onErr);
|
|
621
|
+
});
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function buildResponse(res, buf) {
|
|
625
|
+
const status = res.statusCode || 0;
|
|
626
|
+
// 204/304 带 body 会被 Response 拒绝
|
|
627
|
+
const body = status === 204 || status === 304 ? null : buf;
|
|
628
|
+
const headers = new Headers();
|
|
629
|
+
for (const [k, v] of Object.entries(res.headers || {})) {
|
|
630
|
+
if (v === undefined) continue;
|
|
631
|
+
if (Array.isArray(v)) for (const item of v) headers.append(k, item);
|
|
632
|
+
else headers.set(k, String(v));
|
|
633
|
+
}
|
|
634
|
+
return new Response(body, {
|
|
635
|
+
status: status >= 200 && status <= 599 ? status : 502,
|
|
636
|
+
statusText: res.statusMessage || '',
|
|
637
|
+
headers,
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** 超时(AbortSignal.timeout)要原样抛出 TimeoutError,调用方靠它区分「超时」和「连不上」 */
|
|
642
|
+
function abortAware(e, signal) {
|
|
643
|
+
if (signal?.aborted) return signal.reason instanceof Error ? signal.reason : new Error('aborted');
|
|
644
|
+
return e;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* 我们自己管理解压:只发 identity,**不要** accept-encoding。
|
|
649
|
+
*
|
|
650
|
+
* 原生 fetch 会替我们解开 gzip;这里拿到的是原始字节,如果对方还压着,
|
|
651
|
+
* `res.json()` 会直接报「不是合法 JSON」——那种错误极难对上号。
|
|
652
|
+
*/
|
|
653
|
+
function stripUnsupported(raw) {
|
|
654
|
+
const out = {};
|
|
655
|
+
for (const [k, v] of Object.entries(raw || {})) {
|
|
656
|
+
const key = k.toLowerCase();
|
|
657
|
+
if (key === 'accept-encoding' || key === 'connection' || key === 'host') continue;
|
|
658
|
+
out[k] = v;
|
|
659
|
+
}
|
|
660
|
+
return out;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function normalizeBody(body) {
|
|
664
|
+
if (body === undefined || body === null) return null;
|
|
665
|
+
if (typeof body === 'string') return Buffer.from(body);
|
|
666
|
+
if (Buffer.isBuffer(body) || body instanceof Uint8Array) return Buffer.from(body);
|
|
667
|
+
if (body instanceof URLSearchParams) return Buffer.from(body.toString());
|
|
668
|
+
throw new Error('代理模式下不支持这个请求体类型(只支持字符串 / Buffer)');
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** 给测试和「设置页」用:清掉缓存与「判死」记录 */
|
|
672
|
+
export function resetProxyState() {
|
|
673
|
+
cache = null;
|
|
674
|
+
deadUntil.clear();
|
|
675
|
+
}
|
package/src/runtime.js
CHANGED
|
@@ -6,6 +6,20 @@
|
|
|
6
6
|
*/
|
|
7
7
|
export const SENSITIVE_KEY = /^(auth_token|token|access_token|secret|client_secret|cookie|password)$/i;
|
|
8
8
|
|
|
9
|
+
/**
|
|
10
|
+
* 文本级脱敏。抽出来给面板 `/api/plugins` 下发错误栈用:handler 抛出的
|
|
11
|
+
* `Error.stack` 里可能带请求 URL / token,原样回浏览器会泄密。
|
|
12
|
+
* 事件报文仍走下面的 `redact()`(对象递归),这里只管一段文本。
|
|
13
|
+
*/
|
|
14
|
+
export function redactText(value) {
|
|
15
|
+
return String(value ?? '')
|
|
16
|
+
.replace(/auth_token=[^&"\s]*/g, 'auth_token=***')
|
|
17
|
+
.replace(/msg_idx=[^&"\s]*/g, 'msg_idx=***')
|
|
18
|
+
.replace(/(Authorization["']?\s*[:=]\s*["']?)(?:Bearer\s+)?[A-Za-z0-9._~+/=-]{8,}/gi, '$1***')
|
|
19
|
+
.replace(/((?:token|access_token|password|secret|api[_-]?key|cookie)["']?\s*[:=]\s*["']?)([^\s"',;&]{4,})/gi, '$1***')
|
|
20
|
+
.slice(0, 400);
|
|
21
|
+
}
|
|
22
|
+
|
|
9
23
|
/**
|
|
10
24
|
* 事件报文脱敏。
|
|
11
25
|
* 群消息的 message_scene.ext 里带 auth_token,属于敏感凭证,
|
|
@@ -27,6 +41,10 @@ function redact(value, depth = 0) {
|
|
|
27
41
|
}
|
|
28
42
|
return out;
|
|
29
43
|
}
|
|
44
|
+
/**
|
|
45
|
+
* 事件报文沿用原来的窄规则,**不调用 redactText**:那会把 token=/Authorization
|
|
46
|
+
* 也抹掉、改变既有 sanitizePayload 输出。面板错误栈才走 redactText(见 server.js)。
|
|
47
|
+
*/
|
|
30
48
|
if (typeof value === 'string') {
|
|
31
49
|
return value
|
|
32
50
|
.replace(/auth_token=[^&"\s]*/g, 'auth_token=***')
|