@mrrisega/dsh-remote 0.6.13 → 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.
@@ -76,6 +76,7 @@ import { promisify } from "node:util";
76
76
  import { gzip as gzipCb } from "node:zlib";
77
77
  // 移动端适配层(经隧道访问的官方 dsh web 窄屏注入;DSH_MOBILE_ADAPTER=0 可关闭,默认开启)
78
78
  import { maybeInjectMobileAdapter } from "./mobile-adapter.mjs";
79
+ import { discoverUpstream, resolveUpstreamHint, FALLBACK_UPSTREAM } from "./upstream-discovery.mjs";
79
80
  // 镜像页 E2EE 加密 shim(Phase-4):text/html 注入;DSH_E2EE_SHIM=0 可关闭,叠加 e2ee.enabled 灰度门
80
81
  import { maybeInjectE2eeShim } from "./e2ee-shim.mjs";
81
82
  // E2EE(端到端加密)客户端基建(Phase-2):MK 派生/会话密钥/信封/握手/开关
@@ -114,7 +115,23 @@ const CONFIG_PATH = process.env.DSH_BRIDGE_CONFIG || DEFAULT_CONFIG;
114
115
  // 隧道模式(唯一):bridge 主动 WS 连 relay-router 的 /_bridge
115
116
  const TUNNEL_URL = (process.env.DSH_BRIDGE_TUNNEL_URL || "").replace(/\/+$/, "");
116
117
  const TUNNEL_HEARTBEAT_MS = Math.max(100, Number(process.env.DSH_BRIDGE_HEARTBEAT_MS) || 15_000);
117
- const UPSTREAM = process.env.DSH_BRIDGE_UPSTREAM || "http://127.0.0.1:3080";
118
+ /**
119
+ * 上游 dsh web 的地址。
120
+ *
121
+ * ⚠️ 这里**不能**只信环境变量 + 写死 3080(2026-09-23 两起用户实测):
122
+ * ① `dsh web --port 8090` / `--port 0`(系统分配)→ 3080 没人听;
123
+ * ② **DSH Desktop**(Electron 壳 `dsh-plugin-desktop`)默认 43120,被占用还会 +1。
124
+ * bridge 与 watcher 共用同一份发现实现(`upstream-discovery.mjs`):
125
+ * 显式环境变量 > `<relayDir>/.dsh-upstream`(插件半用 ctx.webServer.port 落盘)> DSH_WEB_URL
126
+ * > **动态发现**(本机 dsh 进程实际监听端口 + Desktop 端口区间,且每个候选都做身份校验)。
127
+ *
128
+ * 用 `let` 是因为:① 发现发生在启动之后(异步);② 上游端口变了要能在**不重启 bridge** 的前提下跟上。
129
+ */
130
+ const RELAY_DIR = path.dirname(CONFIG_PATH);
131
+ let UPSTREAM = (() => {
132
+ const hint = resolveUpstreamHint({ relayDir: RELAY_DIR });
133
+ return hint.url || FALLBACK_UPSTREAM;
134
+ })();
118
135
  // 微信机器人通道总开关:DSH_WECHAT=0 关闭(默认开启)。控制面只 bind 回环,且必须带 bridge_secret。
119
136
  const WECHAT_DISABLED = String(process.env.DSH_WECHAT || "") === "0";
120
137
  // 默认云端服务地址(dsh-remote setup 会显式传入;自建模式无需账号 API)
@@ -385,6 +402,37 @@ const STRIP_RES_HEADERS = new Set([
385
402
  "connection", "keep-alive", "upgrade"
386
403
  ]);
387
404
 
405
+
406
+ /** 上游重新发现的冷却:失败请求可能连成片,不能每个都去 lsof/pgrep + 探端口。 */
407
+ const UPSTREAM_REFRESH_COOLDOWN_MS = 15_000;
408
+ let upstreamRefreshedAt = 0;
409
+ let upstreamRefreshInflight = null;
410
+ /**
411
+ * 重新解析上游地址(带身份校验;显式 DSH_BRIDGE_UPSTREAM 时是恒等操作)。
412
+ * 上游端口变了(Desktop 换端口 / dsh web 重启到别的端口)时,靠它自愈而不必重启 bridge。
413
+ */
414
+ async function refreshUpstream(reason = "") {
415
+ if (upstreamRefreshInflight) return upstreamRefreshInflight;
416
+ const now = Date.now();
417
+ if (now - upstreamRefreshedAt < UPSTREAM_REFRESH_COOLDOWN_MS) return UPSTREAM;
418
+ upstreamRefreshedAt = now;
419
+ upstreamRefreshInflight = (async () => {
420
+ try {
421
+ const found = await discoverUpstream({ relayDir: RELAY_DIR });
422
+ if (found.url && found.url !== UPSTREAM) {
423
+ console.log(`[bridge] 上游地址切换: ${UPSTREAM} → ${found.url}(来源 ${found.source}${reason ? `,${reason}` : ""})`);
424
+ UPSTREAM = found.url;
425
+ }
426
+ return UPSTREAM;
427
+ } catch {
428
+ return UPSTREAM;
429
+ } finally {
430
+ upstreamRefreshInflight = null;
431
+ }
432
+ })();
433
+ return upstreamRefreshInflight;
434
+ }
435
+
388
436
  console.log(`[bridge] 设备 ${DEVICE_ID} → 隧道 ${TUNNEL_URL}/_bridge`);
