dsh-plugin-mesh 0.5.11 → 0.5.13

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.en.md CHANGED
@@ -78,15 +78,16 @@ is often blocked by routers — the panel's **Scan subnet** button works around
78
78
 
79
79
  ## Security defaults — read this
80
80
 
81
- **A first task from an unknown machine does not run.** It is held as
82
- `needs-approval` and the panel asks the owner once ("Allow" / "Deny"); nothing wakes
83
- until it is allowed. Approved machines are remembered locally (`approvedPeers` in
84
- `state.json`). Set `requireApproval: false` to restore fully unattended dispatch.
81
+ **Dispatch works out of the box.** Zero configuration: a machine you can reach can
82
+ hand you a task and it runs, with no prompt. That is deliberate — working immediately
83
+ is the point. Pairing (below) is the gate to turn on; a per-machine “did you allow
84
+ this device?” prompt still exists in the code but is debug-only
85
+ (`DSH_MESH_REQUIRE_APPROVAL=1`) until someone actually asks for it as a setting.
85
86
 
86
87
  Discovery is intentionally public so you can see machines before deciding to talk to
87
88
  them. On an untrusted network (café, dorm, office) also turn on pairing:
88
89
 
89
- 1. Flip the switch in the Mesh panel's **pairing** card — it takes effect immediately, no restart. (Writing `requirePairing: true` in `cordis.patch.yml` also works and pins it on, so the UI cannot turn it off. Pairing also skips the per-machine approval prompt, since it is the stronger trust gesture.)
90
+ 1. Flip the switch in the Mesh panel's **pairing** card — it takes effect immediately, no restart. (Writing `requirePairing: true` in `cordis.patch.yml` also works and pins it on, so the UI cannot turn it off.) A dispatch whose `x-dsh-mesh-token` header does not match this machine's secret is rejected with HTTP 403; discovery and health probes stay public.
90
91
  2. Make the pairing secret identical on both machines (the Mesh panel has a field for it).
91
92
 
92
93
  Note the token travels in a plain HTTP header: it guards against stray devices on
package/README.md CHANGED
@@ -75,14 +75,16 @@ dsh plugin add dsh-plugin-mesh
75
75
  **第 5 步 · 看结果**
76
76
 
77
77
  派出去只是「送达」。对端跑完会把结果派回来,出现在「任务」里。
78
- 第一次往一台**陌生**设备派活时,对方会先弹一次「允许」—— 点过之后不再问(这是默认行为,见下面「安全」)。
78
+ 默认装好就能直接派活,不用配对码、也不用点任何确认 —— 要加一道保护见下面「安全」。
79
79
 
80
80
  ---
81
81
 
82
- ## 安全:默认不再敞着门
82
+ ## 安全:默认能直接派,保护按需打开
83
83
 
84
- - **陌生设备第一次派活,本机要先点一次「允许」**。允许过的设备记在本地,不会重复问。
85
- - 在不可信网络(公司、合租、咖啡厅)里,打开「配对码」:两端用同一个码,别人即使连得上也派不进来。
84
+ - **默认零配置**:同一局域网里发现即可互相派活,没有确认弹窗。这是刻意的 —— 装上就能用是它的价值。
85
+ - 在不可信网络(公司、合租、咖啡厅)里,打开「配对码」:两端用同一个码,码不一致的派活请求直接被 HTTP 403 拒掉。
86
+ - 配对码走的是**明文 HTTP 头**:它挡的是误连上来的陌生设备,挡不住同网段的抓包嗅探 —— 完全不可信的网络别只靠它。
87
+ - 暂时不想被任何人找到:用面板上的「一键关闭」停掉局域网 / 互联网组网。
86
88
  - 对端派来的任务默认用 `workspace-write` 权限,不给 `danger-full-access`。
87
89
  - 所有数据都在本机:没有账号、没有云端、不上报任何统计。
88
90
 
package/client/client.js CHANGED
@@ -4035,7 +4035,7 @@ window.__ModuleLoader__.load({
4035
4035
  ),
4036
4036
  ),
4037
4037
  error ? h("div", { className: "mesh-sheet-error" }, error) : null,
