dsh-mobile-plugin 0.5.81 → 0.5.82

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.
Files changed (55) hide show
  1. package/lib/frpc/provision.cjs +21 -17
  2. package/lib/frpc/runner.cjs +193 -165
  3. package/lib/impl.js +53 -80
  4. package/lib/mirror/pusher.cjs +60 -10
  5. package/lib/mobile/events.js +2 -1
  6. package/lib/mobile/feedback.js +6 -5
  7. package/lib/mobile/file-read.js +4 -2
  8. package/lib/mobile/mux.js +148 -21
  9. package/lib/mobile/paired-devices.js +2 -1
  10. package/lib/mobile/pairing.js +3 -2
  11. package/lib/mobile/relay-control.js +27 -33
  12. package/lib/mobile/session-changes.js +8 -2
  13. package/lib/mobile/session-delivery.js +5 -1
  14. package/lib/mobile/session-file.js +46 -25
  15. package/lib/mobile/session-head.js +7 -3
  16. package/lib/mobile/session-snapshot.js +5 -1
  17. package/lib/mobile/session-step.js +13 -7
  18. package/lib/mobile/session-stop-summary.js +6 -1
  19. package/lib/mobile/stream-registry.js +48 -53
  20. package/lib/mobile/stream.js +17 -2
  21. package/lib/mobile/uploads.js +190 -163
  22. package/lib/p2p/session.cjs +169 -70
  23. package/lib/p2p/wiring.cjs +4 -2
  24. package/lib/panel/index.html +17 -15
  25. package/lib/relay/blob-upload.cjs +103 -0
  26. package/lib/relay/config-store.js +81 -0
  27. package/lib/relay/control.js +94 -46
  28. package/lib/relay/core.js +9 -13
  29. package/lib/relay/lan-proxy.js +44 -7
  30. package/lib/relay/pairing-payload.cjs +14 -5
  31. package/lib/relay/preview-webapp.cjs +150 -0
  32. package/lib/relay/preview.js +35 -8
  33. package/lib/relay/protocol.js +6 -4
  34. package/lib/relay/relay-probe.js +112 -21
  35. package/lib/relay/tunnel-forwarder.cjs +4 -2
  36. package/lib/relay/tunnel.js +39 -8
  37. package/lib/remote/controller.cjs +33 -3
  38. package/lib/remote/host-control.cjs +11 -2
  39. package/lib/remote/router.cjs +83 -33
  40. package/lib/remote/transport.cjs +32 -5
  41. package/lib/remote/tunnel-helper.cjs +51 -25
  42. package/lib/remote/tunnels.cjs +27 -3
  43. package/lib/routes/control-plane.js +25 -17
  44. package/lib/routes/mobile-api.js +21 -18
  45. package/lib/shared/fresh-request.js +32 -1
  46. package/lib/shared/route-order.cjs +118 -132
  47. package/lib/shared/sse-write.js +29 -10
  48. package/lib/shared/via-header.js +5 -12
  49. package/lib/shell/transport-host.js +9 -1
  50. package/lib/sidecar-facade-worker.cjs +156 -112
  51. package/lib/sidecar-facade.cjs +6 -1
  52. package/lib/sidecar-lifecycle.cjs +6 -2
  53. package/lib/tailcat/host-process.cjs +32 -8
  54. package/lib/tailcat/session.cjs +27 -10
  55. package/package.json +6 -6
@@ -1,3 +1,5 @@
1
+ // 配对二维码的 IPv6 候选为手填那条预留一席,避免被条数上限切掉。
2
+ // 生成配对邀请,并独立发布 IPv6 监听候选。
1
3
  'use strict';
2
4
 
