@dsh-mobile/mobile-remote 3.2.7 → 3.3.1
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/FAQ.md +19 -12
- package/LICENSE +0 -0
- package/README.md +40 -40
- package/cordis.patch.yml +8 -4
- package/docs/PRIVACY-POLICY.en.md +89 -47
- package/docs/PRIVACY-POLICY.md +89 -47
- package/docs/SUPPORT.md +5 -5
- package/docs/TERMS-OF-SERVICE.en.md +5 -3
- package/docs/TERMS-OF-SERVICE.md +5 -3
- package/docs/USER-GUIDE.zh-CN.md +562 -0
- package/lib/account-usage.js +0 -0
- package/lib/api-helpers.js +6 -2
- package/lib/assistant-prefs.js +167 -0
- package/lib/auto-config.js +55 -3
- package/lib/backup.js +441 -0
- package/lib/break-reminder.js +133 -0
- package/lib/client.js +321 -77
- package/lib/config.js +96 -5
- package/lib/git-read-bundled-provider.js +32 -3
- package/lib/git-read-service.js +4 -0
- package/lib/host-compat.js +25 -0
- package/lib/http-util.js +6 -2
- package/lib/index.js +1121 -83
- package/lib/memory/context.js +81 -0
- package/lib/memory/decay.js +144 -0
- package/lib/memory/extract.js +146 -0
- package/lib/memory/routes.js +198 -0
- package/lib/memory/store.js +714 -0
- package/lib/notify-copy.js +245 -0
- package/lib/permission-guide.js +184 -0
- package/lib/persona-cards.js +366 -0
- package/lib/proactive-material.js +162 -0
- package/lib/proactive.js +372 -0
- package/lib/protected-paths.js +290 -0
- package/lib/protocol.js +39 -0
- package/lib/rate-limit.js +1 -1
- package/lib/relay/connector.js +208 -14
- package/lib/relay/devices.js +54 -8
- package/lib/relay/fingerprint.js +55 -0
- package/lib/relay/identity.js +69 -0
- package/lib/relay/on-demand.js +89 -0
- package/lib/relay/pairing.js +45 -6
- package/lib/relay/phone.js +89 -12
- package/lib/relay/ws-server.js +245 -0
- package/lib/reminders.js +140 -0
- package/lib/rpc-adapter.js +21 -2
- package/lib/session-rotation.js +198 -0
- package/lib/session-title-cache.js +0 -0
- package/lib/session-title-refresh.js +0 -0
- package/lib/timeline.js +1 -1
- package/package.json +30 -14
- package/CHANGELOG.md +0 -1383
- package/CONTRIBUTING.md +0 -61
- package/docs/00-/345/274/200/345/217/221/346/200/273/347/272/262.md +0 -432
- package/docs/01-PRD.md +0 -148
- package/docs/02-architecture.md +0 -249
- package/docs/03-api.md +0 -882
- package/docs/04-security.md +0 -110
- package/docs/05-test-cases.md +0 -376
- package/docs/06-install-run.md +0 -335
- package/docs/07-user-manual.md +0 -92
- package/docs/08-/346/211/251/345/261/225/345/274/200/345/217/221/346/214/207/345/215/227.md +0 -86
- package/docs/09-compatibility.md +0 -201
- package/docs/11-remote-relay-guide.md +0 -86
- package/docs/APP-ENCRYPTION-DESCRIPTION.md +0 -50
- package/docs/APP-ENCRYPTION-DESCRIPTION.pdf +0 -0
- package/docs/APP-REVIEW-NOTES.md +0 -105
- package/docs/BRAND-ASSETS.md +0 -142
- package/docs/COMPANION-PLAN.md +0 -199
- package/docs/STORE-LAUNCH.md +0 -341
- package/docs/STORE-LISTING.md +0 -190
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按需连接中继(T-11)。
|
|
3
|
+
*
|
|
4
|
+
* 以前只要 relay.enabled 为 true(默认),插件一启动就连上公共中继——哪怕这台电脑从来没配对过手机。
|
|
5
|
+
* 那条连接没有任何用处(没有已配对设备、也没有有效的配对码时,谁都进不来),却让每一台装了插件的
|
|
6
|
+
* 电脑都常驻一条到我们服务器的连接:成本随安装量增长,隐私文本也没法说「不配对就不联网」。
|
|
7
|
+
*
|
|
8
|
+
* 现在的规则:**只有在「有人可能进得来」的时候才连**——
|
|
9
|
+
* · 已经有至少一台经中继配对的手机;或
|
|
10
|
+
* · 用户刚在桌面上要了一个配对码(5 分钟内有效)。
|
|
11
|
+
* 两个条件都不成立就断开:全新安装不产生任何中继连接;撤销最后一台设备、配对码过期没人用,也会断开。
|
|
12
|
+
*
|
|
13
|
+
* T-71 (C-04): only phones and codes **for remote access** count. A phone paired with the desktop's
|
|
14
|
+
* default QR (encrypted LAN only, no relay in the link) never uses the relay, so it must not keep
|
|
15
|
+
* this PC on our relay around the clock (cost, and the PC's IP and uptime seen by us for a user
|
|
16
|
+
* who never asked for remote access). See `relay` in ./devices.js.
|
|
17
|
+
*
|
|
18
|
+
* 这个模块只做「该不该连」的判断,连接本身仍由 RelayConnector 负责(重连、心跳、会话)。
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{ connector: { start():void, stop():void },
|
|
23
|
+
* devices: { list():unknown[], pendingPairings():number, pairingExpiry():number, onRevoke(fn:()=>void):()=>void },
|
|
24
|
+
* log?: (m:string)=>void, now?: ()=>number,
|
|
25
|
+
* setTimer?: typeof setTimeout, clearTimer?: typeof clearTimeout }} o
|
|
26
|
+
*/
|
|
27
|
+
export function createRelayDemand({ connector, devices, log = () => {}, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
|
|
28
|
+
let enabled = false; // 插件是否在运行(effect 生效期间)
|
|
29
|
+
let active = false; // 连接器是否被我们启动了
|
|
30
|
+
let timer = null;
|
|
31
|
+
|
|
32
|
+
const paired = () => (typeof devices.relayPaired === "function" ? devices.relayPaired() : devices.list().length) > 0;
|
|
33
|
+
const wanted = () => paired() || devices.pendingPairings({ relay: true }) > 0;
|
|
34
|
+
const disarm = () => {
|
|
35
|
+
if (timer) clearTimer(timer);
|
|
36
|
+
timer = null;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** 对一下表:该连就连,不该连就断。可以随便多调。返回当前是否在连。 */
|
|
40
|
+
const sync = () => {
|
|
41
|
+
disarm();
|
|
42
|
+
if (!enabled) return active;
|
|
43
|
+
const want = wanted();
|
|
44
|
+
if (want && !active) {
|
|
45
|
+
active = true;
|
|
46
|
+
connector.start();
|
|
47
|
+
log(paired() ? "relay: 有已配对的手机,连接中继" : "relay: 已生成配对码,连接中继等待手机");
|
|
48
|
+
} else if (!want && active) {
|
|
49
|
+
active = false;
|
|
50
|
+
connector.stop();
|
|
51
|
+
log("relay: 没有已配对的手机,也没有有效的配对码,已断开中继");
|
|
52
|
+
}
|
|
53
|
+
// 只靠配对码撑着的连接:最后一个码过期后再对一次表(码被用掉 → 有设备了 → 继续连着)
|
|
54
|
+
if (active && !paired()) {
|
|
55
|
+
timer = setTimer(sync, Math.max(1_000, devices.pairingExpiry({ relay: true }) - now() + 1_000));
|
|
56
|
+
timer.unref?.();
|
|
57
|
+
}
|
|
58
|
+
return active;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// 撤销设备:连接器先踢掉它的会话(它的监听器注册在前),这里再看还需不需要连着
|
|
62
|
+
const unsubscribe = devices.onRevoke(() => sync());
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
sync,
|
|
66
|
+
wanted,
|
|
67
|
+
get active() {
|
|
68
|
+
return active;
|
|
69
|
+
},
|
|
70
|
+
/** 插件启动:开始按需连接。 */
|
|
71
|
+
start() {
|
|
72
|
+
enabled = true;
|
|
73
|
+
return sync();
|
|
74
|
+
},
|
|
75
|
+
/** 插件停止 / 重载:断开,并且在下一次 start() 之前不再连接。 */
|
|
76
|
+
stop() {
|
|
77
|
+
enabled = false;
|
|
78
|
+
disarm();
|
|
79
|
+
if (active) {
|
|
80
|
+
active = false;
|
|
81
|
+
connector.stop();
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
dispose() {
|
|
85
|
+
this.stop();
|
|
86
|
+
unsubscribe();
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|
package/lib/relay/pairing.js
CHANGED
|
@@ -6,6 +6,18 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 手机只需要这些:去哪个中继、哪个房间、认哪把公钥、拿什么码证明「我是被邀请的」。
|
|
8
8
|
* 解析是严格的:中继必须是 wss://(回环地址的 ws:// 仅供本机测试),其它一律拒绝。
|
|
9
|
+
*
|
|
10
|
+
* lan=(T-25)是电脑 LAN 桥上的局域网加密通道:`ws://<局域网 IPv4>:<端口>`。不用 TLS,因为
|
|
11
|
+
* 通道本身就是 Noise 加密、认电脑的公钥;但只接受局域网地址(10/8、172.16/12、192.168/16、
|
|
12
|
+
* 100.64/10、回环),一个被篡改的二维码不能把手机引去连公网上的任意主机。不合规的 lan 地址丢弃,不报错。
|
|
13
|
+
*
|
|
14
|
+
* T-71 (D-01, C-15): an invite may carry no relay at all, only `lan=`. That is the desktop's
|
|
15
|
+
* default QR: an encrypted pairing on the local network that needs no relay room, no account and
|
|
16
|
+
* no subscription (D5: the LAN is free). It needs 1-4 relays **or** at least one valid LAN
|
|
17
|
+
* address. Such a link is `v=2`: apps before T-71 accept only `v=1`, and they answer an unknown
|
|
18
|
+
* version with "this QR code comes from a newer DSH, please update the app" (their own text), which
|
|
19
|
+
* is the right advice. Links with a relay stay `v=1`, readable by every app. The desktop panel keeps
|
|
20
|
+
* the old token QR for apps that cannot be updated yet, labelled as unencrypted.
|
|
9
21
|
*/
|
|
10
22
|
import { b64u } from "./crypto.js";
|
|
11
23
|
|
|
@@ -25,18 +37,42 @@ export function isAllowedRelayUrl(s) {
|
|
|
25
37
|
}
|
|
26
38
|
}
|
|
27
39
|
|
|
40
|
+
/** 局域网 IPv4(含组网常用的 100.64/10 与回环)。 */
|
|
41
|
+
function isLanIPv4(host) {
|
|
42
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
43
|
+
if (!m) return false;
|
|
44
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
45
|
+
if ([m[1], m[2], m[3], m[4]].some((x) => Number(x) > 255)) return false;
|
|
46
|
+
return a === 10 || a === 127 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 局域网加密通道的地址是否可接受:`ws://<局域网 IPv4>:<端口>`,不带账号、路径、查询串、片段。 */
|
|
50
|
+
export function isAllowedLanUrl(s) {
|
|
51
|
+
try {
|
|
52
|
+
const u = new URL(s);
|
|
53
|
+
if (u.protocol !== "ws:" || u.username || u.password || u.search || u.hash) return false;
|
|
54
|
+
if (u.pathname !== "/" && u.pathname !== "") return false;
|
|
55
|
+
if (!/^ws:\/\/[^/]+\/?$/.test(s)) return false; // URL 会把空路径补成 "/",原文里不能有路径
|
|
56
|
+
return isLanIPv4(u.hostname) && u.port !== "";
|
|
57
|
+
} catch {
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
28
62
|
export function buildPairingUri({ relays, roomId, pcPub, otp, name, lan = [] }) {
|
|
29
63
|
if (!ROOM_RE.test(roomId)) throw new Error("bad room id");
|
|
30
64
|
if (pcPub.length !== 32) throw new Error("bad public key");
|
|
31
|
-
if (!Array.isArray(relays) || relays.length
|
|
65
|
+
if (!Array.isArray(relays) || relays.length > MAX_URIS) throw new Error("need 0-4 relay urls");
|
|
32
66
|
for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error(`relay url must be wss:// : ${r}`);
|
|
67
|
+
const lanOk = (Array.isArray(lan) ? lan : []).filter(isAllowedLanUrl).slice(0, MAX_URIS);
|
|
68
|
+
if (relays.length === 0 && lanOk.length === 0) throw new Error("need a relay url or a LAN address");
|
|
33
69
|
const q = new URLSearchParams();
|
|
34
|
-
q.set("v", "1");
|
|
70
|
+
q.set("v", relays.length === 0 ? "2" : "1");
|
|
35
71
|
q.set("room", roomId);
|
|
36
72
|
q.set("pk", b64u.enc(pcPub));
|
|
37
73
|
q.set("otp", otp);
|
|
38
74
|
for (const r of relays) q.append("r", r.replace(/\/+$/, ""));
|
|
39
|
-
for (const l of
|
|
75
|
+
for (const l of lanOk) q.append("lan", l.replace(/\/+$/, ""));
|
|
40
76
|
if (name) q.set("n", String(name).slice(0, 40));
|
|
41
77
|
return `dsh://pair?${q.toString()}`;
|
|
42
78
|
}
|
|
@@ -50,7 +86,8 @@ export function parsePairingUri(uri) {
|
|
|
50
86
|
}
|
|
51
87
|
if (u.protocol !== "dsh:" || u.hostname !== "pair") throw new Error("not a DSH pairing link");
|
|
52
88
|
const p = u.searchParams;
|
|
53
|
-
|
|
89
|
+
const v = p.get("v");
|
|
90
|
+
if (v !== "1" && v !== "2") throw new Error("unsupported version");
|
|
54
91
|
const room = p.get("room") ?? "";
|
|
55
92
|
if (!ROOM_RE.test(room)) throw new Error("bad room id");
|
|
56
93
|
const pk = b64u.dec(p.get("pk") ?? "");
|
|
@@ -58,7 +95,9 @@ export function parsePairingUri(uri) {
|
|
|
58
95
|
const otp = p.get("otp") ?? "";
|
|
59
96
|
if (otp.length < 16 || otp.length > 64 || !/^[A-Za-z0-9_-]+$/.test(otp)) throw new Error("bad pairing code");
|
|
60
97
|
const relays = p.getAll("r").map((r) => r.replace(/\/+$/, ""));
|
|
61
|
-
if (relays.length
|
|
98
|
+
if (relays.length > MAX_URIS || (v === "1" && relays.length === 0)) throw new Error(v === "1" ? "need 1-4 relay urls" : "need 0-4 relay urls");
|
|
62
99
|
for (const r of relays) if (!isAllowedRelayUrl(r)) throw new Error("relay url must be wss://");
|
|
63
|
-
|
|
100
|
+
const lan = p.getAll("lan").filter(isAllowedLanUrl).map((l) => l.replace(/\/+$/, "")).slice(0, MAX_URIS);
|
|
101
|
+
if (relays.length === 0 && lan.length === 0) throw new Error("need a relay url or a LAN address");
|
|
102
|
+
return { room, pk, otp, relays, lan, name: p.get("n") ?? "" };
|
|
64
103
|
}
|
package/lib/relay/phone.js
CHANGED
|
@@ -6,6 +6,14 @@
|
|
|
6
6
|
*
|
|
7
7
|
* 流程:连中继(访客身份)→ 等房主在线 → Noise 发起方握手(消息 1 里带上设备名与一次性配对码)→
|
|
8
8
|
* 读消息 2 → 之后所有流量都是 Noise 传输消息,里面跑多路复用的 HTTP。
|
|
9
|
+
*
|
|
10
|
+
* 电脑闪断后在原连接上续用(`resume: true`,访客协议 v2,见 relay/hub.js「访客协议版本」)
|
|
11
|
+
* 连接地址带 `?v=2`,告诉中继「我认得 host-down,也会在原连接上重新握手」。之后:
|
|
12
|
+
* host-down → 这条 Noise 会话作废:在途请求立刻失败,停止发送,等中继的下一句话;
|
|
13
|
+
* host-up → 用同一把设备密钥在**同一条连接**上重新握手(不带配对码——它已经用掉了),
|
|
14
|
+
* 握手完成后换上新的密钥与新的多路复用会话,`phone.resumes` 加一;
|
|
15
|
+
* 4503 → 电脑没在宽限期内回来,连接关闭,和以前一样重新连接。
|
|
16
|
+
* 不带 `resume`(缺省)就是所有已发布旧版 App 的行为:收到 host-up 只把会话作废,由上层另开连接。
|
|
9
17
|
*/
|
|
10
18
|
import { MuxSession } from "./mux.js";
|
|
11
19
|
import { NoiseInitiator } from "./noise.js";
|
|
@@ -19,10 +27,36 @@ export class PhoneSession {
|
|
|
19
27
|
this.closeCode = null;
|
|
20
28
|
this.closeReason = "";
|
|
21
29
|
this.closed = new Promise((resolve) => (this._resolveClosed = resolve));
|
|
30
|
+
/** open = 会话可用;down = 电脑闪断、等它回来;handshake = 正在(重新)握手。 */
|
|
31
|
+
this.state = "handshake";
|
|
32
|
+
/** 在原连接上重新握手成功的次数。 */
|
|
33
|
+
this.resumes = 0;
|
|
34
|
+
this._waiters = [];
|
|
22
35
|
}
|
|
23
36
|
request(req) {
|
|
37
|
+
if (!this.mux) return Promise.reject(new Error(this.state === "open" ? "session closed" : "computer is reconnecting"));
|
|
24
38
|
return this.mux.request(req);
|
|
25
39
|
}
|
|
40
|
+
/** 等会话(重新)可用。连接已关闭、或 `timeoutMs` 内没等到,则拒绝。 */
|
|
41
|
+
whenOpen(timeoutMs = 10_000) {
|
|
42
|
+
if (this.closeCode !== null) return Promise.reject(new Error(`closed (${this.closeCode})`));
|
|
43
|
+
if (this.state === "open") return Promise.resolve(this);
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
const waiter = { resolve, reject, timer: setTimeout(() => {
|
|
46
|
+
this._waiters = this._waiters.filter((w) => w !== waiter);
|
|
47
|
+
reject(new Error("timed out waiting for the computer"));
|
|
48
|
+
}, timeoutMs) };
|
|
49
|
+
this._waiters.push(waiter);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
_setState(state) {
|
|
53
|
+
this.state = state;
|
|
54
|
+
if (state !== "open") return;
|
|
55
|
+
for (const w of this._waiters.splice(0)) {
|
|
56
|
+
clearTimeout(w.timer);
|
|
57
|
+
w.resolve(this);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
26
60
|
close(code = 1000, reason = "bye") {
|
|
27
61
|
this._shutdown(code, reason);
|
|
28
62
|
try {
|
|
@@ -36,23 +70,31 @@ export class PhoneSession {
|
|
|
36
70
|
this.closeCode = code;
|
|
37
71
|
this.closeReason = reason;
|
|
38
72
|
clearInterval(this.pinger);
|
|
73
|
+
clearTimeout(this._rehandshakeTimer);
|
|
39
74
|
this.mux?.close(`closed ${code}`);
|
|
75
|
+
for (const w of this._waiters.splice(0)) {
|
|
76
|
+
clearTimeout(w.timer);
|
|
77
|
+
w.reject(new Error(`closed (${code})`));
|
|
78
|
+
}
|
|
40
79
|
this._resolveClosed({ code, reason });
|
|
41
80
|
}
|
|
42
81
|
}
|
|
43
82
|
|
|
44
83
|
/**
|
|
45
84
|
* @param {{ relayUrl:string, room:string, pcPub:Uint8Array, device:{priv:Uint8Array,pub:Uint8Array},
|
|
46
|
-
* name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number }} o
|
|
85
|
+
* name?:string, otp?:string, WebSocketImpl?:Function, timeoutMs?:number, resume?:boolean, lan?:boolean }} o
|
|
47
86
|
*/
|
|
48
|
-
export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000 }) {
|
|
87
|
+
export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", otp, WebSocketImpl = globalThis.WebSocket, timeoutMs = 10_000, resume = false, lan = false }) {
|
|
49
88
|
return new Promise((resolve, reject) => {
|
|
50
89
|
const phone = new PhoneSession();
|
|
51
|
-
|
|
90
|
+
// lan:电脑 LAN 桥上的局域网加密通道(T-25),路径不带房间号(房间号只在 Noise 的序言里)
|
|
91
|
+
const base = relayUrl.replace(/\/+$/, "");
|
|
92
|
+
const ws = new WebSocketImpl(lan ? `${base}/v1/lan` : `${base}/v1/guest/${room}${resume ? "?v=2" : ""}`);
|
|
52
93
|
ws.binaryType = "arraybuffer";
|
|
53
94
|
phone.ws = ws;
|
|
54
|
-
|
|
55
|
-
let stage = "relay"; // relay → handshake → open
|
|
95
|
+
let noise = null;
|
|
96
|
+
let stage = "relay"; // relay → handshake → open(resume 时还有:→ down → handshake → open …)
|
|
97
|
+
let opened = false; // 第一次握手完成过了吗(connectPhone 的 Promise 只在那时兑现)
|
|
56
98
|
let cipherOut = null;
|
|
57
99
|
let cipherIn = null;
|
|
58
100
|
const fail = (err) => {
|
|
@@ -67,19 +109,43 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
|
|
|
67
109
|
};
|
|
68
110
|
const timer = setTimeout(() => fail(new Error(`connect timeout in stage ${stage}`)), timeoutMs);
|
|
69
111
|
|
|
112
|
+
/** 握手总是全新的一次:新的临时密钥、新的握手哈希。重握时不带配对码(它是一次性的,已经用掉)。 */
|
|
70
113
|
const startHandshake = () => {
|
|
114
|
+
noise = new NoiseInitiator({ s: device, rs: pcPub, prologue: enc.encode(`DSH-RELAY/1|${room}`) });
|
|
71
115
|
stage = "handshake";
|
|
72
|
-
|
|
116
|
+
phone._setState("handshake");
|
|
117
|
+
ws.send(noise.writeMessage1(enc.encode(JSON.stringify({ v: 1, name, ...(otp && !opened ? { otp } : {}) }))));
|
|
118
|
+
if (opened) {
|
|
119
|
+
clearTimeout(phone._rehandshakeTimer);
|
|
120
|
+
phone._rehandshakeTimer = setTimeout(() => phone.close(4408, "re-handshake timeout"), timeoutMs);
|
|
121
|
+
phone._rehandshakeTimer.unref?.();
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/** 这条 Noise 会话作废:在途请求立刻失败,之后不再往这条会话里发任何东西。 */
|
|
125
|
+
const suspend = () => {
|
|
126
|
+
stage = "down";
|
|
127
|
+
cipherOut = null;
|
|
128
|
+
cipherIn = null;
|
|
129
|
+
const mux = phone.mux;
|
|
130
|
+
phone.mux = null;
|
|
131
|
+
mux?.close("computer is reconnecting");
|
|
132
|
+
phone._setState("down");
|
|
73
133
|
};
|
|
74
134
|
ws.addEventListener("message", (e) => {
|
|
75
135
|
try {
|
|
76
136
|
if (typeof e.data === "string") {
|
|
77
137
|
const msg = JSON.parse(e.data);
|
|
78
138
|
if (stage === "relay" && msg.t === "hello" && msg.host === true) return startHandshake();
|
|
139
|
+
if (msg.t === "host-down") {
|
|
140
|
+
if (resume && stage !== "relay") suspend();
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
79
143
|
if (msg.t === "host-up") {
|
|
80
144
|
if (stage === "relay") return startHandshake();
|
|
81
|
-
// 电脑重新上线(重启 / 换连接):我们的 Noise
|
|
82
|
-
return phone._shutdown(4503, "host restarted");
|
|
145
|
+
// 电脑重新上线(重启 / 换连接):我们的 Noise 会话已经无处可去
|
|
146
|
+
if (!resume) return phone._shutdown(4503, "host restarted"); // 旧版:上层重新连接
|
|
147
|
+
suspend();
|
|
148
|
+
return startHandshake();
|
|
83
149
|
}
|
|
84
150
|
return;
|
|
85
151
|
}
|
|
@@ -89,22 +155,33 @@ export function connectPhone({ relayUrl, room, pcPub, device, name = "Phone", ot
|
|
|
89
155
|
cipherOut = done.send;
|
|
90
156
|
cipherIn = done.recv;
|
|
91
157
|
phone.info = JSON.parse(dec.decode(done.payload));
|
|
92
|
-
|
|
158
|
+
const out = cipherOut;
|
|
159
|
+
phone.mux = new MuxSession({ role: "client", send: (frame) => ws.send(out.encrypt(frame)) });
|
|
160
|
+
stage = "open";
|
|
161
|
+
if (opened) {
|
|
162
|
+
clearTimeout(phone._rehandshakeTimer);
|
|
163
|
+
phone.resumes++;
|
|
164
|
+
// 电脑要求握手后限时内收到一条能解密的数据(防重放);不能指望上层恰好马上发请求
|
|
165
|
+
phone.mux.ping().catch(() => {});
|
|
166
|
+
return phone._setState("open");
|
|
167
|
+
}
|
|
168
|
+
opened = true;
|
|
93
169
|
phone.pinger = setInterval(() => { try { ws.send(JSON.stringify({ t: "ping" })); } catch { /* 连接正在断开 */ } }, 20_000);
|
|
94
170
|
phone.pinger.unref?.();
|
|
95
|
-
stage = "open";
|
|
96
171
|
clearTimeout(timer);
|
|
172
|
+
phone._setState("open");
|
|
97
173
|
return resolve(phone);
|
|
98
174
|
}
|
|
99
175
|
if (stage === "open") phone.mux.receive(cipherIn.decrypt(bytes));
|
|
176
|
+
// stage === "down":作废会话的迟到帧,丢弃
|
|
100
177
|
} catch (err) {
|
|
101
|
-
if (
|
|
178
|
+
if (!opened) return fail(err);
|
|
102
179
|
phone.close(4000, "protocol error");
|
|
103
180
|
}
|
|
104
181
|
});
|
|
105
182
|
ws.addEventListener("close", (e) => {
|
|
106
183
|
phone._shutdown(e.code ?? 1006, e.reason ?? "");
|
|
107
|
-
if (
|
|
184
|
+
if (!opened) {
|
|
108
185
|
clearTimeout(timer);
|
|
109
186
|
reject(Object.assign(new Error(`relay closed during ${stage} (${e.code})`), { code: e.code }));
|
|
110
187
|
}
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 最小的 WebSocket 服务端(RFC 6455),只给局域网加密通道用(T-25)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么自己写:插件除了 `qrcode` 不带任何运行时依赖,Node 只内置了 WebSocket **客户端**。这里需要的
|
|
5
|
+
* 只是「HTTP Upgrade 之后收发整条消息」,加密与认证都在上面一层的 Noise 里,所以只实现协议本身:
|
|
6
|
+
* · 握手:校验 Upgrade / Connection / Sec-WebSocket-Version: 13 / Sec-WebSocket-Key,回 101;
|
|
7
|
+
* · 收:客户端帧必须带掩码;支持分片(续帧);ping 自动回 pong;close 回 close 后断开;
|
|
8
|
+
* RSV 位、未知操作码、控制帧过长或分片 → 1002;消息超过 maxPayload → 1009;文本不是合法 UTF-8 → 1007;
|
|
9
|
+
* · 发:不分片、不带掩码;send(string) 发文本帧,send(Uint8Array) 发二进制帧。
|
|
10
|
+
* 不支持任何扩展(permessage-deflate 等)与子协议:握手时一概不回应,客户端就不会用。
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
|
|
14
|
+
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
15
|
+
const OP = Object.freeze({ CONT: 0, TEXT: 1, BIN: 2, CLOSE: 8, PING: 9, PONG: 10 });
|
|
16
|
+
const utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
17
|
+
|
|
18
|
+
/** 握手请求像不像一个 WebSocket 升级(不读请求体,只看头)。 */
|
|
19
|
+
export function isWebSocketUpgrade(req) {
|
|
20
|
+
const upgrade = String(req.headers.upgrade ?? "").toLowerCase();
|
|
21
|
+
const connection = String(req.headers.connection ?? "").toLowerCase();
|
|
22
|
+
return upgrade === "websocket" && connection.split(",").some((t) => t.trim() === "upgrade");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 拒绝一个升级请求:写一个最小的 HTTP 响应后断开。 */
|
|
26
|
+
export function rejectUpgrade(socket, status, text) {
|
|
27
|
+
try {
|
|
28
|
+
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
29
|
+
} catch {
|
|
30
|
+
/* 已断开 */
|
|
31
|
+
}
|
|
32
|
+
socket.destroy();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 完成握手,返回一条连接;握手不合规则回 400 并返回 null。
|
|
37
|
+
* @param {import("node:http").IncomingMessage} req
|
|
38
|
+
* @param {import("node:net").Socket} socket
|
|
39
|
+
* @param {Buffer} head 升级请求之后已经读到的字节(一般为空)
|
|
40
|
+
* @param {{ maxPayload?: number }} [o]
|
|
41
|
+
*/
|
|
42
|
+
export function acceptWebSocket(req, socket, head, { maxPayload = 1 << 20 } = {}) {
|
|
43
|
+
const key = String(req.headers["sec-websocket-key"] ?? "");
|
|
44
|
+
if (req.method !== "GET" || !isWebSocketUpgrade(req) || req.headers["sec-websocket-version"] !== "13" || !/^[A-Za-z0-9+/]{22}==$/.test(key)) {
|
|
45
|
+
rejectUpgrade(socket, 400, "Bad Request");
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const accept = createHash("sha1").update(key + GUID).digest("base64");
|
|
49
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
|
50
|
+
socket.setNoDelay?.(true);
|
|
51
|
+
return new ServerWebSocket(socket, head, maxPayload);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export class ServerWebSocket {
|
|
55
|
+
constructor(socket, head, maxPayload) {
|
|
56
|
+
this.socket = socket;
|
|
57
|
+
this.maxPayload = maxPayload;
|
|
58
|
+
this.readyState = 1; // 0 connecting · 1 open · 2 closing · 3 closed
|
|
59
|
+
this.closeCode = null;
|
|
60
|
+
this.listeners = { message: [], close: [] };
|
|
61
|
+
this.buf = head?.length ? Buffer.from(head) : Buffer.alloc(0);
|
|
62
|
+
this.frag = null; // 正在拼的分片消息:{ op, parts, size }
|
|
63
|
+
socket.on("data", (chunk) => this.#onData(chunk));
|
|
64
|
+
socket.on("close", () => this.#finish(this.closeCode ?? 1006));
|
|
65
|
+
socket.on("error", () => this.#finish(1006));
|
|
66
|
+
if (this.buf.length) queueMicrotask(() => this.#parse());
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** `message` → (data: string | Uint8Array);`close` → (code: number)。 */
|
|
70
|
+
on(type, fn) {
|
|
71
|
+
this.listeners[type]?.push(fn);
|
|
72
|
+
return this;
|
|
73
|
+
}
|
|
74
|
+
#emit(type, arg) {
|
|
75
|
+
for (const fn of this.listeners[type] ?? []) {
|
|
76
|
+
try {
|
|
77
|
+
fn(arg);
|
|
78
|
+
} catch {
|
|
79
|
+
/* 监听者的错误不影响连接 */
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
send(data) {
|
|
85
|
+
if (this.readyState !== 1) return false;
|
|
86
|
+
const text = typeof data === "string";
|
|
87
|
+
const payload = text ? Buffer.from(data, "utf8") : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
|
|
88
|
+
return this.#write(text ? OP.TEXT : OP.BIN, payload);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** 发 close 帧并在对端回应(或 2 秒)后断开。 */
|
|
92
|
+
close(code = 1000, reason = "") {
|
|
93
|
+
if (this.readyState >= 2) return;
|
|
94
|
+
this.readyState = 2;
|
|
95
|
+
this.closeCode = code;
|
|
96
|
+
const r = Buffer.from(String(reason).slice(0, 100), "utf8").subarray(0, 123);
|
|
97
|
+
const payload = Buffer.alloc(2 + r.length);
|
|
98
|
+
payload.writeUInt16BE(code, 0);
|
|
99
|
+
r.copy(payload, 2);
|
|
100
|
+
this.#write(OP.CLOSE, payload);
|
|
101
|
+
const t = setTimeout(() => this.socket.destroy(), 2000);
|
|
102
|
+
t.unref?.();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** 立刻断开,不走关闭握手(对端在乱发东西时用)。 */
|
|
106
|
+
terminate(code = 1006) {
|
|
107
|
+
this.closeCode ??= code;
|
|
108
|
+
this.socket.destroy();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
#write(op, payload) {
|
|
112
|
+
const n = payload.length;
|
|
113
|
+
let header;
|
|
114
|
+
if (n < 126) {
|
|
115
|
+
header = Buffer.from([0x80 | op, n]);
|
|
116
|
+
} else if (n < 65_536) {
|
|
117
|
+
header = Buffer.alloc(4);
|
|
118
|
+
header[0] = 0x80 | op;
|
|
119
|
+
header[1] = 126;
|
|
120
|
+
header.writeUInt16BE(n, 2);
|
|
121
|
+
} else {
|
|
122
|
+
header = Buffer.alloc(10);
|
|
123
|
+
header[0] = 0x80 | op;
|
|
124
|
+
header[1] = 127;
|
|
125
|
+
header.writeBigUInt64BE(BigInt(n), 2);
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
this.socket.write(Buffer.concat([header, payload]));
|
|
129
|
+
return true;
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
#onData(chunk) {
|
|
136
|
+
this.buf = this.buf.length ? Buffer.concat([this.buf, chunk]) : chunk;
|
|
137
|
+
this.#parse();
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
#fail(code) {
|
|
141
|
+
if (this.readyState >= 2) return void this.socket.destroy();
|
|
142
|
+
this.close(code);
|
|
143
|
+
this.socket.destroy();
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#parse() {
|
|
147
|
+
while (this.readyState === 1 || this.readyState === 2) {
|
|
148
|
+
const b = this.buf;
|
|
149
|
+
if (b.length < 2) return;
|
|
150
|
+
const fin = (b[0] & 0x80) !== 0;
|
|
151
|
+
const rsv = b[0] & 0x70;
|
|
152
|
+
const op = b[0] & 0x0f;
|
|
153
|
+
const masked = (b[1] & 0x80) !== 0;
|
|
154
|
+
let len = b[1] & 0x7f;
|
|
155
|
+
let off = 2;
|
|
156
|
+
if (rsv !== 0 || !masked) return this.#fail(1002); // 没有协商任何扩展;客户端帧必须带掩码
|
|
157
|
+
if (len === 126) {
|
|
158
|
+
if (b.length < 4) return;
|
|
159
|
+
len = b.readUInt16BE(2);
|
|
160
|
+
off = 4;
|
|
161
|
+
} else if (len === 127) {
|
|
162
|
+
if (b.length < 10) return;
|
|
163
|
+
const big = b.readBigUInt64BE(2);
|
|
164
|
+
if (big > BigInt(this.maxPayload)) return this.#fail(1009);
|
|
165
|
+
len = Number(big);
|
|
166
|
+
off = 10;
|
|
167
|
+
}
|
|
168
|
+
const control = op >= 8;
|
|
169
|
+
if (control && (len > 125 || !fin)) return this.#fail(1002);
|
|
170
|
+
if (!control && len > this.maxPayload) return this.#fail(1009);
|
|
171
|
+
if (b.length < off + 4 + len) return;
|
|
172
|
+
const mask = b.subarray(off, off + 4);
|
|
173
|
+
const payload = Buffer.from(b.subarray(off + 4, off + 4 + len));
|
|
174
|
+
for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
|
|
175
|
+
this.buf = b.subarray(off + 4 + len);
|
|
176
|
+
if (!this.#frame(fin, op, payload)) return;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** 处理一帧;返回 false 表示连接已经结束,停止解析。 */
|
|
181
|
+
#frame(fin, op, payload) {
|
|
182
|
+
switch (op) {
|
|
183
|
+
case OP.PING:
|
|
184
|
+
this.#write(OP.PONG, payload);
|
|
185
|
+
return true;
|
|
186
|
+
case OP.PONG:
|
|
187
|
+
return true;
|
|
188
|
+
case OP.CLOSE: {
|
|
189
|
+
const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
|
|
190
|
+
if (this.readyState === 1) {
|
|
191
|
+
// 对端先关:回一个 close 帧(带同样的码),然后断开
|
|
192
|
+
this.readyState = 2;
|
|
193
|
+
this.closeCode = code;
|
|
194
|
+
const echo = payload.length >= 2 ? payload.subarray(0, 2) : Buffer.alloc(0);
|
|
195
|
+
this.#write(OP.CLOSE, echo);
|
|
196
|
+
}
|
|
197
|
+
this.closeCode ??= code;
|
|
198
|
+
this.socket.end();
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
case OP.TEXT:
|
|
202
|
+
case OP.BIN:
|
|
203
|
+
if (this.frag) return this.#fail(1002) ?? false; // 上一条分片消息还没结束
|
|
204
|
+
if (fin) return this.#deliver(op, payload);
|
|
205
|
+
this.frag = { op, parts: [payload], size: payload.length };
|
|
206
|
+
return true;
|
|
207
|
+
case OP.CONT: {
|
|
208
|
+
const f = this.frag;
|
|
209
|
+
if (!f) return this.#fail(1002) ?? false;
|
|
210
|
+
f.size += payload.length;
|
|
211
|
+
if (f.size > this.maxPayload) return this.#fail(1009) ?? false;
|
|
212
|
+
f.parts.push(payload);
|
|
213
|
+
if (!fin) return true;
|
|
214
|
+
this.frag = null;
|
|
215
|
+
return this.#deliver(f.op, Buffer.concat(f.parts));
|
|
216
|
+
}
|
|
217
|
+
default:
|
|
218
|
+
return this.#fail(1002) ?? false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
#deliver(op, payload) {
|
|
223
|
+
if (this.readyState !== 1) return true; // 关闭中:后面的数据不再交出去
|
|
224
|
+
if (op === OP.TEXT) {
|
|
225
|
+
let text;
|
|
226
|
+
try {
|
|
227
|
+
text = utf8.decode(payload);
|
|
228
|
+
} catch {
|
|
229
|
+
this.#fail(1007);
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
this.#emit("message", text);
|
|
233
|
+
} else {
|
|
234
|
+
this.#emit("message", new Uint8Array(payload.buffer, payload.byteOffset, payload.byteLength));
|
|
235
|
+
}
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
#finish(code) {
|
|
240
|
+
if (this.readyState === 3) return;
|
|
241
|
+
this.readyState = 3;
|
|
242
|
+
this.closeCode ??= code;
|
|
243
|
+
this.#emit("close", this.closeCode);
|
|
244
|
+
}
|
|
245
|
+
}
|