dsh-plugin-mesh 0.5.10 → 0.5.12

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
@@ -123,4 +124,16 @@ The full key list with defaults is in [`llms.txt`](llms.txt#configuration).
123
124
  | Issues | https://github.com/peng456/dsh-plugin-mesh/issues |
124
125
  | Contact | geekstartup@163.com |
125
126
 
127
+ ---
128
+
129
+ ## Sponsors
130
+
131
+ <a href="https://omdsh.dev/"><img src="https://omdsh.dev/assets/logo-orca.png" width="22" height="22" alt="Oh My DSH"></a> **[OMDSH](https://omdsh.dev/)** (Oh My DSH) · *Beyond the default.* · DeepSeek Harness developer community
132
+
133
+ Independent and unofficial; it sponsors the model tokens (compute) for this project. Website <https://omdsh.dev/>
134
+
135
+ Thanks, OMDSH. Sponsorship is support, not a purchase: everything here is free, and sponsorship unlocks no features.
136
+
137
+ ---
138
+
126
139
  MIT licensed. Not affiliated with DeepSeek.
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
 
@@ -137,4 +139,16 @@ npm test
137
139
 
138
140
  有问题或想提需求:<https://github.com/peng456/dsh-plugin-mesh/issues> · 邮箱 `geekstartup@163.com`
139
141
 
142
+ ---
143
+
144
+ ## 赞助方
145
+
146
+ <a href="https://omdsh.dev/"><img src="https://omdsh.dev/assets/logo-orca.png" width="22" height="22" alt="Oh My DSH"></a> **[OMDSH](https://omdsh.dev/)**(Oh My DSH)· *Beyond the default.* · DeepSeek Harness 开发者社区
147
+
148
+ 独立、非官方,为本项目赞助模型 token(算力)。官网 <https://omdsh.dev/>
149
+
150
+ 感谢 OMDSH 的支持。赞助是支持,不是购买——本项目全部功能免费,赞助不解锁任何能力。
151
+
152
+ ---
153
+
140
154
  MIT · 与 DeepSeek 官方无隶属关系
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("批准记录有上限,不会无限增长", () => {
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
@@ -13,7 +13,6 @@
13
13
  * 安全:发现是完全公开的(局域网内谁都能看见谁),这是有意设计 ——
14
14
  * 先让你看见机器,再决定要不要和它配对。真正的操作要过 token。
15
15
  */
16
- import dgram from "node:dgram";
17
16
  import { EventEmitter } from "node:events";
18
17
  import os from "node:os";
19
18
  import { sanitizeCapabilities, isCapabilityStale, summarizeCapabilities, currentCapabilities } from "./capabilities.js";
@@ -118,7 +117,10 @@ export function preferredAddress() {
118
117
  * 内存拷贝)。同网段时 Tailscale 自己也会走直连,所以实测延迟差不多,但走
119
118
  * tsnet 仍然多一层用户态转发,没有理由优先。
120
119
  */
121
- 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 };
122
124
 
123
125
  /** 一次失败后把端点标记为 down 的冷却时长;冷却期内不再尝试它。 */
124
126
  export const ENDPOINT_COOLDOWN_MS = 30000;
@@ -205,7 +207,35 @@ export function peerOnline(peer, now = Date.now(), ttlMs = 20000) {
205
207
  * "change" —— 对端列表有任何变化(新增/离线/恢复/信息更新)
206
208
  * "diagnostic" —— 网络层问题(非致命),参数为字符串
207
209
  */
210
+ /**
211
+ * `node:dgram`, resolved on demand.
212
+ *
213
+ * Multicast announce/listen is this module's only consumer of datagram sockets.
214
+ * The sweep timer, the record table and everything active scan writes all work
215
+ * without it, so a host — or a browser page — that has no `dgram` loses passive
216
+ * discovery and nothing else. The specifier is assembled at runtime so a bundler
217
+ * cannot resolve it ahead of time: in a page it must fail at the call, not at the
218
+ * module loader, or the whole plugin never loads.
219
+ * @returns the module namespace.
220
+ */
221
+ async function loadDgramModule() {
222
+ const specifier = "node:" + "dgram";
223
+ return await import(/* @vite-ignore */ specifier);
224
+ }
225
+
226
+ /** The resolved `node:dgram`, once a host that has it asked for multicast. */
227
+ let dgram;
228
+
208
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
+
209
239
  #id;
210
240
  #port;
211
241
  #meta;
@@ -308,6 +338,8 @@ export class MeshDiscovery extends EventEmitter {
308
338
  machine: this.#meta.machine ?? os.hostname(),
309
339
  hostname: os.hostname(),
310
340
  host: this.#address,
341
+ // Which transports this build offers; older peers ignore the field.
342
+ transports: this.transports,
311
343
  port: this.#port,
312
344
  os: `${os.platform()} ${os.release()}`,
313
345
  // 结构化系统身份(平台/系统名/版本/发行版/内核/桌面/架构)。
@@ -369,6 +401,32 @@ export class MeshDiscovery extends EventEmitter {
369
401
 
370
402
  if (!multicast) return this;
371
403
 
404
+ // A page has no datagram sockets, and asking for the module would throw
405
+ // from the loader rather than from here. Say so once and keep the rest of
406
+ // discovery — the sweep, and every record active scan writes — running.
407
+ if (typeof window !== "undefined") {
408
+ this.emit("diagnostic", "multicast discovery is unavailable in a browser page; sweep and active scan still run");
409
+ return this;
410
+ }
411
+ if (dgram !== undefined) {
412
+ this.#startMulticast();
413
+ return this;
414
+ }
415
+ void (async () => {
416
+ try {
417
+ dgram = await loadDgramModule();
418
+ } catch (error) {
419
+ this.emit("diagnostic", `no datagram sockets on this host; passive discovery is off (${error?.message ?? error})`);
420
+ return;
421
+ }
422
+ // Between the caller asking and the module arriving, stop() may have run.
423
+ if (this.#started && this.#multicast && this.#socket === null) this.#startMulticast();
424
+ })();
425
+ return this;
426
+ }
427
+
428
+ /** Bind the multicast socket and start announcing. */
429
+ #startMulticast() {
372
430
  const socket = dgram.createSocket({ type: "udp4", reuseAddr: true });
373
431
  this.#socket = socket;
374
432
 
@@ -863,6 +921,32 @@ export class MeshDiscovery extends EventEmitter {
863
921
  verified: prevEp?.verified === true || verified,
864
922
  };
865
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
+
866
950
  // ── 对端在名片里自报了 tailnet 地址 → 每个地址记一条**未验证**候选端点 ──
867
951
  //
868
952
  // 这样局域网一断就能直接拿它试,不必先扫一遍 tailnet —— 这就是决定 #2
package/lib/index.js CHANGED
@@ -35,8 +35,20 @@ import {
35
35
  import z from "@deepseek-ai/schemastery";
36
36
  import { defineTool } from "@deepseek-ai/dsh-tools";
37
37
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
38
- import { brandString } from "@deepseek-ai/dsh-brand";
38
+ /**
39
+ * A compile-time brand: the value it returns is the value it was given.
40
+ *
41
+ * It used to be imported from `@deepseek-ai/dsh-brand`, which is the right place
42
+ * for the *type*. At runtime it is an identity function, and not every dsh line
43
+ * ships it to every target — the browser build pins an older release whose
44
+ * module is empty — so importing it turns a type-level nicety into a hard
45
+ * dependency on a version this plugin does not otherwise care about.
46
+ * @param {string} value - the string.
47
+ * @returns the same string.
48
+ */
49
+ const brandString = (value) => value;
39
50
  import { MeshDiscovery, preferredAddress, lanIPv4Addresses, macForAddress, orderedEndpoints } from "./discovery.js";
51
+ import { discoverWebPeers, tunnelUrl } from "./web-peers.js";
40
52
  import { candidateAddresses, scanForPeers } from "./scan.js";
41
53
  import { machineFingerprint } from "./identity.js";
42
54
  import {
@@ -96,7 +108,6 @@ import { resolveTailnetChannels } from "./tsnet/channels.js";
96
108
  import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
97
109
  import { createWebProxy } from "./web-proxy.js";
98
110
  import { createSecretReader } from "./desktop-auth.js";
99
- import { createSshManager } from "./ssh-host.js";
100
111
  import { acceptUpgrade } from "./ws-mini.js";
101
112
  import {
102
113
  createDesktopWebForwarder,
@@ -108,7 +119,7 @@ import {
108
119
  export const name = "dsh-plugin-mesh";
109
120
  export const inject = ["tools", "webServer"];
110
121
 
111
- const VERSION = "0.5.10";
122
+ const VERSION = "0.5.12";
112
123
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
113
124
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
114
125
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -124,6 +135,16 @@ const MAX_BODY = 256 * 1024;
124
135
  const MAX_HISTORY = 200;
125
136
  /** 默认固定端口:内网里"扫这个端口 + ping 一下"就能建立连接,无需任何配置。 */
126
137
  export const MESH_DEFAULT_PORT = 45917;
138
+
139
+ /**
140
+ * 「陌生设备首次派活要本机点一次允许」这道闸,已经不是配置项了。
141
+ *
142
+ * 默认关:装上就能派活是这件事的全部价值,该收口的场景交给配对码。
143
+ * 保留实现是为了排查「谁在往我这派活」—— 需要时设环境变量:
144
+ * DSH_MESH_REQUIRE_APPROVAL=1
145
+ * 等有人真的需要常开,再把它捡回配置项(见 docs/DESIGN-NOTES.md)。
146
+ */
147
+ export const DEBUG_REQUIRE_APPROVAL = process.env.DSH_MESH_REQUIRE_APPROVAL === "1";
127
148
  /** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
128
149
  const WEB_PANEL_DEFAULT_PORT = 3080;
129
150
 
@@ -225,6 +246,19 @@ export const Config = z.object({
225
246
  scanTimeoutMs: z.natural().default(800),
226
247
  /** 定期 ping 已知对端(毫秒),0 = 关闭。这条让发现不依赖组播也能保活 */
227
248
  pingIntervalMs: z.natural().default(10000),
249
+
250
+ // ── 页面(浏览器)模式 ──────────────────────────────────────────────
251
+ /**
252
+ * 汇合点地址:页面从它加载,也从它拿名单、走它的同源隧道连桌面。
253
+ * 留空则用页面自己的 origin —— 页面永远是从某个 webdsh 上加载的。
254
+ */
255
+ webHub: z.string().default(""),
256
+ /** 页面里是否扫本网段(汇合点所在 /24)。手填永远生效,这个只是兜底 */
257
+ webScan: z.boolean().default(true),
258
+ /** 页面里手填的对端地址,如 ["192.168.1.9:45917"] */
259
+ manualPeers: z.array(String).default([]),
260
+ /** 页面里重新发现一轮的间隔(毫秒),0 = 只在启动时 */
261
+ webDiscoverIntervalMs: z.natural().default(120000),
228
262
  /**
229
263
  * tailnet 通道的探测间隔(毫秒)。局域网走 pingIntervalMs。
230
264
  *
@@ -241,18 +275,6 @@ export const Config = z.object({
241
275
  */
242
276
  requirePairing: z.boolean().default(false),
243
277
 
244
- /**
245
- * 陌生设备第一次派活时,本机要不要先点一次「允许」。默认 **true**。
246
- *
247
- * 为什么默认开:默认零配置意味着同一网段里谁连得上 45917 都能让本机开一个
248
- * agent 会话。对"自己家三台电脑"这是方便;对"公司 / 合租 / 咖啡厅"就是敞着门。
249
- * 原来的答案是"你去开配对码",但那是个设置项,没人会主动打开。
250
- *
251
- * 只问**第一次**:允许过之后写进 state.json 的 approvedPeers,同一台设备不再问。
252
- * 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
253
- */
254
- requireApproval: z.boolean().default(true),
255
-
256
278
  /** 对端任务在本机新建会话时用的 agent preset */
257
279
  agentPreset: z.string().default("standard"),
258
280
  /** 对端任务在本机新建会话时的权限;默认不给 danger-full-access */
@@ -585,7 +607,7 @@ function forgetApprovedPeer(target) {
585
607
  */
586
608
  function inboundNeedsApproval(config, task) {
587
609
  return needsApproval({
588
- config,
610
+ enabled: DEBUG_REQUIRE_APPROVAL,
589
611
  approved: approvedPeers(),
590
612
  peer: peerOfTask(task),
591
613
  pairingRequired: pairingRequired(config),
@@ -1075,6 +1097,10 @@ function applyUnsafe(ctx, config) {
1075
1097
  peerServer = handle;
1076
1098
  lastPort = handle.port;
1077
1099
  discovery.setPort(handle.port);
1100
+ // The card has to say which transports this build offers, or a peer never
1101
+ // learns it can skip plain HTTP. Set here because it becomes true exactly
1102
+ // when the server — and therefore `/mesh/v1/ws` — is listening.
1103
+ discovery.transports = ["lan", "ws"];
1078
1104
  return handle;
1079
1105
  };
1080
1106
 
@@ -1213,6 +1239,59 @@ function applyUnsafe(ctx, config) {
1213
1239
  if (wantLan) startLanDiscovery();
1214
1240
  }
1215
1241
 
1242
+ // ── 页面与汇合点 ──
1243
+ //
1244
+ // A browser page is the one shape that cannot be found and cannot be dialed:
1245
+ // no multicast, no listening socket. So it does the only thing it can —
1246
+ // attaches to the server it was loaded from, and learns peers from there.
1247
+ // Desktops pointed at the same hub get the reverse: they see the pages in
1248
+ // that registry and dispatch to them through it.
1249
+ if (inPage()) {
1250
+ meshHub = config.webHub !== "" ? String(config.webHub) : location.origin;
1251
+ meshTunnelToken = String(config.tunnelToken ?? "");
1252
+ discovery.transports = ["ws"];
1253
+ try {
1254
+ if (stopHub === undefined) {
1255
+ stopHub = attachHub({
1256
+ hubBase: meshHub,
1257
+ token: meshTunnelToken,
1258
+ identity: { id: discovery.selfRecord().id, machine: config.machineName || hostname() },
1259
+ log,
1260
+ });
1261
+ }
1262
+ const runWebDiscovery = async () => {
1263
+ try {
1264
+ const result = await discoverWebPeers({
1265
+ hubBase: meshHub,
1266
+ discovery,
1267
+ port: discovery.port || MESH_DEFAULT_PORT,
1268
+ manual: config.manualPeers ?? [],
1269
+ scan: config.webScan !== false,
1270
+ token: meshTunnelToken,
1271
+ concurrency: 24,
1272
+ onProgress: (record, host) => log(`页面发现:${record.machine || "?"} @ ${host}`),
1273
+ });
1274
+ if (result.found.length > 0) log(`页面发现 ${String(result.found.length)} 台对端`);
1275
+ } catch (error) {
1276
+ warn(`页面发现失败:${error?.message ?? error}`);
1277
+ }
1278
+ };
1279
+ } catch (error) {
1280
+ warn(`页面接入汇合点失败:${error?.message ?? String(error)}`);
1281
+ }
1282
+ void runWebDiscovery();
1283
+ if (webDiscoveryTimer === undefined && config.webDiscoverIntervalMs > 0) {
1284
+ webDiscoveryTimer = setInterval(() => { void runWebDiscovery() }, config.webDiscoverIntervalMs);
1285
+ webDiscoveryTimer.unref?.();
1286
+ }
1287
+ } else if (config.webHub !== "") {
1288
+ // Desktop pointed at a hub: the pages there are peers whose only address
1289
+ // is the hub itself.
1290
+ meshHub = String(config.webHub);
1291
+ meshTunnelToken = String(config.tunnelToken ?? "");
1292
+ void discoverHubPages({ hubBase: meshHub, discovery, log, warn, port: MESH_DEFAULT_PORT });
1293
+ }
1294
+
1216
1295
  // ── 互联网启动(后台跑:首次要下载 sidecar,不能让界面/接口干等)──
1217
1296
  if (wantNet && !internetUp) {
1218
1297
  void ensureInternet(reason).catch((err) => warn(`互联网通道启动异常:${err?.message ?? err}`));
@@ -2359,6 +2438,8 @@ async function peerFetch(peer, path, opts = {}) {
2359
2438
  // 宁可明确说"这条通道关了",也不要让它退化成"所有通道都失败" —— 后者会让
2360
2439
  // 用户以为对端掉线了,实际是本机自己关的(这类误判在这个项目里踩过)。
2361
2440
  const eps = all.filter((ep) => (ep.transport === "tsnet" ? transportGate.internet : transportGate.lan));
2441
+ // (`ws` and `hub` are both lan-scoped: same network, different framing.)
2442
+ // (`ws` is a lan-scoped transport: same host, same port, different framing.)
2362
2443
  if (eps.length === 0) {
2363
2444
  const closed = new Set();
2364
2445
  for (const ep of all) {
@@ -2389,7 +2470,11 @@ async function peerFetch(peer, path, opts = {}) {
2389
2470
  const res =
2390
2471
  ep.transport === "tsnet"
2391
2472
  ? await fetchViaTailnet(ep, url, { ...rest, timeoutMs })
2392
- : await fetchViaLan(ep, url, { ...rest, timeoutMs });
2473
+ : ep.transport === "ws"
2474
+ ? await fetchViaMeshWs(ep, url, { ...rest, timeoutMs })
2475
+ : ep.transport === "hub"
2476
+ ? await fetchViaHub(ep, url, { ...rest, timeoutMs })
2477
+ : await fetchViaLan(ep, url, { ...rest, timeoutMs });
2393
2478
  activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
2394
2479
  return res;
2395
2480
  } catch (err) {
@@ -2674,9 +2759,256 @@ async function pingKnownPeers({ discovery, config, warn }) {
2674
2759
  }
2675
2760
 
2676
2761
  /** 按**指定**端点发一个请求(保活探测用,不做失败切换)。 */
2762
+ /**
2763
+ * One request over the peer's mesh WebSocket.
2764
+ *
2765
+ * The frame carries what the HTTP request carried — method, path, body — and the
2766
+ * peer hands it to the same route handler, so a caller cannot tell which
2767
+ * transport answered. This is the path a page uses for everything: it can dial
2768
+ * out and read replies, and it can be reached by nothing.
2769
+ *
2770
+ * The pairing code travels in the first frame rather than a header, because a
2771
+ * browser cannot set headers on a WebSocket handshake; the URL would put it in
2772
+ * every proxy log on the way.
2773
+ * @param ep - the endpoint (`host`, `port`, `transport: "ws"`).
2774
+ * @param url - the absolute URL the caller built, of which only path/query matter.
2775
+ * @param opts - `method`, `headers`, `body`, `timeoutMs`.
2776
+ * @returns a `Response`, like the HTTP path returns.
2777
+ */
2778
+ /** Whether this host half is running inside a browser page. */
2779
+ const inPage = () => typeof window !== "undefined" && typeof location !== "undefined";
2780
+
2781
+ /**
2782
+ * The hub a page came from, and its token.
2783
+ *
2784
+ * Module-level rather than threaded through every call: a page has exactly one
2785
+ * hub — the origin that served it — and the endpoint objects discovery stores
2786
+ * carry only host and port. Set once during apply, read on each send.
2787
+ */
2788
+ let meshHub = "";
2789
+ let meshTunnelToken = "";
2790
+
2791
+ /** The hub attachment (page mode) and the rediscovery timer. */
2792
+ let stopHub;
2793
+ let webDiscoveryTimer;
2794
+
2795
+ /**
2796
+ * Put every page the hub knows about into the peer table.
2797
+ *
2798
+ * A page has no address of its own, so its endpoint is the hub plus its id —
2799
+ * `fetchViaHub` turns that back into the relay request. Desktops need this to
2800
+ * dispatch to a page at all.
2801
+ * @param options.hubBase - the hub origin.
2802
+ * @param options.discovery - the registrar.
2803
+ * @returns how many pages were added.
2804
+ */
2805
+ async function discoverHubPages({ hubBase, discovery, log, warn, port }) {
2806
+ try {
2807
+ const response = await fetch(new URL("/__mesh/api/peers", hubBase), { cache: "no-store" });
2808
+ if (!response.ok) return 0;
2809
+ const body = await response.json();
2810
+ const hub = new URL(hubBase);
2811
+ let added = 0;
2812
+ for (const page of body?.pages ?? []) {
2813
+ if (typeof page?.id !== "string") continue;
2814
+ const record = {
2815
+ app: "dsh-mesh",
2816
+ id: String(page.id),
2817
+ machine: String(page.machine ?? page.id),
2818
+ port,
2819
+ transports: ["hub"],
2820
+ };
2821
+ const changed = discovery.note(record, hub.hostname, {
2822
+ transport: "hub",
2823
+ channel: `hub:${page.id}`,
2824
+ port: Number(hub.port) || (hub.protocol === "https:" ? 443 : 80),
2825
+ probeIntervalMs: 60_000,
2826
+ });
2827
+ if (changed) added += 1;
2828
+ }
2829
+ if (added > 0) log(`汇合点上有 ${String(added)} 个页面节点`);
2830
+ return added;
2831
+ } catch (error) {
2832
+ warn(`读取汇合点名单失败:${error?.message ?? error}`);
2833
+ return 0;
2834
+ }
2835
+ }
2836
+
2837
+ /** The hub origin: configured, else the page's own. */
2838
+ function hubOrigin() {
2839
+ return meshHub !== "" ? meshHub : (typeof location !== "undefined" ? location.origin : "");
2840
+ }
2841
+
2842
+ /** The tunnel token, when the hub requires one. */
2843
+ function tunnelToken() {
2844
+ return meshTunnelToken;
2845
+ }
2846
+
2847
+ /** Routes one frame through this instance's peer-server routes (page mode). */
2848
+ let frameRouter;
2849
+
2850
+ /**
2851
+ * Attach this page to its hub: announce, then answer what the hub relays.
2852
+ *
2853
+ * The socket is the page's only inbound path — nothing can POST to a browser —
2854
+ * so a task addressed to this page arrives here as a `request` frame, goes
2855
+ * through the same routes an HTTP caller would have hit, and its answer goes
2856
+ * back on the socket. Reconnects on close: a page that sleeps (a backgrounded
2857
+ * tab) wakes up as a peer again without a reload.
2858
+ * @param options.hubBase - the hub origin.
2859
+ * @param options.token - tunnel/signal token, when the hub requires one.
2860
+ * @param options.identity - `{ id, machine, capabilities }` to announce.
2861
+ * @param options.log - progress sink.
2862
+ * @returns a stop function.
2863
+ */
2864
+ function attachHub({ hubBase, token = "", identity, log }) {
2865
+ let stopped = false;
2866
+ let socket;
2867
+ let retry = 1000;
2868
+ const connect = () => {
2869
+ if (stopped) return;
2870
+ const url = new URL("/__mesh/signal", hubBase);
2871
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
2872
+ if (token !== "") url.searchParams.set("t", token);
2873
+ try {
2874
+ socket = new WebSocket(url.href);
2875
+ } catch (error) {
2876
+ log?.(`页面接入汇合点失败:${error?.message ?? error}`);
2877
+ return;
2878
+ }
2879
+ socket.onopen = () => {
2880
+ retry = 1000;
2881
+ socket.send(JSON.stringify({ type: "hello", ...identity, kind: "page" }));
2882
+ log?.("已接入汇合点");
2883
+ };
2884
+ socket.onmessage = async (event) => {
2885
+ let message;
2886
+ try { message = JSON.parse(String(event.data)); } catch { return; }
2887
+ if (message?.type !== "request") return;
2888
+ // The hub asked this page to handle something. Answer even when routing
2889
+ // throws — a caller waiting on a reply must get one, not a timeout.
2890
+ let answer;
2891
+ try {
2892
+ answer = await frameRouter?.({ method: message.method, path: message.path, body: message.body });
2893
+ } catch (error) {
2894
+ answer = { status: 500, body: JSON.stringify({ ok: false, error: error?.message ?? String(error) }) };
2895
+ }
2896
+ try {
2897
+ socket.send(JSON.stringify({
2898
+ type: "answer",
2899
+ id: message.id,
2900
+ status: answer?.status ?? 500,
2901
+ body: answer?.body ?? "",
2902
+ }));
2903
+ } catch { /* 已断开,重连后再来 */ }
2904
+ };
2905
+ socket.onclose = (event) => {
2906
+ if (stopped) return;
2907
+ setTimeout(connect, (retry = Math.min(retry * 2, 15000)));
2908
+ };
2909
+ socket.onerror = () => { try { socket.close() } catch { /* 已关 */ } };
2910
+ };
2911
+ connect();
2912
+ return () => { stopped = true; try { socket?.close() } catch { /* 已关 */ } };
2913
+ }
2914
+
2915
+ /**
2916
+ * One request relayed to a page that only the hub can reach.
2917
+ *
2918
+ * The desktop keeps an ordinary `fetch` here: it posts to the hub's relay
2919
+ * endpoint and the hub turns that into a frame on the page's own outbound
2920
+ * socket. Which is why a page can be a full peer without ever being able to
2921
+ * accept a connection.
2922
+ * @param ep - endpoint with `channel: "hub:<pageId>"` and the hub's host/port.
2923
+ * @param url - the absolute URL the caller built; only path/query travel.
2924
+ * @param opts - `method`, `body`, `timeoutMs`.
2925
+ * @returns a `Response`, like the HTTP path returns.
2926
+ */
2927
+ async function fetchViaHub(ep, url, opts = {}) {
2928
+ const { timeoutMs = 120000, method = "GET", body } = opts;
2929
+ const parsed = new URL(url);
2930
+ const pageId = String(ep.channel ?? "").replace(/^hub:/, "");
2931
+ const target = `http://${ep.hubHost}:${ep.hubPort}/__mesh/api/task?target=${encodeURIComponent(pageId)}`;
2932
+ const response = await fetch(target, {
2933
+ method: "POST",
2934
+ headers: { "content-type": "application/json" },
2935
+ body: JSON.stringify({
2936
+ method,
2937
+ path: `${parsed.pathname}${parsed.search}`,
2938
+ body: body === undefined ? undefined : (typeof body === "string" ? body : Buffer.from(body).toString("utf8")),
2939
+ }),
2940
+ signal: AbortSignal.timeout(timeoutMs),
2941
+ });
2942
+ const text = await response.text();
2943
+ return new Response(text, { status: response.status, headers: { "content-type": "application/json; charset=utf-8" } });
2944
+ }
2945
+
2946
+ async function fetchViaMeshWs(ep, url, opts = {}) {
2947
+ const { timeoutMs = 20000, method = "GET", headers = {}, body } = opts;
2948
+ const parsed = new URL(url);
2949
+ // In a page every socket has to leave through the server the page came from:
2950
+ // an https page cannot open `ws://`, and the peer has no certificate. The
2951
+ // tunnel completes the last hop on the private network, so this build only
2952
+ // ever needs the one certificate the browser already trusts.
2953
+ const target = inPage()
2954
+ ? tunnelUrl(`${ep.host}:${ep.port}`, hubOrigin(), tunnelToken())
2955
+ : `ws://${ep.host}:${ep.port}/mesh/v1/ws`;
2956
+ return await new Promise((resolvePromise, rejectPromise) => {
2957
+ let settled = false;
2958
+ let socket;
2959
+ const finish = (fn, value) => {
2960
+ if (settled) return;
2961
+ settled = true;
2962
+ clearTimeout(timer);
2963
+ try { socket?.close(); } catch { /* 已关 */ }
2964
+ fn(value);
2965
+ };
2966
+ const timer = setTimeout(() => finish(rejectPromise, new Error(`ws ${ep.host}:${ep.port} timed out`)), timeoutMs);
2967
+ const requestId = randomBytes(6).toString("hex");
2968
+ try {
2969
+ socket = new WebSocket(target);
2970
+ } catch (error) {
2971
+ finish(rejectPromise, error);
2972
+ return;
2973
+ }
2974
+ socket.onopen = () => {
2975
+ socket.send(JSON.stringify({ type: "hello", token: currentSecret() ?? "" }));
2976
+ };
2977
+ socket.onmessage = (event) => {
2978
+ let message;
2979
+ try { message = JSON.parse(String(event.data)); } catch { return; }
2980
+ if (message?.type === "hello") {
2981
+ socket.send(JSON.stringify({
2982
+ type: "req",
2983
+ id: requestId,
2984
+ method,
2985
+ path: `${parsed.pathname}${parsed.search}`,
2986
+ headers,
2987
+ ...(body === undefined ? {} : { body: typeof body === "string" ? body : Buffer.from(body).toString("utf8") }),
2988
+ }));
2989
+ return;
2990
+ }
2991
+ if (message?.type === "error") {
2992
+ finish(rejectPromise, new Error(`ws ${ep.host}:${ep.port}: ${message.error ?? "refused"}`));
2993
+ return;
2994
+ }
2995
+ if (message?.type === "res" && message.id === requestId) {
2996
+ finish(resolvePromise, new Response(String(message.body ?? ""), {
2997
+ status: Number(message.status) || 200,
2998
+ headers: { "content-type": "application/json; charset=utf-8" },
2999
+ }));
3000
+ }
3001
+ };
3002
+ socket.onerror = () => finish(rejectPromise, new Error(`ws ${ep.host}:${ep.port} unreachable`));
3003
+ socket.onclose = () => finish(rejectPromise, new Error(`ws ${ep.host}:${ep.port} closed before a reply`));
3004
+ });
3005
+ }
3006
+
2677
3007
  async function peerFetchEndpoint(ep, url, opts = {}) {
2678
3008
  const { timeoutMs = 20000, ...rest } = opts;
2679
3009
  if (ep.transport === "tsnet") return fetchViaTailnet(ep, url, { ...rest, timeoutMs });
3010
+ if (ep.transport === "ws") return fetchViaMeshWs(ep, url, { ...rest, timeoutMs });
3011
+ if (ep.transport === "hub") return fetchViaHub(ep, url, { ...rest, timeoutMs });
2680
3012
  return fetchViaLan(ep, url, { ...rest, timeoutMs });
2681
3013
  }
2682
3014
 
@@ -2719,7 +3051,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2719
3051
  return transportGate.lan ? "" : "局域网 mesh 已关闭";
2720
3052
  };
2721
3053
 
2722
- const server = createServer(async (req, res) => {
3054
+ const handleRequest = async (req, res) => {
2723
3055
  const url = new URL(req.url, "http://localhost");
2724
3056
  const path = url.pathname;
2725
3057
  const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
@@ -2886,6 +3218,120 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2886
3218
  }
2887
3219
 
2888
3220
  return send(res, 404, { ok: false, error: "not found" });
3221
+ };
3222
+
3223
+ const server = createServer((req, res) => { void handleRequest(req, res); });
3224
+
3225
+ // A page has no reachable server, so its own copy of these routes is only
3226
+ // ever entered through frames from the hub. Publishing the router instead of
3227
+ // duplicating it is what keeps one implementation of every route.
3228
+ frameRouter = async (frame) => await new Promise((resolvePromise) => {
3229
+ void handleRequest(frameRequest(frame), frameResponse(resolvePromise));
3230
+ });
3231
+
3232
+ /** Which transports this build offers; echoed in `hello` so peers need not probe. */
3233
+ const wsTransports = () => ["lan", "ws"];
3234
+
3235
+ /**
3236
+ * The same routes, over a WebSocket, for peers that cannot make an inbound
3237
+ * HTTP connection to this machine.
3238
+ *
3239
+ * A browser page is exactly that: it can dial out, and nothing can dial in.
3240
+ * Running the page as a full peer therefore needs a transport the page itself
3241
+ * can open and read replies on — so this endpoint speaks frames that carry the
3242
+ * same `{method, path, body}` a caller would have sent over HTTP, hands them
3243
+ * to the very same route handler, and returns `{status, body}`. Nothing in the
3244
+ * routes below knows which transport the request arrived on.
3245
+ *
3246
+ * Auth moves from a header to the first frame: a browser cannot set
3247
+ * `x-dsh-mesh-token` on a WebSocket handshake, and putting the pairing code in
3248
+ * a URL would write it into every proxy log on the way.
3249
+ */
3250
+ const wsConnections = new Set();
3251
+
3252
+ /** A request object with the surface `handleRequest` reads. */
3253
+ const frameRequest = ({ method, path, headers, body } = {}) => {
3254
+ const request = new EventEmitter();
3255
+ request.method = String(method ?? "GET").toUpperCase();
3256
+ request.url = String(path ?? "/");
3257
+ request.headers = { ...(headers ?? {}) };
3258
+ request.socket = {
3259
+ remoteAddress: String(request.headers["x-forwarded-for"] ?? "").split(",")[0].trim() || "127.0.0.1",
3260
+ };
3261
+ request.setTimeout = () => request;
3262
+ setImmediate(() => {
3263
+ if (body !== undefined && body !== null) {
3264
+ request.emit("data", Buffer.from(typeof body === "string" ? body : JSON.stringify(body), "utf8"));
3265
+ }
3266
+ request.emit("end");
3267
+ });
3268
+ return request;
3269
+ };
3270
+
3271
+ /** A response object that resolves the frame the peer is waiting for. */
3272
+ const frameResponse = (resolve) => {
3273
+ const chunks = [];
3274
+ let status = 200;
3275
+ let headers = {};
3276
+ return {
3277
+ writeHead(code, next) { status = code; headers = next ?? {}; return this; },
3278
+ setHeader() { return this; },
3279
+ write(chunk) { if (chunk) chunks.push(Buffer.from(chunk)); return true; },
3280
+ end(chunk) {
3281
+ if (chunk) chunks.push(Buffer.from(chunk));
3282
+ resolve({ status, headers, body: Buffer.concat(chunks).toString("utf8") });
3283
+ },
3284
+ };
3285
+ };
3286
+
3287
+ server.on("upgrade", (req, socket, head) => {
3288
+ const url = new URL(req.url ?? "/", "http://localhost");
3289
+ if (url.pathname !== "/mesh/v1/ws") {
3290
+ // Other upgrade routes belong to someone else on this origin; leave the
3291
+ // socket alone rather than destroying a desktop-web stream.
3292
+ return;
3293
+ }
3294
+ const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
3295
+ let authenticated = false;
3296
+ let handle;
3297
+ const send = (payload) => handle?.send(JSON.stringify(payload));
3298
+ const timer = setTimeout(() => {
3299
+ if (!authenticated) {
3300
+ send({ type: "error", error: "unauthenticated: no hello within 5s" });
3301
+ handle?.close();
3302
+ }
3303
+ }, 5000);
3304
+
3305
+ handle = acceptUpgrade(req, socket, head, {
3306
+ onMessage: (text) => {
3307
+ let message;
3308
+ try { message = JSON.parse(text); } catch { return; }
3309
+ if (!authenticated) {
3310
+ if (message?.type !== "hello") return;
3311
+ const ok = !pairingRequired(config) || safeEqual(String(message.token ?? ""), currentSecret());
3312
+ if (!ok) {
3313
+ send({ type: "error", error: "unauthenticated: wrong pairing code" });
3314
+ handle?.close();
3315
+ return;
3316
+ }
3317
+ authenticated = true;
3318
+ clearTimeout(timer);
3319
+ wsConnections.add(handle);
3320
+ // `transports` tells the caller which channels this build offers, so a
3321
+ // peer knows to prefer ws without probing for it on every send.
3322
+ send({ type: "hello", ...self, transports: wsTransports(), instanceId: discovery.instanceId });
3323
+ return;
3324
+ }
3325
+ if (message?.type === "ping") { send({ type: "pong", at: Date.now() }); return; }
3326
+ if (message?.type !== "req") return;
3327
+ const response = frameResponse((result) => send({ type: "res", id: message.id, status: result.status, body: result.body }));
3328
+ void handleRequest(frameRequest(message), response);
3329
+ },
3330
+ onClose: () => {
3331
+ clearTimeout(timer);
3332
+ if (handle) wsConnections.delete(handle);
3333
+ },
3334
+ });
2889
3335
  });
2890
3336
 
2891
3337
  return new Promise((resolvePromise, rejectPromise) => {
@@ -3356,8 +3802,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3356
3802
  // 界面开关一改就得立刻反映出来(端到端测试就是在这抓到过一次 stale)。
3357
3803
  requirePairing: pairingRequired(config),
3358
3804
  requirePairingPinned: pairingPinned(config),
3359
- // 陌生设备首次派活是否要本机点一次「允许」(默认开)
3360
- requireApproval: config.requireApproval !== false,
3805
+ // 陌生设备首次派活是否要本机点一次「允许」(仅调试用,见 DEBUG_REQUIRE_APPROVAL)
3806
+ requireApproval: DEBUG_REQUIRE_APPROVAL,
3361
3807
  useMulticast: config.useMulticast !== false,
3362
3808
  scanOnStart: config.scanOnStart !== false,
3363
3809
  scanIntervalMs: config.scanIntervalMs,
@@ -4478,26 +4924,48 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4478
4924
  //
4479
4925
  // 入口在设备行(与「访问 DSH Web」同一位置)。会话由本机发起,凭据只存本机;
4480
4926
  // 传输走同源 WebSocket(/mesh/api/ssh/ws),所以不需要经过上面对端的 web 转发。
4481
- const ssh = createSshManager({
4482
- stateDir: stateDir(),
4483
- credentialsPath: join(stateDir(), "ssh-credentials.json"),
4484
- log,
4485
- warn,
4486
- });
4487
- ctx.effect(() => () => ssh.closeAll());
4927
+ // The SSH terminal is the one part of this plugin that cannot exist in a
4928
+ // browser: it needs `crypto.generateKeyPairSync` and a raw socket. Ask for it
4929
+ // by a runtime-visible name so a page gets `undefined` here instead of a
4930
+ // module-loader failure that takes the whole plugin down with it.
4931
+ let ssh;
4932
+ {
4933
+ // Loaded on demand for the same reason the module no longer sits at the top
4934
+ // of this file: RSA key generation and raw sockets do not exist in a page,
4935
+ // and a static import would take the whole plugin down over a feature the
4936
+ // page cannot have anyway. Routes registered below check `ssh` when they
4937
+ // run, so settling a moment later is fine.
4938
+ const specifier = "./ssh-host.js";
4939
+ import(/* @vite-ignore */ specifier).then((module) => {
4940
+ ssh = module.createSshManager({
4941
+ stateDir: stateDir(),
4942
+ credentialsPath: join(stateDir(), "ssh-credentials.json"),
4943
+ log,
4944
+ warn,
4945
+ });
4946
+ ctx.effect(() => () => ssh?.closeAll());
4947
+ }).catch((error) => {
4948
+ warn(`SSH 终端不可用(${error?.message ?? error});其余 mesh 功能不受影响`);
4949
+ });
4950
+ }
4488
4951
 
4489
4952
  post("/mesh/api/ssh/known", async (req, res) => {
4490
4953
  const body = await readJson(req);
4491
4954
  const machine = String(body?.machine ?? "").trim();
4492
4955
  // 只回用户名与"是否已部署密钥",不回密码:密码没有再穿过一次网络的理由
4956
+ if (ssh === undefined) return send(res, 503, { ok: false, error: "SSH 终端在这个环境里不可用" });
4493
4957
  const info = ssh.describe(machine);
4494
4958
  return send(res, 200, { ok: true, username: info.username, hasKey: info.hasKey, saved: !!info.username });
4495
4959
  });
4496
4960
 
4497
- post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh.list() }));
4961
+ post("/mesh/api/ssh/sessions", (_req, res) => send(res, 200, { ok: true, sessions: ssh?.list() ?? [] }));
4498
4962
 
4499
4963
  // 一条 upgrade 路由承载所有终端(按会话 id 多路复用)
4500
4964
  const sshUpgrade = (req, socket, head) => {
4965
+ if (ssh === undefined) {
4966
+ try { socket.end("HTTP/1.1 503 Service Unavailable\r\nconnection: close\r\n\r\n"); } catch { /* 已断 */ }
4967
+ return;
4968
+ }
4501
4969
  const chan = acceptUpgrade(req, socket, head, {
4502
4970
  onMessage: async (raw) => {
4503
4971
  let msg;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * 页面里的发现:汇合点名单 + WebSocket 探测 + 手填。
3
+ *
4
+ * 浏览器拿不到 group 播组,也没有能被别人连进来的端口,所以「发现」在页面里
5
+ * 只能反过来做:页面主动往外连。可行的手段只有三种,按代价从小到大——
6
+ *
7
+ * 1. 问汇合点(它提供本页面,也提供 `/__mesh/api/peers`):一次 HTTP 请求
8
+ * 2. 主动探测:对候选地址开一条 WebSocket,用 `hello` 帧问对面是谁
9
+ * 3. 手填:用户自己写 `192.168.1.9:45917`
10
+ *
11
+ * 每条探测都走汇合点的同源隧道(`/__mesh/tunnel?target=`),因为页面常常是
12
+ * https,而桌面是明文 ws —— 混合内容策略不允许页面直接连 `ws://`。
13
+ *
14
+ * 结果是**喂给 discovery**,而不是另建一份名单:这样主面板、派任务、端点冷却
15
+ * 全都不用改,页面里的节点和真机器长得一样。
16
+ */
17
+
18
+ /** 一条探测结果的形状,与 `discovery.note()` 期望的记录一致。 */
19
+ const APPS = "dsh-mesh";
20
+
21
+ /**
22
+ * 把汇合点的地址拼成页面能用的 ws 隧道 URL。
23
+ * @param {string} target - `host:port`。
24
+ * @param {string} hubBase - 汇合点 origin(页面自己的 origin)。
25
+ * @param {string} token - 隧道令牌,没有则不带。
26
+ * @returns {string} ws(s) URL。
27
+ */
28
+ export function tunnelUrl(target, hubBase, token = "") {
29
+ const url = new URL("/__mesh/tunnel", hubBase);
30
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
31
+ url.searchParams.set("target", target);
32
+ if (token !== "") url.searchParams.set("t", token);
33
+ return url.href;
34
+ }
35
+
36
+ /**
37
+ * 打开一条隧道并完成 hello 握手。
38
+ * @param {string} target - `host:port`。
39
+ * @param {object} options - `hubBase`、`token`、`timeoutMs`。
40
+ * @returns {Promise<object|null>} 对端自述的名片,或 null(超时/不像 DSH)。
41
+ */
42
+ export function probePeer(target, { hubBase, token = "", timeoutMs = 900 } = {}) {
43
+ return new Promise((resolve) => {
44
+ let socket;
45
+ let settled = false;
46
+ const finish = (value) => {
47
+ if (settled) return;
48
+ settled = true;
49
+ clearTimeout(timer);
50
+ try { socket?.close(); } catch { /* 已经关了 */ }
51
+ resolve(value);
52
+ };
53
+ const timer = setTimeout(() => finish(null), timeoutMs);
54
+ try {
55
+ socket = new WebSocket(tunnelUrl(target, hubBase, token));
56
+ } catch {
57
+ finish(null);
58
+ return;
59
+ }
60
+ socket.onopen = () => socket.send(JSON.stringify({ type: "hello", token: "" }));
61
+ socket.onmessage = (event) => {
62
+ let message;
63
+ try { message = JSON.parse(String(event.data)); } catch { return; }
64
+ // 隧道自己会回 `{type:"error"}`(不在私网段、端口不对、对端拒连)。
65
+ if (message?.type === "error") { finish(null); return; }
66
+ if (message?.type !== "hello") return;
67
+ if (message.app !== APPS || !message.id) { finish(null); return; }
68
+ finish(message);
69
+ };
70
+ socket.onerror = () => finish(null);
71
+ socket.onclose = () => finish(null);
72
+ });
73
+ }
74
+
75
+ /**
76
+ * 从汇合点的地址推出要扫的 /24。
77
+ *
78
+ * 页面拿不到网络拓扑,但知道自己是从哪台机器加载的——那台机器就在同一个
79
+ * 局域网里,所以它的 /24 就是最合理的猜测。扫不到也不影响什么:手填兜底。
80
+ * @param {URL} hub - 汇合点地址。
81
+ * @returns {string[]} 254 个候选地址。
82
+ */
83
+ export function subnetCandidates(hub) {
84
+ const parts = hub.hostname.split(".").map(Number);
85
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return [];
86
+ const prefix = parts.slice(0, 3).join(".");
87
+ const self = parts[3];
88
+ const out = [];
89
+ for (let host = 1; host < 255; host += 1) {
90
+ if (host === self) continue;
91
+ out.push(`${prefix}.${host}`);
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /**
97
+ * 发现页面能连的桌面节点,并把它们记进 discovery。
98
+ *
99
+ * 顺序即优先级:先问汇合点(一次请求,最快),再扫网段(并发有上限,最慢),
100
+ * 手填的地址永远参与(用户明确说了那里有东西,不要再替他决定)。
101
+ * @param options.hubBase - 汇合点 origin。
102
+ * @param options.discovery - MeshDiscovery 实例。
103
+ * @param options.port - 对端 mesh 端口,默认 45917。
104
+ * @param options.manual - 手填的 `host:port` 列表。
105
+ * @param options.scan - 是否扫网段,默认 true。
106
+ * @param options.token - 隧道令牌。
107
+ * @param options.concurrency - 并发探测数,默认 30(手机端建议 10)。
108
+ * @param options.onProgress - 每探到一个就回调一次。
109
+ * @returns {Promise<{hub: number, scanned: number, manual: number, found: string[]}>}
110
+ */
111
+ export async function discoverWebPeers({
112
+ hubBase,
113
+ discovery,
114
+ port = 45917,
115
+ manual = [],
116
+ scan = true,
117
+ token = "",
118
+ concurrency = 30,
119
+ onProgress,
120
+ } = {}) {
121
+ const hub = new URL(hubBase);
122
+ const found = [];
123
+ let fromHub = 0;
124
+ let scanned = 0;
125
+ let fromManual = 0;
126
+
127
+ /** 记一条:名片来自对端,地址是我们观察到的。 */
128
+ const remember = (record, host) => {
129
+ if (record.id === undefined) return false;
130
+ const changed = discovery.note(record, host, {
131
+ transport: "ws",
132
+ channel: `ws:${host}`,
133
+ port: Number(record.port) || port,
134
+ probeIntervalMs: 60_000,
135
+ });
136
+ if (changed) {
137
+ found.push(`${record.machine || host} (${host})`);
138
+ onProgress?.(record, host);
139
+ }
140
+ return changed;
141
+ };
142
+
143
+ // ── 1. 汇合点名单 ──────────────────────────────────────────────────────
144
+ try {
145
+ const response = await fetch(new URL("/__mesh/api/peers", hub), { cache: "no-store" });
146
+ if (response.ok) {
147
+ const body = await response.json();
148
+ // 汇合点列出的**桌面**节点:它们自己登记过,地址就是 registry 里那个。
149
+ for (const entry of body?.desktops ?? []) {
150
+ if (!entry?.address) continue;
151
+ const record = { app: APPS, id: entry.id, machine: entry.machine, port: port, transports: ["ws"] };
152
+ if (remember(record, String(entry.address).split(":")[0])) fromHub += 1;
153
+ }
154
+ }
155
+ } catch {
156
+ // 汇合点不可达不影响后面两步
157
+ }
158
+
159
+ // ── 2. 手填 ────────────────────────────────────────────────────────────
160
+ for (const entry of manual ?? []) {
161
+ const [host, rawPort] = String(entry).split(":");
162
+ const target = `${host}:${Number(rawPort) || port}`;
163
+ const card = await probePeer(target, { hubBase, token });
164
+ scanned += 1;
165
+ if (card === null) continue;
166
+ if (remember({ ...card, port: Number(rawPort) || port }, host)) fromManual += 1;
167
+ }
168
+
169
+ // ── 3. 扫网段(并发上限,探到就停) ────────────────────────────────────
170
+ if (scan) {
171
+ const candidates = subnetCandidates(hub);
172
+ for (let index = 0; index < candidates.length; index += concurrency) {
173
+ const batch = candidates.slice(index, index + concurrency);
174
+ const results = await Promise.all(batch.map(async (host) => {
175
+ const card = await probePeer(`${host}:${port}`, { hubBase, token });
176
+ return card === null ? null : { host, card };
177
+ }));
178
+ for (const hit of results) {
179
+ if (hit === null || hit === undefined) continue;
180
+ scanned += 1;
181
+ remember({ ...hit.card, port }, hit.host);
182
+ }
183
+ }
184
+ }
185
+
186
+ return { hub: fromHub, scanned, manual: fromManual, found };
187
+ }
package/llms.txt CHANGED
@@ -36,7 +36,7 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
36
36
  - The prefilled feedback issue carries the same diagnostics text as the diagnostics section; `buildDiagnostics()` deliberately excludes secrets (pairing code, tsnet auth key). The author's email (`geekstartup@163.com`) is the fallback when GitHub is unreachable.
37
37
  - **First-contact approval (default on).** An inbound task from a machine that is not in `state.json`'s `approvedPeers` is stored with `status: "needs-approval"` and answered with **HTTP 202** `{ok:true,pendingApproval:true}`; no agent session is created. The owner allows or denies it in the panel (`POST /mesh/api/approval` `{id,action:"allow"|"deny"}`); allowing adds the peer to `approvedPeers` and immediately runs the stored task. `POST /mesh/api/approval/revoke` `{machine}` removes trust. Replies (a task whose `thread` matches an outbound dispatch to the same machine) bypass the gate — otherwise the result would never come back. With `requirePairing` on (or the pairing switch enabled) the gate is skipped: pairing is the stronger trust gesture.
38
38
  - `GET /mesh/api/demo` returns a read-only snapshot of this machine (platform, CPU, memory, load, uptime, a few runtimes) used by the panel's single-machine demo. It contains no secrets and changes no state.
39
- - `/mesh/api/state` additionally exposes `config.requireApproval`, `approvals[]` (pending first-contact tasks) and `approvedPeers[]` (`{machine,address,at}`).
39
+ - `/mesh/api/state` additionally exposes `approvals[]` (pending first-contact tasks, only present when the debug gate below is on) and `approvedPeers[]` (`{machine,address,at}`).
40
40
 
41
41
  ## Usage patterns (agent to agent)
42
42
 
@@ -152,7 +152,6 @@ Override by id in the profile's `cordis.patch.yml`:
152
152
  | `pingIntervalMs` | natural | `10000` | LAN health probe period |
153
153
  | `tsnetProbeIntervalMs` | natural | `60000` | Tailnet health probe period |
154
154
  | `requirePairing` | boolean | `false` | **Default off: the peer API accepts unauthenticated task POSTs.** Setting it `true` here pins pairing on; otherwise the Mesh panel's pairing switch (persisted in `state.json`) decides |
155
- | `requireApproval` | boolean | `true` | First task from an unknown machine is held as `needs-approval` until the owner clicks Allow. Set `false` to restore fully unattended dispatch. Ignored (no prompt) when pairing is on |
156
155
  | `agentPreset` | string | `"standard"` | Agent preset for auto-created sessions |
157
156
  | `permissionPreset` | string | `"workspace-write"` | Permission preset for auto-created sessions |
158
157
  | `workspaceRoot` | string | `""` | |
@@ -190,7 +189,7 @@ Outbound dispatch tries LAN first, then each tailnet channel in order.
190
189
 
191
190
  - Ports: TCP `45917` (peer HTTP), UDP `45892` (multicast group `239.255.42.99`).
192
191
  - Discovery is intentionally public: any host on the same L2 network can see the machine and its self-reported card.
193
- - With `requireApproval: true` (the default) a first task from an unknown machine does **not** wake anything: it is held for local approval. Once approved, later tasks from that machine run unattended. Set `requireApproval: false` to get fully unattended dispatch (the pre-0.6 behaviour).
192
+ - A task from any machine that can reach the port wakes an agent and runs, with no prompt. The per-machine first-contact approval gate (`needs-approval` + `POST /mesh/api/approval`) is **debug-only**, not a config key: start the host with `DSH_MESH_REQUIRE_APPROVAL=1` to test it. Pairing is the supported gate.
194
193
  - With `requirePairing: false` (the default) there is still no cryptographic authentication of the sender: the trust decision is per-machine, made by the owner, not by a shared secret. On untrusted networks turn on the pairing switch in the Mesh panel (immediate, no restart) or set `requirePairing: true`, and make both machines share one secret. The token travels in a plain HTTP header — it guards against stray devices, not against a network sniffer.
195
194
  - The shared secret is stored in `~/.dsh/mesh/state.json` (mode 0600) alongside `machineName`, the persisted `instanceIds`, and the tsnet auth key. It is never included in the multicast card.
196
195
  - Persistent identity is a UUID per profile; the OS machine fingerprint is used only to reclaim a reinstalled device (same name, or the old record already offline). Two live instances on one physical machine are kept separate.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "type": "module",
5
5
  "description": "把跑不完的活交给另一台电脑;跑完,结果回到你面前。两台装了 DSH 的电脑各装一次,自动互相发现,任务派过去由对端的 agent 执行,结果派回来。Hand a long task to another machine: your DSH instances find each other, the peer runs it, and the result comes back. No pairing codes, no IPs, no Tailscale client.",
6
6
  "license": "MIT",