dsh-plugin-mesh 0.5.11 → 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
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("批准记录有上限,不会无限增长", () => {
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
package/lib/index.js CHANGED
@@ -48,6 +48,7 @@ import { createUserMessage } from "@deepseek-ai/dsh-llm";
48
48
  */
49
49
  const brandString = (value) => value;
50
50
  import { MeshDiscovery, preferredAddress, lanIPv4Addresses, macForAddress, orderedEndpoints } from "./discovery.js";
51
+ import { discoverWebPeers, tunnelUrl } from "./web-peers.js";
51
52
  import { candidateAddresses, scanForPeers } from "./scan.js";
52
53
  import { machineFingerprint } from "./identity.js";
53
54
  import {
@@ -118,7 +119,7 @@ import {
118
119
  export const name = "dsh-plugin-mesh";
119
120
  export const inject = ["tools", "webServer"];
120
121
 
121
- const VERSION = "0.5.11";
122
+ const VERSION = "0.5.12";
122
123
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
123
124
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
124
125
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -134,6 +135,16 @@ const MAX_BODY = 256 * 1024;
134
135
  const MAX_HISTORY = 200;
135
136
  /** 默认固定端口:内网里"扫这个端口 + ping 一下"就能建立连接,无需任何配置。 */
136
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";
137
148
  /** 对端 DSH Web 的部署默认端口(回环代理拿不到对端自报地址时按它拼)。 */
138
149
  const WEB_PANEL_DEFAULT_PORT = 3080;
139
150
 
@@ -235,6 +246,19 @@ export const Config = z.object({
235
246
  scanTimeoutMs: z.natural().default(800),
236
247
  /** 定期 ping 已知对端(毫秒),0 = 关闭。这条让发现不依赖组播也能保活 */
237
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),
238
262
  /**
239
263
  * tailnet 通道的探测间隔(毫秒)。局域网走 pingIntervalMs。
240
264
  *
@@ -251,18 +275,6 @@ export const Config = z.object({
251
275
  */
252
276
  requirePairing: z.boolean().default(false),
253
277
 
254
- /**
255
- * 陌生设备第一次派活时,本机要不要先点一次「允许」。默认 **true**。
256
- *
257
- * 为什么默认开:默认零配置意味着同一网段里谁连得上 45917 都能让本机开一个
258
- * agent 会话。对"自己家三台电脑"这是方便;对"公司 / 合租 / 咖啡厅"就是敞着门。
259
- * 原来的答案是"你去开配对码",但那是个设置项,没人会主动打开。
260
- *
261
- * 只问**第一次**:允许过之后写进 state.json 的 approvedPeers,同一台设备不再问。
262
- * 开了 requirePairing 就不再重复问 —— 配对码是更强的信任动作。
263
- */
264
- requireApproval: z.boolean().default(true),
265
-
266
278
  /** 对端任务在本机新建会话时用的 agent preset */
267
279
  agentPreset: z.string().default("standard"),
268
280
  /** 对端任务在本机新建会话时的权限;默认不给 danger-full-access */
@@ -595,7 +607,7 @@ function forgetApprovedPeer(target) {
595
607
  */
596
608
  function inboundNeedsApproval(config, task) {
597
609
  return needsApproval({
598
- config,
610
+ enabled: DEBUG_REQUIRE_APPROVAL,
599
611
  approved: approvedPeers(),
600
612
  peer: peerOfTask(task),
601
613
  pairingRequired: pairingRequired(config),
@@ -1085,6 +1097,10 @@ function applyUnsafe(ctx, config) {
1085
1097
  peerServer = handle;
1086
1098
  lastPort = handle.port;
1087
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"];
1088
1104
  return handle;
1089
1105
  };
1090
1106
 
@@ -1223,6 +1239,59 @@ function applyUnsafe(ctx, config) {
1223
1239
  if (wantLan) startLanDiscovery();
1224
1240
  }
1225
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
+
1226
1295
  // ── 互联网启动(后台跑:首次要下载 sidecar,不能让界面/接口干等)──
1227
1296
  if (wantNet && !internetUp) {
1228
1297
  void ensureInternet(reason).catch((err) => warn(`互联网通道启动异常:${err?.message ?? err}`));
@@ -2369,6 +2438,8 @@ async function peerFetch(peer, path, opts = {}) {
2369
2438
  // 宁可明确说"这条通道关了",也不要让它退化成"所有通道都失败" —— 后者会让
2370
2439
  // 用户以为对端掉线了,实际是本机自己关的(这类误判在这个项目里踩过)。
2371
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.)
2372
2443
  if (eps.length === 0) {
2373
2444
  const closed = new Set();
2374
2445
  for (const ep of all) {
@@ -2399,7 +2470,11 @@ async function peerFetch(peer, path, opts = {}) {
2399
2470
  const res =
2400
2471
  ep.transport === "tsnet"
2401
2472
  ? await fetchViaTailnet(ep, url, { ...rest, timeoutMs })
2402
- : 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 });
2403
2478
  activeDiscovery?.markEndpoint(peer.id, endpointKeyOf(ep), { ok: true, rttMs: Date.now() - started });
2404
2479
  return res;
2405
2480
  } catch (err) {
@@ -2684,9 +2759,256 @@ async function pingKnownPeers({ discovery, config, warn }) {
2684
2759
  }
2685
2760
 
2686
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
+
2687
3007
  async function peerFetchEndpoint(ep, url, opts = {}) {
2688
3008
  const { timeoutMs = 20000, ...rest } = opts;
2689
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 });
2690
3012
  return fetchViaLan(ep, url, { ...rest, timeoutMs });
2691
3013
  }
2692
3014
 
@@ -2729,7 +3051,7 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2729
3051
  return transportGate.lan ? "" : "局域网 mesh 已关闭";
2730
3052
  };
2731
3053
 
2732
- const server = createServer(async (req, res) => {
3054
+ const handleRequest = async (req, res) => {
2733
3055
  const url = new URL(req.url, "http://localhost");
2734
3056
  const path = url.pathname;
2735
3057
  const self = { ...discovery.selfRecord(), instanceId: discovery.instanceId };
@@ -2896,6 +3218,120 @@ function startPeerServer(ctx, { config, discovery, inbound, outbound, log, warn,
2896
3218
  }
2897
3219
 
2898
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
+ });
2899
3335
  });
2900
3336
 
2901
3337
  return new Promise((resolvePromise, rejectPromise) => {
@@ -3366,8 +3802,8 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3366
3802
  // 界面开关一改就得立刻反映出来(端到端测试就是在这抓到过一次 stale)。
3367
3803
  requirePairing: pairingRequired(config),
3368
3804
  requirePairingPinned: pairingPinned(config),
3369
- // 陌生设备首次派活是否要本机点一次「允许」(默认开)
3370
- requireApproval: config.requireApproval !== false,
3805
+ // 陌生设备首次派活是否要本机点一次「允许」(仅调试用,见 DEBUG_REQUIRE_APPROVAL)
3806
+ requireApproval: DEBUG_REQUIRE_APPROVAL,
3371
3807
  useMulticast: config.useMulticast !== false,
3372
3808
  scanOnStart: config.scanOnStart !== false,
3373
3809
  scanIntervalMs: config.scanIntervalMs,
@@ -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.11",
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",