dsh-mobile-plugin 0.5.81 → 0.5.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dsh-mobile-credentials/lib/credentials.js +5 -0
- package/lib/client.js +171 -5
- package/lib/frpc/provision.cjs +21 -17
- package/lib/frpc/runner.cjs +231 -168
- package/lib/impl.js +77 -107
- package/lib/index.js +1 -1
- package/lib/mirror/pusher.cjs +60 -10
- package/lib/mobile/approval-memory.js +2 -55
- package/lib/mobile/approvals.js +6 -82
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/feedback.js +6 -5
- package/lib/mobile/file-read.js +4 -2
- package/lib/mobile/host-bridge.js +12 -1
- package/lib/mobile/mux.js +148 -21
- package/lib/mobile/paired-devices.js +2 -1
- package/lib/mobile/pairing.js +8 -7
- package/lib/mobile/relay-control.js +33 -38
- package/lib/mobile/session-changes.js +8 -2
- package/lib/mobile/session-delivery.js +5 -1
- package/lib/mobile/session-file.js +46 -25
- package/lib/mobile/session-head.js +7 -3
- package/lib/mobile/session-snapshot.js +5 -1
- package/lib/mobile/session-step.js +13 -7
- package/lib/mobile/session-stop-summary.js +6 -1
- package/lib/mobile/stream-registry.js +48 -53
- package/lib/mobile/stream.js +17 -2
- package/lib/mobile/uploads.js +190 -163
- package/lib/p2p/session.cjs +169 -70
- package/lib/p2p/wiring.cjs +4 -2
- package/lib/panel/index.html +44 -24
- package/lib/relay/blob-upload.cjs +103 -0
- package/lib/relay/config-store.js +79 -0
- package/lib/relay/control.js +131 -52
- package/lib/relay/core.js +55 -17
- package/lib/relay/lan-discovery.cjs +22 -14
- package/lib/relay/lan-port-policy.cjs +8 -2
- package/lib/relay/lan-proxy.js +47 -12
- package/lib/relay/pairing-payload.cjs +14 -5
- package/lib/relay/preview-webapp.cjs +150 -0
- package/lib/relay/preview.js +35 -8
- package/lib/relay/protocol.js +6 -4
- package/lib/relay/relay-probe.js +112 -21
- package/lib/relay/status.js +4 -7
- package/lib/relay/tunnel-forwarder.cjs +4 -2
- package/lib/relay/tunnel.js +39 -8
- package/lib/remote/controller.cjs +33 -3
- package/lib/remote/host-control.cjs +11 -2
- package/lib/remote/router.cjs +83 -33
- package/lib/remote/transport.cjs +32 -5
- package/lib/remote/tunnel-helper.cjs +51 -25
- package/lib/remote/tunnels.cjs +27 -3
- package/lib/routes/control-plane.js +41 -53
- package/lib/routes/mobile-api.js +21 -31
- package/lib/shared/fresh-request.js +32 -1
- package/lib/shared/route-order.cjs +118 -132
- package/lib/shared/sse-write.js +29 -10
- package/lib/shared/via-header.js +5 -12
- package/lib/shell/transport-host.js +9 -1
- package/lib/shell/updater.js +18 -6
- package/lib/sidecar-facade-worker.cjs +165 -118
- package/lib/sidecar-facade.cjs +6 -1
- package/lib/sidecar-lifecycle.cjs +6 -2
- package/lib/tailcat/host-process.cjs +32 -8
- package/lib/tailcat/session.cjs +27 -10
- package/package.json +6 -6
- package/lib/mobile/auto-review.js +0 -178
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 短暂占用先重试原端口,固定入口禁止自动换号。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 只发布已监听入口;发布失败时停止换号,现有固定入口仍可使用。
|
|
3
4
|
const { canChangeLanPort } = require('./lan-port-policy.cjs');
|
|
@@ -76,22 +77,29 @@ function createLanDiscovery({ instanceId, onChange = () => {}, makeBonjour = onE
|
|
|
76
77
|
return { publish, stop, snapshot: () => ({ ...view }) };
|
|
77
78
|
}
|
|
78
79
|
|
|
79
|
-
/**
|
|
80
|
-
async function bindLanEndpoint({ requestedPort, createProxy, discovery, store, instanceId, isCurrent = () => true
|
|
81
|
-
|
|
80
|
+
/** 短暂占用先重试原入口;固定穿透与旧手机始终保留原端口。 */
|
|
81
|
+
async function bindLanEndpoint({ requestedPort, createProxy, discovery, store, instanceId, lockReason = '', isCurrent = () => true,
|
|
82
|
+
retryDelays = [250, 750], wait = ms => new Promise(resolve => setTimeout(resolve, ms)) }) {
|
|
83
|
+
let proxy;
|
|
82
84
|
let changed = false;
|
|
83
|
-
|
|
84
|
-
await proxy.start();
|
|
85
|
-
} catch (error) {
|
|
86
|
-
await proxy.stop();
|
|
87
|
-
if (error?.code !== 'EADDRINUSE') throw error;
|
|
88
|
-
if (!canChangeLanPort(store, instanceId)) {
|
|
89
|
-
throw new Error(`端口 ${requestedPort} 已被占用;为保留旧版或未知能力手机的连接地址,未自动换端口。请释放占用后重试。`);
|
|
90
|
-
}
|
|
85
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
91
86
|
if (!isCurrent()) throw new Error('局域网配置已更新');
|
|
92
|
-
proxy = createProxy(
|
|
93
|
-
try { await proxy.start();
|
|
94
|
-
|
|
87
|
+
proxy = createProxy(requestedPort);
|
|
88
|
+
try { await proxy.start(); break; }
|
|
89
|
+
catch (error) {
|
|
90
|
+
await proxy.stop();
|
|
91
|
+
if (error?.code !== 'EADDRINUSE') throw error;
|
|
92
|
+
if (attempt < retryDelays.length) { await wait(retryDelays[attempt]); continue; }
|
|
93
|
+
if (lockReason) throw new Error(`端口 ${requestedPort} 已被占用;${lockReason === 'fixed' ? '已开启固定端口' : '穿透或固定地址依赖此端口'},未自动换端口。请释放占用后重试。`);
|
|
94
|
+
if (!canChangeLanPort(store, instanceId)) {
|
|
95
|
+
throw new Error(`端口 ${requestedPort} 已被占用;为保留旧版或未知能力手机的连接地址,未自动换端口。请释放占用后重试。`);
|
|
96
|
+
}
|
|
97
|
+
if (!isCurrent()) throw new Error('局域网配置已更新');
|
|
98
|
+
proxy = createProxy(0);
|
|
99
|
+
try { await proxy.start(); } catch (retryError) { await proxy.stop(); throw retryError; }
|
|
100
|
+
changed = true;
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
95
103
|
}
|
|
96
104
|
if (!isCurrent()) { await proxy.stop(); throw new Error('局域网配置已更新'); }
|
|
97
105
|
const port = proxy.port();
|
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
//
|
|
2
|
+
// 固定入口禁止漂移;新端口仅在监听和发现发布成功后保存。
|
|
3
|
+
|
|
4
|
+
function lanPortLockReason(state, forwarding = false) {
|
|
5
|
+
if (state.lanPortFixed === true) return 'fixed';
|
|
6
|
+
if (forwarding || state.manualLanUrl || state.manualIpv6Url || state.manualTcpUrl) return 'forwarding';
|
|
7
|
+
return '';
|
|
8
|
+
}
|
|
3
9
|
|
|
4
10
|
function canChangeLanPort(store, instanceId) {
|
|
5
11
|
store.refresh?.();
|
|
@@ -34,4 +40,4 @@ function createLanPortPolicy({ state, saveState }) {
|
|
|
34
40
|
};
|
|
35
41
|
}
|
|
36
42
|
|
|
37
|
-
module.exports = { canChangeLanPort, createLanPortPolicy };
|
|
43
|
+
module.exports = { lanPortLockReason, canChangeLanPort, createLanPortPolicy };
|
package/lib/relay/lan-proxy.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 代理已授权移动请求,独立绑定双栈监听并透传 mux 手机端存活证明。
|
|
1
2
|
'use strict';
|
|
2
3
|
// 只绑定指定入口;换号决策交给带发现能力保护的生命周期。
|
|
3
4
|
// 电脑加密配对与隧道透传仅按精确路径放行,身份由上游独立协议校验。
|
|
@@ -66,10 +67,9 @@ const CORS_MAX_AGE = '600';
|
|
|
66
67
|
function createLanProxy(opts) {
|
|
67
68
|
const {
|
|
68
69
|
lanPort,
|
|
70
|
+
ipv4Enabled = true,
|
|
69
71
|
pairingCode,
|
|
70
72
|
pairingTicket = '',
|
|
71
|
-
// 新配对权限档位(电脑侧选定);局域网这条配对入口与中转那条同一档位。
|
|
72
|
-
pairingTier = 'full',
|
|
73
73
|
instanceId,
|
|
74
74
|
// 换身份过渡期的旧实例号:本机此刻同时认新号和旧号(见 core.rotateIdentity)。
|
|
75
75
|
previousInstanceId = '',
|
|
@@ -398,7 +398,7 @@ function createLanProxy(opts) {
|
|
|
398
398
|
}
|
|
399
399
|
const headers = withViaHeader(
|
|
400
400
|
Object.fromEntries(Object.entries(req.headers).filter(([k]) => !HOP_BY_HOP.has(k))),
|
|
401
|
-
'lan',
|
|
401
|
+
req.socket?.localFamily === 'IPv6' ? 'ipv6' : 'lan',
|
|
402
402
|
`${formatHost(upstreamHost)}:${upstreamPort}`,
|
|
403
403
|
);
|
|
404
404
|
const isSse = String(req.headers.accept || '').toLowerCase().includes('text/event-stream');
|
|
@@ -498,6 +498,7 @@ function createLanProxy(opts) {
|
|
|
498
498
|
* 永久留在闭包里,几小时后宿主整进程 OOM。
|
|
499
499
|
*/
|
|
500
500
|
function handleUpgrade(req, socket, head) {
|
|
501
|
+
const mux = req.method === 'GET' && String(req.url || '').split('?')[0] === '/api/mobile/v1/mux';
|
|
501
502
|
const remoteComputer = req.method === 'GET'
|
|
502
503
|
&& String(req.url || '').split('?')[0] === '/api/mobile/v1/remote-computers/tunnel';
|
|
503
504
|
if (!remoteComputer && !authorized(req)) {
|
|
@@ -508,7 +509,7 @@ function createLanProxy(opts) {
|
|
|
508
509
|
|
|
509
510
|
const headers = withViaHeader(
|
|
510
511
|
Object.fromEntries(Object.entries(req.headers).filter(([key, value]) => !HOP_BY_HOP.has(key) && value !== undefined)),
|
|
511
|
-
'lan',
|
|
512
|
+
req.socket?.localFamily === 'IPv6' ? 'ipv6' : 'lan',
|
|
512
513
|
`${formatHost(upstreamHost)}:${upstreamPort}`,
|
|
513
514
|
);
|
|
514
515
|
// 上游要认得这条请求:新 T1 记录没有存下来的宿主令牌,就把请求里出示的那一枚
|
|
@@ -521,6 +522,7 @@ function createLanProxy(opts) {
|
|
|
521
522
|
up = new WebSocket(`ws://${formatHost(upstreamHost)}:${upstreamPort}${req.url}`, {
|
|
522
523
|
headers,
|
|
523
524
|
handshakeTimeout: WS_UPSTREAM_HANDSHAKE_MS,
|
|
525
|
+
...(mux ? { autoPong: false } : {}),
|
|
524
526
|
});
|
|
525
527
|
} catch (err) {
|
|
526
528
|
refuseSocket(socket, 502, `无法连接上游:${err.message}`);
|
|
@@ -530,6 +532,7 @@ function createLanProxy(opts) {
|
|
|
530
532
|
/** 是否已经给手机回过响应(成功或失败),保证只回一次。 */
|
|
531
533
|
let settled = false;
|
|
532
534
|
let phoneWs = null;
|
|
535
|
+
let closeMux = null;
|
|
533
536
|
let upstreamReady = false;
|
|
534
537
|
let pendingBytes = 0;
|
|
535
538
|
/** 上游已连上、手机握手还没完成时先到达的字节。 */
|
|
@@ -599,6 +602,36 @@ function createLanProxy(opts) {
|
|
|
599
602
|
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
600
603
|
settled = true;
|
|
601
604
|
phoneWs = ws;
|
|
605
|
+
if (mux) {
|
|
606
|
+
let closed = false;
|
|
607
|
+
const pingPhone = (data) => {
|
|
608
|
+
if (closed || ws.readyState !== WebSocket.OPEN) return;
|
|
609
|
+
try { ws.ping(data); } catch { closeMux(true); }
|
|
610
|
+
};
|
|
611
|
+
const pongUpstream = (data) => {
|
|
612
|
+
if (closed || up.readyState !== WebSocket.OPEN) return;
|
|
613
|
+
try { up.pong(data); } catch { closeMux(true); }
|
|
614
|
+
};
|
|
615
|
+
closeMux = (terminate = false) => {
|
|
616
|
+
if (closed) return;
|
|
617
|
+
closed = true;
|
|
618
|
+
up.off('ping', pingPhone);
|
|
619
|
+
ws.off('pong', pongUpstream);
|
|
620
|
+
socket.off('error', abandon);
|
|
621
|
+
socket.off('close', abandon);
|
|
622
|
+
dropPending();
|
|
623
|
+
if (terminate) {
|
|
624
|
+
try { ws.terminate(); } catch { /* 已断开 */ }
|
|
625
|
+
dropUpstream();
|
|
626
|
+
} else {
|
|
627
|
+
try { ws.close(); } catch { /* 已断开 */ }
|
|
628
|
+
try { up.close(); } catch { /* 已断开 */ }
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
// 本机不代答宿主心跳;只有真实手机的协议 pong 才能证明这条 mux 仍可用。
|
|
632
|
+
up.on('ping', pingPhone);
|
|
633
|
+
ws.on('pong', pongUpstream);
|
|
634
|
+
}
|
|
602
635
|
try {
|
|
603
636
|
// 先补发暂存、再放行上游:暂停期间挂监听不会丢,恢复才一次性派发。
|
|
604
637
|
for (const entry of pending) {
|
|
@@ -611,9 +644,9 @@ function createLanProxy(opts) {
|
|
|
611
644
|
ws.on('message', (data, isBinary) => {
|
|
612
645
|
if (up.readyState === WebSocket.OPEN) up.send(data, { binary: isBinary });
|
|
613
646
|
});
|
|
614
|
-
ws.on('close', () => { try { up.close(); } catch { /* ignore */ } });
|
|
615
|
-
ws.on('error', () => { try { up.terminate(); } catch { /* ignore */ } });
|
|
616
|
-
up.on('close', () => { try { ws.close(); } catch { /* ignore */ } });
|
|
647
|
+
ws.on('close', (code) => { if (mux) closeMux(code === 1006); else { try { up.close(); } catch { /* ignore */ } } });
|
|
648
|
+
ws.on('error', () => { if (mux) closeMux(true); else { try { up.terminate(); } catch { /* ignore */ } } });
|
|
649
|
+
up.on('close', (code) => { if (mux) closeMux(code === 1006); else { try { ws.close(); } catch { /* ignore */ } } });
|
|
617
650
|
});
|
|
618
651
|
});
|
|
619
652
|
|
|
@@ -625,6 +658,7 @@ function createLanProxy(opts) {
|
|
|
625
658
|
return;
|
|
626
659
|
}
|
|
627
660
|
log(`ws 上游中断:${code}`);
|
|
661
|
+
if (mux && closeMux) { closeMux(true); return; }
|
|
628
662
|
// 上游已经出局,暂存再没有去处。
|
|
629
663
|
dropPending();
|
|
630
664
|
if (phoneWs && phoneWs.readyState === WebSocket.OPEN) {
|
|
@@ -763,8 +797,8 @@ function createLanProxy(opts) {
|
|
|
763
797
|
pairThrottle.noteSuccess();
|
|
764
798
|
// 新签发的是每设备凭据本身,它同时当 Bearer、cookie 与 deviceCredential
|
|
765
799
|
// (§3.2)。旁路子进程里这一步要打到主进程(唯一写方,§3.7)。
|
|
766
|
-
//
|
|
767
|
-
return Promise.resolve(issueCredential(device, { ...(issuedExtra || {}), permissions: permissions.permissionsForTier(
|
|
800
|
+
// 权限位一律全权(档位已移除),与中转那条配对入口同一口径。
|
|
801
|
+
return Promise.resolve(issueCredential(device, { ...(issuedExtra || {}), permissions: permissions.permissionsForTier('full') })).then((issued) => {
|
|
768
802
|
const credentialValue = issued.credential;
|
|
769
803
|
// 只有明文老路才用 Set-Cookie 下发凭据;协议 v2 的加密回包已经把
|
|
770
804
|
// token / cookie 放进密文 body,再加一条明文 Set-Cookie 等于把一枚
|
|
@@ -794,7 +828,7 @@ function createLanProxy(opts) {
|
|
|
794
828
|
...(v6Candidates.length ? { ipv6Candidates: v6Candidates } : {}),
|
|
795
829
|
deviceId: issued.deviceId,
|
|
796
830
|
deviceCredential: issued.credential,
|
|
797
|
-
permissions: Array.isArray(issued.permissions) ? issued.permissions : permissions.permissionsForTier(
|
|
831
|
+
permissions: Array.isArray(issued.permissions) ? issued.permissions : permissions.permissionsForTier('full'),
|
|
798
832
|
credentialExpiresAt: issued.expiresAt,
|
|
799
833
|
// 宿主自己的系统标识,不是手机的。手机把它存进设备记录,
|
|
800
834
|
// 好让设备行在第一次 status 轮询之前就画得出图标。
|
|
@@ -901,7 +935,8 @@ function createLanProxy(opts) {
|
|
|
901
935
|
}
|
|
902
936
|
server.once('error', onError)
|
|
903
937
|
server.once('listening', onListening)
|
|
904
|
-
server.listen(port, '0.0.0.0')
|
|
938
|
+
if (ipv4Enabled) server.listen(port, '0.0.0.0')
|
|
939
|
+
else server.listen({ port, host: '::', ipv6Only: true })
|
|
905
940
|
})
|
|
906
941
|
|
|
907
942
|
/**
|
|
@@ -939,7 +974,7 @@ function createLanProxy(opts) {
|
|
|
939
974
|
}
|
|
940
975
|
});
|
|
941
976
|
|
|
942
|
-
bind(lanPort).then(async () => { await startV6(); resolve() }, reject);
|
|
977
|
+
bind(lanPort).then(async () => { if (ipv4Enabled) await startV6(); resolve() }, reject);
|
|
943
978
|
});
|
|
944
979
|
}
|
|
945
980
|
|
|
@@ -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:
|
|
89
|
-
?
|
|
90
|
-
|
|
91
|
-
.
|
|
92
|
-
|
|
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 };
|
package/lib/relay/preview.js
CHANGED
|
@@ -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) =>
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
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 }),
|
package/lib/relay/protocol.js
CHANGED
|
@@ -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,
|
|
20
|
-
registered: 0x02, // id=0
|
|
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, //
|
|
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 = {};
|