@mrrisega/dsh-remote 0.6.12 → 0.6.14

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.
@@ -95,7 +95,34 @@ const RUNTIME_HOST_RE =
95
95
  /(data-sidebar-collapsed|data-details-collapsed|data-rightbar-collapsed|data-shell-overlay)|(pI_x6G_frame|hHd-Xa_root|hHd-Xa_toggle)/;
96
96
 
97
97
  const STYLE = `
98
- /* ===== dsh-remote mobile adapter (bridge 注入;仅 ≤820px 生效,桌面宽屏无任何规则) ===== */
98
+ /* ===== 首屏加载提示(0.6.14)=====
99
+ 为什么要有它:镜像页首屏要拉 dsh web 的全部客户端插件(实测 ~14 MB,一个不可拆分的
100
+ /plugins/?? 聚合请求),免费档限速下几十秒起步。此前页面上**只有官方那个转圈**,
101
+ 用户无法区分"在加载"和"卡死了",只能反复刷新 —— 反而更慢。
102
+ 这里给一句人话提示 + 分阶段的补充说明,加载完成(或超时兜底)即自动移除。
103
+ ⚠️ 刻意**不**放进 @media (max-width:820px):Windows/桌面浏览器打开镜像页同样要等。
104
+ ⚠️ pointer-events:none + 半透明:万一移除逻辑失效,也绝不挡住任何点击。 */
105
+ .dsh-ma-boot {
106
+ position: fixed; inset: 0; z-index: 2147483000;
107
+ display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 14px;
108
+ background: color-mix(in srgb, var(--dsw-alias-bg-base, #0f1115) 88%, transparent);
109
+ backdrop-filter: blur(2px);
110
+ pointer-events: none;
111
+ font-family: inherit; text-align: center; padding: 24px;
112
+ transition: opacity .3s ease;
113
+ }
114
+ .dsh-ma-boot[data-fading="1"] { opacity: 0; }
115
+ .dsh-ma-boot-spin {
116
+ width: 34px; height: 34px; border-radius: 50%;
117
+ border: 3px solid color-mix(in srgb, currentColor 22%, transparent);
118
+ border-top-color: currentColor;
119
+ animation: dsh-ma-boot-spin 1s linear infinite;
120
+ }
121
+ @keyframes dsh-ma-boot-spin { to { transform: rotate(360deg); } }
122
+ .dsh-ma-boot-title { font-size: 15px; font-weight: 600; }
123
+ .dsh-ma-boot-sub { font-size: 13px; line-height: 1.6; opacity: .75; max-width: 22em; }
124
+ .dsh-ma-boot-elapsed { font-size: 12px; opacity: .55; font-variant-numeric: tabular-nums; }
125
+
99
126
  @media (max-width: 820px) {
100
127
  html, body { max-width: 100%; overflow-x: hidden; }
101
128
  html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
@@ -426,6 +453,89 @@ html[data-dsh-ma-merged-e2ee] #dsh-e2ee-badge { display: none !important; }
426
453
  const SCRIPT = `(() => {
427
454
  "use strict";
428
455
 
456
+ /* ===== 首屏加载提示(0.6.14)=====
457
+ 用户反馈:「普通用户加载进入镜像页面时等待时间较长,目前等待过程中一直在转圈」
458
+ —— 官方那个转圈不告诉用户任何事。这里在**页面解析的第一时间**就挂上一条人话提示,
459
+ 并在官方 UI 就绪(或兜底超时)后自动移除。
460
+
461
+ ⚠️ 必须放在所有主机判定(HOSTISH / NARROW)之前:首屏慢的正是这些判定等不到的时候。
462
+ ⚠️ 只做提示,不做任何拦截:pointer-events:none,也没有遮罩语义。 */
463
+ var maBootTip = null, maBootTimers = [], maBootStart = Date.now(), maBootElapsedTimer = 0, maBootWatchTimer = 0;
464
+ function maBootSet(cls, text) {
465
+ try { var n = maBootTip && maBootTip.querySelector(cls); if (n) n.textContent = text; } catch (e) { /* 忽略 */ }
466
+ }
467
+ function maBootShow() {
468
+ try {
469
+ if (maBootTip) return;
470
+ if (!document.body) return; // 解析太早(body 还没出来)→ 交给 DOMContentLoaded 再挂
471
+ maBootTip = document.createElement("div");
472
+ maBootTip.className = "dsh-ma-boot";
473
+ maBootTip.setAttribute("role", "status");
474
+ maBootTip.setAttribute("aria-live", "polite");
475
+ maBootTip.innerHTML =
476
+ '<div class="dsh-ma-boot-spin" aria-hidden="true"></div>' +
477
+ '<div class="dsh-ma-boot-title">正在加载远程桌面…</div>' +
478
+ '<div class="dsh-ma-boot-sub">首次打开需要下载较完整的前端资源,请稍候</div>' +
479
+ '<div class="dsh-ma-boot-elapsed">已等待 0 秒</div>';
480
+ document.body.appendChild(maBootTip);
481
+ // 秒表:让"到底等了多久"可见(用户据此判断是慢还是死了)
482
+ maBootElapsedTimer = setInterval(function () {
483
+ try {
484
+ var s = Math.floor((Date.now() - maBootStart) / 1000);
485
+ var n = maBootTip && maBootTip.querySelector(".dsh-ma-boot-elapsed");
486
+ if (n) n.textContent = "已等待 " + s + " 秒";
487
+ } catch (e) { /* 忽略 */ }
488
+ }, 1000);
489
+ maBootTimers.push(setTimeout(function () {
490
+ maBootSet(".dsh-ma-boot-sub", "网络较慢时可能需要一两分钟;加载完成后会自动进入,不用重复刷新");
491
+ }, 8000));
492
+ maBootTimers.push(setTimeout(function () {
493
+ maBootSet(".dsh-ma-boot-sub", "还在加载…如果长时间停在这里,可以下拉刷新重试(重复刷新不会更快)");
494
+ }, 30 * 1000));
495
+ } catch (e) { /* 提示失败绝不影响主功能 */ }
496
+ }
497
+ function maBootHide() {
498
+ try {
499
+ for (var i = 0; i < maBootTimers.length; i++) clearTimeout(maBootTimers[i]);
500
+ maBootTimers = [];
501
+ if (maBootElapsedTimer) { clearInterval(maBootElapsedTimer); maBootElapsedTimer = 0; }
502
+ if (maBootWatchTimer) { try { clearInterval(maBootWatchTimer); } catch (e) { /* 忽略 */ } maBootWatchTimer = 0; }
503
+ var tip = maBootTip;
504
+ maBootTip = null;
505
+ if (tip && tip.parentNode) {
506
+ try { tip.setAttribute("data-fading", "1"); } catch (e) { /* 忽略 */ }
507
+ setTimeout(function () { try { if (tip.parentNode) tip.parentNode.removeChild(tip); } catch (e) { /* 忽略 */ } }, 300);
508
+ }
509
+ } catch (e) { /* 忽略 */ }
510
+ }
511
+ /** 官方 UI 是否已经可用了(= 提示可以撤了)。 */
512
+ function maBootLooksReady() {
513
+ try {
514
+ // ① 适配层认出来的官方 frame(与下方 boot() 同一组选择器)
515
+ if (document.querySelector(".pI_x6G_frame, [data-sidebar-collapsed], [data-details-collapsed], [data-rightbar-collapsed]")) return true;
516
+ // ② 出现输入框/会话区也算"进来了"(官方改版首选信号失灵时的兜底)
517
+ return Boolean(document.querySelector('textarea, [contenteditable="true"], [role="textbox"]'));
518
+ } catch (e) { return false; }
519
+ }
520
+ if (document.readyState === "loading") {
521
+ document.addEventListener("DOMContentLoaded", maBootShow);
522
+ } else {
523
+ maBootShow();
524
+ }
525
+ // 轮询撤下:1s 一次,成本可忽略(只是两次 querySelector);一旦撤下就自我停止。
526
+ // 上限与"4 分钟兜底"对齐,避免页面异常时留下常驻定时器。
527
+ maBootWatchTimer = setInterval(function () {
528
+ if (maBootLooksReady()) { maBootHide(); return; }
529
+ if (!maBootTip) { try { clearInterval(maBootWatchTimer); } catch (e) { /* 忽略 */ } maBootWatchTimer = 0; }
530
+ }, 1000);
531
+ maBootTimers.push(setTimeout(function () { maBootHide(); }, 240 * 1000));
532
+ // 页面卸载/进 bfcache 时收干净(测试与真机都靠这条不留悬挂定时器)
533
+ try {
534
+ var maBootBye = function () { maBootHide(); };
535
+ window.addEventListener("pagehide", maBootBye);
536
+ window.addEventListener("unload", maBootBye);
537
+ } catch (e) { /* 忽略 */ }
538
+
429
539
  /* —— 主机门解除(2026-09):镜像页(如 n.risegao.cn)经设备流认证回连同一台 127.0.0.1:3080,
430
540
  桥已把 Host 回环化并剥 Origin(不扩大信任面)。官方客户端以 transport.ownsHost 判定
431
541
  「自有主机」,非回环域名下不置 true 会把设置页置为 memory(不可用)镜像 →
@@ -1096,6 +1206,36 @@ const SCRIPT = `(() => {
1096
1206
  } catch (e8) { /* 引导条失败绝不能影响主功能 */ }
1097
1207
  };