3
5
  /**
@@ -85,11 +87,18 @@ function pairingPayload(state, lanPort) {
85
87
  // **二维码里只带前两条**:一块网卡能报出「一条稳定地址 + 两条隐私地址」(RFC 4941 的
86
88
  // 临时地址按小时轮换,写进码里的那两条多半扫完就过期了),三条一起塞要吃掉近三十个模块。
87
89
  // 前两条够手机实测择优;`/connection-info` 那份照旧给全,换前缀之后靠它刷新。
88
- ipv6Candidates: state.lanEnabled
89
- ? withManualIpv6Candidate(ipv6Candidates(port), state.manualIpv6Url)
90
- .map(candidate => candidate.url)
91
- .filter(Boolean)
92
- .slice(0, QR_IPV6_MAX)
90
+ ipv6Candidates: port > 0
91
+ ? (() => {
92
+ const nic = ipv6Candidates(port)
93
+ const merged = withManualIpv6Candidate(nic, state.manualIpv6Url)
94
+ // 手填那条是「手机不在同一个 Wi-Fi 时唯一拨得到」的兜底,不能被二维码的条数上限切掉:
95
+ // 网卡候选截到 QR_IPV6_MAX-1 条,再补上手填那条;没有手填就照常截 QR_IPV6_MAX 条。
96
+ const manual = merged.length > nic.length ? merged[merged.length - 1] : null
97
+ const picked = manual
98
+ ? [...merged.filter(candidate => candidate !== manual).slice(0, QR_IPV6_MAX - 1), manual]
99
+ : merged.slice(0, QR_IPV6_MAX)
100
+ return picked.map(candidate => candidate.url).filter(Boolean)
101
+ })()
93
102
  : [],
94
103
  };
95
104
  if (relayList) payload.relayUrls = relayList;
@@ -0,0 +1,150 @@
1
+ // 解析网页版管道中的每次 HTTP/WS 请求,覆盖可信转发标记并保留流式背压。
2
+ 'use strict';
3
+
4
+ const http = require('node:http');
5
+ const https = require('node:https');
6
+ const net = require('node:net');
7
+ const tls = require('node:tls');
8
+ const { createWebSocketStream } = require('ws');
9
+ const { withViaHeader } = require('../shared/via-header');
10
+
11
+ const OUTPUT_DRAIN_TIMEOUT_MS = 5000;
12
+
13
+ const HOP_BY_HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade']);
14
+
15
+ function openWebappPipe(ws, { port, scheme, hosts, servername, onClose = () => {} }) {
16
+ const stream = createWebSocketStream(ws);
17
+ const sockets = new Set();
18
+ const requests = new Set();
19
+ const secure = scheme === 'https';
20
+ const transport = secure ? https : http;
21
+ const agent = new transport.Agent({ keepAlive: false });
22
+ let closed = false;
23
+ let ending = false;
24
+ let drainTimer = null;
25
+ const close = () => {
26
+ if (closed) return;
27
+ closed = true;
28
+ clearTimeout(drainTimer);
29
+ for (const request of requests) request.destroy();
30
+ for (const socket of sockets) socket.destroy();
31
+ agent.destroy();
32
+ stream.destroy();
33
+ onClose();
34
+ };
35
+ const endStream = stream.end.bind(stream);
36
+ stream.end = (...args) => {
37
+ if (!ending && !closed) {
38
+ ending = true;
39
+ drainTimer = setTimeout(close, OUTPUT_DRAIN_TIMEOUT_MS);
40
+ drainTimer.unref?.();
41
+ }
42
+ return endStream(...args);
43
+ };
44
+ const finishOutput = () => {
45
+ if (closed || stream.writableEnded) return;
46
+ // Duplex的final会等各次ws.send回调后发Close,正常EOF不销毁尚未排空的输出。
47
+ stream.end();
48
+ };
49
+ stream.on('error', close);
50
+ stream.on('close', close);
51
+ ws.on('close', close);
52
+ ws.on('error', close);
53
+
54
+ // 环回目标沿用普通预览的双栈拨号顺序,只在尚未连接时换下一个地址。
55
+ const connect = (callback) => {
56
+ let index = 0;
57
+ const next = (lastError) => {
58
+ if (closed) return callback(new Error('预览管道已关闭'));
59
+ if (index >= hosts.length) return callback(lastError || new Error('网页版上游不可达'));
60
+ const host = hosts[index++];
61
+ const socket = secure
62
+ ? tls.connect({ host, port, servername, rejectUnauthorized: false })
63
+ : net.connect({ host, port });
64
+ sockets.add(socket);
65
+ socket.once('close', () => sockets.delete(socket));
66
+ const timer = setTimeout(() => socket.destroy(new Error('网页版上游连接超时')), 10_000);
67
+ timer.unref?.();
68
+ socket.once('close', () => clearTimeout(timer));
69
+ const failed = (error) => { clearTimeout(timer); socket.destroy(); next(error); };
70
+ socket.once('error', failed);
71
+ socket.once(secure ? 'secureConnect' : 'connect', () => {
72
+ clearTimeout(timer);
73
+ socket.off('error', failed);
74
+ if (closed) { socket.destroy(); return; }
75
+ callback(null, socket);
76
+ });
77
+ };
78
+ next();
79
+ };
80
+ agent.createConnection = (_options, callback) => { connect(callback); };
81
+ const headersFor = (req, upgrade = false) => {
82
+ const headers = withViaHeader(
83
+ Object.fromEntries(Object.entries(req.headers).filter(([name]) => upgrade || !HOP_BY_HOP.has(name))),
84
+ 'preview-webapp', `localhost:${port}`,
85
+ );
86
+ // Node已经拆掉入站chunk边界,GET/HEAD也必须重新分帧,不能把正文裸写成第二请求。
87
+ if (!upgrade && req.headers['content-length'] === undefined && req.headers['transfer-encoding']) {
88
+ headers['transfer-encoding'] = 'chunked';
89
+ }
90
+ return headers;
91
+ };
92
+ const optionsFor = (req, upgrade = false) => ({
93
+ host: 'localhost', port, method: req.method, path: req.url, headers: headersFor(req, upgrade), agent,
94
+ });
95
+ const trackRequest = (request) => {
96
+ requests.add(request);
97
+ request.once('close', () => requests.delete(request));
98
+ return request;
99
+ };
100
+ const server = http.createServer({ requestTimeout: 0, headersTimeout: 0, keepAliveTimeout: 0 }, (req, res) => {
101
+ const upstream = trackRequest(transport.request(optionsFor(req), (reply) => {
102
+ res.writeHead(reply.statusCode || 502, Object.fromEntries(Object.entries(reply.headers).filter(([name]) => !HOP_BY_HOP.has(name))));
103
+ res.flushHeaders();
104
+ reply.on('error', close);
105
+ reply.pipe(res);
106
+ }));
107
+ upstream.on('error', () => {
108
+ if (closed) return;
109
+ if (res.headersSent) { close(); return; }
110
+ res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8', connection: 'close' });
111
+ res.once('finish', finishOutput);
112
+ res.end('网页版上游不可达');
113
+ });
114
+ req.on('aborted', () => upstream.destroy());
115
+ req.on('error', close);
116
+ res.on('close', () => { if (!res.writableEnded) upstream.destroy(); });
117
+ req.pipe(upstream);
118
+ });
119
+ server.on('clientError', close);
120
+ server.on('upgrade', (req, socket, head) => {
121
+ const upstream = trackRequest(transport.request(optionsFor(req, true)));
122
+ upstream.on('error', close);
123
+ upstream.on('response', (reply) => {
124
+ socket.write(`HTTP/1.1 ${reply.statusCode || 502} ${reply.statusMessage || 'Bad Gateway'}\r\nconnection: close\r\n\r\n`);
125
+ reply.pipe(socket);
126
+ });
127
+ upstream.on('upgrade', (reply, target, upstreamHead) => {
128
+ sockets.add(target);
129
+ target.once('end', finishOutput);
130
+ target.once('close', (hadError) => {
131
+ sockets.delete(target);
132
+ if (hadError || !target.readableEnded) close();
133
+ else finishOutput();
134
+ });
135
+ target.on('error', close);
136
+ if (closed) { target.destroy(); return; }
137
+ const lines = [`HTTP/1.1 ${reply.statusCode} ${reply.statusMessage}`];
138
+ for (let i = 0; i + 1 < reply.rawHeaders.length; i += 2) lines.push(`${reply.rawHeaders[i]}: ${reply.rawHeaders[i + 1]}`);
139
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`, 'latin1');
140
+ if (upstreamHead.length) socket.write(upstreamHead);
141
+ if (head.length) target.write(head);
142
+ socket.pipe(target).pipe(socket);
143
+ });
144
+ upstream.end();
145
+ });
146
+ server.emit('connection', stream);
147
+ return { close };
148
+ }
149
+
150
+ module.exports = { openWebappPipe, OUTPUT_DRAIN_TIMEOUT_MS };
@@ -1,3 +1,4 @@
1
+ // 连接既有预览目标,并为宿主网页版逐请求标记可信转发来源。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -32,6 +33,7 @@ const net = require('node:net');
32
33
  const tls = require('node:tls');
33
34
  const { WebSocketServer } = require('ws');
34
35
  const { ipv4Number, ipv6Number } = require('./lan-network.cjs');
36
+ const { openWebappPipe } = require('./preview-webapp.cjs');
35
37
 
36
38
  /**
37
39
  * 同一个宿主上同时在跑的预览连接上限。
@@ -245,6 +247,7 @@ function createPreviewService({ authorized, protectedPorts, ownWebPort = () => n
245
247
  * ——端口本身不是长期授权,是一次使用留下的痕迹,用于手机端展示与排查。
246
248
  */
