dsh-plugin-mesh 0.5.18 → 0.5.20

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/client/client.js CHANGED
@@ -728,7 +728,7 @@ window.__ModuleLoader__.load({
728
728
  // ─────────────────────── 样式 ───────────────────────
729
729
 
730
730
  const CSS = `
731
- .mesh-root {
731
+ .mesh-root, .mesh-web-hosted {
732
732
  --mesh-bg: var(--dsw-alias-bg-base);
733
733
  --mesh-surface: var(--dsw-alias-bg-layer-1);
734
734
  --mesh-surface-2: var(--dsw-alias-bg-layer-2);
@@ -775,6 +775,11 @@ window.__ModuleLoader__.load({
775
775
  border-radius: 999px;
776
776
  }
777
777
  .mesh-root ::-webkit-scrollbar-track { background: transparent; }
778
+ /* body 级常驻宿主:只借 .mesh-root 的变量与排版,不要它的布局(它是主面板外壳)。 */
779
+ .mesh-web-hosted {
780
+ position: static; display: block; flex: none;
781
+ min-height: 0; overflow: visible; background: none;
782
+ }
778
783
 
779
784
  /* ── 顶栏 ── */
780
785
  .mesh-topbar {
@@ -810,6 +815,8 @@ window.__ModuleLoader__.load({
810
815
  display: flex; flex-direction: column;
811
816
  background: var(--mesh-bg);
812
817
  }
818
+ /* 搬出 MeshApp 之后由 body 级宿主接管定位:盖住整屏,但仍低于应用自己的弹层(1000+)。 */
819
+ .mesh-web-hosted .mesh-web-layer { position: fixed; inset: 0; z-index: 900; }
813
820
  .mesh-web-bar {
814
821
  flex: 0 0 auto;
815
822
  display: flex; align-items: center; gap: 8px;
@@ -4441,6 +4448,333 @@ window.__ModuleLoader__.load({
4441
4448
  );
4442
4449
  }
4443
4450
 
4451
+ // ─────────────────────── 常驻 Web 面板层 ───────────────────────
4452
+
4453
+ /** 空闲多久拆掉面板(毫秒);localStorage 写 mesh.webPanelIdleMs = 0 表示「收起即拆」。 */
4454
+ const WEB_PANEL_IDLE_KEY = "mesh.webPanelIdleMs";
4455
+ const WEB_PANEL_IDLE_DEFAULT = 10 * 60 * 1000;
4456
+ /** 可见期间的心跳上限:面板开着就定期把宿主的宽限期续上(见 startBeat)。 */
4457
+ const WEB_PANEL_HEARTBEAT_MAX = 4 * 60 * 1000;
4458
+
4459
+ function readWebPanelIdleMs() {
4460
+ try {
4461
+ const raw = window.localStorage.getItem(WEB_PANEL_IDLE_KEY);
4462
+ // 注意:没设置时 getItem 返回 null,而 Number(null) === 0 —— 直接 Number()
4463
+ // 会把「没配置」读成「收起即拆」,于是每次 hide() 立刻销毁 iframe,秒切失效。
4464
+ if (raw !== null && String(raw).trim() !== "") {
4465
+ const ms = Number(raw);
4466
+ if (Number.isFinite(ms) && ms >= 0) return ms;
4467
+ }
4468
+ } catch {
4469
+ /* 没有 localStorage(隐私模式 / 非浏览器宿主):用默认值 */
4470
+ }
4471
+ return WEB_PANEL_IDLE_DEFAULT;
4472
+ }
4473
+
4474
+ /** 让宿主回收这块面板的回环反代与 tailnet 出站流(keepalive:页面正在关也发得出去)。 */
4475
+ function closePeerPanel(peer, force) {
4476
+ if (!peer || typeof fetch !== "function") return;
4477
+ try {
4478
+ fetch(`${API}/web-panel/close`, {
4479
+ method: "POST",
4480
+ headers: { "content-type": "application/json" },
4481
+ body: JSON.stringify(force ? { peer, force: true } : { peer }),
4482
+ keepalive: true,
4483
+ }).catch(() => {});
4484
+ } catch {
4485
+ /* 尽力而为:宿主自己的空闲 sweep 会兜底回收 */
4486
+ }
4487
+ }
4488
+
4489
+ /**
4490
+ * 常驻 Web 面板层:对端 DSH Web 的 iframe 挂在 document.body 上,
4491
+ * **不随 MeshApp 卸载**。
4492
+ *
4493
+ * 为什么必须搬出来:main 这个 slot 是 keyed 渲染(dsh-client-ui-layout),
4494
+ * activePanelId 一旦离开 mesh(点侧栏任何一个会话、切别的面板、换 workspace),
4495
+ * MeshApp 就整棵卸载,组件里的 iframe 跟着销毁、对端页面从头重载 —— 而宿主
4496
+ * 那边的回环反代明明还在 10 分钟宽限期里。iframe 的寿命不能挂在一个会被卸载
4497
+ * 的组件上。
4498
+ *
4499
+ * 时效销毁(三层,缺一不可):
4500
+ * 1. 收起(面板「返回」或 MeshApp 被卸载)→ 只 display:none,iframe、对端
4501
+ * 会话、滚动位置全留着;IDLE_MS 内再打开就是原样显示(不请求宿主、不重建
4502
+ * iframe)—— 这才是「秒切」;
4503
+ * 2. 空闲超过 IDLE_MS(默认 10 分钟,与宿主 WEB_PANEL_IDLE_MS 对齐)→ 卸载
4504
+ * iframe + force-close 宿主反代,不留孤儿端口和 tailnet 出站流;
4505
+ * 3. 页面 pagehide → 尽力 force-close(keepalive),双保险。
4506
+ */
4507
+ function createWebPanelLayer() {
4508
+ let hostEl = null; // body 级容器
4509
+ let root = null; // 独立 React root:与 MeshApp 的生命周期无关
4510
+ let timer = null; // 空闲销毁计时器
4511
+ let beat = null; // 可见期间的心跳计时器
4512
+ let beatMiss = 0; // 连续失败次数(对端短暂掉出发现列表时别一击必杀)
4513
+ let beatOverride = 0; // 仅自测用:覆盖心跳间隔
4514
+ let panel = null; // 当前面板;null = 没有 iframe
4515
+ let hooks = null; // { push, fallback }:MeshApp 挂载时注册,卸载即清空
4516
+ let pagehideBound = false;
4517
+
4518
+ const keyOf = (peer) => (peer && (peer.machine || peer.id)) || "";
4519
+ const nameOf = (peer) => (peer && (peer.machine || peer.id)) || "对端";
4520
+
4521
+ function ensureHost() {
4522
+ if (hostEl !== null) return true;
4523
+ if (typeof document === "undefined" || !document.body) return false;
4524
+ hostEl = document.createElement("div");
4525
+ hostEl.className = "mesh-web-hosted";
4526
+ document.body.appendChild(hostEl);
4527
+ root = require("react-dom/client").createRoot(hostEl);
4528
+ if (!pagehideBound) {
4529
+ pagehideBound = true;
4530
+ window.addEventListener("pagehide", () => {
4531
+ // 页面要走了:先把 iframe 的引用扔掉,再尽力让宿主立刻回收。
4532
+ const key = panel ? panel.key : "";
4533
+ panel = null;
4534
+ if (key) closePeerPanel(key, true);
4535
+ });
4536
+ }
4537
+ return true;
4538
+ }
4539
+
4540
+ function paint() {
4541
+ if (root === null) return;
4542
+ root.render(h(WebPanel, { panel, onClose: hide, onReload: reload }));
4543
+ }
4544
+
4545
+ function clearTimer() {
4546
+ if (timer === null) return;
4547
+ clearTimeout(timer);
4548
+ timer = null;
4549
+ }
4550
+
4551
+ function startIdleTimer() {
4552
+ clearTimer();
4553
+ // 现读而不是插件加载时读一次:改 mesh.webPanelIdleMs 不用重载界面。
4554
+ const idleMs = readWebPanelIdleMs();
4555
+ if (!(idleMs > 0)) {
4556
+ destroy();
4557
+ return;
4558
+ }
4559
+ timer = setTimeout(() => {
4560
+ timer = null;
4561
+ destroy();
4562
+ }, idleMs);
4563
+ }
4564
+
4565
+ /** 心跳间隔:取宽限期的一半,夹在 15s–4min 之间(后台标签页的定时器会被节流)。 */
4566
+ function beatInterval() {
4567
+ if (beatOverride > 0) return beatOverride;
4568
+ const idleMs = readWebPanelIdleMs();
4569
+ const half = idleMs > 0 ? idleMs / 2 : WEB_PANEL_HEARTBEAT_MAX;
4570
+ return Math.max(15 * 1000, Math.min(WEB_PANEL_HEARTBEAT_MAX, half));
4571
+ }
4572
+
4573
+ function clearBeat() {
4574
+ if (beat === null) return;
4575
+ clearInterval(beat);
4576
+ beat = null;
4577
+ }
4578
+
4579
+ function startBeat() {
4580
+ clearBeat();
4581
+ beatMiss = 0;
4582
+ beat = setInterval(() => {
4583
+ void ensureAlive();
4584
+ }, beatInterval());
4585
+ }
4586
+
4587
+ /**
4588
+ * 续命 + 自愈。
4589
+ *
4590
+ * 宿主的回收按 lastUsedAt 的「空闲 10 分钟」算,它不知道面板是不是正开在
4591
+ * 屏幕上 —— 只在打开那一刻刷新的话,一直开着的面板会在第 10 分钟被
4592
+ * sweep 掉反代(画面还在,后续请求开始失败)。所以可见期间定期打一次
4593
+ * /web-panel:命中复用分支只刷新 lastUsedAt,不重建、不换端口。
4594
+ *
4595
+ * 顺便自愈:如果反代真被回收后重建过,返回的地址会变,这里把 iframe
4596
+ * 指过去(页面重载一次),而不是让用户对着一个死地址。
4597
+ */
4598
+ async function ensureAlive() {
4599
+ if (panel === null || panel.state !== "ready") return;
4600
+ const key = panel.key;
4601
+ const url = panel.url;
4602
+ let r = null;
4603
+ try {
4604
+ r = await api("/web-panel", { peer: key });
4605
+ } catch {
4606
+ return; // 网络抖动不算失效,下一次心跳再试
4607
+ }
4608
+ if (panel === null || panel.key !== key || panel.state !== "ready") return;
4609
+ if (r && r.ok === true && typeof r.url === "string") {
4610
+ beatMiss = 0;
4611
+ if (r.url === url) return;
4612
+ panel = { ...panel, url: r.url, remote: r.remote || panel.remote, reloadKey: (panel.reloadKey || 0) + 1 };
4613
+ paint();
4614
+ notify("info", "宿主那边的反代被回收过,已重新建连并重载页面。");
4615
+ return;
4616
+ }
4617
+ // 对端可能只是短暂掉出发现列表(peers 有 TTL):连续两次问不到才判死。
4618
+ beatMiss += 1;
4619
+ if (beatMiss < 2) return;
4620
+ destroy();
4621
+ notify("warn", "这块面板的反代已被宿主收回,请重新打开。");
4622
+ }
4623
+
4624
+ function notify(kind, text) {
4625
+ try {
4626
+ if (hooks && typeof hooks.push === "function") hooks.push(kind, text);
4627
+ } catch {
4628
+ /* toast 只是提示,失败不影响面板 */
4629
+ }
4630
+ }
4631
+
4632
+ /** 拆掉 iframe 并让宿主回收反代:空闲到期、插件卸载、换设备都走这里。 */
4633
+ function destroy() {
4634
+ clearTimer();
4635
+ clearBeat();
4636
+ const key = panel ? panel.key : "";
4637
+ panel = null;
4638
+ if (root !== null) {
4639
+ try {
4640
+ root.unmount();
4641
+ } catch {
4642
+ /* 已经不在渲染树里也无所谓 */
4643
+ }
4644
+ root = null;
4645
+ }
4646
+ if (hostEl !== null && hostEl.parentNode) hostEl.parentNode.removeChild(hostEl);
4647
+ hostEl = null;
4648
+ if (key) closePeerPanel(key, true);
4649
+ }
4650
+
4651
+ /** 收起:只隐藏。iframe 与对端会话留着,等 IDLE_MS 到期才真拆。 */
4652
+ function hide() {
4653
+ if (panel === null || panel.hidden) return;
4654
+ clearBeat();
4655
+ panel = { ...panel, hidden: true, hiddenAt: Date.now() };
4656
+ paint();
4657
+ startIdleTimer();
4658
+ }
4659
+
4660
+ /** 重载同一个地址(对端重启过、iframe 白屏时用),不动宿主反代。 */
4661
+ function reload() {
4662
+ if (panel === null || !panel.url) return;
4663
+ clearTimer();
4664
+ panel = { ...panel, state: "ready", hidden: false, hiddenAt: 0, reloadKey: (panel.reloadKey || 0) + 1 };
4665
+ paint();
4666
+ startBeat();
4667
+ }
4668
+
4669
+ async function open(peer, opts) {
4670
+ const force = !!(opts && opts.force);
4671
+ const key = keyOf(peer);
4672
+ if (!key) return;
4673
+ if (!ensureHost()) {
4674
+ notify("error", "当前宿主没有可用的 document.body,打不开应用内面板。");
4675
+ return;
4676
+ }
4677
+ // 快路:同一台设备、iframe 还活着(IDLE_MS 内)→ 直接显示,不请求宿主、
4678
+ // 不重建 iframe。页面状态、滚动位置、对端会话原样都在。
4679
+ if (panel !== null && panel.key === key && panel.state === "ready") {
4680
+ clearTimer();
4681
+ if (force) {
4682
+ reload();
4683
+ return;
4684
+ }
4685
+ panel = { ...panel, peer, name: nameOf(peer), hidden: false, hiddenAt: 0 };
4686
+ paint();
4687
+ startBeat();
4688
+ // 收起过一段时间的(接近宽限期)从这一刻起续命,别刚打开就被宿主 sweep。
4689
+ void ensureAlive();
4690
+ return;
4691
+ }
4692
+ // 换设备:旧面板的反代先还给宿主,别留一个孤儿端口。
4693
+ if (panel !== null && panel.key !== key) closePeerPanel(panel.key, true);
4694
+ clearTimer();
4695
+ panel = {
4696
+ key,
4697
+ peer,
4698
+ name: nameOf(peer),
4699
+ state: "loading",
4700
+ url: "",
4701
+ remote: "",
4702
+ hasSession: true,
4703
+ note: "",
4704
+ hidden: false,
4705
+ hiddenAt: 0,
4706
+ reloadKey: 0,
4707
+ };
4708
+ paint();
4709
+ let r = null;
4710
+ try {
4711
+ r = await api("/web-panel", { peer: key });
4712
+ } catch (error) {
4713
+ r = { ok: false, error: String((error && error.message) || error) };
4714
+ }
4715
+ // 期间被收起并到期拆掉、或又换了设备:这次响应作废。
4716
+ if (panel === null || panel.key !== key || panel.state !== "loading") return;
4717
+ if (r && r.ok === true && typeof r.url === "string") {
4718
+ panel = {
4719
+ ...panel,
4720
+ state: "ready",
4721
+ url: r.url,
4722
+ remote: r.remote || "",
4723
+ hasSession: r.hasSession !== false,
4724
+ note: r.note || "",
4725
+ hidden: false,
4726
+ reloadKey: 0,
4727
+ };
4728
+ paint();
4729
+ startBeat();
4730
+ if (panel.hasSession === false) {
4731
+ notify("warn", `${panel.name} 那边没给出可用 token,面板可能停在登录页。`);
4732
+ }
4733
+ return;
4734
+ }
4735
+ const detail = (r && r.error) || "未知原因";
4736
+ panel = null;
4737
+ paint();
4738
+ notify("warn", `应用内面板起不来(${detail}),改用外部方式打开。`);
4739
+ try {
4740
+ if (hooks && typeof hooks.fallback === "function") await hooks.fallback(peer);
4741
+ } catch (error) {
4742
+ notify("error", `外部方式也打不开:${String((error && error.message) || error)}`);
4743
+ }
4744
+ }
4745
+
4746
+ return {
4747
+ open,
4748
+ hide,
4749
+ reload,
4750
+ /** 当前面板的只读快照(不把 live 引用交给外部)。 */
4751
+ current: () =>
4752
+ panel === null
4753
+ ? null
4754
+ : { key: panel.key, name: panel.name, hidden: !!panel.hidden, hasSession: panel.hasSession !== false },
4755
+ /** MeshApp 挂载时注册 toast / 兜底打开;卸载时清空。 */
4756
+ setHooks: (next) => {
4757
+ hooks = next || null;
4758
+ },
4759
+ clearHooks: () => {
4760
+ hooks = null;
4761
+ },
4762
+ /** 插件被卸载/热更:拆干净,别在 body 上留一个 iframe。 */
4763
+ dispose: () => {
4764
+ hooks = null;
4765
+ destroy();
4766
+ },
4767
+ /** 仅供自测:面板是否处于「iframe 活着」的状态。 */
4768
+ __alive: () => panel !== null && panel.state === "ready",
4769
+ /** 仅供自测:覆盖心跳间隔(0 = 恢复自动)。 */
4770
+ __setHeartbeatMs: (ms) => {
4771
+ beatOverride = Number(ms) > 0 ? Number(ms) : 0;
4772
+ if (panel !== null && !panel.hidden) startBeat();
4773
+ },
4774
+ };
4775
+ }
4776
+
4777
+ const webPanelLayer = createWebPanelLayer();
4444
4778
 
4445
4779
  /** 去掉终端控制序列:没有 xterm 时,把 ANSI 转义剥掉才不会满屏乱码。 */
4446
4780
  function stripAnsi(text) {
@@ -8127,8 +8461,8 @@ window.__ModuleLoader__.load({
8127
8461
  const [taskFilter, setTaskFilter] = react.useState("all");
8128
8462
  const [composer, setComposer] = react.useState(null);
8129
8463
  const [probe, setProbe] = react.useState(null);
8130
- // 对端 DSH Web 的应用内面板:{ peer, name, state: loading|ready, url, note, hasSession, reloadKey }
8131
- const [webPanel, setWebPanel] = react.useState(null);
8464
+ // 对端 DSH Web 的面板不在这里:它由 webPanelLayer 挂在 document.body 上,
8465
+ // 这样 Mesh 面板被卸载(点侧栏任何会话)时 iframe 不会被销毁。
8132
8466
  // SSH 终端面板:null 或某个 peer
8133
8467
  const [sshPeer, setSshPeer] = react.useState(null);
8134
8468
  const [scanning, setScanning] = react.useState(false);
@@ -8353,59 +8687,15 @@ window.__ModuleLoader__.load({
8353
8687
  /**
8354
8688
  * 打开对端的 DSH Web。
8355
8689
  *
8356
- * 主路是**应用内面板**:宿主起一个回环反代(认证在服务端做),这里只
8357
- * 把它的地址塞进同源 iframe —— 不依赖壳的浏览器 WebView(本机没有),
8358
- * 也不受对端 cookie 的 SameSite=Strict 影响。
8359
- * 反代起不来时才退回老的"浏览器页签 / 外部浏览器"那条链。
8690
+ * 面板本身由 webPanelLayer(body 级常驻层)持有:这里只做转交。之所以
8691
+ * 不在组件里管,是因为主面板 slot 是 keyed 渲染,MeshApp 一卸载 iframe
8692
+ * 就会跟着销毁 —— 而宿主那边的回环反代还在宽限期里,本来可以秒切。
8360
8693
  */
8361
- const openWeb = async (peer, opts) => {
8362
- const force = !!(opts && opts.force);
8363
- const name = (peer && peer.machine) || "对端";
8364
- const key = (peer && (peer.machine || peer.id)) || "";
8365
- const cachedKey =
8366
- webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8367
- // 之前收起来的同一台设备:直接显示,不请求宿主、不重建 iframe。
8368
- // 页面状态、滚动位置、对端会话原样还在(宿主那边代理也在宽限期内)。
8369
- // 超过宽限期就不再走快路——那时宿主可能已经把代理回收了,直接显示
8370
- // 只会看到一个连不上的 iframe。
8371
- const hiddenFor = webPanel && webPanel.hiddenAt ? Date.now() - webPanel.hiddenAt : Infinity;
8372
- if (!force && webPanel && webPanel.url && cachedKey && cachedKey === key && hiddenFor < 8 * 60 * 1000) {
8373
- setWebPanel((prev) => ({ ...(prev || { peer, name }), peer, name, hidden: false, hiddenAt: 0, state: "ready" }));
8374
- return;
8375
- }
8376
- // force = 用户点「重新加载面板」:保留同一个代理地址,只让 iframe 重载
8377
- setWebPanel((prev) => ({
8378
- peer,
8379
- name,
8380
- state: "loading",
8381
- hidden: false,
8382
- reloadKey: force && prev && prev.url ? (prev.reloadKey || 0) + 1 : 0,
8383
- }));
8384
- try {
8385
- const r = await api("/web-panel", { peer: (peer && (peer.machine || peer.id)) || "" });
8386
- if (r && r.ok === true && typeof r.url === "string") {
8387
- setWebPanel((prev) => ({
8388
- ...(prev || { peer, name }),
8389
- state: "ready",
8390
- url: r.url,
8391
- remote: r.remote || "",
8392
- hasSession: r.hasSession !== false,
8393
- note: r.note || "",
8394
- hidden: false,
8395
- reloadKey: (prev && prev.reloadKey) || 0,
8396
- }));
8397
- if (r.hasSession === false) {
8398
- push("warn", `${name} 那边没给出可用 token,面板可能停在登录页。`);
8399
- }
8400
- return;
8401
- }
8402
- setWebPanel(null);
8403
- push("warn", `应用内面板起不来(${(r && r.error) || "未知原因"}),改用外部方式打开。`);
8404
- } catch (error) {
8405
- setWebPanel(null);
8406
- push("warn", `应用内面板起不来(${String((error && error.message) || error)}),改用外部方式打开。`);
8407
- }
8694
+ const openWeb = (peer, opts) => webPanelLayer.open(peer, opts);
8408
8695
 
8696
+ /** 应用内面板起不来时,退回旧的"浏览器页签 / 外部浏览器"那条链。 */
8697
+ const openWebFallback = async (peer) => {
8698
+ const name = (peer && peer.machine) || "对端";
8409
8699
  let result;
8410
8700
  try {
8411
8701
  result = await openDshWebPage(peer);
@@ -8455,27 +8745,15 @@ window.__ModuleLoader__.load({
8455
8745
  push("warn", "当前宿主没有 layout 服务,无法自动回到会话;用侧边栏切回对话即可。");
8456
8746
  };
8457
8747
 
8458
- /**
8459
- * 关掉对端 Web 面板:先卸载前端这一层,再尽力让宿主把反代也停掉
8460
- * (停不掉只是多一个回环端口,不影响正确性)。
8461
- */
8462
- const closeWebPanel = () => {
8463
- const machine = webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8464
- // 只收起、不卸载:iframe 留着,对端页面的会话状态和滚动位置都还在;
8465
- // 宿主收到 close 只把它标记成空闲,宽限期内不拆代理和出站流。
8466
- setWebPanel((prev) => (prev ? { ...prev, hidden: true, hiddenAt: Date.now() } : null));
8467
- if (!machine) return;
8468
- api("/web-panel/close", { peer: machine }).catch(() => {
8469
- /* 关闭是尽力而为 */
8470
- });
8471
- };
8748
+ // 面板层用的 toast 与兜底:push 是 useCallback 稳定的,这里只挂一次。
8749
+ react.useEffect(() => {
8750
+ webPanelLayer.setHooks({ push, fallback: openWebFallback });
8751
+ return () => webPanelLayer.clearHooks();
8752
+ }, [push]);
8472
8753
 
8473
- /** 重新拉起面板(对端重启过、或 iframe 白屏时用)。 */
8474
- const reloadWebPanel = () => {
8475
- const peer = webPanel && webPanel.peer;
8476
- if (!peer) return;
8477
- void openWeb(peer, { force: true });
8478
- };
8754
+ // Mesh 面板被卸载(点侧栏任何会话、切别的面板、换 workspace)→ 只收起,
8755
+ // 不拆 iframe:宽限期内再打开就是原样秒切。
8756
+ react.useEffect(() => () => webPanelLayer.hide(), []);
8479
8757
 
8480
8758
  /** 派发成功的统一收尾:toast + 让轮询立刻刷新。
8481
8759
  * 设备页弹层和主页的派发面板共用它,免得两处提示文案慢慢走散。
@@ -8861,7 +9139,6 @@ window.__ModuleLoader__.load({
8861
9139
  onCopy: copyTransfer,
8862
9140
  })
8863
9141
  : null,
8864
- h(WebPanel, { panel: webPanel, onClose: closeWebPanel, onReload: reloadWebPanel }),
8865
9142
  sshPeer ? h(SshPanel, { peer: sshPeer, onClose: () => setSshPeer(null) }) : null,
8866
9143
  h(Toasts, { items: toasts, onClose: close }),
8867
9144
  h(DemoOverlay, { open: demoOpen, onClose: () => setDemoOpen(false) }),
@@ -8904,6 +9181,10 @@ window.__ModuleLoader__.load({
8904
9181
  ctx.slots.register({ name: "main", key: PANEL_ID }, MeshApp),
8905
9182
  );
8906
9183
  registerAtPeerSource(ctx);
9184
+ // 常驻层不走 slot 的生命周期:插件停用/热更时要自己把 body 上的 iframe 收掉。
9185
+ if (typeof ctx.effect === "function") {
9186
+ ctx.effect(() => () => webPanelLayer.dispose(), "mesh: 常驻 Web 面板层");
9187
+ }
8907
9188
  ctx.logger?.info?.("mesh client: 已注册 Mesh 工作台");
8908
9189
  }
8909
9190
 
@@ -8924,6 +9205,10 @@ window.__ModuleLoader__.load({
8924
9205
  resolveWebUrl,
8925
9206
  openDshWebPage,
8926
9207
  WebPanel,
9208
+ webPanelLayer,
9209
+ createWebPanelLayer,
9210
+ readWebPanelIdleMs,
9211
+ WEB_PANEL_IDLE_DEFAULT,
8927
9212
  CapabilityChips,
8928
9213
  TaskRow,
8929
9214
  TaskDetail,
@@ -13,6 +13,7 @@
13
13
  import { strict as assert } from "node:assert";
14
14
  import { createHmac } from "node:crypto";
15
15
  import { createServer } from "node:http";
16
+ import { gzipSync } from "node:zlib";
16
17
  import { connect as netConnect } from "node:net";
17
18
  import {
18
19
  PEER_WEB_PREFIX,
@@ -273,8 +274,14 @@ console.log("── 端到端:本机反代 → mesh 隧道 → GUI(含同源
273
274
  const originOk = origin === undefined || new URL(String(origin)).host === host;
274
275
  if (!/^127\.0\.0\.1:\d+$/.test(host) || !originOk) { res.writeHead(403); res.end("forbidden"); return; }
275
276
  if (!cookieValid(cookie, host)) { res.writeHead(401); res.end("unauthorized"); return; }
276
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
277
- res.end("<title>peer gui</title>");
277
+ // 宿主 Web 可能自己压过:这里照做,覆盖「注入垫片前先解压」这条路径。
278
+ const body = Buffer.from("<title>peer gui</title>");
279
+ const wantsGzip = String(req.headers["accept-encoding"] ?? "").includes("gzip");
280
+ res.writeHead(200, {
281
+ "content-type": "text/html; charset=utf-8",
282
+ ...wantsGzip ? { "content-encoding": "gzip" } : {},
283
+ });
284
+ res.end(wantsGzip ? gzipSync(body) : body);
278
285
  });
279
286
  const guiInfo = await listen(gui);
280
287
  const forwarder = createPeerWebForwarder({ portOf: () => guiInfo.port, secretOf: () => SESSION });
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `/api` 信任围栏探测的自测(`lib/web-fence.js`)。
3
+ *
4
+ * 这段护栏盯的是**一次真实误判**(2026-11-13,Mac 看 Android 机 `hos`):
5
+ * 对端 `/` 返回 200,观看端就判定"局域网可达"并开直连代理;可对端 `/api`
6
+ * 的信任围栏只认它自己的权威,于是 `/api/remote.mux` 的 WS 升级永远 403,
7
+ * 界面停在「重新连接中…」。判别式只有状态码一条,所以要钉死三件事:
8
+ * · `403` 才算"被围栏挡住"(页面通、接口不通);
9
+ * · `401`/`200`/`404` 是"围栏过了,只是没登录"——绝不能误判成 fenced;
10
+ * · 超时/连不上返回 `undefined`,不许把探测失败伪装成"对端拒绝我"。
11
+ *
12
+ * node lib/_selftest-web-fence.mjs
13
+ */
14
+ import { strict as assert } from "node:assert";
15
+ import { createServer } from "node:http";
16
+ import { API_FENCE_PROBE_PATH, probeApiFence } from "./web-fence.js";
17
+
18
+ let passed = 0;
19
+ let failed = 0;
20
+ async function test(name, fn) {
21
+ try {
22
+ await fn();
23
+ passed += 1;
24
+ console.log(` ✓ ${name}`);
25
+ } catch (err) {
26
+ failed += 1;
27
+ console.log(` ✗ ${name}`);
28
+ console.log(` ${err?.message ?? err}`);
29
+ }
30
+ }
31
+
32
+ /** 起一个只回答固定状态码的假对端,返回基址与关闭函数。 */
33
+ async function fakePeer(status, { onRequest } = {}) {
34
+ const server = createServer((req, res) => {
35
+ onRequest?.(req);
36
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
37
+ res.end(String(status));
38
+ });
39
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
40
+ const { port } = server.address();
41
+ return {
42
+ base: `http://127.0.0.1:${port}/`,
43
+ close: () => new Promise((resolve) => server.close(resolve)),
44
+ };
45
+ }
46
+
47
+ console.log("\n── 403 = 围栏把本机权威拒了 ──");
48
+
49
+ await test("403 → fenced=true,note 说清是 /api 围栏与 host:port", async () => {
50
+ const peer = await fakePeer(403);
51
+ try {
52
+ const probe = await probeApiFence(peer.base);
53
+ assert.equal(probe.fenced, true);
54
+ assert.match(probe.note, /403/);
55
+ // note 里要带上**对端权威**(host:port),否则用户不知道该给对端登记什么。
56
+ assert.ok(probe.note.includes(new URL(peer.base).host), `note 里没有权威 ${new URL(peer.base).host}`);
57
+ assert.match(probe.note, /trustedHosts/);
58
+ } finally {
59
+ await peer.close();
60
+ }
61
+ });
62
+
63
+ await test("探测路径落在 /api 前缀下(围栏在路由之前执行)", async () => {
64
+ let seen = "";
65
+ const peer = await fakePeer(403, { onRequest: (req) => { seen = req.url ?? ""; } });
66
+ try {
67
+ await probeApiFence(peer.base);
68
+ assert.equal(seen, API_FENCE_PROBE_PATH);
69
+ assert.ok(seen.startsWith("/api/"), `${seen} 不在 /api 前缀下`);
70
+ } finally {
71
+ await peer.close();
72
+ }
73
+ });
74
+
75
+ await test("探测是只读的:不带 Cookie、不带 Authorization", async () => {
76
+ let headers = {};
77
+ const peer = await fakePeer(403, { onRequest: (req) => { headers = req.headers; } });
78
+ try {
79
+ await probeApiFence(peer.base);
80
+ assert.equal(headers.cookie, undefined);
81
+ assert.equal(headers.authorization, undefined);
82
+ assert.equal(headers["x-dsh-mesh-token"], undefined);
83
+ } finally {
84
+ await peer.close();
85
+ }
86
+ });
87
+
88
+ console.log("\n── 401/200/404 = 围栏过了,只是没登录(不能误判) ──");
89
+
90
+ for (const status of [401, 200, 404]) {
91
+ await test(`${status} → fenced=false`, async () => {
92
+ const peer = await fakePeer(status);
93
+ try {
94
+ const probe = await probeApiFence(peer.base);
95
+ assert.equal(probe.fenced, false, `${status} 被误判成围栏拒绝`);
96
+ assert.match(probe.note, new RegExp(String(status)));
97
+ } finally {
98
+ await peer.close();
99
+ }
100
+ });
101
+ }
102
+
103
+ console.log("\n── 没有结论时不撒谎 ──");
104
+
105
+ await test("连不上 → fenced=undefined(不是 false,也不是 true)", async () => {
106
+ const probe = await probeApiFence("http://127.0.0.1:1/", { timeoutMs: 300 });
107
+ assert.equal(probe.fenced, undefined);
108
+ assert.match(probe.note, /300ms|没有响应/);
109
+ });
110
+
111
+ await test("地址解析不了 → fenced=undefined", async () => {
112
+ const probe = await probeApiFence("not-a-url");
113
+ assert.equal(probe.fenced, undefined);
114
+ assert.match(probe.note, /解析不了/);
115
+ });
116
+
117
+ await test("对端不答(挂住)→ 超时后 fenced=undefined,如实报超时", async () => {
118
+ const server = createServer(() => { /* 永不响应 */ });
119
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
120
+ const { port } = server.address();
121
+ try {
122
+ const started = Date.now();
123
+ const probe = await probeApiFence(`http://127.0.0.1:${port}/`, { timeoutMs: 200 });
124
+ assert.equal(probe.fenced, undefined);
125
+ assert.ok(Date.now() - started < 2000, "超时没生效");
126
+ } finally {
127
+ await new Promise((resolve) => server.close(resolve));
128
+ }
129
+ });
130
+
131
+ console.log(`\n${failed === 0 ? "✓" : "✗"} web-fence: ${passed} passed, ${failed} failed\n`);
132
+ process.exit(failed === 0 ? 0 : 1);
@@ -192,6 +192,74 @@ test("对端 GUI 只绑回环、又没隧道 → 不许拨它的 3080(那里
192
192
  assert.equal(plan.mode, "none");
193
193
  });