1098
1208
 
1209
+ /* 适配层自己创建的「抽屉入口」引用(汉堡按钮 / 遮罩),提到 boot() 外层保存。
1210
+ 为什么必须提到外层:官方 SPA 重渲染时会整片替换 body 子树,把这两个节点一起冲掉;
1211
+ 留住引用才能在下面的「存在性看门狗」里把**同一个节点**补回去(节点不变 → 挂在它上面的
1212
+ click 处理、CSS 类、aria 属性全都原样保留,不会出现"补回来点不动"的假按钮)。 */
1213
+ let maHamburger = null, maScrim = null;
1214
+
1215
+ /* 节点是否已经脱离文档。判不出来时一律当作"还在"—— 宁可不补,也绝不重复插入。 */
1216
+ const maDetached = (el) => {
1217
+ if (!el) return false;
1218
+ try { if (typeof el.isConnected === "boolean") return !el.isConnected; } catch (eConn) { /* 继续退化 */ }
1219
+ try {
1220
+ const b = document.body;
1221
+ if (b && typeof b.contains === "function") return !b.contains(el);
1222
+ } catch (eHas) { /* 继续退化 */ }
1223
+ return false;
1224
+ };
1225
+
1226
+ /* —— 存在性看门狗:「建好了」不等于「一直都在」----------------------------------
1227
+ done=true 只保证**曾经**建出来过。官方在路由/会话切换时会重建 DOM 子树,我们的汉堡按钮
1228
+ 与遮罩会跟着消失 —— 用户看到的就是"抽屉按钮用着用着又没了"。
1229
+ 这里按**引用**补回(不是重建),只在窄屏做(宽屏本来就不需要抽屉入口)。
1230
+ 幂等:节点还在文档里 → 什么都不做;boot 还没成功(引用为 null) → 同样什么都不做。 */
1231
+ const ensureDrawerChrome = () => {
1232
+ try {
1233
+ if (!NARROW() || !document.body) return;
1234
+ if (maDetached(maScrim)) document.body.appendChild(maScrim);
1235
+ if (maDetached(maHamburger)) document.body.appendChild(maHamburger);
1236
+ } catch (eChrome) { /* 补不回去也不能影响抽屉开合本身 */ }
1237
+ };
1238
+
1099
1239
  let done = false;