247
249
  const grants = new Map();
250
+ const deviceConnections = new Map();
248
251
  let activeStreams = 0;
249
252
  let closed = false;
250
253
 
@@ -507,18 +510,42 @@ function createPreviewService({ authorized, protectedPorts, ownWebPort = () => n
507
510
  return refuseUpgrade(socket, 503, 'Service Unavailable', '预览连接数已达上限');
508
511
  }
509
512
 
510
- wss.handleUpgrade(req, socket, head, (ws) => openPipe(ws, {
511
- port,
512
- scheme: target.scheme,
513
- hosts: previewDialTargets(target.host),
514
- // IP 字面量不给 SNI:Node 直接把 IP 当 servername 判成非法参数,环回双栈掉落出来的
515
- // 地址也一样——所以这里取的是手机点名的那个主机。
516
- servername: net.isIP(target.host) ? undefined : target.host,
517
- }));
513
+ wss.handleUpgrade(req, socket, head, (ws) => {
514
+ const record = req.__dshRecord;
515
+ deviceConnections.set(ws, { deviceId: record?.deviceId || '', instanceId: record?.instanceId || req.__dshInstanceId || '' });
516
+ ws.once('close', () => deviceConnections.delete(ws));
517
+ const plan = {
518
+ port,
519
+ scheme: target.scheme,
520
+ hosts: previewDialTargets(target.host),
521
+ servername: net.isIP(target.host) ? undefined : target.host,
522
+ };
523
+ if (parsePreviewMode(req) !== 'webapp') { openPipe(ws, plan); return; }
524
+ activeStreams += 1;
525
+ noteGrant(port);
526
+ openWebappPipe(ws, { ...plan, onClose: () => { activeStreams -= 1; } });
527
+ });
518
528
  }