389
437
  console.log(`[bridge] 上游 ${UPSTREAM}`);
390
438
 
@@ -816,6 +864,9 @@ export async function handleHttpFrame(dchOrSend, frame) {
816
864
  send(reply);
817
865
  console.log(`[bridge] ${method} ${path} → ${reply.status} (${Date.now() - t0}ms, ${(reply.body.length * 3 / 4 / 1024).toFixed(0)}KB)`);
818
866
  } catch (e) {
867
+ // 上游不可达是「端口可能变了」的最强信号(Desktop 换端口 / dsh web 重启到别的端口):
868
+ // 触发一次带冷却的重新发现,后续请求自动跟上,不必重启 bridge。
869
+ void refreshUpstream("上游请求失败");
819
870
  console.log(`[bridge] ${method} ${path} 上游错误: ${e.message}`);
820
871
  send({ id, type: "http", status: 502, headers: { "content-type": "application/json" }, body: Buffer.from(JSON.stringify({ error: String(e.message || e) })).toString("base64"), bodyBase64: true });
821
872
  }
@@ -877,6 +928,7 @@ export async function handleLegacyFrame(dchOrSend, frame) {
877
928
  send({ id, status: reply.status, headers: reply.headers, body: text });
878
929
  console.log(`[bridge] legacy ${method} ${path} → ${reply.status} (${Date.now() - t0}ms)`);
879
930
  } catch (e) {
931
+ void refreshUpstream("上游请求失败(legacy)");
880
932
  console.log(`[bridge] legacy ${method} ${path} 上游错误: ${e.message}`);
881
933
  send({ id, status: 502, headers: {}, body: JSON.stringify({ error: String(e.message || e) }) });
882
934
  }