194
194
 
195
+ console.log("\n── 拨通但 /api 被围栏挡住:直连无意义,必须改走隧道 ──");
196
+
197
+ const FENCE_NOTE = "对端 /api 拒绝本机权威(HTTP 403):192.168.1.6:3080 不在对端的 trustedHosts 里";
198
+
199
+ test("有隧道时:围栏 → stream,而不是照旧直连", () => {
200
+ const plan = planWebTarget({
201
+ reportedBase: "http://192.168.1.6:3080/",
202
+ reportedPort: 3080,
203
+ reachable: true,
204
+ apiFenceNote: FENCE_NOTE,
205
+ tunnel: { prefix: "/mesh/peer-web", ticket: "tk", header: "x-dsh-peer-web" },
206
+ tsnetHost: "100.81.214.118",
207
+ meshPort: 45917,
208
+ guiBoundEverywhere: true,
209
+ });
210
+ assert.equal(plan.mode, "stream");
211
+ assert.equal(plan.prefix, "/mesh/peer-web");
212
+ assert.equal(plan.ticket, "tk");
213
+ // 原因要原样透出来:用户得知道"不是网络不通,是对端没认我"。
214
+ assert.ok(plan.note.includes(FENCE_NOTE), `note 里缺围栏原因:${plan.note}`);
215
+ });
216
+
217
+ test("没隧道时:围栏 → none,且 note 说的是围栏、不是'拨不通'", () => {
218
+ const plan = planWebTarget({
219
+ reportedBase: "http://192.168.1.6:3080/",
220
+ reportedPort: 3080,
221
+ reachable: true,
222
+ apiFenceNote: FENCE_NOTE,
223
+ tunnel: null,
224
+ tsnetHost: "",
225
+ meshPort: 0,
226
+ guiBoundEverywhere: true,
227
+ });
228
+ assert.equal(plan.mode, "none");
229
+ assert.ok(plan.note.includes("403"));
230
+ assert.doesNotMatch(plan.note, /拨不通/);
231
+ });
232
+
233
+ test("围栏 + 只有 tailnet 出路:仍走 stream(通道直连对端 GUI)", () => {
234
+ const plan = planWebTarget({
235
+ reportedBase: "http://10.73.218.12:3080/",
236
+ reportedPort: 3080,
237
+ reachable: true,
238
+ apiFenceNote: FENCE_NOTE,
239
+ tunnel: null,
240
+ tsnetHost: "100.81.214.118",
241
+ meshPort: 45917,
242
+ guiBoundEverywhere: true,
243
+ });
244
+ assert.equal(plan.mode, "stream");
245
+ assert.equal(plan.address, "100.81.214.118:3080");
246
+ assert.ok(plan.note.includes(FENCE_NOTE));
247
+ });
248
+
249
+ test("空白 note = 没围栏这回事,行为与以前一字不差", () => {
250
+ const plan = planWebTarget({
251
+ reportedBase: "http://192.168.1.6:3080/",
252
+ reportedPort: 3080,
253
+ reachable: true,
254
+ apiFenceNote: " ",
255
+ tunnel: { prefix: "/mesh/peer-web", ticket: "tk" },
256
+ tsnetHost: "100.81.214.118",
257
+ meshPort: 45917,
258
+ });
259
+ assert.equal(plan.mode, "direct");
260
+ assert.equal(plan.remoteBase, "http://192.168.1.6:3080/");
261
+ });
262
+
195
263
  console.log("\n── 什么时候该探测(别给局域网加延迟)──");