4038
- h("p", { className: "mesh-hint" }, "派发是异步的:这里成功只代表对端收了。它跑完会把结果派回来,出现在「任务」里。第一次派给陌生设备时,对方会先问你一次。⌘/Ctrl + Enter 发送。"),
4038
+ h("p", { className: "mesh-hint" }, "派发是异步的:这里成功只代表对端收了。它跑完会把结果派回来,出现在「任务」里。⌘/Ctrl + Enter 发送。"),
4039
4039
  ),
4040
4040
  h(
4041
4041
  "div",
package/cordis.patch.yml CHANGED
@@ -53,12 +53,6 @@
53
53
  # 若网络不完全可信(合租/公司/有访客设备),改成 true 再对齐配对码。
54
54
  requirePairing: false
55
55
 
56
- # 陌生设备第一次派活时,本机先弹一次确认(默认开)。
57
- # 允许过的设备写进 state.json 的 approvedPeers,同一台不再问。
58
- # 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
59
- # 想让内网完全免打扰(自己家几台机器)就改成 false。
60
- requireApproval: true
61
-
62
56
  # 对端任务在本机新建会话时的选项
63
57
  agentPreset: standard
64
58
  # 对端派来的是外部不可信输入,默认不给 danger-full-access
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * 「陌生设备首次派活要确认」的自测。
3
3
  *
4
- * 这是安全相关判定,判错的后果是静默的:界面上写着"默认会先问你",实际上
5
- * 陌生机器照样能直接让本机开一个 agent 会话。所以用断言盯死这几件事:
6
- * · 缺省要拦(不能因为 config 里没写这个键就放行)
7
- * · 显式 false 才不拦
4
+ * 这道闸已经从配置项降级成「仅调试用」(DSH_MESH_REQUIRE_APPROVAL=1),
5
+ * 判错的后果是静默的:界面上写着"默认不问",实际上陌生机器会被挂起;或者
6
+ * 反过来,明明开了闸却照样放行。所以用断言盯死这几件事:
7
+ * · enabled 不为 true = 不拦(默认关,装上就能派活)
8
+ * · 只有 enabled: true 才拦
8
9
  * · 允许过一台,就只放行这一台(按机器名或地址命中)
9
10
  * · 配对码开启时不重复问(它是更强的信任动作)
10
11
  * · 撤销之后立刻重新拦
@@ -46,31 +47,36 @@ const taskFrom = (machine, address = "") => ({
46
47
  sourceAddress: address,
47
48
  });
48
49
 
49
- console.log("\n── 缺省必须拦:这是「装上就安全」的底线 ──");
50
+ console.log("\n── 默认放行:只有调试开关打开才拦 ──");
50
51
 
51
- test("config 里没有 requireApproval 这个键 → 仍然要拦", () => {
52
+ test("不传 enabled → 不拦(默认关,装上就能直接派活)", () => {
52
53
  const peer = peerOfTask(taskFrom("陌生机"));
53
- assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
54
+ assert.equal(needsApproval({ approved: [], peer }), false);
54
55
  });
55
56
 
56
- test("显式 requireApproval: false 才放行(老用户想回到零配置)", () => {
57
+ test("enabled: false → 不拦", () => {
57
58
  const peer = peerOfTask(taskFrom("陌生机"));
58
- assert.equal(needsApproval({ config: { requireApproval: false }, approved: [], peer }), false);
59
+ assert.equal(needsApproval({ enabled: false, approved: [], peer }), false);
60
+ });
61
+
62
+ test("enabled: true 才拦", () => {
63
+ const peer = peerOfTask(taskFrom("陌生机"));
64
+ assert.equal(needsApproval({ enabled: true, approved: [], peer }), true);
59
65
  });
60
66
 
61
67
  test("配对码已开启 → 不再重复问(配对码是更强的信任动作)", () => {
62
68
  const peer = peerOfTask(taskFrom("陌生机"));
63
- assert.equal(needsApproval({ config: {}, approved: [], peer, pairingRequired: true }), false);
69
+ assert.equal(needsApproval({ enabled: true, approved: [], peer, pairingRequired: true }), false);
64
70
  });
65
71
 
66
72
  console.log("\n── 允许过的机器要记住,且只记这一台 ──");
67
73
 
68
- test("允许 A 之后 A 免问、B 仍然要问", () => {
74
+ test("开了闸之后:允许 A,A 免问、B 仍然要问", () => {
69
75
  const a = peerOfTask(taskFrom("A机"));
70
76
  const b = peerOfTask(taskFrom("B机"));
71
77
  const approved = approvePeer([], a, "2026-01-01T00:00:00.000Z");
72
- assert.equal(needsApproval({ config: {}, approved, peer: a }), false);
73
- assert.equal(needsApproval({ config: {}, approved, peer: b }), true);
78
+ assert.equal(needsApproval({ enabled: true, approved, peer: a }), false);
79
+ assert.equal(needsApproval({ enabled: true, approved, peer: b }), true);
74
80
  });
75
81
 
76
82
  test("机器名大小写不敏感(Windows 上尤其重要)", () => {
@@ -106,7 +112,7 @@ test("撤销之后立刻重新拦", () => {
106
112
  const a = peerOfTask(taskFrom("A机"));
107
113
  const approved = approvePeer([], a);
108
114
  const revoked = revokePeer(approved, "a机");
109
- assert.equal(needsApproval({ config: {}, approved: revoked, peer: a }), true);
115
+ assert.equal(needsApproval({ enabled: true, approved: revoked, peer: a }), true);
110
116
  });
111
117
 
112
118
  console.log("\n── 坏数据不能把闸门炸开 ──");
@@ -117,9 +123,9 @@ test("approvedPeers 是 null / 字符串 / 混入坏条目 → 归一化成空
117
123
  assert.deepEqual(normalizeApproved([null, 1, "x", {}, { machine: "ok" }]).length, 1);
118
124
  });
119
125
 
120
- test("既没有机器名也没有地址的对端 → 必须问(不能因为认不出来就放行)", () => {
126
+ test("开了闸时,认不出是谁的对端 → 必须问(不能因为认不出来就放行)", () => {
121
127
  const peer = peerOfTask({ from: "", sourceAddress: "" });
122
- assert.equal(needsApproval({ config: {}, approved: [], peer }), true);
128
+ assert.equal(needsApproval({ enabled: true, approved: [], peer }), true);
123
129
  });
124
130
 
125
131
  test("批准记录有上限,不会无限增长", () => {
@@ -0,0 +1,317 @@
1
+ /**
2
+ * 「经 mesh 口转发对端 Web GUI」的自测。
3
+ *
4
+ * 断言的重点不是"能转发",而是**改写是否真的到位** —— 这条通道的全部难点都在
5
+ * 那三个头上:Host / Origin(对端围栏按它判同源,不改就 403)、Cookie(会话只能
6
+ * 由被看端自己签)。历史教训是"看着接好了、其实一用就 403",所以这里逐条验,
7
+ * 并且验票据被抹掉、Set-Cookie 不外泄。
8
+ *
9
+ * 全部无外网:上游与被测转发器都只监听 127.0.0.1,端口由系统分配。
10
+ *
11
+ * node lib/_selftest-peer-web.mjs
12
+ */
13
+ import { strict as assert } from "node:assert";
14
+ import { createHmac } from "node:crypto";
15
+ import { createServer } from "node:http";
16
+ import { connect as netConnect } from "node:net";
17
+ import {
18
+ PEER_WEB_PREFIX,
19
+ PEER_WEB_TICKET_HEADER,
20
+ PEER_WEB_TICKET_TTL_MS,
21
+ createPeerWebForwarder,
22
+ createPeerWebTicket,
23
+ inspectPeerWebTicket,
24
+ peerWebRemainder,
25
+ verifyPeerWebTicket,
26
+ } from "./peer-web.js";
27
+ import { signSessionCookie } from "./desktop-auth.js";
28
+ import { createWebProxy } from "./web-proxy.js";
29
+
30
+ let passed = 0;
31
+ let failed = 0;
32
+ function test(name, fn) {
33
+ try {
34
+ const result = fn();
35
+ if (result instanceof Promise) return result.then(
36
+ () => { passed += 1; console.log(` ✓ ${name}`); },
37
+ (error) => { failed += 1; console.log(` ✗ ${name}\n ${error?.message ?? error}`); },
38
+ );
39
+ passed += 1;
40
+ console.log(` ✓ ${name}`);
41
+ } catch (error) {
42
+ failed += 1;
43
+ console.log(` ✗ ${name}\n ${error?.message ?? error}`);
44
+ }
45
+ return Promise.resolve();
46
+ }
47
+
48
+ /** 起一个只监听回环的服务器,返回 { port, close }。 */
49
+ function listen(server) {
50
+ return new Promise((resolvePromise) => {
51
+ server.listen(0, "127.0.0.1", () => {
52
+ resolvePromise({
53
+ port: server.address().port,
54
+ close: () => new Promise((done) => server.close(() => done())),
55
+ });
56
+ });
57
+ });
58
+ }
59
+
60
+ const SECRET = "mesh-secret-for-test";
61
+ const WEB_SECRET = Buffer.from("browser-session-secret-for-test", "utf8");
62
+
63
+ console.log("── 票据 ──");
64
+ await test("合法票据:12 小时内有效", () => {
65
+ const ticket = createPeerWebTicket(SECRET, { now: 1_000_000 });
66
+ assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_000_000 }), { ok: true });
67
+ assert.equal(verifyPeerWebTicket(SECRET, ticket, { now: 1_000_000 + PEER_WEB_TICKET_TTL_MS - 1 }), true);
68
+ });
69
+
70
+ await test("过期票据:报 expired,不报 malformed", () => {
71
+ const ticket = createPeerWebTicket(SECRET, { now: 1_000_000, ttlMs: 1000 });
72
+ // expiresAt = 1_001_000:到期那一刻就该拒绝(<= now)
73
+ assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_001_000 }), { ok: false, reason: "expired" });
74
+ });
75
+
76
+ await test("换密钥签的票据:报 signature(不是过期、不是格式)", () => {
77
+ const ticket = createPeerWebTicket("someone-else", { now: 1_000_000 });
78
+ assert.deepEqual(inspectPeerWebTicket(SECRET, ticket, { now: 1_000_000 }), { ok: false, reason: "signature" });
79
+ });
80
+
81
+ await test("篡改有效期:报 signature", () => {
82
+ const ticket = createPeerWebTicket(SECRET, { now: 1_000_000, ttlMs: 1000 });
83
+ const forged = Buffer.from(String(Date.now() + 10 * PEER_WEB_TICKET_TTL_MS)).toString("base64url")
84
+ + ticket.slice(ticket.lastIndexOf("."));
85
+ assert.deepEqual(inspectPeerWebTicket(SECRET, forged, { now: 1_000_000 }), { ok: false, reason: "signature" });
86
+ });
87
+
88
+ await test("空/畸形票据:报 malformed", () => {
89
+ assert.deepEqual(inspectPeerWebTicket(SECRET, ""), { ok: false, reason: "malformed" });
90
+ assert.deepEqual(inspectPeerWebTicket(SECRET, "nodot"), { ok: false, reason: "malformed" });
91
+ assert.deepEqual(inspectPeerWebTicket(SECRET, "a."), { ok: false, reason: "malformed" });
92
+ });
93
+
94
+ console.log("── 路径还原 ──");
95
+ await test("剥前缀 + 抹掉票据参数", () => {
96
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/api/state`), "/api/state");
97
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/api/x?a=1&t=zzz`), "/api/x?a=1");
98
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/plugins/p.js?t=zzz`), "/plugins/p.js");
99
+ });
100
+
101
+ await test("DSH 的 /plugins/??a,b&rev=… 逐字节保留(回归:编码坏会让模块脚本吃到 index.html)", () => {
102
+ const raw = `${PEER_WEB_PREFIX}/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5`;
103
+ assert.equal(
104
+ peerWebRemainder(raw),
105
+ "/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5",
106
+ );
107
+ assert.equal(
108
+ peerWebRemainder(`${raw}&t=ticket`),
109
+ "/plugins/??@deepseek-ai/dsh-client-modules/client.js,@x/y/client.js&rev=cddf5581d5d5",
110
+ );
111
+ });
112
+
113
+ await test("只摘 t 参数:&t=、?t= 都不误伤邻居参数", () => {
114
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/a?x=1&t=zz&y=2`), "/a?x=1&y=2");
115
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/a?t=zz`), "/a");
116
+ });
117
+
118
+ await test("前缀本身 → /", () => {
119
+ assert.equal(peerWebRemainder(PEER_WEB_PREFIX), "/");
120
+ assert.equal(peerWebRemainder(`${PEER_WEB_PREFIX}/`), "/");
121
+ });
122
+
123
+ await test("前缀外 → undefined", () => {
124
+ assert.equal(peerWebRemainder("/mesh/v1/health"), undefined);
125
+ assert.equal(peerWebRemainder("/mesh/peer-webx/a"), undefined);
126
+ });
127
+
128
+ console.log("── HTTP 转发 ──");
129
+ {
130
+ const seen = [];
131
+ const upgraded = [];
132
+ const upstream = createServer((req, res) => {
133
+ seen.push({ url: req.url, headers: req.headers });
134
+ res.writeHead(200, { "content-type": "application/json", "set-cookie": "upstream=forbidden-to-leak" });
135
+ res.end(JSON.stringify({ ok: true, url: req.url }));
136
+ });
137
+ // 上游的流式载波:只回 101,稍后关掉(这里不需要真的说 WS 帧)
138
+ upstream.on("upgrade", (req, socket) => {
139
+ upgraded.push({ url: req.url, headers: req.headers });
140
+ socket.write("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n");
141
+ setTimeout(() => socket.destroy(), 150);
142
+ });
143
+ const upstreamInfo = await listen(upstream);
144
+ const forwarder = createPeerWebForwarder({
145
+ portOf: () => upstreamInfo.port,
146
+ secretOf: () => WEB_SECRET,
147
+ });
148
+ const mesh = createServer((req, res) => forwarder.handle(req, res));
149
+ mesh.on("upgrade", (req, socket, head) => forwarder.upgrade(req, socket, head));
150
+ const meshInfo = await listen(mesh);
151
+
152
+ await test("转发到上游:路径正确、票据被抹掉", async () => {
153
+ const res = await fetch(`http://127.0.0.1:${meshInfo.port}${PEER_WEB_PREFIX}/api/state?a=1&t=secret-ticket`, {
154
+ headers: { [PEER_WEB_TICKET_HEADER]: "secret-ticket", "x-dsh-mesh-token": "mesh-secret" },
155
+ });
156
+ assert.equal(res.status, 200);
157
+ const body = await res.json();
158
+ assert.equal(body.url, "/api/state?a=1");
159
+ assert.equal(seen.length, 1);
160
+ });
161
+
162
+ await test("Host / Origin / Referer 都改写成上游自己的 authority", () => {
163
+ const { headers } = seen[0];
164
+ const authority = `127.0.0.1:${upstreamInfo.port}`;
165
+ assert.equal(headers.host, authority);
166
+ assert.equal(headers.origin, `http://${authority}`);
167
+ assert.equal(headers.origin, `http://${headers.host}`, "Origin 必须与 Host 同源,否则对端围栏 403");
168
+ });
169
+
170
+ await test("会话 cookie 由转发器按上游 authority 自己签", () => {
171
+ const { headers } = seen[0];
172
+ const authority = `127.0.0.1:${upstreamInfo.port}`;
173
+ const expected = signSessionCookie(WEB_SECRET, authority);
174
+ const cookie = String(headers.cookie ?? "");
175
+ const name = cookie.slice(0, cookie.indexOf("="));
176
+ // cookie 名绑定 authority;payload 里也必须写的就是上游 authority。
177
+ // (签名含 issuedAt,所以不能拿两次签名做字符串比较 —— 只验结构。
178
+ assert.equal(name, expected.name);
179
+ const payload = JSON.parse(Buffer.from(cookie.split(".")[1], "base64url").toString("utf8"));
180
+ assert.equal(payload.authority, authority);
181
+ assert.equal(payload.version, 1);
182
+ });
183
+
184
+ await test("票据头与 mesh 密钥头都不会带给上游", () => {
185
+ assert.equal(seen[0].headers[PEER_WEB_TICKET_HEADER], undefined);
186
+ assert.equal(seen[0].headers["x-dsh-mesh-token"], undefined);
187
+ });
188
+
189
+ await test("上游的 Set-Cookie 不会泄进隧道", async () => {
190
+ const res = await fetch(`http://127.0.0.1:${meshInfo.port}${PEER_WEB_PREFIX}/api/state`);
191
+ assert.equal(res.headers.get("set-cookie"), null);
192
+ });
193
+
194
+ await test("没有 Web 端口时如实 503,不装作转发成功", async () => {
195
+ const noGui = createServer((req, res) => {
196
+ createPeerWebForwarder({ portOf: () => 0, secretOf: () => WEB_SECRET }).handle(req, res);
197
+ });
198
+ const noGuiInfo = await listen(noGui);
199
+ const res = await fetch(`http://127.0.0.1:${noGuiInfo.port}${PEER_WEB_PREFIX}/`);
200
+ assert.equal(res.status, 503);
201
+ const text = await res.text();
202
+ assert.match(text, /Web GUI/);
203
+ await noGuiInfo.close();
204
+ });
205
+
206
+ console.log("── WebSocket 升级 ──");
207
+ await test("升级请求被搬到上游并回 101", async () => {
208
+ const reply = await new Promise((resolvePromise, reject) => {
209
+ const socket = netConnect(meshInfo.port, "127.0.0.1", () => {
210
+ socket.write(
211
+ [
212
+ `GET ${PEER_WEB_PREFIX}/api/remote.mux HTTP/1.1`,
213
+ `host: 127.0.0.1:${meshInfo.port}`,
214
+ "connection: Upgrade",
215
+ "upgrade: websocket",
216
+ "sec-websocket-version: 13",
217
+ "sec-websocket-key: dGhlIHNhbXBsZSBub25jZQ==",
218
+ `${PEER_WEB_TICKET_HEADER}: t`,
219
+ "",
220
+ "",
221
+ ].join("\r\n"),
222
+ );
223
+ });
224
+ let buffer = "";
225
+ socket.setTimeout(4000);
226
+ socket.on("data", (chunk) => {
227
+ buffer += chunk.toString("utf8");
228
+ if (buffer.includes("\r\n")) {
229
+ socket.destroy();
230
+ resolvePromise(buffer.split("\r\n")[0]);
231
+ }
232
+ });
233
+ socket.on("timeout", () => { socket.destroy(); reject(new Error("升级超时")); });
234
+ socket.on("error", reject);
235
+ });
236
+ assert.match(reply, /101/);
237
+ });
238
+
239
+ await upstreamInfo.close();
240
+ await meshInfo.close();
241
+ }
242
+
243
+
244
+ console.log("── 端到端:本机反代 → mesh 隧道 → GUI(含同源围栏)──");
245
+ {
246
+ const SESSION = Buffer.from("e2e-browser-session-secret", "utf8");
247
+ const fenceSeen = [];
248
+ /**
249
+ * 按真实服务端的**验证**语义校验 cookie(而不是重新签一次做字符串比较 ——
250
+ * 签名里含 issuedAt,两次签名天然不同,比字符串会假失败)。
251
+ */
252
+ const cookieValid = (cookie, host) => {
253
+ const eq = String(cookie).indexOf("=");
254
+ if (eq === -1) return false;
255
+ const [head, value] = [String(cookie).slice(0, eq), String(cookie).slice(eq + 1)];
256
+ if (head !== signSessionCookie(SESSION, host).name) return false;
257
+ const parts = value.split(".");
258
+ if (parts.length !== 3 || parts[0] !== "v1") return false;
259
+ if (parts[2] !== createHmac("sha256", SESSION).update(parts[1]).digest("base64url")) return false;
260
+ try {
261
+ const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
262
+ return payload.authority === host && payload.expiresAt > Date.now();
263
+ } catch {
264
+ return false;
265
+ }
266
+ };
267
+ // 模拟真实 GUI 的围栏:Host 必须是回环,Origin 必须与 Host 同源,cookie 必须验得过
268
+ const gui = createServer((req, res) => {
269
+ const host = String(req.headers.host ?? "");
270
+ const origin = req.headers.origin;
271
+ const cookie = String(req.headers.cookie ?? "");
272
+ fenceSeen.push({ url: req.url, host, origin, cookie });
273
+ const originOk = origin === undefined || new URL(String(origin)).host === host;
274
+ if (!/^127\.0\.0\.1:\d+$/.test(host) || !originOk) { res.writeHead(403); res.end("forbidden"); return; }
275
+ if (!cookieValid(cookie, host)) { res.writeHead(401); res.end("unauthorized"); return; }
276
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
277
+ res.end("<title>peer gui</title>");
278
+ });
279
+ const guiInfo = await listen(gui);
280
+ const forwarder = createPeerWebForwarder({ portOf: () => guiInfo.port, secretOf: () => SESSION });
281
+ const mesh = createServer((req, res) => forwarder.handle(req, res));
282
+ mesh.on("upgrade", (req, socket, head) => forwarder.upgrade(req, socket, head));
283
+ const meshInfo = await listen(mesh);
284
+
285
+ const proxy = await createWebProxy({
286
+ remoteBase: `http://127.0.0.1:${meshInfo.port}/`,
287
+ nonce: "e2e-nonce",
288
+ pathPrefix: PEER_WEB_PREFIX,
289
+ passthrough: true,
290
+ upstreamHeaders: { [PEER_WEB_TICKET_HEADER]: "e2e-ticket" },
291
+ });
292
+
293
+ await test("浏览器的 Origin(回环代理端口)不会让对端 403", async () => {
294
+ const res = await fetch(`${proxy.url}`);
295
+ assert.equal(res.status, 200);
296
+ assert.match(await res.text(), /peer gui/);
297
+ const last = fenceSeen.at(-1);
298
+ assert.equal(last.origin, `http://${last.host}`, "隧道必须把 Origin 改写成上游同源,否则 403");
299
+ assert.equal(last.url, "/", "根路径要落到上游 /");
300
+ });
301
+
302
+ await test("带门禁 cookie 打一个围栏接口:200(不是 403/401)", async () => {
303
+ const first = await fetch(`${proxy.url}`);
304
+ const gate = String(first.headers.get("set-cookie") ?? "").split(";")[0];
305
+ first.body?.cancel?.();
306
+ const res = await fetch(`http://127.0.0.1:${proxy.port}/api/state`, { headers: { cookie: gate } });
307
+ assert.equal(res.status, 200);
308
+ assert.equal(fenceSeen.at(-1).url, "/api/state");
309
+ });
310
+
311
+ await proxy.close();
312
+ await guiInfo.close();
313
+ await meshInfo.close();
314
+ }
315
+
316
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败`);
317
+ process.exitCode = failed === 0 ? 0 : 1;
package/lib/approval.js CHANGED
@@ -6,9 +6,11 @@
6
6
  * 咖啡厅"就是敞着门。原来的答案是"你去开配对码",但那是个**设置项**,没人会
7
7
  * 主动打开 —— 而恐惧是装之前就有的,不是用完才有的。
8
8
  *
9
- * 所以默认改成:陌生设备第一次派活 → 本机弹一次确认;你点过「允许」之后,
10
- * 这台机器才不再问你。配对码(requirePairing)比它更强,开了配对码就说明
11
- * 你已经用共享密钥表达过信任,不再多问一遍。
9
+ * 所以它保留了这套判定,但**不再是配置项**:默认关,只在调试时用环境变量
10
+ * `DSH_MESH_REQUIRE_APPROVAL=1` 打开(见 docs/DESIGN-NOTES.md)。打开后陌生
11
+ * 设备第一次派活 → 本机弹一次确认;你点过「允许」之后,这台机器才不再问你。
12
+ * 配对码(requirePairing)比它更强,开了配对码就说明你已经用共享密钥表达过
13
+ * 信任,不再多问一遍。等有人真的要这个能力,再把它捡回配置项。
12
14
  *
13
15
  * 规则写在这里而不是埋进 3000 行的 index.js:这是安全相关判定,写错了会
14
16
  * "看起来拦住了、实际放行",而这种错误没人会为它写测试。拆出来,单测它。
@@ -111,15 +113,15 @@ export function revokePeer(approved, target) {
111
113
  * **不要**在这里判断"是不是自己派给自己"——那属于路由层,不属于信任层。
112
114
  *
113
115
  * @param {object} input
114
- * @param {object} input.config 插件配置(读 requireApproval)
116
+ * @param {boolean} input.enabled 闸门是否打开(调试环境变量,默认 false)
115
117
  * @param {Array} input.approved state.json 的 approvedPeers
116
118
  * @param {object} input.peer peerOfTask 的返回值
117
119
  * @param {boolean} input.pairingRequired pairingRequired(config) 的结果
118
120
  * @returns {boolean}
119
121
  */
120
- export function needsApproval({ config = {}, approved = [], peer = {}, pairingRequired = false }) {
121
- // 显式 false 才关;缺省按开(schema 默认也是 true)。
122
- if (config?.requireApproval === false) return false;
122
+ export function needsApproval({ enabled = false, approved = [], peer = {}, pairingRequired = false }) {
123
+ // 只有显式打开才拦:这不是配置项,缺省一律放行(装上就能直接派活)。
124
+ if (enabled !== true) return false;
123
125
  // 配对码是比"点一次允许"更强的信任动作:开了它就不再重复问。
124
126
  if (pairingRequired) return false;
125
127
  if (!peer || !(peer.machine || peer.address)) return true;
package/lib/discovery.js CHANGED
@@ -117,7 +117,10 @@ export function preferredAddress() {
117
117
  * 内存拷贝)。同网段时 Tailscale 自己也会走直连,所以实测延迟差不多,但走
118
118
  * tsnet 仍然多一层用户态转发,没有理由优先。
119
119
  */
120
- export const TRANSPORT_RANK = { lan: 0, tsnet: 1 };
120
+ // `ws` sits ahead of plain HTTP: same host and port, but the connection can
121
+ // push. When it fails, ordering falls through to `lan` exactly as before, so
122
+ // this is a preference and not a dependency.
123
+ export const TRANSPORT_RANK = { ws: -1, lan: 0, tsnet: 1 };
121
124
 
122
125
  /** 一次失败后把端点标记为 down 的冷却时长;冷却期内不再尝试它。 */
123
126
  export const ENDPOINT_COOLDOWN_MS = 30000;
@@ -224,6 +227,15 @@ async function loadDgramModule() {
224
227
  let dgram;
225
228
 
226
229
  export class MeshDiscovery extends EventEmitter {
230
+ /**
231
+ * Which transports this instance offers, as its card advertises them.
232
+ *
233
+ * `lan` is unconditional — the HTTP server is the desktop's own shape. A
234
+ * build that also serves the mesh WebSocket adds `ws`; a page (which has no
235
+ * inbound surface at all) leaves it empty.
236
+ */
237
+ transports = ["lan"];
238
+
227
239
  #id;
228
240
  #port;
229
241
  #meta;
@@ -326,6 +338,8 @@ export class MeshDiscovery extends EventEmitter {
326
338
  machine: this.#meta.machine ?? os.hostname(),
327
339
  hostname: os.hostname(),
328
340
  host: this.#address,
341
+ // Which transports this build offers; older peers ignore the field.
342
+ transports: this.transports,
329
343
  port: this.#port,
330
344
  os: `${os.platform()} ${os.release()}`,
331
345
  // 结构化系统身份(平台/系统名/版本/发行版/内核/桌面/架构)。
@@ -907,6 +921,32 @@ export class MeshDiscovery extends EventEmitter {
907
921
  verified: prevEp?.verified === true || verified,
908
922
  };
909
923
 
924
+ // A peer that says it speaks the mesh WebSocket gets a second endpoint on
925
+ // the same address. Ordering prefers it; a failure falls through to the
926
+ // HTTP endpoint below it, so the fallback needs no branch in the send path.
927
+ if (Array.isArray(msg.transports) && msg.transports.includes("ws") && host && port) {
928
+ const wsPrev = peer.endpoints.ws;
929
+ peer.endpoints.ws = {
930
+ key: "ws",
931
+ transport: "ws",
932
+ channel: "ws",
933
+ host,
934
+ port,
935
+ lastSeen: now,
936
+ lastOkAt: wsPrev?.lastOkAt ?? 0,
937
+ lastFailAt: wsPrev?.lastFailAt ?? 0,
938
+ okCount: wsPrev?.okCount ?? 0,
939
+ failCount: wsPrev?.failCount ?? 0,
940
+ rttMs: wsPrev?.rttMs ?? 0,
941
+ downUntil: wsPrev?.downUntil ?? 0,
942
+ // Claimed, not proven: only a successful send or probe may verify it.
943
+ verified: wsPrev?.verified === true,
944
+ };
945
+ } else if (peer.endpoints.ws !== undefined && !Array.isArray(msg.transports)) {
946
+ // Older peer: it never advertised transports, so it has no ws endpoint.
947
+ delete peer.endpoints.ws;
948
+ }
949
+
910
950
  // ── 对端在名片里自报了 tailnet 地址 → 每个地址记一条**未验证**候选端点 ──
911
951
  //
912
952
  // 这样局域网一断就能直接拿它试,不必先扫一遍 tailnet —— 这就是决定 #2