1100
1240
  const boot = () => {
1101
1241
  if (!HOSTISH()) return;
@@ -1228,6 +1368,7 @@ const SCRIPT = `(() => {
1228
1368
  const scrim = document.createElement("div");
1229
1369
  scrim.className = "dsh-ma-scrim";
1230
1370
  document.body.appendChild(scrim);
1371
+ maScrim = scrim; // 供「存在性看门狗」在被官方冲掉后补回
1231
1372
  scrim.addEventListener("click", (e) => {
1232
1373
  e.stopPropagation();
1233
1374
  userWantsOpen = false; // 用户明确要关(遮罩的作用就是关抽屉)
@@ -1245,6 +1386,7 @@ const SCRIPT = `(() => {
1245
1386
  hamburger.setAttribute("aria-label", "打开菜单");
1246
1387
  hamburger.innerHTML = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" aria-hidden="true"><path d="M4 6h16M4 12h16M4 18h10"/></svg>';
1247
1388
  document.body.appendChild(hamburger);
1389
+ maHamburger = hamburger; // 供「存在性看门狗」在被官方冲掉后补回
1248
1390
  hamburger.addEventListener("click", (e) => {
1249
1391
  e.stopPropagation(); e.preventDefault();
1250
1392
  const nowOpen = document.documentElement.classList.contains("dsh-ma-sidebar-open");
@@ -1516,10 +1658,82 @@ const SCRIPT = `(() => {
1516
1658
  };
1517
1659
 
1518
1660
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot); else boot();
1519
- /* 官方模块系统异步挂载 UI,晚一点再补几次(幂等,done 守卫);同时等鲸鱼/设置弹层就位 */
1520
- [700, 1600, 3200, 7000, 12000].forEach((ms) =>
1521
- setTimeout(() => { try { boot(); whaleHookInit(); watchSettings(); } catch (e) { /* 幂等重试 */ } }, ms)
1522
- );
1661
+
1662
+ /* ================= 执行时机:无限期等待官方 DOM 就绪 =================
1663
+ 用户实测原话(2026-09-2x):「在网络比较慢的情况下,左边的抽屉按钮有时候出不来。
1664
+ 甭管网络有多慢,都要让那个抽屉能加载出来。」
1665
+ ⚠️ 旧实现是**一组写死的固定重试**([700, 1600, 3200, 7000, 12000]ms),而汉堡按钮的创建
1666
+ 排在 boot() 里 "if (!frame) return;" 那一行之后 —— 官方 SPA bundle 有 13.4MB(实测未压缩),
1667
+ 免费档被中继限速到 128KB/s 时冷启动要 1-2 分钟,官方 frame 在 12 秒内根本没出现:
1668
+ 5 次重试全部在那一行返回 → done 永远为 false → 汉堡按钮**永远**不创建
1669
+ → 用户看到"左边抽屉按钮出不来"。任何固定窗口都只是把这个阈值往后挪,治不了根。
1670
+ 现在改成「事件驱动 + 低频兜底」的**无限期**等待,只要抽屉入口还没建好就一直试:
1671
+ · MutationObserver(document/subtree):官方 frame 一挂上就立刻跟上(网络快时零延迟);
1672
+ · setInterval(1000ms):兜底 + 存在性看门狗 —— observer 不可用/被绕过时照样收敛,
1673
+ 也负责在 done 之后发现官方重渲染冲掉了我们的节点并补回。
1674
+ 两条路都只是"再调一次 pump()",pump 内部**全部幂等**(done / fabDone / whaleGuardsOn /
1675
+ settingsWatchOn / drawerAutoCloseOn 等守卫都在),重复调用不会产生任何副作用,
1676
+ 也不改变"执行什么"——开合、遮罩不变量、sync()、isDrawer() 判定一行未动。 */
1677
+ let maTorn = false, maInterval = 0, maObserver = null, maRafPending = false;
1678
+ /* 廉价的"boot() 还有事可做吗"闸门(只读两个现成的布尔标志,不做任何 DOM 操作):
1679
+ · fab 还没建出来(fabDone=false) → 要跑;
1680
+ · 抽屉那段还没建好(done=false)且当前是窄屏 → 要跑(旋转/缩放回窄屏也能补建)。
1681
+ 两者都不成立 → boot() 里已无事可做,**绝不能**再跑:boot() 第一行 HOSTISH() 会把
1682
+ documentElement.outerHTML 整个序列化一遍(最长 200KB),而官方流式输出时每帧都有 DOM
1683
+ 变更 —— 没有这道闸门就会变成每秒几十次全量序列化(旧实现只跑 5 次,不会有这个问题)。 */
1684
+ const bootUseful = () => !fabDone || (!done && NARROW());
1685
+ const pump = () => {
1686
+ if (maTorn) return;
1687
+ if (bootUseful()) { try { boot(); } catch (eBoot) { /* 幂等重试 */ } }
1688
+ try { ensureDrawerChrome(); } catch (eChrome2) { /* 忽略 */ }
1689
+ if (!whaleGuardsOn || !settingsWatchOn) {
1690
+ try { whaleHookInit(); watchSettings(); } catch (eHook) { /* 两者内部都自带一次性守卫 */ }
1691
+ }
1692
+ };
1693
+ /* 节流:一次 DOM 变更往往产生几十条记录,逐条 boot() 就是忙轮询。
1694
+ 统一合并成"本帧最多跑一次"(有 rAF 用 rAF,没有就退化成 0ms 宏任务) —— 天然去重。 */
1695
+ const schedulePump = () => {
1696
+ if (maTorn || maRafPending) return;
1697
+ maRafPending = true;
1698
+ const run = () => { maRafPending = false; pump(); };
1699
+ try { if (typeof requestAnimationFrame === "function") { requestAnimationFrame(run); return; } } catch (eRaf) { /* 退化 */ }
1700
+ setTimeout(run, 0);
1701
+ };
1702
+ /* 挂上"叫醒"的两条路。做成可重入(先清旧的再建新的),这样 bfcache 恢复后能重新武装。 */
1703
+ const maArm = () => {
1704
+ maTorn = false;
1705
+ maRafPending = false; // 冻结时若有一帧没跑到,不清掉就会永远挡住后续调度
1706
+ try { if (maObserver) maObserver.disconnect(); } catch (eA1) { /* 忽略 */ }
1707
+ maObserver = null;
1708
+ try { if (maInterval) clearInterval(maInterval); } catch (eA2) { /* 忽略 */ }
1709
+ maInterval = 0;
1710
+ try {
1711
+ if (typeof MutationObserver === "function" && document.documentElement) {
1712
+ maObserver = new MutationObserver(schedulePump);
1713
+ /* 只观察 childList+subtree:节点被官方换掉/新增才叫醒我们。
1714
+ ⚠️ 刻意**不**观察 attributes —— 我们自己的 sync() 就会不停改 class,那会变成自激循环。 */
1715
+ maObserver.observe(document.documentElement, { childList: true, subtree: true });
1716
+ }
1717
+ } catch (eObs) { maObserver = null; /* 退化:只靠下面的兜底表 */ }
1718
+ try { maInterval = setInterval(pump, 1000); } catch (eInt) { maInterval = 0; }
1719
+ };
1720
+ maArm();
1721
+ /* 清理:页面卸载时断开观察者与兜底表(bfcache/长驻页面都不留悬挂回调)。
1722
+ pagehide 覆盖 bfcache 场景,unload 兜底更老的浏览器。 */
1723
+ const maTeardown = () => {
1724
+ maTorn = true;
1725
+ try { if (maObserver) maObserver.disconnect(); } catch (eD1) { /* 忽略 */ }
1726
+ maObserver = null;
1727
+ try { if (maInterval) clearInterval(maInterval); } catch (eD2) { /* 忽略 */ }
1728
+ maInterval = 0;
1729
+ };
1730
+ try { window.addEventListener("pagehide", maTeardown); } catch (ePh) { /* 忽略 */ }
1731
+ try { window.addEventListener("unload", maTeardown); } catch (eUl) { /* 忽略 */ }
1732
+ /* 手机上"切到别的 App 再切回来"走的常是 bfcache:pagehide(persisted=true) → pageshow(persisted=true)。
1733
+ DOM 原样保留但计时器/观察者已断 —— 这里重新武装,否则回到页面后看门狗就永久失灵了。 */
1734
+ try {
1735
+ window.addEventListener("pageshow", (ev) => { try { if (ev && ev.persisted) maArm(); } catch (ePs) { /* 忽略 */ } });
1736
+ } catch (ePs2) { /* 忽略 */ }
1523
1737
  } catch (e) { if (window.console) console.warn("[dsh-mobile-adapter]", e && e.message); }
1524
1738
  })();`;
1525
1739
 
@@ -0,0 +1,292 @@
1
+ /**
2
+ * 上游(dsh web)地址发现 —— **单一实现**,watcher(dsh-setup.mjs)与 bridge(dsh-bridge.mjs)共用。
3
+ *
4
+ * ## 为什么需要它
5
+ *
6
+ * 桥接链路的两端(watcher 的存活探测、bridge 的转发目标)原本把上游写死
7
+ * `http://127.0.0.1:3080`(独立 `dsh web` 的默认端口)。但真实世界里端口是会变的:
8
+ *
9
+ * · `dsh web --port 8090` / profile 里配了 port / `--port 0` 让系统分配空闲端口;
10
+ * · **DSH Desktop**(Electron 壳 `dsh-plugin-desktop`)默认监听 **43120**,且被占用时按 +1 递增;
11
+ * · `dsh web` 重启后端口可能不同。
12
+ *
13
+ * 2026-09-23 用户实测(DSH Desktop 2.0.4 + 插件 0.6.10):上游在 43120,而 watcher 探 3080 →
14
+ * **永远探不到 → bridge 永远不被派生 → 面板永久停在「正在启动 Bridge…」**,设备从未登记。
15
+ * 这不是"某个用户环境特殊",而是**所有改了端口的用户**都会踩的同一类问题,所以要有通用发现。
16
+ *
17
+ * ## 发现顺序(先便宜后昂贵,每一步都做**身份校验**)
18
+ *
19
+ * 1. `DSH_BRIDGE_UPSTREAM`(显式覆盖,部署/排障用)—— 唯一不做探测就采信的来源;
20
+ * 2. `<relayDir>/.dsh-upstream`(**插件半**在宿主进程里用 `ctx.webServer.port` 落盘,最权威);
21
+ * 3. `DSH_WEB_URL` 的端口;
22
+ * 4. **实测端口**:本进程的祖先进程 / 本机 dsh 进程正在 LISTEN 的端口(lsof / netstat);
23
+ * 5. 静态候选:3080 + DSH Desktop 的 43120 及其递增区间。
24
+ *
25
+ * ⚠️ 第 4、5 步必须**校验身份**:43120 之类的端口可能被别的本地程序占用,
26
+ * 把 bridge 接到一个陌生人身上既不可用、也可能泄露数据。判据见 `looksLikeDshWeb`。
27
+ *
28
+ * ⚠️ 探测全部**并行**且有总预算:本地端口连接被拒是瞬时的,只有"端口在听但不回包"才会等到超时,
29
+ * 串行探 12 个候选最坏要十几秒,会让 watcher 的轮询卡住。
30
+ */
31
+
32
+ import fs from "node:fs";
33
+ import path from "node:path";
34
+ import { execFileSync } from "node:child_process";
35
+
36
+ /** 插件半落盘的上游地址文件名(与 packages/dsh-remote-web/lib/index.js 的常量同名同义)。 */
37
+ export const UPSTREAM_FILE = ".dsh-upstream";
38
+ /** 独立 `dsh web` 的默认端口(历史行为,最后的兜底)。 */
39
+ export const FALLBACK_UPSTREAM = "http://127.0.0.1:3080";
40
+ /** DSH Desktop(Electron 壳)的默认 Web 端口;被占用时它按 +1 递增,所以要扫一段区间。 */
41
+ export const DESKTOP_DEFAULT_PORT = 43120;
42
+ /** Desktop 端口区间扫多少个(43120..43120+11)。 */
43
+ export const DESKTOP_PORT_SCAN = 12;
44
+ /** 单个候选的探测超时(本地回环,超过它基本就是"在听但不回包")。 */
45
+ const PROBE_TIMEOUT_MS = 900;
46
+
47
+ /** 规范化:去尾斜杠;非 http(s) 一律丢弃(返回空串)。 */
48
+ export function normalizeUpstream(value) {
49
+ const raw = String(value ?? "").trim();
50
+ if (!raw) return "";
51
+ if (!/^https?:\/\/[^\s]+$/i.test(raw)) return "";
52
+ return raw.replace(/\/+$/, "");
53
+ }
54
+
55
+ /** 从字符串里取端口(拿不到返回 0)。 */
56
+ function portOf(value) {
57
+ try {
58
+ const n = Number(new URL(String(value)).port);
59
+ return Number.isInteger(n) && n > 0 ? n : 0;
60
+ } catch {
61
+ return 0;
62
+ }
63
+ }
64
+
65
+ /** 1) 显式环境变量。 */
66
+ export function upstreamFromEnv(env = process.env) {
67
+ return normalizeUpstream(env.DSH_BRIDGE_UPSTREAM);
68
+ }
69
+
70
+ /** 2) 插件半落盘的端口文件(插件不在场/首次安装时可能没有)。 */
71
+ export function upstreamFromFile(relayDir) {
72
+ if (!relayDir) return "";
73
+ try {
74
+ return normalizeUpstream(fs.readFileSync(path.join(relayDir, UPSTREAM_FILE), "utf8"));
75
+ } catch {
76
+ return "";
77
+ }
78
+ }
79
+
80
+ /** 3) DSH_WEB_URL 的端口(bridge 的 loopback 围栏只认 127.0.0.1,这里也统一回环地址)。 */
81
+ export function upstreamFromDshWebUrl(env = process.env) {
82
+ const raw = String(env.DSH_WEB_URL || "").trim();
83
+ if (!raw) return "";
84
+ const port = portOf(raw);
85
+ return port ? `http://127.0.0.1:${port}` : "";
86
+ }
87
+
88
+ /**
89
+ * 按优先级取出"提示地址"(不做任何网络探测)。
90
+ * @returns {{url: string, source: "env"|"file"|"dsh_web_url"|""}}
91
+ */
92
+ export function resolveUpstreamHint({ relayDir = "", env = process.env } = {}) {
93
+ const explicit = upstreamFromEnv(env);
94
+ if (explicit) return { url: explicit, source: "env" };
95
+ const fromFile = upstreamFromFile(relayDir);
96
+ if (fromFile) return { url: fromFile, source: "file" };
97
+ const fromWebUrl = upstreamFromDshWebUrl(env);
98
+ if (fromWebUrl) return { url: fromWebUrl, source: "dsh_web_url" };
99
+ return { url: "", source: "" };
100
+ }
101
+
102
+ // ---------- 实测端口(best effort,任何失败都只是少一个候选,绝不影响主流程) ----------
103
+
104
+ function tryExec(cmd, args, timeoutMs = 4000) {
105
+ try {
106
+ return String(execFileSync(cmd, args, { encoding: "utf8", timeout: timeoutMs, stdio: ["ignore", "pipe", "ignore"] }) || "");
107
+ } catch {
108
+ return "";
109
+ }
110
+ }
111
+
112
+ /** 某进程正在 LISTEN 的 TCP 端口。macOS/Linux 用 lsof,Windows 用 netstat -ano。 */
113
+ export function listeningPortsOfPid(pid, platform = process.platform) {
114
+ const n = Number(pid);
115
+ if (!Number.isInteger(n) || n <= 0) return [];
116
+ const ports = new Set();
117
+ if (platform === "win32") {
118
+ for (const line of tryExec("netstat", ["-ano"], 6000).split(/\r?\n/)) {
119
+ if (!/LISTENING/i.test(line)) continue;
120
+ const cols = line.trim().split(/\s+/);
121
+ if (cols.length < 5) continue;
122
+ if (Number(cols[cols.length - 1]) !== n) continue;
123
+ const m = /:(\d+)$/.exec(cols[1] || "");
124
+ if (m) ports.add(Number(m[1]));
125
+ }
126
+ return [...ports];
127
+ }
128
+ const out = tryExec("lsof", ["-nP", "-a", "-p", String(n), "-iTCP", "-sTCP:LISTEN"], 5000);
129
+ for (const line of out.split("\n")) {
130
+ const m = /:(\d+)\s*\(LISTEN\)/.exec(line);
131
+ if (m) ports.add(Number(m[1]));
132
+ }
133
+ return [...ports];
134
+ }
135
+
136
+ /** 祖先进程 pid(最多 6 层):被插件/宿主拉起的 watcher、bridge 走这条路能找到宿主。 */
137
+ export function ancestorPids(startPid = process.pid, maxDepth = 6, platform = process.platform) {
138
+ if (platform === "win32") return []; // Windows 无 ps;靠 netstat+pgrep 不可行,交给端口文件与静态候选
139
+ const out = [];
140
+ let pid = Number(startPid);
141
+ for (let i = 0; i < maxDepth; i++) {
142
+ const txt = tryExec("ps", ["-o", "ppid=", "-p", String(pid)], 2000).trim();
143
+ const ppid = Number(txt);
144
+ if (!Number.isInteger(ppid) || ppid <= 1) break;
145
+ out.push(ppid);
146
+ pid = ppid;
147
+ }
148
+ return out;
149
+ }
150
+
151
+ /** 本机 dsh 相关进程(pgrep)—— Desktop 壳/独立 dsh web 都可能命中。 */
152
+ export function dshProcessPids(platform = process.platform) {
153
+ if (platform === "win32") return [];
154
+ const out = tryExec("pgrep", ["-f", "dsh"], 4000);
155
+ return out
156
+ .split(/\s+/)
157
+ .map((s) => Number(s))
158
+ .filter((n) => Number.isInteger(n) && n > 1 && n !== process.pid);
159
+ }
160
+
161
+ /**
162
+ * 候选列表(已去重,按"可能性"排序),每项带**来源标注**(用于日志与测试断言)。
163
+ * 顺序 = 提示里的端口 → 显式额外端口 → DSH_WEB_URL 的端口 → 祖先/dsh 进程实测监听端口
164
+ * → 3080 → Desktop 默认端口区间。
165
+ * @returns {Array<{port:number, source:string}>}
166
+ */
167
+ export function candidatePorts({ relayDir = "", env = process.env, extraPorts = [], platform = process.platform } = {}) {
168
+ const out = [];
169
+ const seen = new Set();
170
+ const push = (p, source) => {
171
+ const n = Number(p);
172
+ if (!Number.isInteger(n) || n <= 0 || n >= 65536 || seen.has(n)) return;
173
+ seen.add(n);
174
+ out.push({ port: n, source });
175
+ };
176
+ const hint = resolveUpstreamHint({ relayDir, env });
177
+ push(portOf(hint.url), hint.source || "hint");
178
+ for (const p of extraPorts) push(p, "extra");
179
+ push(portOf(upstreamFromDshWebUrl(env)), "dsh_web_url");
180
+ const pids = [...new Set([process.pid, ...ancestorPids(process.pid, 6, platform), ...dshProcessPids(platform)])];
181
+ for (const pid of pids) for (const p of listeningPortsOfPid(pid, platform)) push(p, "process");
182
+ push(3080, "static");
183
+ for (let i = 0; i < DESKTOP_PORT_SCAN; i++) push(DESKTOP_DEFAULT_PORT + i, "static");
184
+ return out;
185
+ }
186
+
187
+ // ---------- 身份校验 ----------
188
+
189
+ /**
190
+ * 这个地址**真的**是 dsh web 吗?
191
+ *
192
+ * 为什么必须有:候选探测会去敲 43120 这类可能被别的程序占用的端口。只看"端口有响应"就把
193
+ * bridge 接上去,用户会得到一个"能连上但不工作"的怪状态,而且等于把这台机器的流量交给陌生服务。
194
+ * 判据取 dsh web 自身的稳定特征(HTML/标题/鉴权文案),任一命中即通过。
195
+ */
196
+ export const DSH_WEB_MARKERS = [
197
+ "__ModuleLoader__",
198
+ "dsh-client-modules",
199
+ "deepseek harness",
200
+ "dsh web authentication required",
201
+ "dsh-remote"
202
+ ];
203
+
204
+ export function looksLikeDshWeb(status, text) {
205
+ const body = String(text || "").toLowerCase();
206
+ if (!body) return false;
207
+ if (status >= 500) return false;
208
+ return DSH_WEB_MARKERS.some((m) => body.includes(m));
209
+ }
210
+
211
+ /**
212
+ * 探测一个候选:GET `/`,带身份校验。
213
+ * @returns {Promise<boolean>}
214
+ */
215
+ export async function probeDshWeb(url, { timeoutMs = PROBE_TIMEOUT_MS, fetchImpl } = {}) {
216
+ const target = normalizeUpstream(url);
217
+ if (!target) return false;
218
+ const doFetch = fetchImpl || globalThis.fetch;
219
+ if (typeof doFetch !== "function") return false;
220
+ try {
221
+ const ac = new AbortController();
222
+ const timer = setTimeout(() => ac.abort(), timeoutMs);
223
+ let res;
224
+ try {
225
+ // redirect: manual —— 不跟随跳转(跳走的多半不是我们要的宿主)
226
+ res = await doFetch(`${target}/`, { signal: ac.signal, redirect: "manual" });
227
+ } finally {
228
+ clearTimeout(timer);
229
+ }
230
+ const status = Number(res && res.status) || 0;
231
+ if (status >= 500) return false;
232
+ // 只读前 8KB 足够命中特征;读流失败按"不是"处理(宁可少一个候选,不可误接)
233
+ let text = "";
234
+ try {
235
+ if (res.body && typeof res.body.getReader === "function") {
236
+ const reader = res.body.getReader();
237
+ const { value } = await reader.read();
238
+ text = value ? Buffer.from(value).toString("utf8") : "";
239
+ try { await reader.cancel(); } catch { /* ignore */ }
240
+ } else if (typeof res.text === "function") {
241
+ text = await res.text();
242
+ }
243
+ } catch { /* 读失败 → text 为空 → 判否 */ }
244
+ return looksLikeDshWeb(status, text.slice(0, 8192));
245
+ } catch {
246
+ return false;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * 发现上游地址(带身份校验)。
252
+ *
253
+ * @param {number[]} [extraPorts] 调用方已知的额外候选(排在静态候选之前;测试与特化部署用)。
254
+ * @returns {Promise<{url: string, source: string, probed: number[], rejected: string[]}>}
255
+ * source: env | file | dsh_web_url | process | static | extra | fallback
256
+ */
257
+ export async function discoverUpstream({
258
+ relayDir = "",
259
+ env = process.env,
260
+ timeoutMs = PROBE_TIMEOUT_MS,
261
+ fetchImpl,
262
+ platform = process.platform,
263
+ extraPorts = [],
264
+ log
265
+ } = {}) {
266
+ const hint = resolveUpstreamHint({ relayDir, env });
267
+ // ① 显式环境变量:部署方说是什么就是什么(不探测,保持既有语义)
268
+ if (hint.source === "env") return { url: hint.url, source: "env", probed: [], rejected: [] };
269
+ // ② 提示地址先验证:文件/DSh_WEB_URL 都可能过期(宿主换端口/换了程序占用)
270
+ if (hint.url && (await probeDshWeb(hint.url, { timeoutMs, fetchImpl }))) {
271
+ return { url: hint.url, source: hint.source, probed: [portOf(hint.url)], rejected: [] };
272
+ }
273
+
274
+ // ③ 候选并行探测(本地端口,拒绝是瞬时的;并行是为了不让 watcher 卡住)
275
+ const hintPort = portOf(hint.url);
276
+ const entries = candidatePorts({ relayDir, env, platform, extraPorts }).filter((e) => e.port !== hintPort);
277
+ const results = await Promise.all(entries.map(async (e) => ({ ...e, ok: await probeDshWeb(`http://127.0.0.1:${e.port}`, { timeoutMs, fetchImpl }) })));
278
+ const hit = results.find((r) => r.ok);
279
+ if (hit) {
280
+ const url = `http://127.0.0.1:${hit.port}`;
281
+ if (typeof log === "function") log(`[upstream] 动态发现上游 ${url}(来源 ${hit.source};提示 ${hint.url || "无"} 不可用)`);
282
+ return { url, source: hit.source, probed: entries.map((e) => e.port), rejected: hint.url ? [hint.url] : [] };
283
+ }
284
+
285
+ // ④ 都没找到:保持历史行为(3080),让上层按"上游没起来"正常重试
286
+ return {
287
+ url: hint.url || FALLBACK_UPSTREAM,
288
+ source: hint.url ? hint.source : "fallback",
289
+ probed: entries.map((e) => e.port),
290
+ rejected: hint.url ? [hint.url] : []
291
+ };
292
+ }