dsh-mobile-ios 0.2.16 → 0.2.18
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/LICENSE +21 -21
- package/README.md +311 -284
- package/cordis.patch.yml +20 -20
- package/entries/plugin.mjs +197 -223
- package/entries/sidecar.mjs +92 -111
- package/lib/client.js +1754 -1621
- package/lib/vendor/qrcode-generator.cjs +2297 -2297
- package/lib/vendor/qrcode-utf8.cjs +26 -26
- package/package.json +3 -2
- package/src/adapter/artifacts.mjs +235 -235
- package/src/adapter/cordis-host.mjs +1444 -1225
- package/src/adapter/mock-host.mjs +498 -430
- package/src/adapter/mux-host.mjs +99 -99
- package/src/adapter/session-history.mjs +241 -241
- package/src/cloudflare.mjs +735 -698
- package/src/dns-label.mjs +32 -32
- package/src/dns-probe.mjs +110 -110
- package/src/file-log.mjs +68 -68
- package/src/gateway.mjs +285 -285
- package/src/host-name.mjs +42 -0
- package/src/pairing.mjs +300 -300
- package/src/protocol.mjs +59 -59
- package/src/provision-local.mjs +883 -560
- package/src/provision-select.mjs +105 -0
- package/src/rest.mjs +958 -894
- package/src/ring.mjs +148 -148
- package/src/server.mjs +246 -246
- package/src/tunnel-error.mjs +91 -0
- package/src/tunnel-state.mjs +122 -0
- package/src/tunnel.mjs +544 -544
- package/src/version.mjs +24 -24
- package/src/ws.mjs +332 -332
- package/src/zone-health.mjs +430 -251
package/src/ws.mjs
CHANGED
|
@@ -1,332 +1,332 @@
|
|
|
1
|
-
// ws.mjs — WS 传输层(RFC6455 最小子集 + ticket 鉴权 + 握手泵)
|
|
2
|
-
// 安全要点(ADR-13):一次性 ticket 走 Sec-WebSocket-Protocol,不进 URL query——
|
|
3
|
-
// query 会落到反向代理日志与崩溃上报里。
|
|
4
|
-
|
|
5
|
-
import crypto from 'node:crypto';
|
|
6
|
-
import { fail } from './protocol.mjs';
|
|
7
|
-
|
|
8
|
-
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
9
|
-
const OP_TEXT = 0x1;
|
|
10
|
-
const OP_BINARY = 0x2;
|
|
11
|
-
const OP_CLOSE = 0x8;
|
|
12
|
-
const OP_PING = 0x9;
|
|
13
|
-
const OP_PONG = 0xa;
|
|
14
|
-
const SUBPROTOCOL = 'dsh.v1';
|
|
15
|
-
const TICKET_TTL_MS = 30_000;
|
|
16
|
-
const HELLO_TIMEOUT_MS = 5_000;
|
|
17
|
-
|
|
18
|
-
const acceptKey = (key) => crypto.createHash('sha1').update(key + GUID).digest('base64');
|
|
19
|
-
|
|
20
|
-
export function encodeFrame(opcode, payload = Buffer.alloc(0)) {
|
|
21
|
-
const len = payload.length;
|
|
22
|
-
let header;
|
|
23
|
-
if (len < 126) {
|
|
24
|
-
header = Buffer.alloc(2);
|
|
25
|
-
header[1] = len;
|
|
26
|
-
} else if (len < 65536) {
|
|
27
|
-
header = Buffer.alloc(4);
|
|
28
|
-
header[1] = 126;
|
|
29
|
-
header.writeUInt16BE(len, 2);
|
|
30
|
-
} else {
|
|
31
|
-
header = Buffer.alloc(10);
|
|
32
|
-
header[1] = 127;
|
|
33
|
-
header.writeBigUInt64BE(BigInt(len), 2);
|
|
34
|
-
}
|
|
35
|
-
header[0] = 0x80 | opcode;
|
|
36
|
-
return Buffer.concat([header, payload]);
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
class FrameParser {
|
|
40
|
-
constructor(onMessage, onControl, maxFrame = 4 * 1024 * 1024) {
|
|
41
|
-
this.buf = Buffer.alloc(0);
|
|
42
|
-
this.frag = [];
|
|
43
|
-
this.onMessage = onMessage;
|
|
44
|
-
this.onControl = onControl;
|
|
45
|
-
this.maxFrame = maxFrame;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
push(chunk) {
|
|
49
|
-
this.buf = Buffer.concat([this.buf, chunk]);
|
|
50
|
-
for (;;) {
|
|
51
|
-
const b = this.buf;
|
|
52
|
-
if (b.length < 2) return;
|
|
53
|
-
const fin = (b[0] & 0x80) !== 0;
|
|
54
|
-
const opcode = b[0] & 0x0f;
|
|
55
|
-
const masked = (b[1] & 0x80) !== 0;
|
|
56
|
-
let len = b[1] & 0x7f;
|
|
57
|
-
let off = 2;
|
|
58
|
-
|
|
59
|
-
if (len === 126) {
|
|
60
|
-
if (b.length < 4) return;
|
|
61
|
-
len = b.readUInt16BE(2);
|
|
62
|
-
off = 4;
|
|
63
|
-
} else if (len === 127) {
|
|
64
|
-
if (b.length < 10) return;
|
|
65
|
-
const big = b.readBigUInt64BE(2);
|
|
66
|
-
if (big > BigInt(this.maxFrame)) throw new Error('帧过大');
|
|
67
|
-
len = Number(big);
|
|
68
|
-
off = 10;
|
|
69
|
-
}
|
|
70
|
-
if (len > this.maxFrame) throw new Error('帧过大');
|
|
71
|
-
|
|
72
|
-
let mask = null;
|
|
73
|
-
if (masked) {
|
|
74
|
-
if (b.length < off + 4) return;
|
|
75
|
-
mask = b.subarray(off, off + 4);
|
|
76
|
-
off += 4;
|
|
77
|
-
}
|
|
78
|
-
if (b.length < off + len) return;
|
|
79
|
-
|
|
80
|
-
let payload = b.subarray(off, off + len);
|
|
81
|
-
if (mask) {
|
|
82
|
-
const out = Buffer.allocUnsafe(len);
|
|
83
|
-
for (let i = 0; i < len; i += 1) out[i] = payload[i] ^ mask[i % 4];
|
|
84
|
-
payload = out;
|
|
85
|
-
}
|
|
86
|
-
this.buf = b.subarray(off + len);
|
|
87
|
-
|
|
88
|
-
if (opcode === OP_PING) this.onControl('ping', payload);
|
|
89
|
-
else if (opcode === OP_PONG) this.onControl('pong', payload);
|
|
90
|
-
else if (opcode === OP_CLOSE) this.onControl('close', payload);
|
|
91
|
-
else if (opcode === OP_TEXT || opcode === OP_BINARY) {
|
|
92
|
-
if (!fin) this.frag.push(payload);
|
|
93
|
-
else if (this.frag.length) {
|
|
94
|
-
this.frag.push(payload);
|
|
95
|
-
const full = Buffer.concat(this.frag);
|
|
96
|
-
this.frag = [];
|
|
97
|
-
this.onMessage(full);
|
|
98
|
-
} else this.onMessage(payload);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
export class TicketStore {
|
|
105
|
-
constructor({ now = () => Date.now() } = {}) {
|
|
106
|
-
this.now = now;
|
|
107
|
-
this.map = new Map();
|
|
108
|
-
}
|
|
109
|
-
issue(deviceId) {
|
|
110
|
-
// 前缀不是装饰:日志/崩溃上报里能一眼认出并做密钥扫描(契约 WsTicket.pattern 要求 tkt_)
|
|
111
|
-
const ticket = `tkt_${crypto.randomBytes(18).toString('base64url')}`;
|
|
112
|
-
this.map.set(ticket, { deviceId, expiresAt: this.now() + TICKET_TTL_MS });
|
|
113
|
-
return { ticket, expiresInSec: TICKET_TTL_MS / 1000 };
|
|
114
|
-
}
|
|
115
|
-
/** 一次性:取出即删 */
|
|
116
|
-
consume(ticket) {
|
|
117
|
-
const rec = this.map.get(ticket);
|
|
118
|
-
if (!rec) return null;
|
|
119
|
-
this.map.delete(ticket);
|
|
120
|
-
if (rec.expiresAt <= this.now()) return null;
|
|
121
|
-
return rec;
|
|
122
|
-
}
|
|
123
|
-
get size() {
|
|
124
|
-
return this.map.size;
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function parseSubprotocols(header = '') {
|
|
129
|
-
return String(header)
|
|
130
|
-
.split(',')
|
|
131
|
-
.map((s) => s.trim())
|
|
132
|
-
.filter(Boolean);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
export function attachWebSocket(server, { core, pairing, tickets, log = () => {}, hostAllow = () => true }) {
|
|
136
|
-
const connections = new Set();
|
|
137
|
-
let handshakes = 0;
|
|
138
|
-
let rejects = 0;
|
|
139
|
-
|
|
140
|
-
server.on('upgrade', (req, socket, head) => {
|
|
141
|
-
const deny = (status, code, message) => {
|
|
142
|
-
rejects += 1;
|
|
143
|
-
const body = JSON.stringify({ code, message });
|
|
144
|
-
socket.write(
|
|
145
|
-
`HTTP/1.1 ${status} ${status === 401 ? 'Unauthorized' : status === 403 ? 'Forbidden' : 'Bad Request'}\r\n` +
|
|
146
|
-
'Content-Type: application/json; charset=utf-8\r\n' +
|
|
147
|
-
`Content-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`
|
|
148
|
-
);
|
|
149
|
-
socket.destroy();
|
|
150
|
-
};
|
|
151
|
-
|
|
152
|
-
const key = req.headers['sec-websocket-key'];
|
|
153
|
-
if (!key) return deny(400, 4400, '缺少 Sec-WebSocket-Key');
|
|
154
|
-
|
|
155
|
-
const url = new URL(req.url, 'http://127.0.0.1');
|
|
156
|
-
if (url.pathname !== '/ws/mobile') return deny(400, 4404, '未知的 WS 路径');
|
|
157
|
-
|
|
158
|
-
if (!hostAllow(req.headers.host)) return deny(403, 4003, '这台主机不信任当前地址');
|
|
159
|
-
|
|
160
|
-
const protos = parseSubprotocols(req.headers['sec-websocket-protocol']);
|
|
161
|
-
const ticketItem = protos.find((p) => p.startsWith('ticket.'));
|
|
162
|
-
let device = null;
|
|
163
|
-
try {
|
|
164
|
-
if (ticketItem) {
|
|
165
|
-
const rec = tickets.consume(ticketItem.slice('ticket.'.length));
|
|
166
|
-
if (!rec) return deny(401, 4001, '连接票据无效或已过期');
|
|
167
|
-
device = [...pairing.byDeviceId.values()].find((d) => d.deviceId === rec.deviceId) || null;
|
|
168
|
-
if (!device) return deny(401, 4001, '设备不存在');
|
|
169
|
-
if (device.revoked) return deny(401, 4009, '这台设备已被撤销');
|
|
170
|
-
} else if (/^ticket\s+/i.test(String(req.headers.authorization || ''))) {
|
|
171
|
-
// 某些客户端(如 URLSession)不允许自定义 Sec-WebSocket-Protocol,
|
|
172
|
-
// 用 Authorization: Ticket <t> 承载同一张一次性票据,仍然不进 URL。
|
|
173
|
-
const raw = String(req.headers.authorization).replace(/^ticket\s+/i, '');
|
|
174
|
-
const rec = tickets.consume(raw);
|
|
175
|
-
if (!rec) return deny(401, 4001, '连接票据无效或已过期');
|
|
176
|
-
device = [...pairing.byDeviceId.values()].find((d) => d.deviceId === rec.deviceId) || null;
|
|
177
|
-
if (!device) return deny(401, 4001, '设备不存在');
|
|
178
|
-
if (device.revoked) return deny(401, 4009, '这台设备已被撤销');
|
|
179
|
-
} else if (req.headers.authorization) {
|
|
180
|
-
// 降级路径:宿主不支持票据时用长期凭证(PRD §10.4)
|
|
181
|
-
device = pairing.verify(String(req.headers.authorization).replace(/^Bearer\s+/i, ''));
|
|
182
|
-
} else {
|
|
183
|
-
return deny(401, 4001, '缺少设备凭证');
|
|
184
|
-
}
|
|
185
|
-
} catch (err) {
|
|
186
|
-
return deny(401, err.code === 4009 ? 4009 : 4001, err.message);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const accept = acceptKey(key);
|
|
190
|
-
// RFC 6455 §4.1:只有当客户端在请求里声明了子协议,服务端才可以在 101 里回
|
|
191
|
-
// Sec-WebSocket-Protocol。无条件回会被严格执行协议的客户端判为「响应非法」并断开
|
|
192
|
-
// ——Apple 的 URLSession 就是如此,表现为 "There was a bad response from the server",
|
|
193
|
-
// 而服务端只看到「握手超时」,极易误判成客户端没发 hello。
|
|
194
|
-
const handshakeLines = [
|
|
195
|
-
'HTTP/1.1 101 Switching Protocols',
|
|
196
|
-
'Upgrade: websocket',
|
|
197
|
-
'Connection: Upgrade',
|
|
198
|
-
`Sec-WebSocket-Accept: ${accept}`,
|
|
199
|
-
];
|
|
200
|
-
if (protos.length > 0) handshakeLines.push(`Sec-WebSocket-Protocol: ${SUBPROTOCOL}`);
|
|
201
|
-
handshakeLines.push('', '');
|
|
202
|
-
socket.write(handshakeLines.join('\r\n'));
|
|
203
|
-
handshakes += 1;
|
|
204
|
-
|
|
205
|
-
let closed = false;
|
|
206
|
-
let helloTimer = null;
|
|
207
|
-
const session = core.addSession({
|
|
208
|
-
device,
|
|
209
|
-
remote: req.socket.remoteAddress || '',
|
|
210
|
-
send: (obj) => {
|
|
211
|
-
if (closed || socket.destroyed) return;
|
|
212
|
-
session.lastFrameAt = Date.now();
|
|
213
|
-
session.sent += 1;
|
|
214
|
-
socket.write(encodeFrame(OP_TEXT, Buffer.from(JSON.stringify(obj))));
|
|
215
|
-
},
|
|
216
|
-
close: (code = 1000, reason = '') => {
|
|
217
|
-
if (closed) return;
|
|
218
|
-
closed = true;
|
|
219
|
-
const payload = Buffer.alloc(2 + Buffer.byteLength(reason));
|
|
220
|
-
payload.writeUInt16BE(code, 0);
|
|
221
|
-
payload.write(reason, 2);
|
|
222
|
-
if (!socket.destroyed) {
|
|
223
|
-
socket.write(encodeFrame(OP_CLOSE, payload));
|
|
224
|
-
socket.end();
|
|
225
|
-
}
|
|
226
|
-
clearTimeout(helloTimer);
|
|
227
|
-
connections.delete(conn);
|
|
228
|
-
core.removeSession(session);
|
|
229
|
-
},
|
|
230
|
-
});
|
|
231
|
-
const conn = { session, socket, device };
|
|
232
|
-
connections.add(conn);
|
|
233
|
-
|
|
234
|
-
const rejectAndClose = (err) => {
|
|
235
|
-
rejects += 1;
|
|
236
|
-
const code = err.code || 4500;
|
|
237
|
-
session.send({ t: 'reject', code, message: err.message, ...(err.extra || {}) });
|
|
238
|
-
session.close(1008, 'rejected');
|
|
239
|
-
log(`ws reject ${code} (${err.message})`);
|
|
240
|
-
};
|
|
241
|
-
|
|
242
|
-
const parser = new FrameParser(
|
|
243
|
-
(payload) => {
|
|
244
|
-
let msg;
|
|
245
|
-
try {
|
|
246
|
-
msg = JSON.parse(payload.toString('utf8'));
|
|
247
|
-
} catch {
|
|
248
|
-
return rejectAndClose(fail(4400, '帧不是合法 JSON'));
|
|
249
|
-
}
|
|
250
|
-
if (msg.t === 'hello') {
|
|
251
|
-
clearTimeout(helloTimer);
|
|
252
|
-
try {
|
|
253
|
-
core.handleHello(session, msg);
|
|
254
|
-
// hello 已通过凭证校验:把客户端「关于」页当前的设备名全称同步到注册表,
|
|
255
|
-
// 面板下一次刷新即可看到改名后的名字(配对时记下的名字只是初始值)。
|
|
256
|
-
if (typeof msg.deviceName === 'string') {
|
|
257
|
-
pairing.renameDevice(session.device.deviceId, msg.deviceName);
|
|
258
|
-
}
|
|
259
|
-
} catch (err) {
|
|
260
|
-
rejectAndClose(err);
|
|
261
|
-
}
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
if (msg.t === 'req') {
|
|
265
|
-
core
|
|
266
|
-
.handleReq(session, msg)
|
|
267
|
-
.then((res) => session.send({ t: 'res', id: res.id, ok: true, data: res.data }))
|
|
268
|
-
.catch((err) => session.send({ t: 'res', id: msg.id, ok: false, error: err.toJSON?.() ?? { code: 4500, message: String(err) } }));
|
|
269
|
-
return;
|
|
270
|
-
}
|
|
271
|
-
if (msg.t === 'ping') {
|
|
272
|
-
session.send({ t: 'pong', serverTime: new Date().toISOString() });
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
rejectAndClose(fail(4400, `未知帧类型 ${msg.t}`));
|
|
276
|
-
},
|
|
277
|
-
(kind, payload) => {
|
|
278
|
-
if (kind === 'ping') socket.write(encodeFrame(OP_PONG, payload));
|
|
279
|
-
else if (kind === 'close') session.close(1000, '');
|
|
280
|
-
}
|
|
281
|
-
);
|
|
282
|
-
|
|
283
|
-
helloTimer = setTimeout(() => {
|
|
284
|
-
if (!session.ready) rejectAndClose(fail(4004, '握手超时'));
|
|
285
|
-
}, HELLO_TIMEOUT_MS);
|
|
286
|
-
|
|
287
|
-
if (head?.length) parser.push(head);
|
|
288
|
-
socket.on('data', (chunk) => {
|
|
289
|
-
try {
|
|
290
|
-
parser.push(chunk);
|
|
291
|
-
} catch (err) {
|
|
292
|
-
log(`ws parse error: ${err.message}`);
|
|
293
|
-
session.close(1011, 'parse error');
|
|
294
|
-
}
|
|
295
|
-
});
|
|
296
|
-
socket.on('error', () => session.close(1011, 'socket error'));
|
|
297
|
-
socket.on('close', () => session.close(1000, ''));
|
|
298
|
-
});
|
|
299
|
-
|
|
300
|
-
// 空闲回收:客户端应 15s 一次 ping;120s 无帧说明对端已死,回收连接
|
|
301
|
-
const sweep = setInterval(() => {
|
|
302
|
-
for (const { session } of connections) {
|
|
303
|
-
if (session.ready && Date.now() - session.lastFrameAt > 120_000) {
|
|
304
|
-
log(`ws idle timeout ${session.deviceId}`);
|
|
305
|
-
session.close(1001, 'idle timeout');
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
}, 30_000);
|
|
309
|
-
sweep.unref?.();
|
|
310
|
-
|
|
311
|
-
return {
|
|
312
|
-
stats: () => ({ connections: connections.size, handshakes, rejects }),
|
|
313
|
-
/**
|
|
314
|
-
* 模拟链路中断:直接 destroy 底层 socket,不发 close 帧。
|
|
315
|
-
* 与 closeAll(优雅 1001)区分开——客户端在两种情况下该走的重连逻辑不同。
|
|
316
|
-
*/
|
|
317
|
-
dropAll: () => {
|
|
318
|
-
let n = 0;
|
|
319
|
-
for (const { socket } of [...connections]) {
|
|
320
|
-
if (socket && !socket.destroyed) {
|
|
321
|
-
socket.destroy();
|
|
322
|
-
n += 1;
|
|
323
|
-
}
|
|
324
|
-
}
|
|
325
|
-
return n;
|
|
326
|
-
},
|
|
327
|
-
closeAll: () => {
|
|
328
|
-
clearInterval(sweep);
|
|
329
|
-
for (const { session } of [...connections]) session.close(1001, 'server stopping');
|
|
330
|
-
},
|
|
331
|
-
};
|
|
332
|
-
}
|
|
1
|
+
// ws.mjs — WS 传输层(RFC6455 最小子集 + ticket 鉴权 + 握手泵)
|
|
2
|
+
// 安全要点(ADR-13):一次性 ticket 走 Sec-WebSocket-Protocol,不进 URL query——
|
|
3
|
+
// query 会落到反向代理日志与崩溃上报里。
|
|
4
|
+
|
|
5
|
+
import crypto from 'node:crypto';
|
|
6
|
+
import { fail } from './protocol.mjs';
|
|
7
|
+
|
|
8
|
+
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
9
|
+
const OP_TEXT = 0x1;
|
|
10
|
+
const OP_BINARY = 0x2;
|
|
11
|
+
const OP_CLOSE = 0x8;
|
|
12
|
+
const OP_PING = 0x9;
|
|
13
|
+
const OP_PONG = 0xa;
|
|
14
|
+
const SUBPROTOCOL = 'dsh.v1';
|
|
15
|
+
const TICKET_TTL_MS = 30_000;
|
|
16
|
+
const HELLO_TIMEOUT_MS = 5_000;
|
|
17
|
+
|
|
18
|
+
const acceptKey = (key) => crypto.createHash('sha1').update(key + GUID).digest('base64');
|
|
19
|
+
|
|
20
|
+
export function encodeFrame(opcode, payload = Buffer.alloc(0)) {
|
|
21
|
+
const len = payload.length;
|
|
22
|
+
let header;
|
|
23
|
+
if (len < 126) {
|
|
24
|
+
header = Buffer.alloc(2);
|
|
25
|
+
header[1] = len;
|
|
26
|
+
} else if (len < 65536) {
|
|
27
|
+
header = Buffer.alloc(4);
|
|
28
|
+
header[1] = 126;
|
|
29
|
+
header.writeUInt16BE(len, 2);
|
|
30
|
+
} else {
|
|
31
|
+
header = Buffer.alloc(10);
|
|
32
|
+
header[1] = 127;
|
|
33
|
+
header.writeBigUInt64BE(BigInt(len), 2);
|
|
34
|
+
}
|
|
35
|
+
header[0] = 0x80 | opcode;
|
|
36
|
+
return Buffer.concat([header, payload]);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
class FrameParser {
|
|
40
|
+
constructor(onMessage, onControl, maxFrame = 4 * 1024 * 1024) {
|
|
41
|
+
this.buf = Buffer.alloc(0);
|
|
42
|
+
this.frag = [];
|
|
43
|
+
this.onMessage = onMessage;
|
|
44
|
+
this.onControl = onControl;
|
|
45
|
+
this.maxFrame = maxFrame;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
push(chunk) {
|
|
49
|
+
this.buf = Buffer.concat([this.buf, chunk]);
|
|
50
|
+
for (;;) {
|
|
51
|
+
const b = this.buf;
|
|
52
|
+
if (b.length < 2) return;
|
|
53
|
+
const fin = (b[0] & 0x80) !== 0;
|
|
54
|
+
const opcode = b[0] & 0x0f;
|
|
55
|
+
const masked = (b[1] & 0x80) !== 0;
|
|
56
|
+
let len = b[1] & 0x7f;
|
|
57
|
+
let off = 2;
|
|
58
|
+
|
|
59
|
+
if (len === 126) {
|
|
60
|
+
if (b.length < 4) return;
|
|
61
|
+
len = b.readUInt16BE(2);
|
|
62
|
+
off = 4;
|
|
63
|
+
} else if (len === 127) {
|
|
64
|
+
if (b.length < 10) return;
|
|
65
|
+
const big = b.readBigUInt64BE(2);
|
|
66
|
+
if (big > BigInt(this.maxFrame)) throw new Error('帧过大');
|
|
67
|
+
len = Number(big);
|
|
68
|
+
off = 10;
|
|
69
|
+
}
|
|
70
|
+
if (len > this.maxFrame) throw new Error('帧过大');
|
|
71
|
+
|
|
72
|
+
let mask = null;
|
|
73
|
+
if (masked) {
|
|
74
|
+
if (b.length < off + 4) return;
|
|
75
|
+
mask = b.subarray(off, off + 4);
|
|
76
|
+
off += 4;
|
|
77
|
+
}
|
|
78
|
+
if (b.length < off + len) return;
|
|
79
|
+
|
|
80
|
+
let payload = b.subarray(off, off + len);
|
|
81
|
+
if (mask) {
|
|
82
|
+
const out = Buffer.allocUnsafe(len);
|
|
83
|
+
for (let i = 0; i < len; i += 1) out[i] = payload[i] ^ mask[i % 4];
|
|
84
|
+
payload = out;
|
|
85
|
+
}
|
|
86
|
+
this.buf = b.subarray(off + len);
|
|
87
|
+
|
|
88
|
+
if (opcode === OP_PING) this.onControl('ping', payload);
|
|
89
|
+
else if (opcode === OP_PONG) this.onControl('pong', payload);
|
|
90
|
+
else if (opcode === OP_CLOSE) this.onControl('close', payload);
|
|
91
|
+
else if (opcode === OP_TEXT || opcode === OP_BINARY) {
|
|
92
|
+
if (!fin) this.frag.push(payload);
|
|
93
|
+
else if (this.frag.length) {
|
|
94
|
+
this.frag.push(payload);
|
|
95
|
+
const full = Buffer.concat(this.frag);
|
|
96
|
+
this.frag = [];
|
|
97
|
+
this.onMessage(full);
|
|
98
|
+
} else this.onMessage(payload);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export class TicketStore {
|
|
105
|
+
constructor({ now = () => Date.now() } = {}) {
|
|
106
|
+
this.now = now;
|
|
107
|
+
this.map = new Map();
|
|
108
|
+
}
|
|
109
|
+
issue(deviceId) {
|
|
110
|
+
// 前缀不是装饰:日志/崩溃上报里能一眼认出并做密钥扫描(契约 WsTicket.pattern 要求 tkt_)
|
|
111
|
+
const ticket = `tkt_${crypto.randomBytes(18).toString('base64url')}`;
|
|
112
|
+
this.map.set(ticket, { deviceId, expiresAt: this.now() + TICKET_TTL_MS });
|
|
113
|
+
return { ticket, expiresInSec: TICKET_TTL_MS / 1000 };
|
|
114
|
+
}
|
|
115
|
+
/** 一次性:取出即删 */
|
|
116
|
+
consume(ticket) {
|
|
117
|
+
const rec = this.map.get(ticket);
|
|
118
|
+
if (!rec) return null;
|
|
119
|
+
this.map.delete(ticket);
|
|
120
|
+
if (rec.expiresAt <= this.now()) return null;
|
|
121
|
+
return rec;
|
|
122
|
+
}
|
|
123
|
+
get size() {
|
|
124
|
+
return this.map.size;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function parseSubprotocols(header = '') {
|
|
129
|
+
return String(header)
|
|
130
|
+
.split(',')
|
|
131
|
+
.map((s) => s.trim())
|
|
132
|
+
.filter(Boolean);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function attachWebSocket(server, { core, pairing, tickets, log = () => {}, hostAllow = () => true }) {
|
|
136
|
+
const connections = new Set();
|
|
137
|
+
let handshakes = 0;
|
|
138
|
+
let rejects = 0;
|
|
139
|
+
|
|
140
|
+
server.on('upgrade', (req, socket, head) => {
|
|
141
|
+
const deny = (status, code, message) => {
|
|
142
|
+
rejects += 1;
|
|
143
|
+
const body = JSON.stringify({ code, message });
|
|
144
|
+
socket.write(
|
|
145
|
+
`HTTP/1.1 ${status} ${status === 401 ? 'Unauthorized' : status === 403 ? 'Forbidden' : 'Bad Request'}\r\n` +
|
|
146
|
+
'Content-Type: application/json; charset=utf-8\r\n' +
|
|
147
|
+
`Content-Length: ${Buffer.byteLength(body)}\r\nConnection: close\r\n\r\n${body}`
|
|
148
|
+
);
|
|
149
|
+
socket.destroy();
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const key = req.headers['sec-websocket-key'];
|
|
153
|
+
if (!key) return deny(400, 4400, '缺少 Sec-WebSocket-Key');
|
|
154
|
+
|
|
155
|
+
const url = new URL(req.url, 'http://127.0.0.1');
|
|
156
|
+
if (url.pathname !== '/ws/mobile') return deny(400, 4404, '未知的 WS 路径');
|
|
157
|
+
|
|
158
|
+
if (!hostAllow(req.headers.host)) return deny(403, 4003, '这台主机不信任当前地址');
|
|
159
|
+
|
|
160
|
+
const protos = parseSubprotocols(req.headers['sec-websocket-protocol']);
|
|
161
|
+
const ticketItem = protos.find((p) => p.startsWith('ticket.'));
|
|
162
|
+
let device = null;
|
|
163
|
+
try {
|
|
164
|
+
if (ticketItem) {
|
|
165
|
+
const rec = tickets.consume(ticketItem.slice('ticket.'.length));
|
|
166
|
+
if (!rec) return deny(401, 4001, '连接票据无效或已过期');
|
|
167
|
+
device = [...pairing.byDeviceId.values()].find((d) => d.deviceId === rec.deviceId) || null;
|
|
168
|
+
if (!device) return deny(401, 4001, '设备不存在');
|
|
169
|
+
if (device.revoked) return deny(401, 4009, '这台设备已被撤销');
|
|
170
|
+
} else if (/^ticket\s+/i.test(String(req.headers.authorization || ''))) {
|
|
171
|
+
// 某些客户端(如 URLSession)不允许自定义 Sec-WebSocket-Protocol,
|
|
172
|
+
// 用 Authorization: Ticket <t> 承载同一张一次性票据,仍然不进 URL。
|
|
173
|
+
const raw = String(req.headers.authorization).replace(/^ticket\s+/i, '');
|
|
174
|
+
const rec = tickets.consume(raw);
|
|
175
|
+
if (!rec) return deny(401, 4001, '连接票据无效或已过期');
|
|
176
|
+
device = [...pairing.byDeviceId.values()].find((d) => d.deviceId === rec.deviceId) || null;
|
|
177
|
+
if (!device) return deny(401, 4001, '设备不存在');
|
|
178
|
+
if (device.revoked) return deny(401, 4009, '这台设备已被撤销');
|
|
179
|
+
} else if (req.headers.authorization) {
|
|
180
|
+
// 降级路径:宿主不支持票据时用长期凭证(PRD §10.4)
|
|
181
|
+
device = pairing.verify(String(req.headers.authorization).replace(/^Bearer\s+/i, ''));
|
|
182
|
+
} else {
|
|
183
|
+
return deny(401, 4001, '缺少设备凭证');
|
|
184
|
+
}
|
|
185
|
+
} catch (err) {
|
|
186
|
+
return deny(401, err.code === 4009 ? 4009 : 4001, err.message);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const accept = acceptKey(key);
|
|
190
|
+
// RFC 6455 §4.1:只有当客户端在请求里声明了子协议,服务端才可以在 101 里回
|
|
191
|
+
// Sec-WebSocket-Protocol。无条件回会被严格执行协议的客户端判为「响应非法」并断开
|
|
192
|
+
// ——Apple 的 URLSession 就是如此,表现为 "There was a bad response from the server",
|
|
193
|
+
// 而服务端只看到「握手超时」,极易误判成客户端没发 hello。
|
|
194
|
+
const handshakeLines = [
|
|
195
|
+
'HTTP/1.1 101 Switching Protocols',
|
|
196
|
+
'Upgrade: websocket',
|
|
197
|
+
'Connection: Upgrade',
|
|
198
|
+
`Sec-WebSocket-Accept: ${accept}`,
|
|
199
|
+
];
|
|
200
|
+
if (protos.length > 0) handshakeLines.push(`Sec-WebSocket-Protocol: ${SUBPROTOCOL}`);
|
|
201
|
+
handshakeLines.push('', '');
|
|
202
|
+
socket.write(handshakeLines.join('\r\n'));
|
|
203
|
+
handshakes += 1;
|
|
204
|
+
|
|
205
|
+
let closed = false;
|
|
206
|
+
let helloTimer = null;
|
|
207
|
+
const session = core.addSession({
|
|
208
|
+
device,
|
|
209
|
+
remote: req.socket.remoteAddress || '',
|
|
210
|
+
send: (obj) => {
|
|
211
|
+
if (closed || socket.destroyed) return;
|
|
212
|
+
session.lastFrameAt = Date.now();
|
|
213
|
+
session.sent += 1;
|
|
214
|
+
socket.write(encodeFrame(OP_TEXT, Buffer.from(JSON.stringify(obj))));
|
|
215
|
+
},
|
|
216
|
+
close: (code = 1000, reason = '') => {
|
|
217
|
+
if (closed) return;
|
|
218
|
+
closed = true;
|
|
219
|
+
const payload = Buffer.alloc(2 + Buffer.byteLength(reason));
|
|
220
|
+
payload.writeUInt16BE(code, 0);
|
|
221
|
+
payload.write(reason, 2);
|
|
222
|
+
if (!socket.destroyed) {
|
|
223
|
+
socket.write(encodeFrame(OP_CLOSE, payload));
|
|
224
|
+
socket.end();
|
|
225
|
+
}
|
|
226
|
+
clearTimeout(helloTimer);
|
|
227
|
+
connections.delete(conn);
|
|
228
|
+
core.removeSession(session);
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
const conn = { session, socket, device };
|
|
232
|
+
connections.add(conn);
|
|
233
|
+
|
|
234
|
+
const rejectAndClose = (err) => {
|
|
235
|
+
rejects += 1;
|
|
236
|
+
const code = err.code || 4500;
|
|
237
|
+
session.send({ t: 'reject', code, message: err.message, ...(err.extra || {}) });
|
|
238
|
+
session.close(1008, 'rejected');
|
|
239
|
+
log(`ws reject ${code} (${err.message})`);
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
const parser = new FrameParser(
|
|
243
|
+
(payload) => {
|
|
244
|
+
let msg;
|
|
245
|
+
try {
|
|
246
|
+
msg = JSON.parse(payload.toString('utf8'));
|
|
247
|
+
} catch {
|
|
248
|
+
return rejectAndClose(fail(4400, '帧不是合法 JSON'));
|
|
249
|
+
}
|
|
250
|
+
if (msg.t === 'hello') {
|
|
251
|
+
clearTimeout(helloTimer);
|
|
252
|
+
try {
|
|
253
|
+
core.handleHello(session, msg);
|
|
254
|
+
// hello 已通过凭证校验:把客户端「关于」页当前的设备名全称同步到注册表,
|
|
255
|
+
// 面板下一次刷新即可看到改名后的名字(配对时记下的名字只是初始值)。
|
|
256
|
+
if (typeof msg.deviceName === 'string') {
|
|
257
|
+
pairing.renameDevice(session.device.deviceId, msg.deviceName);
|
|
258
|
+
}
|
|
259
|
+
} catch (err) {
|
|
260
|
+
rejectAndClose(err);
|
|
261
|
+
}
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
if (msg.t === 'req') {
|
|
265
|
+
core
|
|
266
|
+
.handleReq(session, msg)
|
|
267
|
+
.then((res) => session.send({ t: 'res', id: res.id, ok: true, data: res.data }))
|
|
268
|
+
.catch((err) => session.send({ t: 'res', id: msg.id, ok: false, error: err.toJSON?.() ?? { code: 4500, message: String(err) } }));
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
if (msg.t === 'ping') {
|
|
272
|
+
session.send({ t: 'pong', serverTime: new Date().toISOString() });
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
rejectAndClose(fail(4400, `未知帧类型 ${msg.t}`));
|
|
276
|
+
},
|
|
277
|
+
(kind, payload) => {
|
|
278
|
+
if (kind === 'ping') socket.write(encodeFrame(OP_PONG, payload));
|
|
279
|
+
else if (kind === 'close') session.close(1000, '');
|
|
280
|
+
}
|
|
281
|
+
);
|
|
282
|
+
|
|
283
|
+
helloTimer = setTimeout(() => {
|
|
284
|
+
if (!session.ready) rejectAndClose(fail(4004, '握手超时'));
|
|
285
|
+
}, HELLO_TIMEOUT_MS);
|
|
286
|
+
|
|
287
|
+
if (head?.length) parser.push(head);
|
|
288
|
+
socket.on('data', (chunk) => {
|
|
289
|
+
try {
|
|
290
|
+
parser.push(chunk);
|
|
291
|
+
} catch (err) {
|
|
292
|
+
log(`ws parse error: ${err.message}`);
|
|
293
|
+
session.close(1011, 'parse error');
|
|
294
|
+
}
|
|
295
|
+
});
|
|
296
|
+
socket.on('error', () => session.close(1011, 'socket error'));
|
|
297
|
+
socket.on('close', () => session.close(1000, ''));
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// 空闲回收:客户端应 15s 一次 ping;120s 无帧说明对端已死,回收连接
|
|
301
|
+
const sweep = setInterval(() => {
|
|
302
|
+
for (const { session } of connections) {
|
|
303
|
+
if (session.ready && Date.now() - session.lastFrameAt > 120_000) {
|
|
304
|
+
log(`ws idle timeout ${session.deviceId}`);
|
|
305
|
+
session.close(1001, 'idle timeout');
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}, 30_000);
|
|
309
|
+
sweep.unref?.();
|
|
310
|
+
|
|
311
|
+
return {
|
|
312
|
+
stats: () => ({ connections: connections.size, handshakes, rejects }),
|
|
313
|
+
/**
|
|
314
|
+
* 模拟链路中断:直接 destroy 底层 socket,不发 close 帧。
|
|
315
|
+
* 与 closeAll(优雅 1001)区分开——客户端在两种情况下该走的重连逻辑不同。
|
|
316
|
+
*/
|
|
317
|
+
dropAll: () => {
|
|
318
|
+
let n = 0;
|
|
319
|
+
for (const { socket } of [...connections]) {
|
|
320
|
+
if (socket && !socket.destroyed) {
|
|
321
|
+
socket.destroy();
|
|
322
|
+
n += 1;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return n;
|
|
326
|
+
},
|
|
327
|
+
closeAll: () => {
|
|
328
|
+
clearInterval(sweep);
|
|
329
|
+
for (const { session } of [...connections]) session.close(1001, 'server stopping');
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
}
|