196
264
 
197
265
  test("同网段地址不探测", () => {
@@ -0,0 +1,273 @@
1
+ /**
2
+ * 常驻 Web 面板层(client.js 的 webPanelLayer)自测。
3
+ *
4
+ * 面板层是唯一直接碰 document.body 的部分,用假 DOM + 假 fetch 就能把生命周期
5
+ * 从头到尾走一遍,不需要浏览器:
6
+ *
7
+ * 打开 → 收起(只隐藏)→ 宽限期内复开(不请求、不重建 = 秒切)
8
+ * → 空闲到期(unmount + 摘宿主 + force-close 宿主反代)
9
+ * → 换设备(旧面板先还给宿主)→ dispose(插件卸载不留孤儿)
10
+ *
11
+ * node lib/_selftest-webhost.mjs
12
+ */
13
+ import { strict as assert } from "node:assert";
14
+ import { readFileSync } from "node:fs";
15
+ import { fileURLToPath } from "node:url";
16
+ import { dirname, join } from "node:path";
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url));
19
+ const BUNDLE = join(HERE, "..", "client", "client.js");
20
+
21
+ // ── 假 DOM ──
22
+ const created = [];
23
+ function fakeEl(tag) {
24
+ return {
25
+ tagName: tag,
26
+ className: "",
27
+ id: "",
28
+ style: {},
29
+ children: [],
30
+ parentNode: null,
31
+ appendChild(child) {
32
+ this.children.push(child);
33
+ child.parentNode = this;
34
+ return child;
35
+ },
36
+ removeChild(child) {
37
+ this.children = this.children.filter((item) => item !== child);
38
+ child.parentNode = null;
39
+ },
40
+ textContent: "",
41
+ };
42
+ }
43
+ const body = fakeEl("body");
44
+ globalThis.document = {
45
+ body,
46
+ head: null, // installStyle() 直接早退:样式不在本自测的范围内
47
+ createElement: (tag) => {
48
+ const el = fakeEl(tag);
49
+ created.push(el);
50
+ return el;
51
+ },
52
+ getElementById: () => null,
53
+ };
54
+
55
+ // ── 假 localStorage / window ──
56
+ const store = new Map([["mesh.webPanelIdleMs", "25"]]);
57
+ const listeners = new Map();
58
+ let captured = null;
59
+ globalThis.window = {
60
+ __ModuleLoader__: {
61
+ load: (entry) => {
62
+ captured = entry;
63
+ },
64
+ },
65
+ localStorage: {
66
+ getItem: (key) => (store.has(key) ? store.get(key) : null),
67
+ setItem: (key, value) => store.set(key, String(value)),
68
+ },
69
+ addEventListener: (name, fn) => listeners.set(name, fn),
70
+ };
71
+
72
+ // ── 假 fetch(地址与失败都可由用例控制)──
73
+ const calls = [];
74
+ let hostUrl = "http://127.0.0.1:4321/?k=x";
75
+ let hostFail = false;
76
+ globalThis.fetch = async (url, init) => {
77
+ const payload = init && init.body ? JSON.parse(init.body) : {};
78
+ calls.push({ url: String(url), body: payload, keepalive: !!(init && init.keepalive) });
79
+ if (String(url).endsWith("/mesh/api/web-panel")) {
80
+ if (hostFail) {
81
+ return { ok: true, status: 200, json: async () => ({ ok: false, error: "宿主说保不住了" }) };
82
+ }
83
+ return { ok: true, status: 200, json: async () => ({ ok: true, url: hostUrl, hasSession: true }) };
84
+ }
85
+ return { ok: true, status: 200, json: async () => ({ ok: true }) };
86
+ };
87
+
88
+ // ── 假 react / react-dom/client ──
89
+ const reactStub = {
90
+ createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }),
91
+ useState: (value) => [typeof value === "function" ? value() : value, () => {}],
92
+ useEffect: () => {},
93
+ useMemo: (fn) => fn(),
94
+ useCallback: (fn) => fn,
95
+ useRef: (value) => ({ current: value }),
96
+ Fragment: Symbol("Fragment"),
97
+ };
98
+ const rendered = [];
99
+ let unmounted = 0;
100
+ const reactDomStub = {
101
+ createRoot: () => ({
102
+ render: (node) => rendered.push(node),
103
+ unmount: () => {
104
+ unmounted += 1;
105
+ },
106
+ }),
107
+ };
108
+
109
+ const source = readFileSync(BUNDLE, "utf8");
110
+ new Function("window", `${source}\n`)(globalThis.window);
111
+ const mod = captured.factory((name) => {
112
+ if (name === "react") return reactStub;
113
+ if (name === "react-dom/client") return reactDomStub;
114
+ throw new Error(`未预期的依赖:${name}`);
115
+ });
116
+
117
+ const layer = mod.__test.webPanelLayer;
118
+ const peer = { machine: "hos", id: "x1" };
119
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
120
+
121
+ let passed = 0;
122
+ function ok(name, fn) {
123
+ fn();
124
+ passed += 1;
125
+ console.log(` ✓ ${name}`);
126
+ }
127
+ async function okAsync(name, fn) {
128
+ await fn();
129
+ passed += 1;
130
+ console.log(` ✓ ${name}`);
131
+ }
132
+
133
+ await okAsync("打开:一次 /web-panel,宿主挂到 body 上", async () => {
134
+ await layer.open(peer);
135
+ assert.equal(layer.__alive(), true);
136
+ assert.equal(layer.current().hidden, false);
137
+ assert.equal(calls.length, 1);
138
+ const host = created.find((el) => el.className === "mesh-web-hosted");
139
+ assert.ok(host, "应创建 body 级宿主");
140
+ assert.ok(body.children.includes(host), "宿主必须挂在 body 上");
141
+ });
142
+
143
+ ok("收起:只隐藏,不卸载 iframe", () => {
144
+ layer.hide();
145
+ assert.equal(layer.current().hidden, true);
146
+ assert.equal(layer.__alive(), true);
147
+ assert.equal(unmounted, 0);
148
+ });
149
+
150
+ await okAsync("宽限期内复开:不重建 iframe(秒切),只顺手续一次命", async () => {
151
+ const before = rendered.length;
152
+ const opens = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
153
+ await layer.open(peer);
154
+ assert.equal(layer.current().hidden, false);
155
+ assert.equal(rendered.length, before + 1, "只重绘一次");
156
+ assert.equal(unmounted, 0, "复开不该重建 root");
157
+ await sleep(10);
158
+ const after = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
159
+ assert.equal(after, opens + 1, "复开应顺带打一次 /web-panel 续命(只刷新 lastUsedAt)");
160
+ });
161
+
162
+ await okAsync("空闲到期:unmount + 摘宿主 + force-close 宿主反代", async () => {
163
+ layer.hide();
164
+ await sleep(80);
165
+ assert.equal(layer.__alive(), false);
166
+ assert.equal(unmounted, 1);
167
+ assert.equal(body.children.length, 0, "宿主应从 body 摘掉");
168
+ const close = calls.find((call) => call.url.endsWith("/web-panel/close"));
169
+ assert.ok(close, "到期应通知宿主 close");
170
+ assert.equal(close.body.force, true, "到期必须 force-close");
171
+ assert.equal(close.body.peer, "hos");
172
+ });
173
+
174
+ await okAsync("换设备:旧面板先还给宿主,不留孤儿端口", async () => {
175
+ calls.length = 0;
176
+ await layer.open(peer);
177
+ await layer.open({ machine: "myserver-wb", id: "y2" });
178
+ const closed = calls.filter((call) => call.url.endsWith("/web-panel/close"));
179
+ assert.equal(closed.length, 1);
180
+ assert.equal(closed[0].body.peer, "hos");
181
+ assert.equal(closed[0].body.force, true);
182
+ });
183
+
184
+ ok("dispose:插件卸载后 body 上不留宿主", () => {
185
+ layer.dispose();
186
+ assert.equal(layer.__alive(), false);
187
+ assert.equal(body.children.length, 0);
188
+ });
189
+
190
+ // ── 回归:没配置 mesh.webPanelIdleMs 时必须落到默认 10 分钟 ──
191
+ // getItem 未命中返回 null,而 Number(null) 是 0 —— 曾经因此把「没配置」读成
192
+ // 「收起即拆」,每次 hide() 立刻销毁 iframe,秒切整个失效。
193
+ const emptyStore = new Map();
194
+ let captured2 = null;
195
+ globalThis.window = {
196
+ __ModuleLoader__: {
197
+ load: (entry) => {
198
+ captured2 = entry;
199
+ },
200
+ },
201
+ localStorage: {
202
+ getItem: (key) => (emptyStore.has(key) ? emptyStore.get(key) : null),
203
+ setItem: (key, value) => emptyStore.set(key, String(value)),
204
+ },
205
+ addEventListener: () => {},
206
+ };
207
+ new Function("window", `${readFileSync(BUNDLE, "utf8")}\n`)(globalThis.window);
208
+ const mod2 = captured2.factory((name) => {
209
+ if (name === "react") return reactStub;
210
+ if (name === "react-dom/client") return reactDomStub;
211
+ throw new Error(`未预期的依赖:${name}`);
212
+ });
213
+
214
+ ok("未配置空闲时长 → 默认 10 分钟(不是 0)", () => {
215
+ assert.equal(mod2.__test.WEB_PANEL_IDLE_DEFAULT, 10 * 60 * 1000);
216
+ assert.equal(mod2.__test.readWebPanelIdleMs(), mod2.__test.WEB_PANEL_IDLE_DEFAULT);
217
+ });
218
+
219
+ await okAsync("默认配置下收起:宽限期内 iframe 必须还活着", async () => {
220
+ const layer2 = mod2.__test.webPanelLayer;
221
+ await layer2.open({ machine: "hos", id: "x1" });
222
+ layer2.hide();
223
+ await sleep(40);
224
+ assert.equal(layer2.__alive(), true, "收起后立刻销毁 = 秒切失效");
225
+ layer2.dispose();
226
+ assert.equal(layer2.__alive(), false);
227
+ });
228
+
229
+ await okAsync("可见期间心跳:按时续命,地址不变就不重载", async () => {
230
+ const layer2 = mod2.__test.webPanelLayer;
231
+ hostUrl = "http://127.0.0.1:5555/?k=keep";
232
+ await layer2.open({ machine: "hos", id: "x1" });
233
+ const base = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
234
+ const before = rendered.length;
235
+ layer2.__setHeartbeatMs(20);
236
+ await sleep(70);
237
+ const after = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
238
+ assert.ok(after > base, "心跳应持续打 /web-panel");
239
+ assert.equal(rendered.length, before, "地址没变就不该重绘/重载");
240
+ assert.equal(layer2.__alive(), true);
241
+ layer2.dispose();
242
+ });
243
+
244
+ await okAsync("心跳自愈:宿主回收后重建过(地址变了)→ iframe 换到新地址重载", async () => {
245
+ const layer3 = mod2.__test.webPanelLayer;
246
+ hostUrl = "http://127.0.0.1:6666/?k=old";
247
+ await layer3.open({ machine: "hos", id: "x1" });
248
+ const before = rendered.length;
249
+ hostUrl = "http://127.0.0.1:7777/?k=new";
250
+ layer3.__setHeartbeatMs(20);
251
+ await sleep(70);
252
+ const last = rendered[rendered.length - 1];
253
+ assert.equal(rendered.length, before + 1, "地址变了应重绘一次");
254
+ assert.ok(last && last.props && last.props.panel, "最后一次渲染应带 panel");
255
+ assert.equal(last.props.panel.url, "http://127.0.0.1:7777/?k=new");
256
+ assert.equal(last.props.panel.reloadKey, 1, "重载计数应 +1");
257
+ layer3.dispose();
258
+ });
259
+
260
+ await okAsync("心跳失败:宿主说保不住 → 拆面板并提示重开", async () => {
261
+ const layer4 = mod2.__test.webPanelLayer;
262
+ hostUrl = "http://127.0.0.1:8888/?k=x";
263
+ hostFail = false;
264
+ await layer4.open({ machine: "hos", id: "x1" });
265
+ hostFail = true;
266
+ layer4.__setHeartbeatMs(20);
267
+ await sleep(70);
268
+ assert.equal(layer4.__alive(), false, "保不住时应销毁面板");
269
+ layer4.dispose();
270
+ hostFail = false;
271
+ });
272
+
273
+ console.log(`\n全部通过:${passed} 通过 / 0 失败`);
package/lib/index.js CHANGED
@@ -109,6 +109,7 @@ import { resolveTailnetChannels } from "./tsnet/channels.js";
109
109
  import { tailnetFetch, tailnetOrigin, isTailnetAddress } from "./tsnet/bridge.js";