519
529
 
530
+ const dropConnections = (deviceId, instanceId, deferClose) => {
531
+ const selected = [];
532
+ for (const [ws, identity] of deviceConnections) {
533
+ if (instanceId !== undefined && identity.instanceId !== String(instanceId || '')) continue;
534
+ if (deviceId !== undefined && identity.deviceId !== deviceId) continue;
535
+ deviceConnections.delete(ws);
536
+ if (ws.readyState === 3) continue;
537
+ selected.push(ws);
538
+ }
539
+ const close = () => { for (const ws of selected) { try { ws.terminate(); } catch { /* 已关闭 */ } } };
540
+ if (deferClose) deferClose(close);
541
+ else close();
542
+ return selected.length;
543
+ };
544
+
520
545
  return {
521
546
  handleUpgrade,
547
+ dropDevice: (deviceId, instanceId, deferClose) => dropConnections(deviceId, instanceId, deferClose),
548
+ dropAll: (instanceId) => dropConnections(undefined, instanceId),
522
549
  /** 「预览碰过哪些端口」的快照,供状态接口展示。 */
523
550
  grants: () => [...grants.values()].sort((a, b) => a.port - b.port).map((grant) => ({ ...grant })),
524
551
  stats: () => ({ activeStreams, maxStreams: MAX_PREVIEW_STREAMS }),
@@ -1,3 +1,4 @@
1
+ // 注册字段与关闭原因同步 relay-core 协议说明,blobPut 旧 id0 与协商 idN 语义保持。
1
2
  'use strict';
2
3
 
3
4
  /**
@@ -16,8 +17,8 @@
16
17
  */
17
18
 
18
19
  const T = {
19
- register: 0x01, // id=0 JSON {instanceId, name, lanUrls?, lanCandidates?, secret?}
20
- registered: 0x02, // id=0 JSON {}
20
+ register: 0x01, // id=0 JSON {instanceId,name?,version?,license?,secret?,lanUrls?,lanCandidates?};不发 pairingCode
21
+ registered: 0x02, // id=0 JSON {ok,mirror,blobUpload?:{maxChunkBytes,maxBlobBytes}}
21
22
  updatePairing: 0x03, // id=0 JSON {}(保留编号,宿主已不再发;中转从不读)
22
23
  httpRequest: 0x04, // id=N JSON {method, path, headers};body 随后以 httpBody 流式发送
23
24
  httpBody: 0x05, // id=N raw bytes(空 payload = body 结束)
@@ -30,7 +31,7 @@ const T = {
30
31
  wsError: 0x0C, // id=N JSON {message}
31
32
  wsText: 0x0D, // id=N raw bytes(上游 WS 文本帧数据)
32
33
  wsBinary: 0x0E, // id=N raw bytes(上游 WS 二进制帧数据)
33
- wsClose: 0x0F, // id=N 2B 大端 close code
34
+ wsClose: 0x0F, // id=N 2B 大端 close code + 可选 UTF-8 reason(最多 123B)
34
35
  ping: 0x10, // id=0 空
35
36
  pong: 0x11, // id=0 空
36
37
  pairRequest: 0x12, // id=0 JSON {requestId, device:{id?, deviceId?, name?, platform?, osVersion?, appVersion?, ip?}}(手机配对 → 请求桌面授权;ip 由中转注入)
@@ -44,7 +45,8 @@ const T = {
44
45
  pushRegister: 0x1A, // id=0 JSON {deviceId, platform, token};宿主代 App 上报 iOS 推送令牌(本实例)
45
46
  pushSend: 0x1B, // id=0 JSON {deviceId, title, body, sessionId?, kind};宿主请求中转发一条 APNs 推送
46
47
  migrate: 0x1C, // id=0 JSON {to, at};宿主在旧隧道上登记「这台搬去哪个中转」,to 空串 = 撤销
47
- blobPut: 0x1D, // id=0 JSON {scope, key, creds, cipher};宿主把 HK 加密的历史 blob(base64url 密文)推给中转,中转只存不解
48
+ blobPut: 0x1D, // id0旧整包/空cipher;协商idN {offset,total,final,cipher,scope?,key?,creds?},反向{ok,nextOffset,done,error?}
49
+ blobDelete: 0x1E, // id0 {scope,key}或{scope,keys},只删本实例
48
50
  };
49
51
 
50
52
  const TYPE_NAME = {};
@@ -1,12 +1,14 @@
1
+ // 中转健康响应与注册失败分账,延迟、冷却和衰减均按单调经过时间计算。
1
2
  'use strict'
2
- // 公用中转「电脑决定」的延迟探测:worker 连中转前先量一遍各候选的 /healthz 延迟,
3
- // 把最快的那台排在前面再按序连(失败仍按现有逻辑顺延到下一台)。
3
+ // 公用中转「电脑决定」的延迟探测:worker 连中转前先量各候选的健康响应延迟,
4
+ // 把最快的那台排在前面再连。健康响应不代表隧道注册成功,注册失败证据由调用方单独保存。
4
5
  //
5
6
  // 两件事分开:`orderByLatency` 是纯函数(只排顺序、不碰网络),`probeRelayHealth` 是薄探测
6
- // (发一次 GET、量到响应为止、超时或报错返回 null)。探测结果交给排序函数,两者互不依赖。
7
+ // (发一次 GET、校验完整响应,失败返回 null)。探测结果交给排序函数,两者互不依赖。
7
8
 
8
9
  const http = require('node:http')
9
10
  const https = require('node:https')
11
+ const { performance } = require('node:perf_hooks')
10
12
 
11
13
  /**
12
14
  * 按实测延迟给候选地址排序:量到延迟的按升序在前,不可达 / 没量到的排后面。
@@ -36,51 +38,140 @@ function orderByLatency(urls, latencyByUrl) {
36
38
  return [...reachable.map((item) => item.url), ...unreachable]
37
39
  }
38
40
 
41
+ const RELAY_HEALTH_SERVICE = 'dsh-mobile-relay'
42
+ const MAX_HEALTH_BODY_BYTES = 16 * 1024
43
+
39
44
  /**
40
- * 对 `url + '/healthz'` 发一次 GET,量出从发起到拿到响应(任意状态码都算)的毫秒数。
45
+ * 对现有 `/api/mobile/v1/health` 发一次 GET,只认 2xx、ok 与中转固定服务名。
41
46
  *
42
- * 超时或报错返回 null(= 这条当期不可达)。按 URL 协议选 http / https,用 `req.setTimeout`
43
- * 起超时后 `destroy`,不走全局 fetch。
47
+ * 校验完整的小响应体后才接受首字节延迟;不跟随重定向,避免把门户页当成健康中转。
48
+ * 一个总定时器覆盖 DNS、连接、响应头和响应体,滴流也不能延长探测预算。
44
49
  *
45
50
  * @param {string} url 中转地址
46
- * @param {{ timeoutMs?: number }} [options] 超时毫秒,默认 1500
47
- * @returns {Promise<number|null>} 延迟毫秒,或 null
51
+ * @param {{ timeoutMs?: number }} [options] 总超时毫秒,默认 1500
52
+ * @returns {Promise<number|null>} 首字节延迟毫秒,或 null
48
53
  */
49
54
  function probeRelayHealth(url, options = {}) {
50
- const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 1500
55
+ const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : 1500
51
56
  return new Promise((resolve) => {
52
57
  let healthUrl
53
58
  try {
54
- healthUrl = new URL(`${String(url).replace(/\/+$/, '')}/healthz`)
59
+ healthUrl = new URL(`${String(url).replace(/\/+$/, '')}/api/mobile/v1/health`)
60
+ if (healthUrl.protocol !== 'http:' && healthUrl.protocol !== 'https:') {
61
+ resolve(null)
62
+ return
63
+ }
55
64
  } catch {
56
65
  resolve(null)
57
66
  return
58
67
  }
59
68
  const client = healthUrl.protocol === 'https:' ? https : http
60
- const startedAt = Date.now()
69
+ const startedAt = performance.now()
61
70
  let settled = false
71
+ let req
72
+ let response
62
73
  const finish = (value) => {
63
74
  if (settled) return
64
75
  settled = true
76
+ clearTimeout(timer)
77
+ if (value === null) {
78
+ if (response) response.destroy()
79
+ if (req) req.destroy()
80
+ }
65
81
  resolve(value)
66
82
  }
67
- let req
83
+ const timer = setTimeout(() => finish(null), timeoutMs)
68
84
  try {
69
85
  // agent:false:一次性连接,探完就关,别把 keep-alive 的 socket 留在进程里。
70
86
  req = client.get(healthUrl, { agent: false }, (res) => {
71
- res.resume()
72
- finish(Date.now() - startedAt)
87
+ response = res
88
+ const latency = performance.now() - startedAt
89
+ let size = 0
90
+ const chunks = []
91
+ res.on('error', () => finish(null))
92
+ res.on('aborted', () => finish(null))
93
+ res.on('close', () => { if (!res.complete) finish(null) })
94
+ if (!(res.statusCode >= 200 && res.statusCode < 300)) {
95
+ finish(null)
96
+ return
97
+ }
98
+ if (Number(res.headers['content-length']) > MAX_HEALTH_BODY_BYTES) {
99
+ finish(null)
100
+ return
101
+ }
102
+ res.on('data', (chunk) => {
103
+ if (settled) return
104
+ size += chunk.length
105
+ if (size > MAX_HEALTH_BODY_BYTES) {
106
+ finish(null)
107
+ return
108
+ }
109
+ chunks.push(chunk)
110
+ })
111
+ res.on('end', () => {
112
+ if (settled) return
113
+ try {
114
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
115
+ finish(body && body.ok === true && body.service === RELAY_HEALTH_SERVICE ? latency : null)
116
+ } catch {
117
+ finish(null)
118
+ }
119
+ })
73
120
  })
121
+ req.on('error', () => finish(null))
74
122
  } catch {
75
123
  finish(null)
76
- return
77
124
  }
78
- req.on('error', () => finish(null))
79
- req.setTimeout(timeoutMs, () => {
80
- finish(null)
81
- req.destroy()
82
- })
83
125
  })
84
126
  }
85
127
 
86
- module.exports = { orderByLatency, probeRelayHealth }
128
+ /** 注册失败与健康延迟分账:只有真实注册成功清账,失败成本随时间衰减。 */
129
+ function createRelayRegistrationLedger({ now = () => performance.now() } = {}) {
130
+ const failures = new Map()
131
+ const penaltyOf = (url) => {
132
+ const fact = failures.get(url)
133
+ if (!fact) return 0
134
+ const count = Math.max(0, fact.count - Math.floor(Math.max(0, now() - fact.at) / 300000))
135
+ if (!count) failures.delete(url)
136
+ return count * 8000
137
+ }
138
+ return {
139
+ noteFailure(url) {
140
+ const count = penaltyOf(url) / 8000
141
+ failures.set(url, { count: Math.min(4, count + 1), at: now() })
142
+ },
143
+ noteSuccess(url) { failures.delete(url) },
144
+ order(urls, latencyByUrl) {
145
+ const latency = (url) => latencyByUrl instanceof Map ? latencyByUrl.get(url) : latencyByUrl?.[url]
146
+ const measured = urls.map(latency).filter((ms) => typeof ms === 'number' && Number.isFinite(ms) && ms >= 0)
147
+ const unknown = Math.max(1500, ...measured) + 1
148
+ const cost = (url) => {
149
+ const ms = latency(url)
150
+ return (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0 ? ms : unknown) + penaltyOf(url)
151
+ }
152
+ const present = new Set(urls)
153
+ for (const url of failures.keys()) if (!present.has(url)) failures.delete(url)
154
+ const cooling = (url) => penaltyOf(url) > 0 && Math.max(0, now() - failures.get(url).at) < 30000
155
+ return [...urls].sort((a, b) => {
156
+ const aCooling = cooling(a), bCooling = cooling(b)
157
+ if (aCooling !== bCooling) return aCooling ? 1 : -1
158
+ // 全部都在短冷却时照样重试,先试最久没失败的,封顶后也不能粘在固定前几条。
159
+ if (aCooling && bCooling && failures.get(a).at !== failures.get(b).at) return failures.get(a).at - failures.get(b).at
160
+ return cost(a) - cost(b)
161
+ })
162
+ },
163
+ }
164
+ }
165
+
166
+ /** 只报告真实环境配置或代理失败证据,不输出代理地址与认证材料。 */
167
+ function relayFailureMessage(error, env = process.env) {
168
+ const message = String(error && typeof error.message === 'string' ? error.message : error || '连接失败')
169
+ if (message.includes('宿主中转与总控目前只支持直连出网')) return message
170
+ const configured = ['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'https_proxy', 'http_proxy', 'all_proxy']
171
+ .filter((name) => typeof env[name] === 'string' && env[name].trim())
172
+ if (!configured.length && !/\b407\b|proxy authentication|proxy connect/i.test(message)) return message
173
+ const evidence = configured.length ? `检测到环境代理 ${configured.join('、')}` : '对端返回代理认证或连接错误'
174
+ return `${message};${evidence}。宿主中转与总控目前只支持直连出网,未使用环境代理;请允许目标地址直连或更换可直连网络。`
175
+ }
176
+
177
+ module.exports = { orderByLatency, probeRelayHealth, createRelayRegistrationLedger, relayFailureMessage }
@@ -1,3 +1,4 @@
1
+ // 在隧道落点覆盖可信来源标记,区分固定的直连与点对点入口。
1
2
  'use strict';
2
3
  // 落点代理转给宿主 web 服务时跟随宿主实际绑定地址(不再写死回环),回环绑定行为不变。
3
4
 
@@ -42,6 +43,7 @@ const HOP_BY_HOP = new Set([
42
43
  */
43
44
  function createTunnelForwarder(options) {
44
45
  const upstreamPort = options.upstreamPort;
46
+ const via = options.via === 'p2p' ? 'p2p' : VIA_TUNNEL;
45
47
  const upstreamHost = typeof options.upstreamHost === 'function'
46
48
  ? options.upstreamHost
47
49
  : () => options.upstreamHost || DEFAULT_UPSTREAM_HOST;
@@ -62,7 +64,7 @@ function createTunnelForwarder(options) {
62
64
  function forwardedHeaders(incoming) {
63
65
  return withViaHeader(
64
66
  Object.fromEntries(Object.entries(incoming).filter(([key, value]) => !HOP_BY_HOP.has(key) && value !== undefined)),
65
- VIA_TUNNEL,
67
+ via,
66
68
  upstreamOf(),
67
69
  );
68
70
  }
@@ -112,7 +114,7 @@ function createTunnelForwarder(options) {
112
114
  lines.push(`${req.rawHeaders[at]}: ${req.rawHeaders[at + 1]}`);
113
115
  }
114
116
  lines.push(`Host: ${upstreamOf()}`);
115
- lines.push(`${VIA_HEADER}: ${VIA_TUNNEL}`);
117
+ lines.push(`${VIA_HEADER}: ${via}`);
116
118
  // 头是按字节传的,Node 的 rawHeaders 就是 latin1 解出来的,按同一个编码写回。
117
119
  return Buffer.from(`${lines.join('\r\n')}\r\n\r\n`, 'latin1');
118
120
  }
@@ -1,3 +1,4 @@
1
+ // 注册取消与单调心跳保持原语义,blob逐片确认独立于HTTP/WS请求。
1
2
  'use strict';
2
3
  // 中转隧道把请求转给宿主 web 服务时,上游地址跟随宿主实际绑定地址(可能不是回环)。
3
4
 
@@ -18,6 +19,8 @@
18
19
  */
19
20
 
20
21
  const http = require('node:http');
22
+ const { performance } = require('node:perf_hooks');
23
+ const { BlobUpload } = require('./blob-upload.cjs');
21
24
  const { WebSocket } = require('ws');
22
25
  const { T, jsonFrame, encodeFrame, createFrameDecoder, parseJson, encodeClosePayload, decodeClosePayload } = require('./protocol.js');
23
26
  const { isFreshRequest } = require('../shared/fresh-request');
@@ -100,6 +103,7 @@ class RelayTunnel {
100
103
  this.onPairRequest = opts.onPairRequest || (() => {});
101
104
  this.onLog = opts.onLog || (() => {});
102
105
  this.ws = null;
106
+ this.cancelRegistration = null;
103
107
  this.wsClients = new Map(); // relay 侧 ws id -> 上游 ws client
104
108
  this.reqClients = new Map(); // relay 侧 http id -> { req, res }
105
109
  this.sseClients = new Set();
@@ -122,6 +126,7 @@ class RelayTunnel {
122
126
  this.lastControlError = null;
123
127
  // 清除所有授权的等待回调(一次一个);由 requestRevokeAll 注入,revokeAllAck 触发。
124
128
  this._revokeAllAck = null;
129
+ this.blobUpload = new BlobUpload(this);
125
130
  }
126
131
 
127
132
  log(...args) {
@@ -167,6 +172,7 @@ class RelayTunnel {
167
172
  trySendJson(type, id, obj) {
168
173
  try { return this.trySendEncodedFrame(jsonFrame(type, id, obj)); } catch { return 'error'; }
169
174
  }
175
+ pushBlob(frame) { return this.blobUpload.send(frame); }
170
176
  sendFrame(type, id, payload) { return this.trySendFrame(type, id, payload) === 'sent'; }
171
177
  sendJson(type, id, obj) { return this.trySendJson(type, id, obj) === 'sent'; }
172
178
  createHttpResponseEntry(req = null, res = null, isSse = false) {
@@ -289,7 +295,9 @@ class RelayTunnel {
289
295
  return false;
290
296
  }
291
297
  const size = isChunk ? body.length : frame.length;
292
- const mustQueue = isChunk && body.length > HTTP_RESPONSE_CHUNK_BYTES;
298
+ const blobNeedsWindow = this.blobUpload.active?.waiting
299
+ && Number(this.ws?.bufferedAmount || 0) + size > TUNNEL_BUFFER_LOW_WATER_BYTES - 128 * 1024;
300
+ const mustQueue = (isChunk && body.length > HTTP_RESPONSE_CHUNK_BYTES) || blobNeedsWindow;
293
301
  if (!entry.pendingFrames.length && !mustQueue && !entry.relayPaused) {
294
302
  const result = isChunk ? this.trySendFrame(type, id, body) : this.trySendEncodedFrame(frame);
295
303
  if (result === 'sent') {
@@ -357,7 +365,9 @@ class RelayTunnel {
357
365
  const index = (start + step) % count;
358
366
  const [id, entry] = all[index];
359
367
  if (entry.done || entry.relayPaused || !entry.pendingFrames?.length) continue;
360
- if (Number(this.ws.bufferedAmount || 0) + HTTP_RESPONSE_CHUNK_BYTES + 16 > MAX_TUNNEL_BUFFERED_BYTES) break;
368
+ // blob等发送时留一小片窗口;HTTP仍逐流轮转,blob一片发出后即恢复原预算。
369
+ const ceiling = this.blobUpload.active?.waiting ? TUNNEL_BUFFER_LOW_WATER_BYTES - 128 * 1024 : MAX_TUNNEL_BUFFERED_BYTES;
370
+ if (Number(this.ws.bufferedAmount || 0) + HTTP_RESPONSE_CHUNK_BYTES + 16 > ceiling) break;
361
371
  const item = entry.pendingFrames[0];
362
372
  let result;
363
373
  if (item.type === T.httpChunk) {
@@ -506,6 +516,7 @@ class RelayTunnel {
506
516
  const done = (fn, arg) => {
507
517
  if (!settled) {
508
518
  settled = true;
519
+ this.cancelRegistration = null;
509
520
  fn(arg);
510
521
  }
511
522
  };
@@ -516,14 +527,24 @@ class RelayTunnel {
516
527
  this.ws = ws;
517
528
  const timer = setTimeout(() => {
518
529
  done(reject, new Error('注册超时'));
519
- try { ws.close(); } catch { /* ignore */ }
530
+ try { ws.terminate(); } catch { /* ignore */ }
520
531
  }, 8000);
532
+ this.cancelRegistration = () => {
533
+ clearTimeout(timer);
534
+ const error = new Error('隧道注册已取消');
535
+ error.code = 'relay_cancelled';
536
+ done(reject, error);
537
+ };
521
538
 
522
539
  const push = createFrameDecoder((frame) => {
540
+ if (this.ws !== ws) return;
523
541
  if (frame.type === T.registered) {
542
+ if (settled) return;
524
543
  // 回执里带 `mirror`:对端说不存镜像,就只推摘要(凭据 + 两个 revision),正文不推。
525
544
  // 老中转回的是空载荷,`parseJson` 给空对象,于是判定为「存」——与以前完全一样。
526
- this.relayMirror = parseJson(frame.payload).mirror !== false;
545
+ const registered = parseJson(frame.payload);
546
+ this.relayMirror = registered.mirror !== false;
547
+ this.blobUpload.configure(registered.blobUpload);
527
548
  clearTimeout(timer);
528
549
  done(resolve);
529
550
  this.onRegistered();
@@ -533,12 +554,15 @@ class RelayTunnel {
533
554
  });
534
555
 
535
556
  ws.on('open', () => {
557
+ if (this.ws !== ws) return;
536
558
  this.sendJson(T.register, 0, this.registrationPayload());
537
559
  });
538
560
  ws.on('message', (data, isBinary) => push(Buffer.isBuffer(data) ? data : Buffer.from(data)));
539
561
  ws.on('close', (code, reason) => {
540
562
  clearTimeout(timer);
563
+ if (this.ws !== ws) { done(reject, new Error(`隧道关闭: ${code} ${reason}`)); return; }
541
564
  this.stopHeartbeat();
565
+ this.blobUpload.close();
542
566
  this.log(`tunnel closed: ${code} ${reason}`);
543
567
  this.ws = null;
544
568
  this.clearHttpPumpTimer();
@@ -572,6 +596,8 @@ class RelayTunnel {
572
596
  }
573
597
 
574
598
  stop() {
599
+ this.blobUpload.close();
600
+ this.cancelRegistration?.();
575
601
  this.stopHeartbeat();
576
602
  this.clearHttpPumpTimer();
577
603
  for (const [, client] of this.wsClients) {
@@ -584,18 +610,19 @@ class RelayTunnel {
584
610
  this.cancelledHttp.clear();
585
611
  this.cancelledWs.clear();
586
612
  if (this.ws) {
587
- try { this.ws.close(); } catch { /* ignore */ }
613
+ const ws = this.ws;
588
614
  this.ws = null;
615
+ try { ws.terminate(); } catch { /* ignore */ }
589
616
  }
590
617
  }
591
618
 
592
619
  // ── 心跳 ──────────────────────────────────────────────────────────
593
620
  startHeartbeat() {
594
621
  this.stopHeartbeat();
595
- this.lastPong = Date.now();
622
+ this.lastPong = performance.now();
596
623
  this.hbTimer = setInterval(() => {
597
624
  if (!this.connected) return;
598
- if (Date.now() - this.lastPong > PONG_TIMEOUT_MS) {
625
+ if (performance.now() - this.lastPong > PONG_TIMEOUT_MS) {
599
626
  this.log('心跳超时,断开隧道');
600
627
  try { this.ws.terminate(); } catch { /* ignore */ }
601
628
  return;
@@ -613,6 +640,10 @@ class RelayTunnel {
613
640
  // ── 帧分发 ────────────────────────────────────────────────────────
614
641
  handleFrame(frame) {
615
642
  const { type, id, payload } = frame;
643
+ if (type === T.blobPut && id !== 0) {
644
+ this.blobUpload.onAck(id, parseJson(payload));
645
+ return;
646
+ }
616
647
  // id=0 的 wsError 是中转在断开之前给的一句话(现在还只用于「注册被拒」):先记下来,
617
648
  // 等随后的 close 回调把它带进 start() 的 reject,调用方按 `code` 分流。
618
649
  if (type === T.wsError && id === 0) {
@@ -797,7 +828,7 @@ class RelayTunnel {
797
828
  this.sendFrame(T.pong, 0, Buffer.alloc(0));
798
829
  break;
799
830
  case T.pong:
800
- this.lastPong = Date.now();
831
+ this.lastPong = performance.now();
801
832
  break;
802
833
  case T.revokeAllAck: {
803
834
  const msg = parseJson(payload);