@@ -1469,6 +1521,9 @@ function startWeChat() {
1469
1521
  const cfg = loadLocalConfig();
1470
1522
  wechatRuntime = createWeChatRuntime({
1471
1523
  relayDir,
1524
+ // 上游地址在 runTunnel() 开头已完成动态发现(见 refreshUpstream),所以这里拿到的是真实端口。
1525
+ // ⚠️ 这是**取值**而非引用:运行中若上游端口又变了(自愈重发现),微信通道要等 bridge 重启才跟上;
1526
+ // 隧道转发那一侧不受影响(它每次都读最新的 UPSTREAM)。
1472
1527
  upstream: UPSTREAM,
1473
1528
  cookieOf: harnessCookieOf,
1474
1529
  secret: process.env.DSH_BRIDGE_SECRET || (typeof cfg.bridge_secret === "string" ? cfg.bridge_secret : ""),
@@ -1514,6 +1569,10 @@ function redactText(e) {
1514
1569
  }
1515
1570
 
1516
1571
  async function runTunnel() {
1572
+ // 先动态确定上游再连隧道:上游端口不是 3080 时(DSH Desktop 默认 43120)这一步是关键 ——
1573
+ // 否则 bridge 会连上中继、手机也能打开页面,但每个请求都打到一个没人听的端口。
1574
+ await refreshUpstream("启动");
1575
+ console.log(`[bridge] 上游地址已确定: ${UPSTREAM}`);
1517
1576
  const token = await resolveToken();
1518
1577
  if (!token) {
1519
1578
  console.error("[bridge] 隧道模式需要账号认证:请设 DSH_BRIDGE_TOKEN,或 DSH_BRIDGE_PHONE+DSH_BRIDGE_PASSWORD");
@@ -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(不可用)镜像 →
@@ -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
+ }
@@ -29,6 +29,7 @@ import path from "node:path";
29
29
  import { spawn, spawnSync, execSync } from "node:child_process";
30
30
  import { fileURLToPath } from "node:url";
31
31
  import { childStopped, stopChildGracefully } from "./clients/dsh-remote/src/lifecycle.mjs";
32
+ import { discoverUpstream, resolveUpstreamHint, FALLBACK_UPSTREAM } from "./clients/dsh-remote/upstream-discovery.mjs";
32
33
 
33
34
  const THIS_DIR = path.dirname(fileURLToPath(import.meta.url)); // 本包目录(仓库或 node_modules)
34
35
  const IS_NPM_INSTALL = THIS_DIR.includes(`${path.sep}node_modules${path.sep}`);
@@ -779,14 +780,21 @@ function restartBridgeService() {
779
780
  * 【2026-09-23 用户实测事故】这里原本处处写死 `http://127.0.0.1:3080`:只要用户的 dsh web
780
781
  * 不在默认端口(`dsh web --port 8090`、profile 里配了 port、或 `--port 0` 让系统分配空闲端口),
781
782
  * watcher 的在线探测就**永远**失败 → bridge 永远不启动,而面板只会说「正在启动 Bridge…」。
782
- * 优先级:显式环境变量 > 插件半留下的端口文件 > DSH_WEB_URL > 默认 3080。
783
- * 为什么要有「端口文件」这一层:开机自启(登录任务 / launchd)拉起 watcher 时**没有**任何环境变量,
784
- * 只有插件半知道 dsh web 真实监听在哪个端口,所以它会把地址落盘(见插件 half 的 publishUpstream)。
783
+ * 优先级:显式环境变量 > **运行时动态发现** > 插件半留下的端口文件 > DSH_WEB_URL > 默认 3080。
784
+ *
785
+ * 为什么还要「动态发现」这一层(2026-09-23 第二起实测,DSH Desktop):
786
+ * DSH Desktop(Electron 壳 `dsh-plugin-desktop`)默认把 Web 服务放在 **43120**,被占用还会 +1;
787
+ * 而端口文件要等**插件半**加载后才有。于是「端口文件还没写」或「写的是上一轮的旧端口」时,
788
+ * 光靠文件仍会永久探错端口。发现逻辑(含 DSH 进程实际监听端口 + Desktop 端口区间 + 身份校验)
789
+ * 统一在 clients/dsh-remote/upstream-discovery.mjs,watcher 与 bridge 共用同一份实现。
785
790
  */
786
791
  const UPSTREAM_FILE = ".dsh-upstream";
792
+ /** 运行时动态发现到的上游(优于可能过期的端口文件;进程内缓存)。 */
793
+ let discoveredUpstream = "";
787
794
  function upstreamUrl() {
788
795
  const explicit = String(process.env.DSH_BRIDGE_UPSTREAM || "").trim();
789
796
  if (explicit) return explicit.replace(/\/+$/, "");
797
+ if (discoveredUpstream) return discoveredUpstream;
790
798
  try {
791
799
  const fromFile = String(fs.readFileSync(path.join(CONFIG_DIR, UPSTREAM_FILE), "utf8")).trim();
792
800
  if (/^https?:\/\/[^\s]+$/i.test(fromFile)) return fromFile.replace(/\/+$/, "");
@@ -798,28 +806,69 @@ function upstreamUrl() {
798
806
  if (u.port) return `http://127.0.0.1:${u.port}`; // bridge 的 loopback 围栏只认 127.0.0.1
799
807
  } catch { /* 非 URL:忽略 */ }
800
808
  }
801
- return "http://127.0.0.1:3080";
809
+ return FALLBACK_UPSTREAM;
802
810
  }
803
811
  /** 上游端口(诊断/日志用;取不到就回退 3080)。 */
804
812
  function upstreamPort() {
805
813
  try { return Number(new URL(upstreamUrl()).port) || 3080; } catch { return 3080; }
806
814
  }
807
815
 
816
+ /** 发现结果缓存与冷却:避免每轮轮询都去 lsof/pgrep + 逐个端口探测。 */
817
+ let upstreamDiscoveryAt = 0;
818
+ let upstreamDiscoveryInflight = null;
819
+ const UPSTREAM_DISCOVERY_COOLDOWN_MS = 15_000;
820
+
808
821
  /**
809
- * dsh web 是否正在运行(默认 127.0.0.1:3080,端口以 upstreamUrl() 为准)。
810
- * bridge 本身依赖 dsh web 才工作:dsh web 没开时 bridge 起来也会立刻退出,
811
- * 所以「装完当下 bridge 没在跑」是**正常状态**,不能当失败吓用户(见 install 汇总)。
822
+ * 动态发现上游(带身份校验),成功后写入 `discoveredUpstream` 供全局复用。
823
+ * @param {boolean} force 忽略冷却(探测失败后的重试用)
812
824
  */
813
- async function isDshWebUp(timeoutMs = 1200) {
825
+ async function refreshUpstreamDiscovery(force = false) {
826
+ if (upstreamDiscoveryInflight) return upstreamDiscoveryInflight;
827
+ const now = Date.now();
828
+ if (!force && now - upstreamDiscoveryAt < UPSTREAM_DISCOVERY_COOLDOWN_MS) return upstreamUrl();
829
+ upstreamDiscoveryAt = now;
830
+ upstreamDiscoveryInflight = (async () => {
831
+ try {
832
+ const found = await discoverUpstream({ relayDir: CONFIG_DIR, log: (m) => console.log(`[dsh-remote] ${m}`) });
833
+ // 「提示地址验证通过」与「候选命中」都值得记下来;fallback(什么都没找到)不污染现有判断
834
+ if (found.url && found.source !== "fallback") discoveredUpstream = found.url;
835
+ return upstreamUrl();
836
+ } catch {
837
+ return upstreamUrl();
838
+ } finally {
839
+ upstreamDiscoveryInflight = null;
840
+ }
841
+ })();
842
+ return upstreamDiscoveryInflight;
843
+ }
844
+
845
+ /** 上游是否**有响应**(判据刻意宽松:4xx/5xx 也算"端口在听",那种情况问题在别处)。 */
846
+ async function upstreamReachable(url = upstreamUrl(), timeoutMs = 1200) {
814
847
  try {
815
848
  const ac = new AbortController();
816
849
  const timer = setTimeout(() => ac.abort(), timeoutMs);
817
- await fetch(upstreamUrl() + "/", { signal: ac.signal });
850
+ await fetch(url + "/", { signal: ac.signal });
818
851
  clearTimeout(timer);
819
852
  return true;
820
853
  } catch { return false; }
821
854
  }
822
855
 
856
+ /**
857
+ * dsh web 是否正在运行(端口以 upstreamUrl() 为准,**绝不写死 3080**)。
858
+ * bridge 本身依赖 dsh web 才工作:dsh web 没开时 bridge 起来也会立刻退出,
859
+ * 所以「装完当下 bridge 没在跑」是**正常状态**,不能当失败吓用户(见 install 汇总)。
860
+ *
861
+ * 探测失败时会**主动做一次动态发现**再试一次 —— 这一条正是 DSH Desktop 场景的关键:
862
+ * 上游在 43120(Desktop 默认,占用还会 +1),而端口文件可能还没写或写着上一轮的旧端口。
863
+ */
864
+ async function isDshWebUp(timeoutMs = 1200) {
865
+ if (await upstreamReachable(upstreamUrl(), timeoutMs)) return true;
866
+ const before = upstreamUrl();
867
+ const after = await refreshUpstreamDiscovery(true);
868
+ if (after === before) return false;
869
+ return upstreamReachable(after, timeoutMs);
870
+ }
871
+
823
872
  /**
824
873
  * 解析 dsh web profile 目录(安装与插件管理共用同一口径)。
825
874
  */
@@ -1125,14 +1174,13 @@ async function runBridge() {
1125
1174
  /** 限流提示只打一次,避免刷屏。 */
1126
1175
  let warnedRateLimit = false;
1127
1176
 
1128
- // watcher:检测 dsh web 是否存活(端口以 upstreamUrl() 为准,绝不写死 3080),存活才启动 bridge
1129
- const checkUpstream = () => new Promise((resolve) => {
1130
- const t = setTimeout(() => resolve(false), 2000);
1131
- fetch(upstreamUrl() + "/")
1132
- .then(() => { clearTimeout(t); resolve(true); })
1133
- .catch(() => { clearTimeout(t); resolve(false); });
1134
- });
1177
+ // watcher:检测 dsh web 是否存活(端口动态解析,绝不写死 3080),存活才启动 bridge。
1178
+ // 走 isDshWebUp():探测失败会自动做一次动态发现(DSH Desktop 的 43120 / 自定义端口都靠它)。
1179
+ const checkUpstream = () => isDshWebUp(2000);
1135
1180
 
1181
+ // 先做一次动态发现再打印/派生:否则日志会长期写着错误的端口(用户实测就卡在
1182
+ // 「等待 dsh web(127.0.0.1:3080)启动...」而真实上游在 43120)。
1183
+ await refreshUpstreamDiscovery(true);
1136
1184
  console.log(`[dsh-remote] 等待 dsh web(${upstreamUrl()})启动...`);
1137
1185
  let bridgeProc = null;
1138
1186
  let starting = false;