dsh-mobile-plugin 0.5.80 → 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.
- package/docs/extension-authoring.md +32 -0
- package/lib/frpc/provision.cjs +21 -17
- package/lib/frpc/runner.cjs +193 -165
- package/lib/impl.js +66 -81
- package/lib/mirror/pusher.cjs +60 -10
- package/lib/mobile/auth.js +20 -5
- package/lib/mobile/claim-identity.js +116 -0
- 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/mux.js +148 -21
- package/lib/mobile/paired-devices.js +2 -1
- package/lib/mobile/pairing.js +3 -2
- package/lib/mobile/permissions.js +2 -0
- package/lib/mobile/relay-control.js +27 -33
- 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 +17 -15
- package/lib/relay/blob-upload.cjs +103 -0
- package/lib/relay/config-store.js +81 -0
- package/lib/relay/control.js +132 -48
- package/lib/relay/core.js +34 -14
- package/lib/relay/identity-rotate.cjs +27 -0
- package/lib/relay/lan-proxy.js +71 -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/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 +25 -17
- package/lib/routes/mobile-api.js +32 -18
- 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 +15 -1
- package/lib/sidecar-facade-worker.cjs +176 -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/feedback.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
'use strict';
|
|
2
|
-
// AI
|
|
2
|
+
// AI 查清问题后直接把反馈提交到分发平台;官方回复在维护者反馈队列跟进,AI 代提的不进 App 反馈列表(2026-11-20)。
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* 给模型的「反馈」能力:用户在用插件 / App 时遇到问题,AI 先排查;真查出原因后,由 AI
|
|
@@ -8,7 +8,8 @@
|
|
|
8
8
|
* ## 两条途径
|
|
9
9
|
*
|
|
10
10
|
* - **分发平台**:公开反馈接口,与 App 里的反馈页同一个(`/api/sdk/feedback`)。插件把
|
|
11
|
-
*
|
|
11
|
+
* 当前连接的设备身份一并带上。官方回复在维护者反馈队列里跟进(`npm run feedback` 查看),
|
|
12
|
+
* 这条由 AI 代提的反馈不会出现在 App 的反馈列表里。这条本模块能真的替用户提交。
|
|
12
13
|
* - **GitHub**:插件代码本身的 bug 可以直接提 PR。这条路依赖用户自己登录 GitHub,
|
|
13
14
|
* 插件无法代提,所以只把仓库与前提写进说明,由 AI 自己判断走不走。
|
|
14
15
|
*
|
|
@@ -44,7 +45,7 @@ function feedbackChannels() {
|
|
|
44
45
|
{
|
|
45
46
|
kind: 'distribution',
|
|
46
47
|
name: 'APP 分发系统反馈',
|
|
47
|
-
description: '提交到分发平台的公开反馈接口(与 App
|
|
48
|
+
description: '提交到分发平台的公开反馈接口(与 App 里的反馈页同一个)。插件会自动带上当前连接的设备身份;官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。',
|
|
48
49
|
endpoint: `${PLATFORM_ORIGIN}${FEEDBACK_PATH}`,
|
|
49
50
|
requiresLogin: false,
|
|
50
51
|
},
|
|
@@ -150,7 +151,7 @@ async function submitFeedback(deps, content, threadKey, deviceId) {
|
|
|
150
151
|
return {
|
|
151
152
|
threadKey: key,
|
|
152
153
|
message: key
|
|
153
|
-
? `已提交到分发平台,反馈线程 ${key}
|
|
154
|
+
? `已提交到分发平台,反馈线程 ${key}。官方回复在维护者反馈队列里跟进(npm run feedback 查看),这条由 AI 代提的反馈不会出现在 App 的反馈列表里。`
|
|
154
155
|
: '已提交到分发平台。',
|
|
155
156
|
};
|
|
156
157
|
}
|
|
@@ -165,7 +166,7 @@ function registerFeedbackTool(ctx, deps) {
|
|
|
165
166
|
ctx.tools.register(defineTool({
|
|
166
167
|
name: 'dsh_feedback',
|
|
167
168
|
description: 'Report a real problem with this mobile plugin or the AI-HUB app. '
|
|
168
|
-
+ 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; the
|
|
169
|
+
+ 'Feedback routes: (1) the APP distribution platform — `submit` sends the content to it, and the plugin fills in the connected device identity automatically; official replies are followed up in the maintainer feedback queue (run `npm run feedback`), and this AI-submitted feedback will not appear in the in-app feedback list. '
|
|
169
170
|
+ '(2) GitHub — code-level bugs can go to https://github.com/WNLUO/dsh-mobile-plugin as a pull request or issue, but that needs the user to be logged into GitHub and is not submitted by this tool. '
|
|
170
171
|
+ 'Use `channels` to list both routes. Only submit after you have actually found the cause: describe the problem, what you checked, and the reproduction or suggested fix.',
|
|
171
172
|
parameters: {
|
package/lib/mobile/file-read.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 按既有允许区读取文件,并将字节范围交给统一响应实现。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -14,7 +15,7 @@
|
|
|
14
15
|
* 2. 认出允许区之后的失败分开报:盘上没有 404 `missing`、不是普通文件 400 `not-a-file`、
|
|
15
16
|
* 超过 512MB 413 `too-large`。码与文案跟 `/session/file` 同一套,App 那边一套分支就够。
|
|
16
17
|
* 3. 字节流式回写,不在插件进程里缓冲。响应那一半(明文的整份 / 206 一段、协议 v2 的分块
|
|
17
|
-
* 信封,含 `offset`
|
|
18
|
+
* 信封,含 `offset` / `length` 校验与起始块序号)**直接调 `/session/file` 那一份**:两边抄一份形状
|
|
18
19
|
* 必然漂,而漂了的症状是「手机上永远下载中」或「取回来的那段解不开」,没有报错。
|
|
19
20
|
*/
|
|
20
21
|
|
|
@@ -124,7 +125,7 @@ async function resolveReadableFile(ctx, declared, sessionId) {
|
|
|
124
125
|
}
|
|
125
126
|
|
|
126
127
|
/**
|
|
127
|
-
* POST { path(绝对), sessionId? } →
|
|
128
|
+
* POST { path(绝对), sessionId?, offset?, length? } → 该文件范围的原始字节。
|
|
128
129
|
*
|
|
129
130
|
* @param {object} ctx 插件上下文
|
|
130
131
|
* @param {object} req node:http IncomingMessage
|
|
@@ -168,6 +169,7 @@ async function handleFileRead(ctx, req, res) {
|
|
|
168
169
|
size: info.size,
|
|
169
170
|
header,
|
|
170
171
|
rawOffset: body && body.offset,
|
|
172
|
+
rawLength: body && body.length,
|
|
171
173
|
});
|
|
172
174
|
}
|
|
173
175
|
|
package/lib/mobile/mux.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 将已鉴权设备的多路请求限制在移动 API,并管理心跳、响应头期限与上游生命周期。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -20,8 +21,17 @@
|
|
|
20
21
|
*/
|
|
21
22
|
|
|
22
23
|
const http = require('node:http');
|
|
24
|
+
const { performance } = require('node:perf_hooks');
|
|
23
25
|
const { StringDecoder } = require('node:string_decoder');
|
|
24
26
|
const { WebSocketServer } = require('ws');
|
|
27
|
+
const { withViaHeader } = require('../shared/via-header');
|
|
28
|
+
|
|
29
|
+
const MOBILE_PATH = /^\/api\/mobile\/v1\/[a-zA-Z0-9/_-]+(?:\?[^\r\n#]*)?$/;
|
|
30
|
+
const CONNECTION_HEADERS = new Set([
|
|
31
|
+
'authorization', 'cookie', 'x-dsh-device-credential', 'x-dsh-device', 'x-dsh-instance',
|
|
32
|
+
'x-dsh-device-name', 'x-dsh-device-model', 'x-dsh-platform', 'x-dsh-os-version',
|
|
33
|
+
'x-dsh-app-version', 'x-dsh-package-id', 'x-dsh-build-number', 'x-dsh-channel', 'x-dsh-lan-discovery',
|
|
34
|
+
]);
|
|
25
35
|
|
|
26
36
|
/** 单帧上限:与中转 `MAX_WS_MESSAGE_BYTES` / 宿主预览管道对齐(8 MiB)。 */
|
|
27
37
|
const MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
|
|
@@ -35,6 +45,9 @@ const MAX_CONNECTIONS = 32;
|
|
|
35
45
|
const SEND_HIGH_WATER_BYTES = 4 * 1024 * 1024;
|
|
36
46
|
const SEND_LOW_WATER_BYTES = 1 * 1024 * 1024;
|
|
37
47
|
const SEND_RESUME_POLL_MS = 20;
|
|
48
|
+
const REVOKE_DRAIN_TIMEOUT_MS = 5000;
|
|
49
|
+
const HEARTBEAT_INTERVAL_MS = 15_000;
|
|
50
|
+
const PONG_TIMEOUT_MS = 45_000;
|
|
38
51
|
|
|
39
52
|
/** 上游拨号超时:只覆盖「还没拿到响应头」这一段,之后是长连接,不能有读超时。 */
|
|
40
53
|
const UPSTREAM_HEADER_TIMEOUT_MS = 30_000;
|
|
@@ -42,7 +55,7 @@ const UPSTREAM_HEADER_TIMEOUT_MS = 30_000;
|
|
|
42
55
|
/** 不往上游转发的逐跳头(与隧道/预览同一口径)。 */
|
|
43
56
|
const HOP_BY_HOP = new Set([
|
|
44
57
|
'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
|
|
45
|
-
'te', 'trailer', 'transfer-encoding', 'upgrade', 'host',
|
|
58
|
+
'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
|
|
46
59
|
]);
|
|
47
60
|
|
|
48
61
|
function safeJson(text) {
|
|
@@ -53,7 +66,7 @@ function safeJson(text) {
|
|
|
53
66
|
* 建一个 mux 服务。
|
|
54
67
|
*
|
|
55
68
|
* @param {object} opts
|
|
56
|
-
* @param {{host?:string, port:number}} opts.upstream 本地移动 API 地址(一般 `127.0.0.1:<webPort>`)。
|
|
69
|
+
* @param {{host?:string, port:number, agent?:import('node:http').Agent}} opts.upstream 本地移动 API 地址(一般 `127.0.0.1:<webPort>`)。
|
|
57
70
|
* @param {(req: import('node:http').IncomingMessage) => boolean} opts.authorize 握手鉴权。
|
|
58
71
|
* @param {(msg: string) => void} [opts.onLog]
|
|
59
72
|
*/
|
|
@@ -65,6 +78,7 @@ function createMuxService(opts = {}) {
|
|
|
65
78
|
|
|
66
79
|
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
|
|
67
80
|
let connectionCount = 0;
|
|
81
|
+
const deviceConnections = new Map();
|
|
68
82
|
|
|
69
83
|
/**
|
|
70
84
|
* 宿主 webServer 的升级处理器(`ctx.webServer.registerUpgrade`)。
|
|
@@ -85,28 +99,60 @@ function createMuxService(opts = {}) {
|
|
|
85
99
|
try { socket.destroy(); } catch { /* ignore */ }
|
|
86
100
|
return;
|
|
87
101
|
}
|
|
88
|
-
|
|
102
|
+
const trustedHeaders = {};
|
|
103
|
+
for (const [name, value] of Object.entries(req.headers || {})) {
|
|
104
|
+
const key = name.toLowerCase();
|
|
105
|
+
if (CONNECTION_HEADERS.has(key)) trustedHeaders[key] = value;
|
|
106
|
+
}
|
|
107
|
+
wss.handleUpgrade(req, socket, head, (ws) => openConnection(ws, req, trustedHeaders));
|
|
89
108
|
}
|
|
90
109
|
|
|
91
|
-
function openConnection(ws) {
|
|
110
|
+
function openConnection(ws, upgradeReq, trustedHeaders) {
|
|
92
111
|
connectionCount += 1;
|
|
112
|
+
const identity = { deviceId: upgradeReq.__dshRecord?.deviceId || '', instanceId: upgradeReq.__dshRecord?.instanceId || '' };
|
|
113
|
+
deviceConnections.set(ws, identity);
|
|
93
114
|
/** id → 一条在飞的本地请求。 */
|
|
94
115
|
const streams = new Map();
|
|
95
116
|
let closed = false;
|
|
117
|
+
let revoking = false;
|
|
118
|
+
let gracefulId = null;
|
|
119
|
+
let closeTimer = null;
|
|
120
|
+
let drainPoll = null;
|
|
121
|
+
let finishDrain = null;
|
|
122
|
+
let lastPong = performance.now();
|
|
123
|
+
let heartbeatTimer = null;
|
|
96
124
|
|
|
97
|
-
const send = (obj) => {
|
|
98
|
-
if (closed || ws.readyState !== 1 /* OPEN */) return;
|
|
99
|
-
try { ws.send(JSON.stringify(obj)); } catch {
|
|
125
|
+
const send = (obj, callback) => {
|
|
126
|
+
if (closed || ws.readyState !== 1 /* OPEN */) { callback?.(new Error('mux closed')); return; }
|
|
127
|
+
try { ws.send(JSON.stringify(obj), callback); } catch (error) { callback?.(error); }
|
|
128
|
+
};
|
|
129
|
+
const closeAfterDrain = () => {
|
|
130
|
+
if (closed) return;
|
|
131
|
+
if (ws.bufferedAmount > 0) { drainPoll = setTimeout(closeAfterDrain, SEND_RESUME_POLL_MS); return; }
|
|
132
|
+
try { ws.close(1000, 'device revoked'); } catch { ws.terminate(); }
|
|
100
133
|
};
|
|
101
134
|
const fail = (id, message) => send({ t: 'err', id, message: String(message || 'error') });
|
|
102
135
|
|
|
136
|
+
const releaseUpstreamSocket = (entry) => {
|
|
137
|
+
if (entry.activeUpstreamSocket && entry.onUpstreamSocketClose) entry.activeUpstreamSocket.off('close', entry.onUpstreamSocketClose);
|
|
138
|
+
entry.activeUpstreamSocket = null;
|
|
139
|
+
entry.onUpstreamSocketClose = null;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const clearHeaderTimer = (entry) => {
|
|
143
|
+
clearTimeout(entry.headerTimer);
|
|
144
|
+
entry.headerTimer = null;
|
|
145
|
+
};
|
|
146
|
+
|
|
103
147
|
/** 收掉一条逻辑流:销毁上游请求、释放槽位。 */
|
|
104
148
|
const dropStream = (id, reason) => {
|
|
105
149
|
const entry = streams.get(id);
|
|
106
150
|
if (!entry) return;
|
|
107
151
|
streams.delete(id);
|
|
152
|
+
clearHeaderTimer(entry);
|
|
108
153
|
if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
|
|
109
|
-
|
|
154
|
+
releaseUpstreamSocket(entry);
|
|
155
|
+
try { if (!entry.responseEnded) entry.req?.destroy(); } catch { /* ignore */ }
|
|
110
156
|
if (reason) fail(id, reason);
|
|
111
157
|
};
|
|
112
158
|
|
|
@@ -123,24 +169,34 @@ function createMuxService(opts = {}) {
|
|
|
123
169
|
|
|
124
170
|
const startRequest = (frame) => {
|
|
125
171
|
const id = frame.id;
|
|
126
|
-
if (typeof id !== 'number') return;
|
|
172
|
+
if (typeof id !== 'number' || revoking) return;
|
|
127
173
|
if (streams.has(id)) { fail(id, 'duplicate id'); return; }
|
|
128
174
|
if (streams.size >= MAX_STREAMS_PER_CONNECTION) { fail(id, 'too many streams'); return; }
|
|
129
175
|
const method = String(frame.method || 'GET').toUpperCase();
|
|
130
|
-
const path = typeof frame.path === 'string'
|
|
131
|
-
|
|
176
|
+
const path = typeof frame.path === 'string' ? frame.path : '';
|
|
177
|
+
if (!MOBILE_PATH.test(path)) { fail(id, 'mobile API path required'); return; }
|
|
178
|
+
const forwarded = {};
|
|
132
179
|
if (frame.headers && typeof frame.headers === 'object') {
|
|
133
180
|
for (const [k, v] of Object.entries(frame.headers)) {
|
|
134
|
-
if (!k || HOP_BY_HOP.has(k.toLowerCase())) continue;
|
|
135
|
-
|
|
181
|
+
if (!k || HOP_BY_HOP.has(k.toLowerCase()) || CONNECTION_HEADERS.has(k.toLowerCase())) continue;
|
|
182
|
+
forwarded[k.toLowerCase()] = v;
|
|
136
183
|
}
|
|
137
184
|
}
|
|
138
|
-
const
|
|
185
|
+
const headers = withViaHeader({ ...forwarded, ...trustedHeaders }, 'mux', `${upstreamHost}:${upstreamPort}`);
|
|
186
|
+
// 正文由bodyEnd结束,所有方法都交给Node分块,GET/HEAD也不能退化成裸字节追加。
|
|
187
|
+
headers['transfer-encoding'] = 'chunked';
|
|
188
|
+
const entry = { req: null, res: null, activeUpstreamSocket: null, onUpstreamSocketClose: null, responseEnded: false, paused: false, resumeTimer: null, headerTimer: null, decoder: new StringDecoder('utf8') };
|
|
139
189
|
streams.set(id, entry);
|
|
190
|
+
const headerTimer = setTimeout(() => {
|
|
191
|
+
if (entry.headerTimer === headerTimer && !closed && streams.get(id) === entry && !entry.res) dropStream(id, 'upstream header timeout');
|
|
192
|
+
}, UPSTREAM_HEADER_TIMEOUT_MS);
|
|
193
|
+
entry.headerTimer = headerTimer;
|
|
194
|
+
headerTimer.unref?.();
|
|
140
195
|
|
|
141
196
|
let req;
|
|
142
197
|
try {
|
|
143
|
-
req = http.request({ host: upstreamHost, port: upstreamPort, method, path, headers }, (res) => {
|
|
198
|
+
req = http.request({ host: upstreamHost, port: upstreamPort, method, path, headers, ...(opts.upstream?.agent ? { agent: opts.upstream.agent } : {}) }, (res) => {
|
|
199
|
+
clearHeaderTimer(entry);
|
|
144
200
|
if (closed || streams.get(id) !== entry) { res.destroy(); return; }
|
|
145
201
|
entry.res = res;
|
|
146
202
|
const respHeaders = {};
|
|
@@ -162,10 +218,18 @@ function createMuxService(opts = {}) {
|
|
|
162
218
|
});
|
|
163
219
|
res.on('end', () => {
|
|
164
220
|
if (streams.get(id) !== entry) return;
|
|
165
|
-
|
|
221
|
+
entry.responseEnded = true;
|
|
222
|
+
releaseUpstreamSocket(entry);
|
|
223
|
+
entry.req = null;
|
|
166
224
|
const rest = entry.decoder.end();
|
|
167
225
|
if (rest) send({ t: 'chunk', id, text: rest });
|
|
168
|
-
send({ t: 'end', id })
|
|
226
|
+
send({ t: 'end', id }, (error) => {
|
|
227
|
+
if (streams.get(id) === entry) streams.delete(id);
|
|
228
|
+
if (revoking && gracefulId === id) {
|
|
229
|
+
if (error) ws.terminate();
|
|
230
|
+
else closeAfterDrain();
|
|
231
|
+
}
|
|
232
|
+
});
|
|
169
233
|
});
|
|
170
234
|
res.on('error', () => { if (streams.get(id) === entry) dropStream(id, 'upstream response error'); });
|
|
171
235
|
});
|
|
@@ -174,7 +238,13 @@ function createMuxService(opts = {}) {
|
|
|
174
238
|
return;
|
|
175
239
|
}
|
|
176
240
|
entry.req = req;
|
|
177
|
-
req.
|
|
241
|
+
req.on('socket', (socket) => {
|
|
242
|
+
if (closed || streams.get(id) !== entry || entry.responseEnded || req.destroyed || socket.destroyed) return;
|
|
243
|
+
releaseUpstreamSocket(entry);
|
|
244
|
+
entry.activeUpstreamSocket = socket;
|
|
245
|
+
entry.onUpstreamSocketClose = () => releaseUpstreamSocket(entry);
|
|
246
|
+
socket.once('close', entry.onUpstreamSocketClose);
|
|
247
|
+
});
|
|
178
248
|
req.on('error', (error) => { if (streams.get(id) === entry) dropStream(id, error && error.message ? error.message : 'upstream error'); });
|
|
179
249
|
if (frame.body !== undefined && frame.body !== null) {
|
|
180
250
|
if (typeof frame.body !== 'string') { dropStream(id, 'bad body'); return; }
|
|
@@ -184,6 +254,7 @@ function createMuxService(opts = {}) {
|
|
|
184
254
|
|
|
185
255
|
const onFrame = (frame) => {
|
|
186
256
|
if (!frame || typeof frame !== 'object') return;
|
|
257
|
+
if (revoking && (frame.id !== gracefulId || !['body', 'bodyEnd'].includes(frame.t))) return;
|
|
187
258
|
switch (frame.t) {
|
|
188
259
|
case 'req': startRequest(frame); break;
|
|
189
260
|
case 'body': {
|
|
@@ -207,16 +278,58 @@ function createMuxService(opts = {}) {
|
|
|
207
278
|
const cleanup = () => {
|
|
208
279
|
if (closed) return;
|
|
209
280
|
closed = true;
|
|
281
|
+
clearInterval(heartbeatTimer);
|
|
282
|
+
heartbeatTimer = null;
|
|
283
|
+
clearTimeout(closeTimer);
|
|
284
|
+
clearTimeout(drainPoll);
|
|
285
|
+
finishDrain?.();
|
|
286
|
+
deviceConnections.delete(ws);
|
|
210
287
|
connectionCount -= 1;
|
|
211
288
|
for (const entry of streams.values()) {
|
|
289
|
+
clearHeaderTimer(entry);
|
|
212
290
|
if (entry.resumeTimer) clearTimeout(entry.resumeTimer);
|
|
291
|
+
releaseUpstreamSocket(entry);
|
|
213
292
|
try { entry.req && entry.req.destroy(); } catch { /* ignore */ }
|
|
214
293
|
}
|
|
215
294
|
streams.clear();
|
|
216
295
|
};
|
|
217
296
|
|
|
297
|
+
heartbeatTimer = setInterval(() => {
|
|
298
|
+
if (closed || revoking) return;
|
|
299
|
+
if (ws.readyState !== 1 || performance.now() - lastPong >= PONG_TIMEOUT_MS) {
|
|
300
|
+
cleanup();
|
|
301
|
+
try { ws.terminate(); } catch { /* 已关闭 */ }
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
try { ws.ping(); } catch {
|
|
305
|
+
cleanup();
|
|
306
|
+
try { ws.terminate(); } catch { /* 已关闭 */ }
|
|
307
|
+
}
|
|
308
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
309
|
+
heartbeatTimer.unref?.();
|
|
310
|
+
ws.on('pong', () => { if (!closed) lastPong = performance.now(); });
|
|
311
|
+
|
|
312
|
+
identity.revoke = (response) => {
|
|
313
|
+
const socket = response?.socket;
|
|
314
|
+
const owner = socket && !socket.destroyed && [...streams].find(([, entry]) => {
|
|
315
|
+
const upstream = entry.activeUpstreamSocket;
|
|
316
|
+
return !entry.responseEnded && entry.req && !entry.req.destroyed && upstream && !upstream.destroyed
|
|
317
|
+
&& upstream.localPort === socket.remotePort && upstream.remotePort === socket.localPort;
|
|
318
|
+
});
|
|
319
|
+
if (!owner) { ws.terminate(); return; }
|
|
320
|
+
revoking = true;
|
|
321
|
+
clearInterval(heartbeatTimer);
|
|
322
|
+
heartbeatTimer = null;
|
|
323
|
+
clearHeaderTimer(owner[1]);
|
|
324
|
+
gracefulId = owner[0];
|
|
325
|
+
response.__dshMuxDrained = new Promise(resolve => { finishDrain = resolve; });
|
|
326
|
+
closeTimer = setTimeout(() => { try { ws.terminate(); } catch { /* 已关闭 */ } }, REVOKE_DRAIN_TIMEOUT_MS);
|
|
327
|
+
closeTimer.unref?.();
|
|
328
|
+
for (const id of [...streams.keys()]) if (id !== gracefulId) dropStream(id);
|
|
329
|
+
};
|
|
330
|
+
|
|
218
331
|
ws.on('message', (data, isBinary) => {
|
|
219
|
-
if (isBinary) return; // 契约只走 JSON 文本帧
|
|
332
|
+
if (closed || isBinary) return; // 契约只走 JSON 文本帧
|
|
220
333
|
const frame = safeJson(data.toString('utf8'));
|
|
221
334
|
if (!frame) { onLog('mux: bad json frame'); return; }
|
|
222
335
|
onFrame(frame);
|
|
@@ -225,7 +338,21 @@ function createMuxService(opts = {}) {
|
|
|
225
338
|
ws.on('error', cleanup);
|
|
226
339
|
}
|
|
227
340
|
|
|
228
|
-
|
|
341
|
+
const dropConnections = (deviceId, instanceId, response) => {
|
|
342
|
+
let count = 0;
|
|
343
|
+
for (const [ws, identity] of deviceConnections) {
|
|
344
|
+
if (instanceId !== undefined && identity.instanceId !== String(instanceId || '')) continue;
|
|
345
|
+
if (deviceId !== undefined && identity.deviceId !== deviceId) continue;
|
|
346
|
+
deviceConnections.delete(ws);
|
|
347
|
+
if (ws.readyState === 3) continue;
|
|
348
|
+
count += 1;
|
|
349
|
+
try { identity.revoke(response); } catch { ws.terminate(); }
|
|
350
|
+
}
|
|
351
|
+
return count;
|
|
352
|
+
};
|
|
353
|
+
const dropDevice = (deviceId, instanceId, response) => dropConnections(deviceId, instanceId, response);
|
|
354
|
+
const dropAll = (instanceId, response) => dropConnections(undefined, instanceId, response);
|
|
355
|
+
return { handleUpgrade, dropDevice, dropAll, MAX_MESSAGE_BYTES };
|
|
229
356
|
}
|
|
230
357
|
|
|
231
|
-
module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS };
|
|
358
|
+
module.exports = { createMuxService, MAX_MESSAGE_BYTES, MAX_STREAMS_PER_CONNECTION, MAX_CONNECTIONS, REVOKE_DRAIN_TIMEOUT_MS };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 展示本实例设备,并在吊销回执写完后关闭选中的在途连接。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -167,7 +168,7 @@ async function handlePairedDevicesRevoke(req, res, deps) {
|
|
|
167
168
|
}
|
|
168
169
|
let closed = 0;
|
|
169
170
|
try {
|
|
170
|
-
closed = typeof deps.dropDeviceStreams === 'function' ? deps.dropDeviceStreams(deviceId) : 0;
|
|
171
|
+
closed = typeof deps.dropDeviceStreams === 'function' ? deps.dropDeviceStreams(deviceId, res) : 0;
|
|
171
172
|
} catch { /* 尽力:断流失败不影响吊销已经落地 */ }
|
|
172
173
|
return sendJson(res, 200, { ok: true, revoked, closed });
|
|
173
174
|
}
|
package/lib/mobile/pairing.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 签发配对凭据,并发布与局域网开关独立的 IPv6 直连候选。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -294,12 +295,12 @@ function createPairHandler(deps) {
|
|
|
294
295
|
// 二维码,这是手机拿到内网地址的唯一机会。回家后那个公网地址若打不通(路由器不支持
|
|
295
296
|
// 回环 / 域名只在外网解析),手机可以靠这批候选找到这台机器,否则只能删设备重配。
|
|
296
297
|
// 语义与 `/connection-info` 那份一致(`advertisedCandidates`:有私网只给私网),
|
|
297
|
-
//
|
|
298
|
+
// 关闭局域网只隐藏 IPv4,独立的 IPv6 监听仍可作为直连候选。
|
|
298
299
|
const port = typeof lanPort === 'function' ? lanPort() : state.lanPort
|
|
299
300
|
const directCandidates = state.lanEnabled && typeof lanCandidates === 'function'
|
|
300
301
|
? lanCandidates(port).map((candidate) => candidate.url).filter(Boolean)
|
|
301
302
|
: []
|
|
302
|
-
const v6Candidates =
|
|
303
|
+
const v6Candidates = port > 0 && typeof ipv6Candidates === 'function'
|
|
303
304
|
? ipv6Candidates(port).map((candidate) => candidate.url).filter(Boolean)
|
|
304
305
|
: []
|
|
305
306
|
// 历史 blob 的实例密钥(HK):只在封包(协议 v2)这条路上产生与下发。明文老路没有
|
|
@@ -129,6 +129,8 @@ const BASE = Object.freeze([
|
|
|
129
129
|
'/api/mobile/v1/notification-prefs',
|
|
130
130
|
'/api/mobile/v1/device-credential/revoke',
|
|
131
131
|
'/api/mobile/v1/device-credential/upgrade',
|
|
132
|
+
// 换身份过渡期:用旧号下的凭据换当前号的新凭据,属于「自愈」,任何已鉴权设备都能调。
|
|
133
|
+
'/api/mobile/v1/device-credential/sync-identity',
|
|
132
134
|
// 手机自助降档:任何已鉴权设备都能把自己的权限往下收 —— 收窄动作本身不该被收窄挡住。
|
|
133
135
|
'/api/mobile/v1/device-credential/permissions',
|
|
134
136
|
]);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 既有中转配置复用有界健康判据与出网诊断,保留本实例吊销回执收尾。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -19,11 +20,13 @@
|
|
|
19
20
|
*/
|
|
20
21
|
|
|
21
22
|
const { randomBytes } = require('node:crypto');
|
|
23
|
+
const { afterResponse: afterResponseFinished } = require('../shared/fresh-request.js');
|
|
22
24
|
|
|
23
25
|
const core = require('../relay/core.js');
|
|
24
26
|
const pairingApproval = require('../relay/pairing-policy.js');
|
|
25
27
|
const applyLedger = require('../relay/apply-ledger.cjs');
|
|
26
28
|
const { probeInstanceId, verifyRelayRegistration } = require('../relay/verify.js');
|
|
29
|
+
const { probeRelayHealth, relayFailureMessage } = require('../relay/relay-probe.js');
|
|
27
30
|
const { canListen } = require('../relay/port-allocator.cjs');
|
|
28
31
|
const { lanCandidates, publicCandidates, ipv6Candidates, withManualIpv6Candidate } = require('../relay/lan-network.cjs');
|
|
29
32
|
const { sendJson, readJsonBody } = require('../shared/http-util');
|
|
@@ -196,6 +199,8 @@ function createRelayControlHandlers(deps) {
|
|
|
196
199
|
restartSidecar = null,
|
|
197
200
|
getSidecar = null,
|
|
198
201
|
credentials = null,
|
|
202
|
+
dropDeviceStreams = () => 0,
|
|
203
|
+
dropAllDeviceStreams = () => 0,
|
|
199
204
|
activeGuard = () => null,
|
|
200
205
|
probeUrls = null,
|
|
201
206
|
verifyRelay = null,
|
|
@@ -318,19 +323,9 @@ function createRelayControlHandlers(deps) {
|
|
|
318
323
|
};
|
|
319
324
|
}
|
|
320
325
|
|
|
321
|
-
/**
|
|
326
|
+
/** 手机代测复用宿主健康判据、正文上限与覆盖完整响应的总预算。 */
|
|
322
327
|
async function probeOne(url) {
|
|
323
|
-
|
|
324
|
-
try {
|
|
325
|
-
const controller = new AbortController();
|
|
326
|
-
const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
|
|
327
|
-
const response = await fetch(`${url}/healthz`, { signal: controller.signal, redirect: 'follow' });
|
|
328
|
-
clearTimeout(timer);
|
|
329
|
-
await response.text().catch(() => '');
|
|
330
|
-
return { url, ms: response.ok ? Date.now() - started : null };
|
|
331
|
-
} catch {
|
|
332
|
-
return { url, ms: null };
|
|
333
|
-
}
|
|
328
|
+
return { url, ms: await probeRelayHealth(url, { timeoutMs: PROBE_TIMEOUT_MS }) };
|
|
334
329
|
}
|
|
335
330
|
|
|
336
331
|
/**
|
|
@@ -532,11 +527,21 @@ function createRelayControlHandlers(deps) {
|
|
|
532
527
|
error: { code: 'confirm-required', message: '吊销全部授权不可撤销,请求需要带 confirm: true' },
|
|
533
528
|
});
|
|
534
529
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
530
|
+
const deviceIds = [...new Set((credentials?.listDevices?.(state.instanceId) || []).map(device => device.deviceId).filter(Boolean))];
|
|
531
|
+
let localRevoked = 0;
|
|
532
|
+
try {
|
|
533
|
+
localRevoked = credentials && typeof credentials.revokeAllByInstance === 'function'
|
|
534
|
+
? credentials.revokeAllByInstance(state.instanceId)
|
|
535
|
+
: 0;
|
|
536
|
+
state.lanSecret = randomBytes(32).toString('hex');
|
|
537
|
+
core.rotatePairing(state);
|
|
538
|
+
core.saveState(state);
|
|
539
|
+
} catch (error) {
|
|
540
|
+
console.warn('[dsh-mobile-plugin] [relay-control] 吊销后收尾失败:', String(error?.message || error));
|
|
541
|
+
}
|
|
542
|
+
for (const deviceId of deviceIds) dropDeviceStreams(deviceId, res);
|
|
543
|
+
dropAllDeviceStreams(res);
|
|
544
|
+
afterResponseFinished(res, async () => {
|
|
540
545
|
let revoked = 0;
|
|
541
546
|
try {
|
|
542
547
|
const sidecar = typeof getSidecar === 'function' ? getSidecar() : null;
|
|
@@ -544,22 +549,11 @@ function createRelayControlHandlers(deps) {
|
|
|
544
549
|
const result = await sidecar.request('/revoke-all', 'POST', undefined, 20_000);
|
|
545
550
|
revoked = Number(result && result.revoked) || 0;
|
|
546
551
|
}
|
|
547
|
-
} catch { /*
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
? credentials.revokeAllByInstance(state.instanceId)
|
|
551
|
-
: 0;
|
|
552
|
-
state.lanSecret = randomBytes(32).toString('hex');
|
|
553
|
-
// 换码的同时换票据(`core.rotatePairing` 一次换码换票):只换码的话,截图里旧二维码
|
|
554
|
-
// 的票据还能再配一台新设备进来。
|
|
555
|
-
core.rotatePairing(state);
|
|
556
|
-
core.saveState(state);
|
|
557
|
-
console.warn(`[dsh-mobile-plugin] [relay-control] 已吊销全部授权:中转 ${revoked}、本机 ${localRevoked}`);
|
|
558
|
-
await syncSidecar().catch(() => undefined);
|
|
559
|
-
} catch (error) {
|
|
560
|
-
console.warn('[dsh-mobile-plugin] [relay-control] 吊销后收尾失败:', String(error?.message || error));
|
|
561
|
-
}
|
|
552
|
+
} catch { /* 中转不可达不影响本机凭据与连接已经失效 */ }
|
|
553
|
+
console.warn(`[dsh-mobile-plugin] [relay-control] 已吊销全部授权:中转 ${revoked}、本机 ${localRevoked}`);
|
|
554
|
+
await syncSidecar().catch(() => undefined);
|
|
562
555
|
});
|
|
556
|
+
sendJson(res, 200, { ok: true, started: true });
|
|
563
557
|
}
|
|
564
558
|
|
|
565
559
|
/** `POST /api/mobile/v1/relay/reconnect` —— 让旁路重读配置并重建隧道。 */
|
|
@@ -687,7 +681,7 @@ function createRelayControlHandlers(deps) {
|
|
|
687
681
|
adjusted: typeof getLanPortAdjusted === 'function' ? getLanPortAdjusted() === true : false,
|
|
688
682
|
},
|
|
689
683
|
/** 隧道为什么被拒那几条判断(宿主那边按中转错误文案推出来的)。 */
|
|
690
|
-
tunnel: snapshot?.tunnel
|
|
684
|
+
tunnel: snapshot?.tunnel ? { ...snapshot.tunnel, ...(snapshot.tunnel.error ? { error: relayFailureMessage(snapshot.tunnel.error) } : {}) } : null,
|
|
691
685
|
/** 这台电脑上跑着的插件与宿主:版本、平台、网页端口,报障时对方第一句就会问这些。 */
|
|
692
686
|
host: {
|
|
693
687
|
plugin: text(snapshot?.appVersion),
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
// 定向读取轮次变更,在连接取消时终止分页历史扫描。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/** 按需读取某轮的已证实前后文本,只读会话事件/直播副本,不读工作区或 Git。 */
|
|
4
5
|
const { sendJson } = require('../shared/http-util');
|
|
5
6
|
const { callSessions } = require('./rpc.js');
|
|
7
|
+
const { requestSignal } = require('../shared/fresh-request');
|
|
6
8
|
const { unwrap } = require('./envelope.js');
|
|
7
9
|
const { foldTurnFacts, turnChangesSnapshot } = require('./turn-facts.js');
|
|
8
10
|
const { liveTurnChangesOf } = require('./live-steps.js');
|
|
@@ -27,10 +29,12 @@ async function readTurnEvents(ctx, sessionId, wantedTurn, address = {}, signal,
|
|
|
27
29
|
let beforeSeq;
|
|
28
30
|
let turn = wantedTurn;
|
|
29
31
|
for (let page = 0; page < maxPages; page += 1) {
|
|
32
|
+
if (signal?.aborted) throw Object.assign(new Error('请求已中断'), { code: 'aborted' });
|
|
30
33
|
const { value, error } = unwrap(await callSessions(ctx, 'history', {
|
|
31
34
|
sessionId, ...address, maxMessages: HISTORY_MESSAGES,
|
|
32
35
|
...(beforeSeq !== undefined ? { beforeSeq } : {}),
|
|
33
36
|
}, 'mobile', signal));
|
|
37
|
+
if (signal?.aborted) throw Object.assign(new Error('请求已中断'), { code: 'aborted' });
|
|
34
38
|
if (error) throw error;
|
|
35
39
|
const entries = value && Array.isArray(value.events) ? value.events : [];
|
|
36
40
|
const batch = entries.map((entry) => entry && entry.event ? entry.event : entry).filter(Boolean)
|
|
@@ -68,9 +72,10 @@ async function handleSessionChanges(ctx, req, res) {
|
|
|
68
72
|
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '子代理会话需要 parentSessionId 和有效 mode' } });
|
|
69
73
|
}
|
|
70
74
|
const address = hasAddress ? { parentSessionId, mode } : {};
|
|
71
|
-
const
|
|
75
|
+
const signal = requestSignal(res);
|
|
72
76
|
try {
|
|
73
|
-
const history = await readTurnEvents(ctx, sessionId, turn, address,
|
|
77
|
+
const history = await readTurnEvents(ctx, sessionId, turn, address, signal);
|
|
78
|
+
if (signal.aborted) return;
|
|
74
79
|
const facts = foldTurnFacts(history.events).get(turn);
|
|
75
80
|
const live = liveTurnChangesOf(ctx, sessionId, turn, history.events);
|
|
76
81
|
const details = live || (facts ? turnChangesSnapshot(facts) : { files: [] });
|
|
@@ -79,6 +84,7 @@ async function handleSessionChanges(ctx, req, res) {
|
|
|
79
84
|
...(history.truncated ? { truncated: true } : {}),
|
|
80
85
|
});
|
|
81
86
|
} catch (error) {
|
|
87
|
+
if (signal.aborted) return;
|
|
82
88
|
const normalized = {
|
|
83
89
|
code: error && typeof error.code === 'string' ? error.code : 'host-call-failed',
|
|
84
90
|
message: error && typeof error.message === 'string' && error.message ? error.message : '读取这一轮的改动失败',
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 按投递标识回查历史,并随客户端断开取消宿主扫描。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -23,6 +24,7 @@
|
|
|
23
24
|
const { sendJson } = require('../shared/http-util');
|
|
24
25
|
const { unwrap } = require('./envelope.js');
|
|
25
26
|
const { callSessions } = require('./rpc.js');
|
|
27
|
+
const { requestSignal } = require('../shared/fresh-request');
|
|
26
28
|
const { deriveMessages } = require('./history-derive.js');
|
|
27
29
|
|
|
28
30
|
/** 一次回查读多少条事件:发件箱的条目只可能出现在最近这几天。 */
|
|
@@ -44,7 +46,9 @@ async function handleSessionDelivery(ctx, req, res) {
|
|
|
44
46
|
if (!sessionId || !clientMessageId || sessionId.length > PARAM_MAX || clientMessageId.length > PARAM_MAX) {
|
|
45
47
|
return sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: '需要 { sessionId, clientMessageId }' } });
|
|
46
48
|
}
|
|
47
|
-
const
|
|
49
|
+
const signal = requestSignal(res);
|
|
50
|
+
const { value, error } = unwrap(await callSessions(ctx, 'history', { sessionId, maxMessages: DELIVERY_HISTORY_WINDOW }, 'mobile', signal));
|
|
51
|
+
if (signal.aborted) return;
|
|
48
52
|
if (error) {
|
|
49
53
|
const missing = error.code === 'session-not-found';
|
|
50
54
|
return sendJson(res, missing ? 404 : 502, {
|