110
110
  import { createWebProxy } from "./web-proxy.js";
111
111
  import { planWebTarget, needsReachabilityProbe, isLoopbackHost } from "./web-target.js";
112
+ import { probeApiFence } from "./web-fence.js";
112
113
  import { planSshTarget, sshDirectCandidates } from "./ssh-target.js";
113
114
  import { createSecretReader } from "./desktop-auth.js";
114
115
  import {
@@ -129,7 +130,7 @@ import {
129
130
  export const name = "dsh-plugin-mesh";
130
131
  export const inject = ["tools", "webServer"];
131
132
 
132
- const VERSION = "0.5.18";
133
+ const VERSION = "0.5.20";
133
134
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
134
135
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
135
136
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
@@ -4951,6 +4952,11 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4951
4952
  // CGNAT 的 10.x,而 `lanReachable` 只是"我绑了 0.0.0.0"。所以这里补一道
4952
4953
  // 本机可达性判断,拨不通就改走 mesh 通道(tailnet 字节流)。
4953
4954
  const direct = await verifyWebBase(remoteBase);
4955
+ // 拨通 ≠ 能用:对端 `/api` 的浏览器信任围栏可能只认它自己的权威(回环 / 已登记),
4956
+ // 那页面能打开、串流(`/api/remote.mux`)却永远 403 —— 界面就停在「重新连接中…」。
4957
+ // 只有对端给了隧道时才花这一次探测:没隧道的话知道答案也没别的路可走。
4958
+ const fence = tunnel ? await probeApiFence(remoteBase) : { fenced: undefined, note: "" };
4959
+ if (fence.fenced === true) log(`对端 /api 围栏拒绝本机权威,改走隧道:${fence.note}`);
4954
4960
  const plan = planWebTarget({
4955
4961
  reportedBase: remoteBase,
4956
4962
  reportedPort: guiPort,
@@ -4961,6 +4967,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4961
4967
  // 对端没报 bind 时不猜"只听回环":老版本做不到这条隧道,保持旧行为。
4962
4968
  guiBoundEverywhere: guiBind ? guiBind === "0.0.0.0" : undefined,
4963
4969
  probeNote: direct.note,
4970
+ apiFenceNote: fence.fenced === true ? fence.note : "",
4964
4971
  });
4965
4972
  if (plan.mode === "stream") {
4966
4973
  const passthrough = Boolean(plan.ticket);
@@ -4974,6 +4981,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4974
4981
  if (lanBase) {
4975
4982
  const probe = await verifyWebBase(lanBase);
4976
4983
  if (probe.reachable !== false) {
4984
+ const lanNote = `经对端局域网 mesh 口隧道(${lanBase}${String(plan.prefix || "").replace(/^\//, "")})`;
4977
4985
  return {
4978
4986
  remoteBase: lanBase,
4979
4987
  pathPrefix: plan.prefix || "",
@@ -4984,7 +4992,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
4984
4992
  guiBind,
4985
4993
  stream: null,
4986
4994
  upstreamHeaders,
4987
- note: `经对端局域网 mesh 口隧道(${lanBase}${String(plan.prefix || "").replace(/^\//, "")})`,
4995
+ note: fence.fenced === true ? `${fence.note} → ${lanNote}` : lanNote,
4988
4996
  };
4989
4997
  }
4990
4998
  }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 对端 GUI 的 `/api` 浏览器信任围栏 —— 「拨通」不等于「能用」。
3
+ *
4
+ * 复现过的现场(2026-11-13,Mac 看 Android 机 `hos`:`192.168.1.6:3080`):
5
+ * · `GET http://192.168.1.6:3080/` → `200`,于是观看端判定"局域网可达",开直连代理;
6
+ * · 同一台机器 `GET /api/anything` → `403 forbidden`。对端 `client-connection` 的
7
+ * `isTrustedApiRequest` 只认**回环权威**或 `trustedHosts` 里登记过的权威;它明明
8
+ * 绑在 `0.0.0.0`,却没把局域网 IP 派生进 `trustedHosts`(Android 壳起 Web 时常见);
9
+ * · 结果:页面能渲染(index 靠 cookie 过),`/api/remote.mux` 的 WS 升级被拒,
10
+ * DSH 客户端按指数退避无限重试 —— 界面永远停在「重新连接中…」。
11
+ *
12
+ * 判别式只有一条,而且干净,看同一个探测请求的状态码:
13
+ * · `403` = 围栏把**本机权威**拒了(页面通、接口不通,直连没有意义,该改走隧道);
14
+ * · `401`/`200`/`404` = 围栏过了,只是没有会话("能用,只是要登录");
15
+ * · 超时/连不上 = `undefined`:别把探测失败伪装成否定事实(AGENTS.md 硬约束 1)。
16
+ *
17
+ * 探测是只读 GET、不带任何凭据、不改对端状态;路径落在 `/api` 前缀下即可 ——
18
+ * 围栏在路由匹配**之前**执行,所以随便一个不存在的端点也能问出答案。
19
+ */
20
+
21
+ /** 探测路径:只要在 `/api` 前缀下就会先过围栏。 */
22
+ export const API_FENCE_PROBE_PATH = "/api/__mesh-fence-probe";
23
+ /** 探测超时:一次局域网来回;超时也只是"没结论",不改变后续决策。 */
24
+ export const API_FENCE_PROBE_MS = 1500;
25
+
26
+ /** 目标地址的权威(`host:port`),用于把话说清楚。 */
27
+ function authorityOf(base) {
28
+ try {
29
+ return new URL(String(base)).host;
30
+ } catch {
31
+ return "";
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 问一次对端:`/api` 的围栏认不认本机这个权威?
37
+ *
38
+ * @param {string} base - 对端 GUI 的绝对地址(`http://host:port/`,不含 token 参数)
39
+ * @param {object} [options]
40
+ * @param {number} [options.timeoutMs] - 探测超时
41
+ * @param {Function} [options.fetchImpl] - 注入用(自测替身)
42
+ * @returns {Promise<{ fenced: boolean | undefined, note: string }>}
43
+ * `fenced: true` 才代表"直连不可用";`undefined` 表示没问出结论。
44
+ */
45
+ export async function probeApiFence(base, { timeoutMs = API_FENCE_PROBE_MS, fetchImpl = globalThis.fetch } = {}) {
46
+ let url;
47
+ try {
48
+ url = new URL(API_FENCE_PROBE_PATH, String(base)).href;
49
+ } catch {
50
+ return { fenced: undefined, note: `地址 ${String(base)} 解析不了` };
51
+ }
52
+ try {
53
+ const res = await fetchImpl(url, {
54
+ method: "GET",
55
+ redirect: "manual",
56
+ headers: { accept: "application/json" },
57
+ signal: AbortSignal.timeout(timeoutMs),
58
+ });
59
+ // 只关心状态码;响应体一律不要(别把对端的错误页留在内存里)。
60
+ try {
61
+ await res.body?.cancel?.();
62
+ } catch {
63
+ /* 取消除失败无所谓 */
64
+ }
65
+ if (res.status === 403) {
66
+ const authority = authorityOf(base);
67
+ return {
68
+ fenced: true,
69
+ note: `对端 /api 拒绝本机权威(HTTP 403):${authority || "本机"} 不在对端的 trustedHosts 里,/api/remote.mux 会被永久拒绝`,
70
+ };
71
+ }
72
+ return { fenced: false, note: `HTTP ${res.status}` };
73
+ } catch (err) {
74
+ return { fenced: undefined, note: `${timeoutMs}ms 内没有响应(${err?.message ?? err})` };
75
+ }
76
+ }
package/lib/web-proxy.js CHANGED
@@ -23,6 +23,7 @@ import { appendFileSync } from "node:fs";
23
23
  import { join } from "node:path";
24
24
  import { homedir } from "node:os";
25
25
  import { connect as netConnect } from "node:net";
26
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
26
27
  // [mesh-keepalive] 复用上游连接:几十个 bundle 请求不该各建一次 TCP。
27
28
  // tailnet 上每次握手就是一个 RTT;局域网/回环上也省掉握手与端口分配。
28
29
  const upstreamAgent = new HttpAgent({ keepAlive: true, maxSockets: 16, maxFreeSockets: 8, timeout: 30000 });
@@ -57,6 +58,23 @@ const ITERATOR_SHIM =
57
58
  '})();</script>';
58
59
 
59
60
  /** 把垫片插到 <head> 之后(越早越好:模块脚本是 defer,但内联脚本会先跑)。 */
61
+
62
+ /**
63
+ * 上游可能已经压过(宿主 Web 有自己的 gzip 中间件)。
64
+ * 注入垫片前必须先解压 —— 否则会往 gzip 字节里插 HTML,页面直接花屏。
65
+ * @param buffer - 上游原始字节
66
+ * @param encoding - 上游 content-encoding
67
+ * @returns 明文字节(无法识别或解压失败时抛错,由调用方回退成原样转发)
68
+ */
69
+ function decodeUpstreamBody(buffer, encoding) {
70
+ const enc = String(encoding ?? "").trim().toLowerCase();
71
+ if (enc === "" || enc === "identity") return buffer;
72
+ if (enc === "gzip" || enc === "x-gzip") return gunzipSync(buffer);
73
+ if (enc === "deflate") return inflateSync(buffer);
74
+ if (enc === "br") return brotliDecompressSync(buffer);
75
+ throw new Error(`不认识的 content-encoding: ${enc}`);
76
+ }
77
+
60
78
  function injectShim(html) {
61
79
  const at = html.indexOf("<head>");
62
80
  if (at === -1) return ITERATOR_SHIM + html;
@@ -255,17 +273,21 @@ export async function createWebProxy({
255
273
  const chunks = [];
256
274
  reply.on("data", (chunk) => chunks.push(chunk));
257
275
  reply.on("end", () => {
276
+ const raw = Buffer.concat(chunks);
258
277
  try {
259
- const body = Buffer.from(injectShim(Buffer.concat(chunks).toString("utf8")), "utf8");
278
+ const text = decodeUpstreamBody(raw, out["content-encoding"]).toString("utf8");
279
+ const body = Buffer.from(injectShim(text), "utf8");
260
280
  delete out["content-encoding"];
261
281
  out["content-length"] = String(body.length);
262
282
  res.writeHead(200, out);
263
283
  res.end(req.method === "HEAD" ? undefined : body);
264
284
  log(`已给文档注入兼容垫片(${body.length}B)`);
265
285
  } catch (error) {
286
+ // 解压/注入失败就原样转发:保留上游的 content-encoding 与字节,
287
+ // 宁可没有垫片,也不能把二进制喂给浏览器解析。
266
288
  warn(`文档注入失败,按原样返回:${error?.message ?? error}`);
267
289
  if (!res.headersSent) res.writeHead(200, out);
268
- res.end(req.method === "HEAD" ? undefined : Buffer.concat(chunks));
290
+ res.end(req.method === "HEAD" ? undefined : raw);
269
291
  }
270
292
  });
271
293
  reply.on("error", () => res.destroy());
package/lib/web-target.js CHANGED
@@ -58,6 +58,9 @@ export function tunnelPrefixOf(tunnel) {
58
58
  * @param {boolean} [input.guiBoundEverywhere] 对端 GUI 是否绑在所有网卡(bind=0.0.0.0);
59
59
  * `undefined` = 对端没报(老版本),按"绑了"处理以保持旧行为
60
60
  * @param {string} [input.probeNote] 探测失败时的原始描述,需原样带进 note
61
+ * @param {string} [input.apiFenceNote] 地址拨得通、但对端 `/api` 的信任围栏拒绝本机权威时的
62
+ * 原因(见 `web-fence.js`);空串 = 没这回事。给了它就**不按直连处理**:页面能打开、
63
+ * 串流(`/api/remote.mux`)却永远 403,直连只会让界面停在「重新连接中…」。
61
64
  * @returns {WebTargetPlan}
62
65
  */
63
66
  export function planWebTarget({
@@ -69,6 +72,7 @@ export function planWebTarget({
69
72
  meshPort = 0,
70
73
  guiBoundEverywhere,
71
74
  probeNote = "",
75
+ apiFenceNote = "",
72
76
  } = {}) {
73
77
  const base = String(reportedBase ?? "");
74
78
  const port = Number(reportedPort) || portOf(base) || 0;
@@ -78,7 +82,11 @@ export function planWebTarget({
78
82
  // 直连过去只会打到**本机自己**的 3080(一个非常难查的假成功)。
79
83
  // 所以这类地址一律不按直连处理,只能走它给的 mesh 口隧道。
80
84
  const loopbackReport = isLoopbackHost(reportedHost);
81
- const direct = reachable !== false && !loopbackReport;
85
+ // 「拨得通」也是假的可达:对端 `/api` 的浏览器信任围栏只认它自己的权威时,
86
+ // 页面能打开、`/api/remote.mux` 却永远 403 —— 直连没有意义,必须先排除。
87
+ const fenceNote = String(apiFenceNote ?? "").trim();
88
+ const fenced = fenceNote.length > 0;
89
+ const direct = reachable !== false && !loopbackReport && !fenced;
82
90
 
83
91
  // 没探测 / 探测通过 → 照旧直连。局域网路径上不多花一毫秒。
84
92
  if (direct) {
@@ -90,9 +98,11 @@ export function planWebTarget({
90
98
  return {
91
99
  mode: "none",
92
100
  remoteBase: base,
93
- note: loopbackReport
94
- ? `对端只报了回环地址 ${base}(它的 GUI 只听 127.0.0.1),且没有 tailnet 通道可用`
95
- : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没有 tailnet 通道可用`,
101
+ note: fenced
102
+ ? fenceNote
103
+ : loopbackReport
104
+ ? `对端只报了回环地址 ${base}(它的 GUI 只听 127.0.0.1),且没有 tailnet 通道可用`
105
+ : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没有 tailnet 通道可用`,
96
106
  };
97
107
  }
98
108
 
@@ -102,7 +112,7 @@ export function planWebTarget({
102
112
 
103
113
  // 隧道挂在**对端的 mesh 口**上:目标是对端 mesh 端口 + 相对前缀。
104
114
  // 这条路把 Host/Origin/会话 cookie 的改写留在对端进程里完成,所以对端 GUI
105
- // 只绑回环也能看;WebSocket(/api/remote.mux)同样走这条。
115
+ // 只绑回环也能看,**不认局域网权威的围栏也一样能过**;WebSocket(/api/remote.mux)同样走这条。
106
116
  if (prefix && ticket && meshPort > 0) {
107
117
  return {
108
118
  mode: "stream",
@@ -110,7 +120,9 @@ export function planWebTarget({
110
120
  prefix,
111
121
  ticket,
112
122
  header,
113
- note: `经对端 mesh 口隧道(对端自报地址 ${base} 不可达)`,
123
+ note: fenced
124
+ ? `${fenceNote};改走对端 mesh 口隧道`
125
+ : `经对端 mesh 口隧道(对端自报地址 ${base} 不可达)`,
114
126
  };
115
127
  }
116
128
 
@@ -125,16 +137,20 @@ export function planWebTarget({
125
137
  prefix: "",
126
138
  ticket: "",
127
139
  header,
128
- note: `经本机 tailnet 通道直连对端 GUI ${host}:${port}(对端自报地址 ${base} 不可达)`,
140
+ note: fenced
141
+ ? `${fenceNote};改走本机 tailnet 通道直连对端 GUI ${host}:${port}`
142
+ : `经本机 tailnet 通道直连对端 GUI ${host}:${port}(对端自报地址 ${base} 不可达)`,
129
143
  };
130
144
  }
131
145
 
132
146
  return {
133
147
  mode: "none",
134
148
  remoteBase: base,
135
- note: loopbackReport || !boundEverywhere
136
- ? `对端 GUI 只听回环(${base}),且没给 mesh 口隧道 —— 需要把对端插件升级到带隧道的版本`
137
- : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没拿到对端 GUI 端口`,
149
+ note: fenced
150
+ ? fenceNote
151
+ : loopbackReport || !boundEverywhere
152
+ ? `对端 GUI 只听回环(${base}),且没给 mesh 口隧道 —— 需要把对端插件升级到带隧道的版本`
153
+ : `对端自报地址 ${base} 从本机拨不通(${probeNote || "无响应"}),且没拿到对端 GUI 端口`,
138
154
  };
139
155
  }
140
156
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.18",
3
+ "version": "0.5.20",
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",
@@ -69,8 +69,8 @@
69
69
  "selftest:update": "node lib/_selftest-update.mjs",
70
70
  "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
71
  "selftest:approval": "node lib/_selftest-approval.mjs",
72
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
73
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
72
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:webfence && npm run selftest:webhost && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
73
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/web-fence.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
74
74
  "build:sidecar": "bash scripts/build-sidecar.sh",
75
75
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
76
76
  "release:plan": "node scripts/release-plan.mjs",
@@ -86,6 +86,8 @@
86
86
  "selftest:at:host": "node --experimental-vm-modules lib/_selftest-at-mention-host.mjs",
87
87
  "selftest:peerweb": "node lib/_selftest-peer-web.mjs",
88
88
  "selftest:webtarget": "node lib/_selftest-web-target.mjs",
89
+ "selftest:webfence": "node lib/_selftest-web-fence.mjs",
90
+ "selftest:webhost": "node lib/_selftest-webhost.mjs",
89
91
  "selftest:sshtarget": "node lib/_selftest-ssh-target.mjs"
90
92
  },
91
93
  "publishConfig": {