@andy.ian/dsh-homing 2.2.2 → 2.3.1

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/index.js CHANGED
@@ -54,6 +54,7 @@ import { createLocalAppRegistry, matchAppPath, probeAppPort } from './lib/local-
54
54
  import { proxyLocalAppHttp, proxyLocalAppUpgrade } from './lib/app-proxy.mjs';
55
55
  import { renderLocalAppsPage } from './lib/local-apps-page.mjs';
56
56
  import { MOBILE_CSS, MOBILE_JS } from './lib/mobile-patch.mjs';
57
+ import { formatAge } from './lib/format-age.mjs';
57
58
 
58
59
  export const name = 'dsh-homing';
59
60
 
@@ -106,7 +107,8 @@ const DEFAULT_CONFIG = {
106
107
  };
107
108
 
108
109
  function normalizeConfig(raw) {
109
- const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) };
110
+ // 所有调用点都传对象(apply 里传 {...rawConfig, ...readSettings()}),raw 不可能为空,去掉防御兜底
111
+ const config = { ...DEFAULT_CONFIG, ...raw };
110
112
  config.sshPort = Number(config.sshPort) || 22;
111
113
  config.listenPort = Number(config.listenPort) || 8787;
112
114
  // 服务器侧端口与 nginx 的 proxy_pass 必须一致,默认固定 8787;本机 listenPort 可以单独改
@@ -349,8 +351,8 @@ function createCookieMinter(credentials, getUpstreamPort) {
349
351
  const hit = ttlByAuthority.get(authority);
350
352
  // 一小时内复用;DSH 上限变化只会发生在它自己重启之后,那时 authority 也会变
351
353
  if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.ttlMs;
354
+ // 代理请求进入 mint 前已通过 getUpstreamPort() 的非空检查(handler 里 !port 会先回 503),port 必为真
352
355
  const port = getUpstreamPort();
353
- if (!port) return COOKIE_TTL_FALLBACK_MS;
354
356
  for (const ttlMs of COOKIE_TTL_CANDIDATES_MS) {
355
357
  const accepted = await probeCookieAccepted({
356
358
  port,
@@ -379,7 +381,54 @@ function createCookieMinter(credentials, getUpstreamPort) {
379
381
  * 以便用真实 DOM 桩做行为测试(见 test/unit.mobile-patch.test.mjs)。
380
382
  * ------------------------------------------------------------------ */
381
383
 
382
- const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
384
+ /**
385
+ * 注入脚本的版本号:用文件修改时间,同步后必然变化 → 浏览器一定取新脚本。
386
+ * (2026-11-15:之前用插件版本号,插件没升版本时手机会一直用缓存的旧脚本,
387
+ * 导致"部署了新诊断代码但手机跑的仍是旧的"。)
388
+ */
389
+ function injectedScriptVersion(relative) {
390
+ try {
391
+ return String(Math.floor(fs.statSync(new URL(relative, import.meta.url)).mtimeMs));
392
+ } catch {
393
+ return PLUGIN_VERSION;
394
+ }
395
+ }
396
+
397
+ const AUTH_GUARD_VER = injectedScriptVersion('./lib/auth-guard.js');
398
+ const CLIENT_REPORT_VER = injectedScriptVersion('./lib/client-report.js');
399
+ const IDB_FALLBACK_VER = injectedScriptVersion('./lib/idb-fallback.js');
400
+
401
+ /**
402
+ * import map:把 `plugins/...` 这类**不带前导斜杠**的说明符映射到绝对路径。
403
+ *
404
+ * 为什么必须加(2026-11-15 定位到的根因):
405
+ * DSH 前端按需加载插件时,会 `import('plugins/??pkg/client.js&rev=...')`。
406
+ * 按 ES 模块规范,说明符必须以 `/`、`./`、`../` 开头,否则被视为「裸包名」,
407
+ * 浏览器直接抛 `Failed to resolve module specifier`。
408
+ * Chrome 里 DSH 自己的解析器能兜住;鸿蒙 ArkWeb 上兜不住,
409
+ * 于是 90 个插件里只有 HTML 预加载的 3 个注册成功,
410
+ * 界面永远停在 "HARNESS / Loading plugins…",首页会话列表也永远不出现。
411
+ *
412
+ * ⚠️ 位置极其重要:import map 必须在**任何 module 加载之前**出现,
413
+ * 否则浏览器会忽略它(并只打一条 console 警告)。
414
+ * 实测 DSH 的 HTML 里 `<script type="module">` 出现在 head 靠后位置
415
+ * (约 offset 47643),如果按常规插到 `</head>` 前就太晚了——
416
+ * 这正是第一版修复没生效的原因。所以必须插在 `<head>` 之后第一件事。
417
+ */
418
+ const IMPORT_MAP = '<script type="importmap">'
419
+ + JSON.stringify({ imports: { 'plugins/': '/plugins/', 'assets/': '/assets/' } })
420
+ + '</script>';
421
+
422
+ // 注入分三段(位置很重要):
423
+ // IMPORT_MAP —— 紧跟 <head> 之后:import map 必须早于任何 module 加载,否则被忽略
424
+ // BASE —— `</head>` 之前:登录守卫 + 错误上报(永远注入)
425
+ // MOBILE —— `</head>` 之前:mobile.css + mobile.js(只在未关闭样式时注入)
426
+ const BASE_INJECTION = '<script src="/dsh_homing/idb-fallback.js?v=' + IDB_FALLBACK_VER + '"></script>'
427
+ + '<script src="/dsh_homing/auth-guard.js?v=' + AUTH_GUARD_VER + '"></script>'
428
+ + '<script src="/dsh_homing/client-report.js?v=' + CLIENT_REPORT_VER + '"></script>';
429
+
430
+ const MOBILE_INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css">'
431
+ + '<script defer src="/dsh_homing/mobile.js"></script>';
383
432
 
384
433
  // 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
385
434
  // 调试页上一键即可设置,页面坏了也点得到。
@@ -498,7 +547,8 @@ function startRestartDaemonDetached() {
498
547
  return false;
499
548
  }
500
549
  const child = spawn(findNodeRuntime(), [cli, 'start'], { detached: true, stdio: 'ignore', windowsHide: true });
501
- child.on('error', (error) => { try { appendAudit(dataDir(), 'restart-daemon-spawn-error', { error: String(error?.message ?? error).slice(0, 200) }); } catch { /* 忽略 */ } });
550
+ // appendAudit 内部已吞掉所有写盘异常,这里不必再包 try/catch
551
+ child.on('error', (error) => { appendAudit(dataDir(), 'restart-daemon-spawn-error', { error: String(error?.message ?? error).slice(0, 200) }); });
502
552
  child.unref();
503
553
  return true;
504
554
  } catch {
@@ -511,9 +561,8 @@ const restartDaemonWatchdog = createRestartDaemonWatchdog({
511
561
  service: restartService,
512
562
  pluginRoot: path.dirname(fileURLToPath(import.meta.url)),
513
563
  dshHome: process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'),
514
- audit: (event, extra) => {
515
- try { appendAudit(dataDir(), event, extra ?? {}); } catch { /* 忽略 */ }
516
- },
564
+ // watchdog 只会传对象({pid}/{stopped}/{}),appendAudit 内部也自带 try/catch:extra ?? {} 与 catch 都不可达
565
+ audit: (event, extra) => appendAudit(dataDir(), event, extra),
517
566
  });
518
567
  void restartDaemonWatchdog;
519
568
 
@@ -521,12 +570,12 @@ void restartDaemonWatchdog;
521
570
  const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
522
571
  + `<script src="/dsh_homing/restart.js"></script>`;
523
572
 
524
- function renderRestartPage({ status, sessions, message, confirmForce, portState }) {
573
+ function renderRestartPage({ status, sessions, message, confirmForce, portState, daemonVersion, staleDaemon }) {
525
574
  const running = status?.running ?? false
526
575
  const paused = status?.paused ?? false
527
576
  const left = status?.pausedSecondsLeft ?? 0
528
577
  const busy = sessions.length > 0
529
- const busyItems = sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · ' + s.age + ' 秒前' + (s.cwd ? ' · ' + escapeHtml(s.cwd) : '') + '</li>').join('')
578
+ const busyItems = sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · 最后活动 ' + formatAge(s.age) + (s.cwd ? ' · ' + escapeHtml(s.cwd) : '') + '</li>').join('')
530
579
 
531
580
  const confirmBlock = confirmForce
532
581
  ? '<div class="card warn"><div class="line"><span class="k">确认强制重启</span><span class="v">' + sessions.length + ' 个会话运行中</span></div>'
@@ -560,7 +609,8 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
560
609
  })()
561
610
 
562
611
  const policy = restartPolicy.status()
563
- const cfg = policy?.config ?? {}
612
+ // runner 的 status() 恒返回对象且带 config 对象:可选链与 ?? {} 不可达
613
+ const cfg = policy.config
564
614
  const nav = topNav()
565
615
 
566
616
  return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
@@ -594,9 +644,17 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
594
644
  + (message ? '<div class="msg" id="restart-msg">' + escapeHtml(message) + '</div>' : '')
595
645
  + confirmBlock
596
646
  + '<div class="card">'
597
- + '<div class="line"><span class="k">守护进程</span><span class="v" id="sup-state">' + (running ? ('运行中 · 重启 ' + (status?.daemon?.restarts ?? 0) + ' 次' + (paused ? (' · 暂停剩 ' + left + ' 秒') : '') + (policy?.active ? (' · 排队已等 ' + (policy.waitedSeconds ?? 0) + ' 秒') : '')) : '未运行') + '</span></div>'
647
+ // policy 来自 restartPolicy.status(),waitedSeconds 恒为数字(非排队时为 0),?? 0 不可达
648
+ + '<div class="line"><span class="k">守护进程</span><span class="v" id="sup-state">' + (running ? ('运行中 · 重启 ' + (status?.daemon?.restarts ?? 0) + ' 次' + (paused ? (' · 暂停剩 ' + left + ' 秒') : '') + (policy?.active ? (' · 排队已等 ' + policy.waitedSeconds + ' 秒') : '')) : '未运行') + '</span></div>'
649
+ + '<div class="line"><span class="k">守护进程版本</span><span class="v" id="daemon-version">' + escapeHtml(staleDaemon ? (String(daemonVersion) + ' · 与插件 ' + PLUGIN_VERSION + ' 不一致') : (daemonVersion ?? '未知')) + '</span></div>'
650
+ + (staleDaemon
651
+ ? '<div class="card warn" style="margin-top:8px"><div class="line"><span class="k">守护进程在跑旧代码</span><span class="v">需重启</span></div>'
652
+ + '<p class="sub" style="margin:4px 0 0">守护进程是常驻进程,插件更新后它仍在执行启动时的旧代码(重启/拉起逻辑不会自动更新)。'
653
+ + '用下面的「重启守护进程」加载新代码;它只重启自己,不会影响正在运行的会话。</p></div>'
654
+ : '')
598
655
  + '<div class="line"><span class="k">重启队列</span><span class="v" id="queue-state">' + (policy?.active ? ('排队中 · ' + escapeHtml(policy.reason || '等待空闲')) : '未排队') + '</span></div>'
599
- + '<div class="line"><span class="k">当前策略</span><span class="v" id="policy-state">' + escapeHtml((cfg.name || 'default') + ' · 安静 ' + Math.round((cfg.quietMs ?? 0) / 1000) + ' 秒 · 轮询 ' + Math.round((cfg.pollMs ?? 0) / 1000) + ' 秒') + '</span></div>'
656
+ // status().config 的 name 恒为非空字符串、quietMs/pollMs 恒为数字:|| / ?? 兜底不可达
657
+ + '<div class="line"><span class="k">当前策略</span><span class="v" id="policy-state">' + escapeHtml(cfg.name + ' · 安静 ' + Math.round(cfg.quietMs / 1000) + ' 秒 · 轮询 ' + Math.round(cfg.pollMs / 1000) + ' 秒') + '</span></div>'
600
658
  + '<div class="line"><span class="k">繁忙</span><span class="v" id="busy-state">' + (busy ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
601
659
  + '<ul id="busy-list">' + busyItems + '</ul>'
602
660
  + LIVE_SCRIPT
@@ -628,6 +686,25 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
628
686
  + '</body></html>'
629
687
  }
630
688
 
689
+ /**
690
+ * /debug 截图上传的限制表。
691
+ *
692
+ * 为什么要放宽类型:手机(HarmonyOS/Android)相册里选中"原图"时,浏览器给出的
693
+ * dataURL 可能是 heic/heif/gif/bmp,而旧实现只认 png/jpeg/webp,一律 400,
694
+ * 用户看到的就是"上传没反应"。这里按 MIME 映射成扩展名,落盘后仍可下载查看。
695
+ */
696
+ const UPLOAD_LIMIT_BYTES = 12 * 1024 * 1024;
697
+ const UPLOAD_IMAGE_EXT = {
698
+ png: 'png',
699
+ jpeg: 'jpg',
700
+ jpg: 'jpg',
701
+ webp: 'webp',
702
+ gif: 'gif',
703
+ bmp: 'bmp',
704
+ heic: 'heic',
705
+ heif: 'heic',
706
+ };
707
+
631
708
  const DEBUG_HTML = `<!doctype html>
632
709
  <html lang="zh-CN"><head><meta charset="utf-8">
633
710
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -639,6 +716,7 @@ const DEBUG_HTML = `<!doctype html>
639
716
  h1 { font-size: 19px; margin: 6px 0 2px; }
640
717
  h2 { font-size: 14px; margin: 26px 0 8px; color:#9aa4b2; font-weight: 600; }
641
718
  .sub { color:#8b93a1; font-size: 13px; margin: 4px 0 0; }
719
+ .err { color:#ff9b9b; }
642
720
  .card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:14px; margin-top:10px; }
643
721
  .row { display:flex; justify-content:space-between; gap:12px; padding:6px 0; font-size:13px; border-bottom:1px solid #21262f; }
644
722
  .row:last-child { border-bottom:0; }
@@ -693,6 +771,15 @@ const DEBUG_HTML = `<!doctype html>
693
771
  {{shots}}
694
772
  </div>
695
773
 
774
+ <h2>网络自检</h2>
775
+ <div class="card">
776
+ <p class="sub">点一下会依次测:首页 HTML、鉴权状态、入口脚本、RPC 通道(/api/remote.mux)、缓存与 Service Worker。
777
+ 每步都有超时,结果同时回传服务端,所以即使页面显示不全也能在电脑端查审计。</p>
778
+ <button id="netdiag-run" type="button">开始检测</button>
779
+ <button id="netdiag-copy" type="button" class="ghost">复制结果</button>
780
+ <pre id="netdiag-out">(还没开始)</pre>
781
+ </div>
782
+
696
783
  <h2>诊断</h2>
697
784
  <div class="card">
698
785
  <div class="row"><span class="k">样式文件</span><span class="v">{{cssInfo}}</span></div>
@@ -709,45 +796,8 @@ const DEBUG_HTML = `<!doctype html>
709
796
  <a class="btn ghost" href="/logout">退出登录</a>
710
797
  </div>
711
798
  </div>
712
- <script>
713
- (() => {
714
- const input = document.getElementById('file')
715
- const button = document.getElementById('send')
716
- const result = document.getElementById('result')
717
- if (!input || !button || !result) return
718
- button.addEventListener('click', async () => {
719
- const file = input.files && input.files[0]
720
- if (!file) { result.textContent = '先选一张图片。'; return }
721
- if (file.size > 12 * 1024 * 1024) { result.textContent = '图片太大(上限 12MB)。'; return }
722
- result.textContent = '读取中…'
723
- const dataUrl = await new Promise((resolve, reject) => {
724
- const reader = new FileReader()
725
- reader.onload = () => resolve(String(reader.result))
726
- reader.onerror = () => reject(new Error('读取失败'))
727
- reader.readAsDataURL(file)
728
- }).catch((error) => { result.textContent = error.message; return null })
729
- if (!dataUrl) return
730
- result.textContent = '上传中…'
731
- try {
732
- const res = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
733
- method: 'POST',
734
- headers: { 'content-type': 'application/json' },
735
- body: JSON.stringify({ name: file.name, dataUrl }),
736
- })
737
- const text = await res.text()
738
- if (!res.ok) { result.textContent = '失败:' + text.slice(0, 200); return }
739
- const data = JSON.parse(text)
740
- result.innerHTML = '已保存:<code>' + data.file + '</code>'
741
- const img = document.createElement('img')
742
- img.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
743
- img.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
744
- document.querySelector('.shots')?.appendChild(img) ?? result.appendChild(img)
745
- } catch (error) {
746
- result.textContent = '网络错误:' + error.message
747
- }
748
- })
749
- })()
750
- </script>
799
+ <script src="/dsh_homing/netdiag.js" defer></script>
800
+ <script src="/dsh_homing/debug.js" defer></script>
751
801
  </body></html>
752
802
  `;
753
803
 
@@ -848,14 +898,20 @@ function sessionRunning(dshHomeDir) {
848
898
  async function collectRestartState(dataDir) {
849
899
  const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
850
900
  const status = await restartService.status();
901
+ const health = await restartService.health();
851
902
  const policyStatus = restartPolicy.status();
852
- const config = policyStatus?.config ?? null;
903
+ // runner 的 status() 恒返回对象且带 config,可选链与 ?? null 不可达
904
+ const config = policyStatus.config;
905
+ // 守护进程是长驻进程:插件升级后如果没重启它,它跑的还是旧代码(2026-11-14 事故根因)。
906
+ const daemonVersion = typeof health?.version === 'string' ? health.version : null;
907
+ const staleDaemon = daemonVersion !== null && daemonVersion !== 'unknown' && daemonVersion !== PLUGIN_VERSION;
853
908
  return {
854
909
  config,
855
910
  policy: {
856
911
  active: policyStatus?.active === true,
857
- reason: policyStatus?.reason ?? '',
858
- waitedSeconds: policyStatus?.waitedSeconds ?? 0,
912
+ // runner 的 status() 保证 reason 是字符串、waitedSeconds 是数字,不需要 ?? 兜底
913
+ reason: policyStatus.reason,
914
+ waitedSeconds: policyStatus.waitedSeconds,
859
915
  busy: policyStatus?.busy === true,
860
916
  },
861
917
  running: status?.running ?? false,
@@ -863,6 +919,8 @@ async function collectRestartState(dataDir) {
863
919
  paused: status?.paused ?? false,
864
920
  pausedSecondsLeft: status?.pausedSecondsLeft ?? 0,
865
921
  busy: sessions.length > 0,
922
+ daemonVersion,
923
+ staleDaemon,
866
924
  sessions: sessions.map((s) => ({ title: s.title || '', cwd: s.cwd || '', age: s.age })),
867
925
  };
868
926
  }
@@ -880,7 +938,8 @@ async function broadcastRestartState(dataDir, extra) {
880
938
  lastPayload = payload;
881
939
  lastPushAt = now;
882
940
  for (const res of [...sseClients]) {
883
- try { res.write((changed ? 'data: ' + payload : ': ping') + '\n\n') } catch { sseClients.delete(res) }
941
+ // ServerResponse.write 只会异步报错、不会同步抛;连接关闭由上面 req.on('close') 清理 sseClients
942
+ res.write((changed ? 'data: ' + payload : ': ping') + '\n\n')
884
943
  }
885
944
  }
886
945
 
@@ -1024,7 +1083,7 @@ function base32Encode(buffer) {
1024
1083
  bits -= 5;
1025
1084
  }
1026
1085
  }
1027
- if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
1086
+ // 两个调用点都是 5 字节的倍数(40/160 bit),bits 恒为 0,无需补尾巴
1028
1087
  return out;
1029
1088
  }
1030
1089
 
@@ -1063,10 +1122,12 @@ const LOGIN_HTML = `<!doctype html>
1063
1122
  <label for="p">密码</label>
1064
1123
  <input id="p" name="password" type="password" autocomplete="current-password" required>
1065
1124
  {{totp}}
1125
+ {{next}}
1066
1126
  <button type="submit">登录</button>
1067
1127
  </form>
1068
1128
  {{message}}
1069
1129
  <div class="hint">登录一次后 3 天内免登录 · <a href="/dsh_homing/reset" style="color:#7aa7ff">忘记密码?</a></div>
1130
+ {{hint}}
1070
1131
  </div></body></html>`;
1071
1132
 
1072
1133
  const RESET_HTML = `<!doctype html>
@@ -1115,7 +1176,16 @@ const RESET_HTML = `<!doctype html>
1115
1176
  const TOTP_FIELD = `<label for="c">验证码</label>
1116
1177
  <input id="c" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]*" maxlength="6" placeholder="验证器里的 6 位数字" required>`;
1117
1178
 
1118
- function sendLogin(res, message = '', requireTotp = false) {
1179
+ /** 只接受本站路径作为登录后的落点,避免开放重定向(//evil.com、/\evil.com 都挡掉)。 */
1180
+ function safeNextPath(value) {
1181
+ const text = String(value ?? '');
1182
+ if (!text.startsWith('/')) return '';
1183
+ if (text.startsWith('//') || text.startsWith('/\\')) return '';
1184
+ if (text.length > 300) return '';
1185
+ return text;
1186
+ }
1187
+
1188
+ function sendLogin(res, message = '', requireTotp = false, next = '', hint = '') {
1119
1189
  res.writeHead(200, {
1120
1190
  'content-type': 'text/html; charset=utf-8',
1121
1191
  'cache-control': 'no-store',
@@ -1125,22 +1195,42 @@ function sendLogin(res, message = '', requireTotp = false) {
1125
1195
  'x-content-type-options': 'nosniff',
1126
1196
  'referrer-policy': 'no-referrer',
1127
1197
  });
1128
- res.end(LOGIN_HTML.replace('{{totp}}', requireTotp ? TOTP_FIELD : '').replace('{{message}}', message));
1198
+ const nextField = next === '' ? '' : `<input type="hidden" name="next" value="${escapeHtml(next)}">`;
1199
+ const hintHtml = hint === '' ? '' : `<div class="hint">${escapeHtml(hint)}</div>`;
1200
+ res.end(
1201
+ LOGIN_HTML
1202
+ .replace('{{totp}}', requireTotp ? TOTP_FIELD : '')
1203
+ .replace('{{next}}', nextField)
1204
+ .replace('{{message}}', message)
1205
+ .replace('{{hint}}', hintHtml),
1206
+ );
1129
1207
  }
1130
1208
 
1131
1209
  /**
1132
- * 登录限速用的客户端标识。
1133
- * 经隧道进来时 socket 一律是 127.0.0.1,真正的来源在 nginx 写的 X-Forwarded-For 里;
1134
- * 只有 socket 是回环时才信任该头,避免局域网客户端伪造它绕过限速。
1210
+ * 读请求体,但**超限时不粗暴断开**。
1211
+ *
1212
+ * 旧实现 readBody 一旦超限就 req.destroy():客户端正在上传时连接被重置,
1213
+ * 浏览器只看到 ECONNRESET,页面上什么都不显示——用户看到的就是"点上传没反应"。
1214
+ * 这里改为把剩余数据读完(drain)再返回 { overflow: true },让调用方能回一个
1215
+ * 正常的 413 JSON,客户端就能看到"图片太大"而不是白屏。
1135
1216
  */
1136
- function clientKey(req) {
1137
- const socket = req.socket.remoteAddress ?? '';
1138
- const isLoopback = socket === '::1' || socket === '127.0.0.1' || socket.startsWith('::ffff:127.');
1139
- if (isLoopback) {
1140
- const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
1141
- if (forwarded) return forwarded;
1142
- }
1143
- return socket;
1217
+ function readBodyWithLimit(req, limit) {
1218
+ return new Promise((resolve) => {
1219
+ let size = 0;
1220
+ let overflow = false;
1221
+ const chunks = [];
1222
+ req.on('data', (chunk) => {
1223
+ size += chunk.length;
1224
+ if (size > limit) {
1225
+ overflow = true;
1226
+ chunks.length = 0;
1227
+ return; // 继续收,把连接读干净,避免 RST
1228
+ }
1229
+ if (!overflow) chunks.push(chunk);
1230
+ });
1231
+ req.on('end', () => resolve({ overflow, size, text: Buffer.concat(chunks).toString('utf8') }));
1232
+ req.on('error', () => resolve({ overflow, size, text: '' }));
1233
+ });
1144
1234
  }
1145
1235
 
1146
1236
  function readBodyBuffer(req, limit) {
@@ -1224,6 +1314,9 @@ function verifyTotp(secret, code, lastStep) {
1224
1314
  return false;
1225
1315
  }
1226
1316
 
1317
+ /** HSTS 有效期:一年。让浏览器在首次 HTTPS 访问后不再尝试明文 http。 */
1318
+ const HSTS_MAX_AGE = 'max-age=31536000';
1319
+
1227
1320
  function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCookies, caCertPath }) {
1228
1321
  const appRegistry = createLocalAppRegistry({
1229
1322
  settingsPath: path.join(dir, 'settings.json'),
@@ -1273,9 +1366,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1273
1366
  }
1274
1367
 
1275
1368
 
1276
- /** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。 */
1369
+ /** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。
1370
+ * value 只会是 string:两个调用点都是 `if (token && entryExpiry(token) > 0)`,
1371
+ * searchParams.get() 的 null 已被短路挡掉(门禁证明 typeof 兜底不可达)。 */
1277
1372
  function entryExpiry(value) {
1278
- if (typeof value !== 'string') return 0;
1279
1373
  const [body, mac] = value.split('.');
1280
1374
  if (!body || !mac) return 0;
1281
1375
  const expected = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
@@ -1310,9 +1404,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1310
1404
  // 目的:登录过的设备都应出现在设备管理页、可单独吊销;
1311
1405
  // 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
1312
1406
  // 只有「浏览器页面导航」才允许自动配对/用入口令牌配对。
1313
- // fetch/XHR/脚本(Accept 不含 text/html)不再产生设备记录,
1314
- // 否则自动化探测会让设备表越堆越多。
1315
- const isBrowserNavigation = (req) => String(req.headers.accept ?? '').includes('text/html')
1407
+ // fetch/XHR/脚本不再产生设备记录,否则自动化探测会让设备表越堆越多。
1408
+ //
1409
+ // 判定必须有明确证据(2026-11-15):
1410
+ // 手机/PWA 的顶层导航会带 `Sec-Fetch-Mode: navigate` 或 `Accept: text/html`;
1411
+ // 没有任何这类证据的请求(自动化探测、健康检查)仍按"非导航"处理,保持 404 语义。
1412
+ const isBrowserNavigation = (req) => {
1413
+ if (String(req.headers.accept ?? '').includes('text/html')) return true
1414
+ if (String(req.headers['sec-fetch-mode'] ?? '').toLowerCase() === 'navigate') return true
1415
+ if (String(req.headers['sec-fetch-dest'] ?? '').toLowerCase() === 'document') return true
1416
+ return false
1417
+ }
1316
1418
 
1317
1419
  const ensureDeviceCookie = (req, cookies) => {
1318
1420
  const existing = currentDevice(req);
@@ -1331,12 +1433,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1331
1433
  };
1332
1434
  const persistDevices = (next) => {
1333
1435
  const saved = deviceStore.saveState(dir, next);
1334
- let mtime = 0;
1335
- try {
1336
- mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
1337
- } catch {
1338
- mtime = 0;
1339
- }
1436
+ // saveState 是同步写盘且刚返回;这里的 statSync 若失败意味着数据目录被外部删除/损坏,
1437
+ // 属于环境故障,不应静默吞掉(旧实现兜底后 deviceCache.mtime 会失真)。门禁证明该 catch 不可达。
1438
+ const mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
1340
1439
  deviceCache = { mtime, state: saved };
1341
1440
  return saved;
1342
1441
  };
@@ -1388,7 +1487,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1388
1487
  bucket.count += 1;
1389
1488
  return bucket.count > limit;
1390
1489
  };
1391
- const clientKey = (req) => String((req.socket && req.socket.remoteAddress) || 'unknown');
1490
+ // 所有路由都经真实 TCP 连接进入 handler,req.socket.remoteAddress 恒为字符串;
1491
+ // 原 `(req.socket && req.socket.remoteAddress) || 'unknown'` 的兜底在门禁里不可达。
1492
+ const clientKey = (req) => String(req.socket.remoteAddress);
1392
1493
  let vncPasswordCache = '';
1393
1494
  async function resolveVncPassword() {
1394
1495
  if (vncPasswordCache !== '') return vncPasswordCache;
@@ -1414,6 +1515,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1414
1515
  }
1415
1516
  let csp = '';
1416
1517
  if (headers && typeof headers === 'object') csp = String(headers['content-security-policy'] ?? '');
1518
+ // 统一给所有响应加 HSTS(2026-11-19):手机浏览器升级后曾默认走 http://,
1519
+ // 远端 80 端口空关闭导致 ERR_EMPTY_RESPONSE;现在 80 已 301 到 https,
1520
+ // 再加上 HSTS 让浏览器第一次访问后直接走 https、不再经过 80。
1521
+ // 只有 HTTPS 响应会被浏览器采纳,明文响应里带这个头是无害的。
1522
+ if (headers && typeof headers === 'object' && headers['strict-transport-security'] === undefined) {
1523
+ headers = { ...headers, 'strict-transport-security': HSTS_MAX_AGE };
1524
+ }
1417
1525
  // 只有插件自己的页面以 default-src 'none' 开头;DSH 前端页面不能改写,
1418
1526
  // 否则会破坏 0.2.2 动态生成的 <script> 模板。
1419
1527
  if (csp.includes("default-src 'none'")) {
@@ -1438,7 +1546,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1438
1546
  };
1439
1547
 
1440
1548
 
1441
- const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
1549
+ // HTTP server 的 IncomingMessage.url 恒为字符串(Node 只在解析出请求行后才进 handler)。
1550
+ const url = new URL(req.url, 'http://dsh-homing.invalid');
1442
1551
  // 活跃时间只由"用户真实操作"刷新:手机端键盘/指针/输入事件会 POST /dsh_homing/alive。
1443
1552
  // 这里不再把任意请求(页面加载、图标、重定向、控制接口)算作用户输入,
1444
1553
  // 否则打开/刷新页面会不断重置安静窗口,排队等待还会被误报成"最近有用户输入"。
@@ -1554,7 +1663,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1554
1663
  result = appRegistry.remove(form.get('id') ?? '');
1555
1664
  }
1556
1665
  appendAudit(dir, 'app-registry-' + action, { id: String(form.get('id') ?? form.get('originalId') ?? ''), ok: result.ok, error: result.error ?? null });
1557
- const message = result.ok ? '已保存,立即生效。' : (result.error ?? '保存失败');
1666
+ // appRegistry 的每条失败路径都带 error 字符串(门禁证明 `?? '保存失败'` 不可达)
1667
+ const message = result.ok ? '已保存,立即生效。' : result.error;
1558
1668
  res.writeHead(303, { location: `/dsh_homing/apps?msg=${encodeURIComponent(message)}${result.ok ? '' : '&error=1'}`, 'cache-control': 'no-store' });
1559
1669
  res.end();
1560
1670
  return;
@@ -1598,15 +1708,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1598
1708
  const upstream = http.request({
1599
1709
  host: '127.0.0.1',
1600
1710
  port: restartDaemonPort,
1601
- path: '/' + rest + (url.search ?? ''),
1711
+ path: '/' + rest + url.search,
1602
1712
  method: req.method,
1603
1713
  timeout: 8000,
1604
1714
  }, (up) => {
1605
- res.writeHead(up.statusCode ?? 502, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
1715
+ res.writeHead(up.statusCode, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
1606
1716
  up.pipe(res);
1607
1717
  });
1608
- upstream.on('timeout', () => { upstream.destroy(); res.writeHead(504).end('restart-daemon timeout'); });
1609
- upstream.on('error', () => { res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: '守护进程未运行' })); });
1718
+ // 注意:timeout 与 error 可能先后触发(destroy 会引发 ECONNRESET),
1719
+ // 第二次 writeHead 会抛 ERR_HTTP_HEADERS_SENT 把插件进程打崩,必须判 headersSent。
1720
+ upstream.on('timeout', () => {
1721
+ if (!res.headersSent) res.writeHead(504).end('restart-daemon timeout');
1722
+ upstream.destroy();
1723
+ });
1724
+ upstream.on('error', () => {
1725
+ if (res.headersSent) { res.destroy(); return; }
1726
+ res.writeHead(502, { 'content-type': 'application/json' });
1727
+ res.end(JSON.stringify({ error: '守护进程未运行' }));
1728
+ });
1610
1729
  upstream.end();
1611
1730
  return;
1612
1731
  }
@@ -1620,15 +1739,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1620
1739
  // 会话繁忙度:以会话文件里的 turnBoundary 为准(step=start 即运行中)
1621
1740
 
1622
1741
  // 重启页面的客户端脚本(外部文件,script-src 'self' 直接放行)
1742
+ // 文件随 npm 包一起发布;读失败属于安装损坏,交给外层 safeHandler 统一 500(不再单点吞异常)。
1623
1743
  if (url.pathname === '/dsh_homing/restart.js' && req.method === 'GET') {
1624
- try {
1625
- const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
1626
- res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1627
- res.end(js);
1628
- } catch (error) {
1629
- res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
1630
- res.end('restart.js 读取失败:' + error.message);
1631
- }
1744
+ const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
1745
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1746
+ res.end(js);
1747
+ return;
1748
+ }
1749
+
1750
+ // 调试页的上传脚本:必须是同源外部文件。
1751
+ // 页面 CSP 是 `script-src 'self'`(没有 'unsafe-inline'),内联 <script> 会被浏览器丢弃,
1752
+ // 这就是 2026-11-15「上传点了没反应」的根因——连请求都没发出。
1753
+ if (url.pathname === '/dsh_homing/debug.js' && req.method === 'GET') {
1754
+ const js = fs.readFileSync(new URL('./lib/debug-page.js', import.meta.url), 'utf8');
1755
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1756
+ res.end(js);
1632
1757
  return;
1633
1758
  }
1634
1759
 
@@ -1720,9 +1845,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1720
1845
  const push = async () => {
1721
1846
  const state = await collectRestartState(dataDir());
1722
1847
  seq += 1;
1723
- try {
1724
- res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
1725
- } catch { sseClients.delete(res) }
1848
+ // res.write 对已销毁的响应不会同步抛异常(只会异步 emit error),无需 try/catch。
1849
+ res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
1726
1850
  };
1727
1851
  void push();
1728
1852
  const timer = setInterval(() => { void push() }, 2000);
@@ -1791,10 +1915,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1791
1915
  const inbox = inboxPaths(dataDir());
1792
1916
  const rest = decodeURIComponent(url.pathname.slice('/dsh_homing/debug/inbox/'.length));
1793
1917
  const parts = rest.split('/');
1794
- const file = path.join(inbox.uploads, path.basename(parts[1] ?? ''));
1918
+ // 缺少图片名时段(/debug/inbox/<id>)时 parts[1] 为空,path.join(uploads,'') 会变成目录,
1919
+ // 直接 createReadStream 一个目录会抛 EISDIR 把进程打崩,所以先挡掉。
1920
+ if (!parts[1]) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
1921
+ const file = path.join(inbox.uploads, path.basename(parts[1]));
1795
1922
  if (!fs.existsSync(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
1796
1923
  res.writeHead(200, { 'content-type': 'image/*', 'cache-control': 'private, max-age=60' });
1797
- fs.createReadStream(file).pipe(res);
1924
+ const stream = fs.createReadStream(file);
1925
+ // writeHead 已经执行过,headersSent 恒为 true;读流失败时只能断开响应,避免未处理的
1926
+ // stream 'error' 事件把进程打崩。
1927
+ stream.on('error', () => res.destroy());
1928
+ stream.pipe(res);
1798
1929
  return;
1799
1930
  }
1800
1931
 
@@ -1802,6 +1933,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1802
1933
  if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
1803
1934
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1804
1935
  const status = await restartService.status();
1936
+ const daemonHealth = await restartService.health();
1937
+ const daemonVersion = typeof daemonHealth?.version === 'string' ? daemonHealth.version : null;
1938
+ const staleDaemon = daemonVersion !== null && daemonVersion !== 'unknown' && daemonVersion !== PLUGIN_VERSION;
1805
1939
  const message = url.searchParams.get('m') ?? '';
1806
1940
  res.writeHead(200, {
1807
1941
  'content-type': 'text/html; charset=utf-8',
@@ -1810,7 +1944,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1810
1944
  'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1811
1945
  });
1812
1946
  const portState = { conflict: await detectRestartPortConflict(), disabled: restartDaemonDisabled(), port: restartDaemonPort };
1813
- res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState }));
1947
+ res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState, daemonVersion, staleDaemon }));
1814
1948
  return;
1815
1949
  }
1816
1950
 
@@ -1818,7 +1952,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1818
1952
  if (url.pathname === '/dsh_homing/restart/daemon' && req.method === 'POST') {
1819
1953
  let message = '';
1820
1954
  appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old' });
1821
- try { await restartService.stop(); } catch { /* 忽略 */ }
1955
+ // restartService.stop() 内部对超时/连接错误都降级 resolve,不会 reject(门禁证明 catch 不可达)
1956
+ await restartService.stop();
1822
1957
  appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old-done' });
1823
1958
  await new Promise((resolve) => setTimeout(resolve, 600));
1824
1959
  const started = startRestartDaemonDetached();
@@ -1849,7 +1984,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1849
1984
  } else {
1850
1985
  // 旧端口上的守护进程用"授权停止"请求关掉,再切换(CLI 的停止请求会被鉴权拒绝)
1851
1986
  if (oldHealth && oldHealth.ok !== false) {
1852
- try { await restartService.stop(); } catch { /* 忽略 */ }
1987
+ // restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
1988
+ await restartService.stop();
1853
1989
  await new Promise((resolve) => setTimeout(resolve, 600));
1854
1990
  }
1855
1991
  writePortOverride(port);
@@ -1859,16 +1995,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1859
1995
  const started = startRestartDaemonDetached();
1860
1996
  const healthy = await waitRestartDaemonHealthy(5000);
1861
1997
  appendAudit(dataDir(), 'restart-daemon-port-change', { from: oldPort, port, started, healthy });
1998
+ // startRestartDaemonDetached 只在「CLI 文件不存在」时返回 false;文件随包发布,
1999
+ // 该分支门禁证明不可达,因此这里只剩「健康/未就绪」两种结果。
1862
2000
  if (healthy) message = '已切换到端口 ' + port + ',守护进程运行正常';
1863
- else if (started) message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
1864
- else message = '已保存端口 ' + port + ',但启动失败,请查看日志';
2001
+ else message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
1865
2002
  }
1866
2003
  } else if (action === 'disable') {
1867
2004
  try {
1868
2005
  fs.mkdirSync(restartDaemonStateDir(), { recursive: true });
1869
2006
  fs.writeFileSync(path.join(restartDaemonStateDir(), 'disabled.json'), JSON.stringify({ at: new Date().toISOString() }));
1870
2007
  } catch { /* 忽略 */ }
1871
- try { await restartService.stop(); } catch { /* 忽略 */ }
2008
+ // restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
2009
+ await restartService.stop();
1872
2010
  appendAudit(dataDir(), 'restart-daemon-disabled', {});
1873
2011
  message = '已关闭重启守护进程';
1874
2012
  } else if (action === 'enable') {
@@ -1915,21 +2053,19 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1915
2053
  return;
1916
2054
  }
1917
2055
  const result = await restartPolicy.force();
2056
+ // restartPolicy.force() 只返回 { ok, ...status() }:status() 里没有 status/error 字段,
2057
+ // 因此「403 / restart-daemon down 文案」分支门禁证明不可达,失败原因统一按"没成功"处理。
1918
2058
  if (wantsJson) {
1919
2059
  const ok = result.ok === true;
1920
- message = ok ? '已触发强制重启' : (result.status === 403
1921
- ? '守护进程拒绝了请求(来源进程校验未通过)'
1922
- : '守护进程未运行或未响应');
2060
+ message = ok ? '已触发强制重启' : '守护进程未运行或未响应';
1923
2061
  res.writeHead(ok ? 200 : 409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1924
- res.end(JSON.stringify({ ok, status: result.status ?? 0, message }));
2062
+ res.end(JSON.stringify({ ok, status: 0, message }));
1925
2063
  return;
1926
2064
  }
1927
2065
  if (result.ok) {
1928
2066
  message = '已触发强制重启(策略层已放行)';
1929
- } else if (result.status === 403) {
1930
- message = '提交失败:守护进程拒绝了请求(来源进程校验未通过),请查看守护进程日志';
1931
2067
  } else {
1932
- message = '提交失败:' + (result.error === 'restart-daemon down' || result.error === 'timeout' ? '守护进程未运行' : String(result.error ?? '未知原因'));
2068
+ message = '提交失败:守护进程未运行或拒绝响应';
1933
2069
  }
1934
2070
  } else if (action === 'pause') {
1935
2071
  const minutes = Number(form.get('minutes'));
@@ -2000,17 +2136,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2000
2136
  res.end(fs.readFileSync(caCertPath));
2001
2137
  return;
2002
2138
  }
2003
- try {
2004
- const openssl = findOpenssl();
2005
- const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
2006
- if (!fs.existsSync(derFile)) {
2007
- spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
2008
- }
2009
- if (fs.existsSync(derFile)) {
2010
- res.end(fs.readFileSync(derFile));
2011
- return;
2012
- }
2013
- } catch { /* 转换失败就退回 PEM */ }
2139
+ // findOpenssl 恒返回字符串(最差是裸命令名 openssl.exe),spawnSync 传字符串命令不会抛;
2140
+ // 转换失败只会表现为 derFile 不存在 → 退回 PEM。门禁证明 try/catch 不可达。
2141
+ const openssl = findOpenssl();
2142
+ const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
2143
+ if (!fs.existsSync(derFile)) {
2144
+ spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
2145
+ }
2146
+ if (fs.existsSync(derFile)) {
2147
+ res.end(fs.readFileSync(derFile));
2148
+ return;
2149
+ }
2014
2150
  res.end(fs.readFileSync(caCertPath));
2015
2151
  return;
2016
2152
  }
@@ -2020,6 +2156,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2020
2156
  || url.pathname === '/dsh_homing/account' || url.pathname === '/dsh_homing/reset'
2021
2157
  || url.pathname === '/dsh_homing/devices'
2022
2158
  || url.pathname === '/files' || url.pathname.startsWith('/files/')
2159
+ // 诊断/自救页必须在"未登录/清过缓存"的状态下也能打开——这正是它们存在的场景
2160
+ || url.pathname === '/dsh_homing/netdiag' || url.pathname === '/dsh_homing/netdiag/report'
2161
+ || url.pathname === '/dsh_homing/netdiag.js'
2162
+ || url.pathname === '/dsh_homing/recover' || url.pathname === '/dsh_homing/recover.js'
2163
+ // 页面内鉴权守卫(auth-guard.js)与客户端错误上报(client-report.js)
2164
+ // 必须在未登录时也能加载与上报
2165
+ || url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
2166
+ || url.pathname === '/dsh_homing/idb-fallback.js'
2167
+ || url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
2168
+ // 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
2169
+ || url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
2170
+ || url.pathname === '/favicon.svg' || url.pathname === '/favicon-dark.svg' || url.pathname === '/favicon.ico'
2023
2171
  || url.pathname === '/debug' || url.pathname === '/dsh_homing/debug'
2024
2172
  || url.pathname.startsWith('/debug/') || url.pathname.startsWith('/dsh_homing/debug/');
2025
2173
 
@@ -2143,6 +2291,188 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2143
2291
  }
2144
2292
  }
2145
2293
 
2294
+ // 鉴权状态查询:给页面内守卫用(auth-guard.js)。
2295
+ // 必须免登录、不缓存——它存在的意义就是告诉页面"你现在其实没登录"。
2296
+ //
2297
+ // 口径必须和「导航闸门」一致:只有**有效会话**才算已登录。
2298
+ // 光有设备 Cookie(配对过但会话过期/被清)不算——那正是用户要求跳登录页的情况。
2299
+ if (url.pathname === '/dsh_homing/auth-state' && req.method === 'GET') {
2300
+ const jar = readCookies(req.headers.cookie);
2301
+ const authenticated = !config.login || sessionValid(req);
2302
+ res.writeHead(200, {
2303
+ 'content-type': 'application/json; charset=utf-8',
2304
+ 'cache-control': 'no-store, must-revalidate',
2305
+ 'x-content-type-options': 'nosniff',
2306
+ });
2307
+ res.end(JSON.stringify({
2308
+ authenticated,
2309
+ hasSession: Boolean(jar[SESSION_COOKIE]),
2310
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
2311
+ login: Boolean(config.login),
2312
+ reason: authenticated ? 'ok' : (jar[SESSION_COOKIE] ? 'session-expired' : 'no-session'),
2313
+ }));
2314
+ return;
2315
+ }
2316
+
2317
+ if (url.pathname === '/dsh_homing/idb-fallback.js' && req.method === 'GET') {
2318
+ // 文件随包发布;读失败由外层 safeHandler 统一 500,不再单点 try/catch
2319
+ const js = fs.readFileSync(new URL('./lib/idb-fallback.js', import.meta.url), 'utf8');
2320
+ res.writeHead(200, {
2321
+ 'content-type': 'application/javascript; charset=utf-8',
2322
+ 'cache-control': 'no-store',
2323
+ });
2324
+ res.end(js);
2325
+ return;
2326
+ }
2327
+
2328
+ if (url.pathname === '/dsh_homing/auth-guard.js' && req.method === 'GET') {
2329
+ const js = fs.readFileSync(new URL('./lib/auth-guard.js', import.meta.url), 'utf8');
2330
+ res.writeHead(200, {
2331
+ 'content-type': 'application/javascript; charset=utf-8',
2332
+ // 注入脚本必须每次取新的:它承载诊断与登录守卫,旧版本会掩盖问题
2333
+ 'cache-control': 'no-store',
2334
+ });
2335
+ res.end(js);
2336
+ return;
2337
+ }
2338
+
2339
+ if (url.pathname === '/dsh_homing/client-report.js' && req.method === 'GET') {
2340
+ const js = fs.readFileSync(new URL('./lib/client-report.js', import.meta.url), 'utf8');
2341
+ res.writeHead(200, {
2342
+ 'content-type': 'application/javascript; charset=utf-8',
2343
+ 'cache-control': 'no-store',
2344
+ });
2345
+ res.end(js);
2346
+ return;
2347
+ }
2348
+
2349
+ // 客户端错误上报:手机上没有 devtools,页面出错只能靠它自己交回证据。
2350
+ // 免登录(页面可能就在"未登录"或"登录失效"时出错)。
2351
+ if (url.pathname === '/dsh_homing/client-error' && req.method === 'POST') {
2352
+ let payload = null;
2353
+ try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
2354
+ if (payload && typeof payload === 'object') {
2355
+ appendAudit(dir, 'client-error', {
2356
+ kind: String(payload.kind ?? '').slice(0, 24),
2357
+ message: String(payload.message ?? '').slice(0, 200),
2358
+ source: String(payload.source ?? '').slice(0, 120),
2359
+ line: payload.line ?? 0,
2360
+ url: String(payload.url ?? '').slice(0, 160),
2361
+ rootExists: payload.rootExists,
2362
+ scriptCount: payload.scriptCount,
2363
+ linkCount: payload.linkCount,
2364
+ resources: Array.isArray(payload.resources) ? payload.resources.slice(0, 6) : undefined,
2365
+ ua: String(payload.ua ?? req.headers['user-agent'] ?? '').slice(0, 60),
2366
+ });
2367
+ } else {
2368
+ appendAudit(dir, 'client-error', { kind: 'bad-json' });
2369
+ }
2370
+ res.writeHead(204, { 'cache-control': 'no-store' });
2371
+ res.end();
2372
+ return;
2373
+ }
2374
+
2375
+ // 手机端网络自检:在真实设备上跑一遍首页加载链路(HTML → assets → plugins 包 → WebSocket),
2376
+ // 把结果回传审计。桌面端复现不了手机的问题时,这是唯一能拿到设备侧证据的办法。
2377
+ // 注意:不要求登录——它恰恰要在"没登录 / 清过缓存 / 转圈"的状态下打开。
2378
+ if (url.pathname === '/dsh_homing/netdiag' && req.method === 'GET') {
2379
+ res.writeHead(200, {
2380
+ 'content-type': 'text/html; charset=utf-8',
2381
+ 'cache-control': 'no-store',
2382
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
2383
+ });
2384
+ res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
2385
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2386
+ <title>网络自检 · DSH 手机入口</title>
2387
+ <style>
2388
+ :root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.7 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
2389
+ h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
2390
+ pre{background:#171a21;border:1px solid #262b36;border-radius:10px;padding:12px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word;user-select:text;-webkit-user-select:text}
2391
+ button{margin:10px 0 0;padding:10px 14px;border-radius:9px;border:0;background:#2a2f3a;color:#e6edf5;font-size:14px;font-weight:600}
2392
+ a{color:#8ab4f8}
2393
+ </style></head><body>
2394
+ <h1>网络自检</h1>
2395
+ <p class="sub">打开这一页会自动跑一遍,每步都有超时;结果同时回传服务端。</p>
2396
+ <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/dsh_homing/debug">调试页</a></p>
2397
+ <pre id="out">检测中…</pre>
2398
+ <button id="copy" type="button">复制结果</button>
2399
+ <script src="/dsh_homing/netdiag.js" defer></script>
2400
+ </body></html>`);
2401
+ return;
2402
+ }
2403
+
2404
+ if (url.pathname === '/dsh_homing/netdiag.js' && req.method === 'GET') {
2405
+ // 记一笔:浏览器到底有没有来取这个脚本。页面停在"检测中"时,
2406
+ // 有没有这条审计就能立刻区分「脚本没加载」和「脚本跑了但卡住」。
2407
+ appendAudit(dir, 'netdiag-js-loaded', { ua: String(req.headers['user-agent'] ?? '').slice(0, 60) });
2408
+ try {
2409
+ const js = fs.readFileSync(new URL('./lib/netdiag.js', import.meta.url), 'utf8');
2410
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
2411
+ res.end(js);
2412
+ } catch (error) {
2413
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
2414
+ res.end('netdiag.js 读取失败:' + String(error?.message ?? error));
2415
+ }
2416
+ return;
2417
+ }
2418
+
2419
+ if (url.pathname === '/dsh_homing/netdiag/report' && req.method === 'POST') {
2420
+ let payload = null;
2421
+ try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
2422
+ const jar = readCookies(req.headers.cookie);
2423
+ appendAudit(dir, 'netdiag', {
2424
+ ...(payload ?? { error: 'bad-json' }),
2425
+ serverSide: {
2426
+ hasSession: Boolean(jar[SESSION_COOKIE]),
2427
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
2428
+ cookieNames: Object.keys(jar),
2429
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
2430
+ },
2431
+ });
2432
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2433
+ res.end('{"ok":true}');
2434
+ return;
2435
+ }
2436
+
2437
+ // 一键自救:注销 Service Worker、清掉 Cache Storage、再回到首页。
2438
+ // 手机"清了站点数据还是一直转圈"时,常见原因是残留的 SW 仍从旧缓存回放页面。
2439
+ if (url.pathname === '/dsh_homing/recover' && req.method === 'GET') {
2440
+ res.writeHead(200, {
2441
+ 'content-type': 'text/html; charset=utf-8',
2442
+ 'cache-control': 'no-store',
2443
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
2444
+ });
2445
+ res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
2446
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2447
+ <title>一键自救 · DSH 手机入口</title>
2448
+ <style>
2449
+ :root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.6 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
2450
+ h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
2451
+ pre{background:#171a21;border:1px solid #262b36;border-radius:10px;padding:12px;font-size:12px;white-space:pre-wrap;word-break:break-all}
2452
+ a{color:#8ab4f8}
2453
+ </style></head><body>
2454
+ <h1>一键自救</h1>
2455
+ <p class="sub">注销 Service Worker、清掉本地缓存,然后回到首页。清完后如果要求登录,就正常登录一次。</p>
2456
+ <p class="sub"><a href="/dsh_homing/netdiag">网络自检</a> · <a href="/">返回 DSH</a></p>
2457
+ <pre id="out">正在清理…</pre>
2458
+ <p class="sub"><a href="/" id="go">清理完点这里回首页</a></p>
2459
+ <script src="/dsh_homing/recover.js" defer></script>
2460
+ </body></html>`);
2461
+ return;
2462
+ }
2463
+
2464
+ if (url.pathname === '/dsh_homing/recover.js' && req.method === 'GET') {
2465
+ try {
2466
+ const js = fs.readFileSync(new URL('./lib/recover.js', import.meta.url), 'utf8');
2467
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
2468
+ res.end(js);
2469
+ } catch (error) {
2470
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
2471
+ res.end('recover.js 读取失败:' + String(error?.message ?? error));
2472
+ }
2473
+ return;
2474
+ }
2475
+
2146
2476
  // 自检:把"兜底转发"这一段的状态暴露出来,便于定位 404
2147
2477
  if (url.pathname === '/dsh_homing/selfcheck') {
2148
2478
  const up = getUpstreamPort();
@@ -2344,22 +2674,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2344
2674
  'content-security-policy': "default-src 'none'",
2345
2675
  });
2346
2676
  const flush = (text, seq) => {
2347
- if (text === '') return;
2348
- try {
2349
- res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
2350
- } catch {
2351
- // 连接已断
2352
- }
2677
+ res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
2353
2678
  };
2354
2679
  const backlog = terminal.since(since);
2355
2680
  if (backlog !== '') flush(backlog, terminal.latestSeq);
2356
2681
  const unsubscribe = terminal.subscribe((text, seq) => flush(text, seq));
2357
2682
  const heartbeat = setInterval(() => {
2358
- try {
2359
- res.write(': ping\n\n');
2360
- } catch {
2361
- clearInterval(heartbeat);
2362
- }
2683
+ res.write(': ping\n\n');
2363
2684
  }, 15000);
2364
2685
  const cleanup = () => {
2365
2686
  clearInterval(heartbeat);
@@ -2461,8 +2782,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2461
2782
  const maxWidth = Number(url.searchParams.get('maxWidth') ?? '1280') || 1280;
2462
2783
  const shot = await windowRemote.captureWindow(hwnd, maxWidth);
2463
2784
  if (!shot.ok) {
2464
- appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error ?? null });
2465
- sendRemoteJson(500, { ok: false, error: shot.error ?? '抓图失败' });
2785
+ appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error });
2786
+ sendRemoteJson(500, { ok: false, error: shot.error });
2466
2787
  return;
2467
2788
  }
2468
2789
  sendRemote(200, {
@@ -2485,8 +2806,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2485
2806
  if (payload.kind === 'rotate') {
2486
2807
  const mode = payload.mode === 'landscape' ? 'landscape' : 'portrait';
2487
2808
  const rotated = await setOrientation(mode);
2488
- appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail ?? null });
2489
- sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail ?? null, screen: rotated.screen ?? null });
2809
+ appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail });
2810
+ sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail, screen: rotated.screen ?? null });
2490
2811
  return;
2491
2812
  }
2492
2813
  if (payload.kind === 'cursor') {
@@ -2921,7 +3242,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2921
3242
  res.writeHead(500, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
2922
3243
  res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
2923
3244
  <h1 style="font-size:18px">预览失败</h1>
2924
- <p style="color:#9aa3b2">${escapeHtml(String(result.error ?? '未知原因'))}</p>
3245
+ <p style="color:#9aa3b2">${escapeHtml(String(result.error))}</p>
2925
3246
  <p><a style="color:#8ab4f8" href="/">← 返回 DSH</a> · <a style="color:#8ab4f8" href="/files?path=${encodeURIComponent(path.dirname(target))}">← 返回文件列表</a></p>
2926
3247
  <p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
2927
3248
  </body>`);
@@ -3070,13 +3391,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3070
3391
  try {
3071
3392
  errors = fs.readFileSync(path.join(dir, 'debug', 'errors.log'), 'utf8').trim().split('\n').filter(Boolean).slice(-3).reverse();
3072
3393
  } catch { /* 没有日志 */ }
3073
- const row = (k, v, cls) => `<div class="row"><span class="k">${k}</span><span class="v ${cls ?? ''}">${v}</span></div>`;
3074
3394
  const deviceCount = deviceStore.partition(devices()).active.length;
3075
3395
  res.writeHead(200, {
3076
3396
  'content-type': 'text/html; charset=utf-8',
3077
3397
  'cache-control': 'no-store',
3078
3398
  'x-frame-options': 'DENY',
3079
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; form-action 'self'; base-uri 'none'",
3399
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
3080
3400
  'x-content-type-options': 'nosniff',
3081
3401
  'referrer-policy': 'no-referrer',
3082
3402
  });
@@ -3105,29 +3425,61 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3105
3425
  }
3106
3426
 
3107
3427
  // 上传截图:接收 dataURL,落盘到 debug/shots/
3428
+ //
3429
+ // 2026-11-15 修复:这个接口之前拒绝时只回一行纯文本、也不写审计,
3430
+ // 结果手机上传失败时既看不到原因、事后也查不到痕迹(audit 里 debug-shot 一直是 0 条)。
3431
+ // 现在:每一次尝试都写审计(成功 debug-shot / 失败 debug-shot-rejected),
3432
+ // 失败原因写清楚(未登录 / JSON 坏了 / 类型不支持 / 超过大小),并给出对应状态码。
3108
3433
  if (debugSub === '/upload' && req.method === 'POST') {
3434
+ const ua = String(req.headers['user-agent'] ?? '').slice(0, 120);
3435
+ const declared = Number(req.headers['content-length'] ?? 0);
3436
+ const reject = (status, reason, extra = {}) => {
3437
+ appendAudit(dir, 'debug-shot-rejected', { reason, status, declaredBytes: declared, ua, ...extra });
3438
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
3439
+ res.end(JSON.stringify({ ok: false, error: reason }));
3440
+ };
3109
3441
  if (!sessionValid(req) && currentDevice(req) === null) {
3110
- res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' });
3111
- res.end('未登录');
3442
+ reject(401, '未登录(会话或设备 Cookie 失效)');
3443
+ return;
3444
+ }
3445
+ if (declared > UPLOAD_LIMIT_BYTES) {
3446
+ // 先把发过来的数据读完再回响应,否则客户端只会看到连接被重置
3447
+ req.resume();
3448
+ reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(declared / 1024 / 1024).toFixed(1)}MB)`);
3449
+ return;
3450
+ }
3451
+ const body = await readBodyWithLimit(req, UPLOAD_LIMIT_BYTES + 4096);
3452
+ if (body.overflow) {
3453
+ reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(body.size / 1024 / 1024).toFixed(1)}MB)`);
3112
3454
  return;
3113
3455
  }
3114
3456
  let parsed = null;
3115
- try { parsed = JSON.parse(await readBody(req, 16 * 1024 * 1024)); } catch { parsed = null; }
3116
- const match = parsed && typeof parsed.dataUrl === 'string'
3117
- ? /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=]+)$/u.exec(parsed.dataUrl)
3118
- : null;
3457
+ try { parsed = JSON.parse(body.text) } catch { parsed = null; }
3458
+ if (parsed === null || typeof parsed !== 'object') {
3459
+ reject(400, '请求体不是合法 JSON(可能是网络中断或被网关截断)');
3460
+ return;
3461
+ }
3462
+ const match = typeof parsed.dataUrl === 'string' ? /^data:image\/([a-z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/iu.exec(parsed.dataUrl) : null;
3119
3463
  if (match === null) {
3120
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
3121
- res.end('只接受 png/jpeg/webp 的 dataURL');
3464
+ reject(400, '只接受图片的 dataURL(data:image/...;base64,...)');
3465
+ return;
3466
+ }
3467
+ const ext = UPLOAD_IMAGE_EXT[match[1].toLowerCase()];
3468
+ if (ext === undefined) {
3469
+ reject(400, `不支持的图片格式:${match[1]}(支持 ${Object.keys(UPLOAD_IMAGE_EXT).join('/')})`);
3122
3470
  return;
3123
3471
  }
3124
- const ext = match[1] === 'jpeg' ? 'jpg' : match[1];
3125
3472
  const stamp = new Date().toISOString().replace(/[:.]/gu, '-').slice(0, 19);
3126
3473
  const shotsDir = path.join(dir, 'debug', 'shots');
3127
- fs.mkdirSync(shotsDir, { recursive: true });
3128
3474
  const name = `${stamp}.${ext}`;
3129
- fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
3130
- appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length });
3475
+ try {
3476
+ fs.mkdirSync(shotsDir, { recursive: true });
3477
+ fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
3478
+ } catch (error) {
3479
+ reject(500, '写入失败:' + String(error?.message ?? error));
3480
+ return;
3481
+ }
3482
+ appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length, ua });
3131
3483
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
3132
3484
  res.end(JSON.stringify({ ok: true, file: name }));
3133
3485
  return;
@@ -3141,7 +3493,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3141
3493
  return;
3142
3494
  }
3143
3495
  const name = decodeURIComponent(debugSub.slice('/files/'.length));
3144
- if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/u.test(name)) {
3496
+ if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp|gif|bmp|heic)$/u.test(name)) {
3145
3497
  res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
3146
3498
  res.end('文件名不合法');
3147
3499
  return;
@@ -3153,8 +3505,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3153
3505
  return;
3154
3506
  }
3155
3507
  const ext = path.extname(name).slice(1).toLowerCase();
3508
+ const types = { png: 'image/png', webp: 'image/webp', gif: 'image/gif', bmp: 'image/bmp', heic: 'image/heic' };
3156
3509
  res.writeHead(200, {
3157
- 'content-type': ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg',
3510
+ 'content-type': types[ext] ?? 'image/jpeg',
3158
3511
  'cache-control': 'no-store',
3159
3512
  });
3160
3513
  res.end(fs.readFileSync(file));
@@ -3200,9 +3553,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3200
3553
  + `<td>${device.lastSeenAt ? escapeHtml(device.lastSeenAt.slice(0, 16).replace('T', ' ')) : '—'}`
3201
3554
  + `<div class="id">${escapeHtml(device.lastIp ?? '')}</div></td>`
3202
3555
  + `<td>${device.createdAt.slice(0, 10)}</td><td>${ops}</td></tr>`;
3203
- const activeRows = active.length === 0
3204
- ? '<tr><td colspan="4" class="muted">还没有配对设备。</td></tr>'
3205
- : active.map((device) => {
3556
+ const activeRows = active.map((device) => {
3206
3557
  const isCurrent = current !== null && current.id === device.id;
3207
3558
  return row(device,
3208
3559
  (isCurrent ? '<span class="badge">当前设备</span> ' : '')
@@ -3250,25 +3601,45 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3250
3601
  return;
3251
3602
  }
3252
3603
 
3253
- // 入口闸门:只认签名令牌或签名 Cookie。
3254
- // 浏览器(Accept 含 text/html)访问未放行路径时,**引导去登录**而不是给死胡同 404:
3255
- // 登录成功即证明持有凭据,之后由登录分支自动补设备令牌(ensureDeviceCookie),
3256
- // 用户不需要再去开外部配对链接。非浏览器的探测仍回 404,不暴露"这里有个门"。
3257
- if (!isLoginPath && !entryAllowed(req, url)) {
3258
- try {
3259
- const jar = readCookies(req.headers.cookie);
3260
- appendAudit(dir, 'gate-redirect', {
3261
- path: url.pathname,
3262
- cookieNames: Object.keys(jar).join(','),
3263
- hasDevice: Boolean(jar[DEVICE_COOKIE]),
3264
- hasSession: Boolean(jar[SESSION_COOKIE]),
3265
- ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
3266
- });
3267
- } catch { /* 诊断不影响响应 */ }
3604
+ // 入口闸门。
3605
+ // 产品口径(2026-11-15):**没有登录、或登录状态已失效 → 自动到登录页**。
3606
+ // - 导航类请求(浏览器打开页面):只认「有效会话」或「有效入口令牌 ?k=」;
3607
+ // 只有设备 Cookie(配对过但会话已过期/被清)也要去登录页。
3608
+ // - 非导航请求(XHR/静态资源/探测):沿用原来的「设备 Cookie 或会话」判定,
3609
+ // 避免登录后页面里的请求被误挡。
3610
+ const isNavigationRequest = isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET';
3611
+ const sessionOk = sessionValid(req);
3612
+ const entryTokenOk = (() => {
3613
+ const token = url.searchParams.get('k');
3614
+ return Boolean(token) && entryExpiry(token) > 0;
3615
+ })();
3616
+ const gateAllowed = isNavigationRequest ? (sessionOk || entryTokenOk) : entryAllowed(req, url);
3617
+ if (!isLoginPath && !gateAllowed) {
3618
+ const gateJar = readCookies(req.headers.cookie);
3619
+ appendAudit(dir, 'gate-redirect', {
3620
+ path: url.pathname,
3621
+ cookieNames: Object.keys(gateJar).join(','),
3622
+ hasDevice: Boolean(gateJar[DEVICE_COOKIE]),
3623
+ hasSession: Boolean(gateJar[SESSION_COOKIE]),
3624
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
3625
+ });
3268
3626
 
3269
- const wantsHtml = String(req.headers.accept ?? '').includes('text/html');
3270
- if (wantsHtml && (url.pathname === '/' || url.pathname === '')) {
3271
- res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
3627
+ // 需求(2026-11-15,产品口径):**没有登录、或登录状态已失效 → 自动到登录页**。
3628
+ // 所以导航类请求只认「有效会话」:只有设备 Cookie(配对过但会话过期/被清)也要去登录页。
3629
+ // 非导航请求(XHR/探测/脚本)保持 404,不暴露入口存在。
3630
+ if (isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET') {
3631
+ const nextUrl = new URL(url.pathname + (url.search || ''), 'http://x');
3632
+ nextUrl.searchParams.delete('k');
3633
+ const nextPath = safeNextPath(nextUrl.pathname + (nextUrl.search || ''));
3634
+ const target = nextPath === '' || nextPath === '/' ? '/login' : '/login?next=' + encodeURIComponent(nextPath);
3635
+ const jar = readCookies(req.headers.cookie);
3636
+ const headers = { location: target, 'cache-control': 'no-store' };
3637
+ // 会话 Cookie 明确存在但已失效:顺手清掉,免得浏览器一直带着坏 Cookie
3638
+ const staleSession = Boolean(jar[SESSION_COOKIE]) && !sessionValid(req);
3639
+ if (staleSession) {
3640
+ headers['set-cookie'] = `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`;
3641
+ }
3642
+ res.writeHead(303, headers);
3272
3643
  res.end();
3273
3644
  return;
3274
3645
  }
@@ -3297,10 +3668,16 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3297
3668
  appendAudit(dir, 'device-paired', { id: created.record.id, name: created.record.name });
3298
3669
  console.log(`[dsh-homing] 新设备已配对:${created.record.name} (${created.record.id})`);
3299
3670
  url.searchParams.delete('k');
3300
- res.writeHead(303, {
3671
+ // 出示有效入口令牌本身就是凭据:配对的同时发会话 Cookie,
3672
+ // 否则"没有会话就跳登录页"的规则会让入口链接紧接着被弹回登录页。
3673
+ const cookies = [
3674
+ `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
3675
+ `${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, created.record.id)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
3676
+ ];
3677
+ res.writeHead(303, {
3301
3678
  location: `${url.pathname}${url.search}`,
3302
3679
  'cache-control': 'no-store',
3303
- 'set-cookie': `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
3680
+ 'set-cookie': cookies,
3304
3681
  });
3305
3682
  res.end();
3306
3683
  return;
@@ -3309,6 +3686,10 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3309
3686
  if (config.login) {
3310
3687
  const ip = clientKey(req);
3311
3688
  if (url.pathname === '/login') {
3689
+ // 登录后回到用户原本想去的页面(?next= 或表单隐藏字段),只接受本站路径
3690
+ const requestedNext = safeNextPath(req.method === 'POST'
3691
+ ? '' // POST 时从表单里读,见下面 form.get('next')
3692
+ : (url.searchParams.get('next') ?? ''));
3312
3693
  if (req.method === 'POST') {
3313
3694
  const deviceForLimit = currentDevice(req);
3314
3695
  const limitKey = deviceForLimit ? deviceForLimit.id : null;
@@ -3344,6 +3725,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3344
3725
  const username = form.get('username') ?? '';
3345
3726
  const password = form.get('password') ?? '';
3346
3727
  const code = (form.get('code') ?? '').trim();
3728
+ const nextAfterLogin = safeNextPath(form.get('next')) || '';
3347
3729
  const ok = safeEqual(username, auth.username) && password.length > 0 && password.length <= 256 && passwordMatches(password);
3348
3730
 
3349
3731
  const recordFailure = (event) => {
@@ -3364,7 +3746,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3364
3746
  if (ok && auth.totpSecret) {
3365
3747
  if (!verifyTotp(auth.totpSecret, code, lastTotpStep)) {
3366
3748
  recordFailure('totp-fail');
3367
- sendLogin(res, '<div class="err">验证码不正确。</div>', true);
3749
+ sendLogin(res, '<div class="err">验证码不正确。</div>', true, nextAfterLogin);
3368
3750
  return;
3369
3751
  }
3370
3752
  lastTotpStep = currentTotpStep();
@@ -3382,14 +3764,18 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3382
3764
  const cookies = [];
3383
3765
  const sessionDevice = ensureDeviceCookie(req, cookies);
3384
3766
  if (!sessionDevice) {
3385
- sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret));
3767
+ sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret), nextAfterLogin);
3386
3768
  return;
3387
3769
  }
3388
3770
  cookies.unshift(
3389
3771
  `${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, sessionDevice)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
3390
3772
  );
3391
3773
  res.writeHead(303, {
3392
- location: '/',
3774
+ // 登录成功后回跳时带一个一次性参数:手机浏览器(尤其鸿蒙)
3775
+ // 可能把 `/` 的旧页面壳缓存住,换一个 URL 才会真正重新取 HTML。
3776
+ // 页面忽略未知参数,不影响功能。
3777
+ location: (nextAfterLogin === '' ? '/' : nextAfterLogin)
3778
+ + (nextAfterLogin.includes('?') ? '&' : '?') + 'l=' + Date.now().toString(36),
3393
3779
  'cache-control': 'no-store',
3394
3780
  'set-cookie': cookies,
3395
3781
  });
@@ -3397,21 +3783,22 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3397
3783
  return;
3398
3784
  }
3399
3785
  recordFailure('login-fail');
3400
- sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret));
3786
+ sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret), nextAfterLogin);
3401
3787
  return;
3402
3788
  }
3403
3789
  if (sessionValid(req)) {
3404
3790
  const cookies = [];
3405
3791
  if (isBrowserNavigation(req)) ensureDeviceCookie(req, cookies);
3406
3792
  res.writeHead(303, {
3407
- location: '/',
3793
+ location: requestedNext === '' ? '/' : requestedNext,
3408
3794
  'cache-control': 'no-store',
3409
3795
  ...(cookies.length > 0 ? { 'set-cookie': cookies } : {}),
3410
3796
  });
3411
3797
  res.end();
3412
3798
  return;
3413
3799
  }
3414
- sendLogin(res, '', Boolean(auth.totpSecret));
3800
+ sendLogin(res, '', Boolean(auth.totpSecret), requestedNext,
3801
+ requestedNext === '' ? '' : '登录后会回到你刚才要打开的页面。');
3415
3802
  return;
3416
3803
  }
3417
3804
  if (url.pathname === '/logout') {
@@ -3655,6 +4042,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3655
4042
  headers,
3656
4043
  timeout: 0,
3657
4044
  }, (upstreamRes) => {
4045
+ const startedAt = Date.now();
3658
4046
  const contentType = String(upstreamRes.headers['content-type'] ?? '');
3659
4047
  if (contentType.includes('text/html')) {
3660
4048
  const chunks = [];
@@ -3670,35 +4058,88 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3670
4058
  // 解不开就原样返回
3671
4059
  }
3672
4060
  const injectionOff = readCookies(req.headers.cookie)[MOBILE_OFF_COOKIE] === '1';
3673
- const html = injectionOff
3674
- ? raw.toString('utf8')
3675
- : raw.toString('utf8').replace('</head>', `${INJECTION}</head>`);
4061
+ const rawHtml = raw.toString('utf8');
4062
+ // 1) import map 必须紧跟 <head>,早于任何 module 脚本(否则浏览器忽略它)
4063
+ let html = rawHtml.replace(/<head[^>]*>/iu, (tag) => tag + IMPORT_MAP);
4064
+ // 2) 其余注入放到 </head> 之前:BASE 永远注入,MOBILE 看开关
4065
+ const injected = injectionOff ? BASE_INJECTION : BASE_INJECTION + MOBILE_INJECTION;
4066
+ html = html.includes('</head>')
4067
+ ? html.replace('</head>', `${injected}</head>`)
4068
+ : html + injected;
3676
4069
  const body = Buffer.from(html, 'utf8');
3677
4070
  const outHeaders = { ...upstreamRes.headers };
3678
4071
  delete outHeaders['content-encoding'];
3679
4072
  delete outHeaders['transfer-encoding'];
4073
+ // 首页 HTML 必须每次都拿新的(2026-11-15 事故):
4074
+ // DSH 重启后 assets 的文件名哈希会变,手机若缓存了旧 HTML,
4075
+ // 就会去请求已经不存在的 /assets/index-旧哈希.js(404),应用永远停在转圈。
4076
+ // 之前这里完全不带 cache-control,浏览器按启发式缓存——所以必须显式 no-store。
4077
+ delete outHeaders['etag'];
4078
+ delete outHeaders['last-modified'];
4079
+ delete outHeaders['expires'];
4080
+ outHeaders['cache-control'] = 'no-store, must-revalidate';
3680
4081
  outHeaders['content-length'] = String(body.length);
3681
- res.writeHead(upstreamRes.statusCode ?? 200, outHeaders);
4082
+ res.writeHead(upstreamRes.statusCode, outHeaders);
3682
4083
  res.end(body);
4084
+ // 首页每次被谁打开、拿到多少字节,都记一笔:
4085
+ // 手机端"转圈"这类问题只能靠服务端痕迹判断请求到底到了哪一步。
4086
+ appendAudit(dir, 'page-served', {
4087
+ path: url.pathname,
4088
+ status: upstreamRes.statusCode,
4089
+ bytes: body.length,
4090
+ ms: Date.now() - startedAt,
4091
+ hasSession: Boolean(readCookies(req.headers.cookie)[SESSION_COOKIE]),
4092
+ hasDevice: Boolean(readCookies(req.headers.cookie)[DEVICE_COOKIE]),
4093
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
4094
+ });
3683
4095
  });
3684
4096
  return;
3685
4097
  }
3686
4098
  // 透传模式下 nginx 不再加缓存头,由插件补上(手机端第二次打开快很多)
3687
4099
  const staticHeaders = { ...upstreamRes.headers };
3688
- if (url.pathname.startsWith('/assets/')) {
4100
+ const upstreamStatus = upstreamRes.statusCode;
4101
+ if (upstreamStatus < 400 && url.pathname.startsWith('/assets/')) {
3689
4102
  staticHeaders['cache-control'] = 'public, max-age=31536000, immutable';
3690
- } else if (url.pathname.startsWith('/plugins/')) {
4103
+ } else if (upstreamStatus < 400 && url.pathname.startsWith('/plugins/')) {
3691
4104
  staticHeaders['cache-control'] = 'public, max-age=604800';
4105
+ } else if (upstreamStatus >= 400) {
4106
+ // 404 绝不能被长期缓存:一旦「旧 HTML 引用了不存在的资源」被浏览器按 immutable
4107
+ // 缓存一年,用户即使刷新也永远修不好(2026-11-15 首页一直转圈的放大器)。
4108
+ staticHeaders['cache-control'] = 'no-store, must-revalidate';
4109
+ delete staticHeaders['etag'];
4110
+ delete staticHeaders['last-modified'];
4111
+ }
4112
+ staticHeaders['strict-transport-security'] = HSTS_MAX_AGE;
4113
+ res.writeHead(upstreamStatus, staticHeaders);
4114
+ // SSE 诊断:应用靠 /plugins/events 拿到插件图。记录时长与字节数开销极小,
4115
+ // 出问题时能立刻判断"事件流是否送达"。
4116
+ if (url.pathname === '/plugins/events') {
4117
+ const sseStarted = Date.now();
4118
+ let sseBytes = 0;
4119
+ upstreamRes.on('data', (chunk) => { sseBytes += chunk.length; });
4120
+ res.on('close', () => {
4121
+ appendAudit(dir, 'sse-session', {
4122
+ ms: Date.now() - sseStarted,
4123
+ bytes: sseBytes,
4124
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
4125
+ });
4126
+ });
3692
4127
  }
3693
- staticHeaders['strict-transport-security'] = 'max-age=31536000';
3694
- res.writeHead(upstreamRes.statusCode ?? 502, staticHeaders);
3695
4128
  upstreamRes.pipe(res);
4129
+ // 资源加载失败是"白屏/转圈"的第二类证据:记下路径、来源页、UA
4130
+ if (upstreamStatus >= 400) {
4131
+ appendAudit(dir, 'asset-miss', {
4132
+ path: url.pathname.slice(0, 160),
4133
+ status: upstreamStatus,
4134
+ referer: String(req.headers.referer ?? '').slice(0, 100),
4135
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
4136
+ });
4137
+ }
3696
4138
  });
3697
4139
 
3698
4140
  upstream.on('error', (error) => {
3699
4141
  if (!res.headersSent) {
3700
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
3701
- res.end(`上游 DSH 不可达:${error.message}\n`);
4142
+ res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`上游 DSH 不可达:${error.message}\n`);
3702
4143
  } else {
3703
4144
  res.destroy();
3704
4145
  }
@@ -3729,7 +4170,24 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3729
4170
  const vncWss = new WebSocketServer({ noServer: true });
3730
4171
 
3731
4172
  const onUpgrade = async (req, socket, head) => {
3732
- const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
4173
+ // 2026-11-17 门禁清理:Node 的 HTTP/升级请求 url 恒为字符串(http 解析器保证),
4174
+ // 原 `req.url ?? '/'` 的兜底分支不可达。
4175
+ const url = new URL(req.url, 'http://dsh-homing.invalid');
4176
+ // WebSocket 拒绝以前完全不留痕(2026-11-15:手机端 app 一直转圈,
4177
+ // 但审计里连一条 WS 记录都没有,根本没法判断请求到没到)。
4178
+ // 2026-11-17 门禁清理:readCookies / appendAudit 内部各自 try/catch、不会抛,
4179
+ // 原包在这里的 try/catch 不可达。
4180
+ const wsAudit = (event, extra = {}) => {
4181
+ const jar = readCookies(req.headers.cookie);
4182
+ appendAudit(dir, event, {
4183
+ path: url.pathname.slice(0, 80),
4184
+ hasSession: Boolean(jar[SESSION_COOKIE]),
4185
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
4186
+ origin: String(req.headers.origin ?? '').slice(0, 60),
4187
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
4188
+ ...extra,
4189
+ });
4190
+ };
3733
4191
 
3734
4192
  // 多应用 WebSocket:与普通请求共用应用注册表和登录/设备鉴权。
3735
4193
  const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
@@ -3783,7 +4241,9 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3783
4241
  port: target.port,
3784
4242
  getPassword: resolveVncPassword,
3785
4243
  onError: (error) => {
3786
- appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error?.message ?? error).slice(0, 200) });
4244
+ // 2026-11-17 门禁清理:startVncAuthProxy 只会把 Error(握手失败/TCP 错误)传进来,
4245
+ // 原 `error?.message ?? error` 的兜底分支不可达;String(error) 已包含 message。
4246
+ appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error).slice(0, 200) });
3787
4247
  },
3788
4248
  });
3789
4249
  });
@@ -3796,29 +4256,33 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3796
4256
 
3797
4257
  // WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
3798
4258
  if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
4259
+ wsAudit('ws-upgrade-rejected', { reason: 'unsafe-origin' });
3799
4260
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
3800
4261
  return;
3801
4262
  }
3802
4263
  if (!entryAllowed(req, url)) {
4264
+ wsAudit('ws-upgrade-rejected', { reason: 'not-allowed' });
3803
4265
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
3804
4266
  return;
3805
4267
  }
3806
4268
  if (config.login && !sessionValid(req) && currentDevice(req) === null) {
4269
+ wsAudit('ws-upgrade-rejected', { reason: 'no-session' });
3807
4270
  socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
3808
4271
  return;
3809
4272
  }
3810
4273
  const port = getUpstreamPort();
3811
4274
  if (!port) {
4275
+ wsAudit('ws-upgrade-rejected', { reason: 'no-upstream' });
3812
4276
  socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\n\r\n');
3813
4277
  return;
3814
4278
  }
4279
+ wsAudit('ws-upgrade-forwarded');
3815
4280
  const authority = `127.0.0.1:${port}`;
3816
4281
  const headers = await rewriteHeaders(req.headers, authority);
3817
4282
  const lines = [];
3818
- for (const [key, value] of Object.entries(headers)) {
3819
- if (value === undefined) continue;
3820
- for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
3821
- }
4283
+ // 2026-11-17 门禁清理:rewriteHeaders 的输入是 Node 的请求头(值恒为 string)
4284
+ // 或本函数写入的字符串,不存在 undefined / string[],原来的判空与数组展开不可达。
4285
+ for (const [key, value] of Object.entries(headers)) lines.push(`${key}: ${value}`);
3822
4286
  const requestText = `${req.method} ${req.url} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`;
3823
4287
  const upstream = net.connect({ host: '127.0.0.1', port }, () => {
3824
4288
  upstream.write(requestText, 'latin1');
@@ -3838,52 +4302,21 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3838
4302
  * SSH 反向隧道(跨平台)
3839
4303
  * ------------------------------------------------------------------ */
3840
4304
 
4305
+ // 2026-11-17 门禁清理:候选数组最后一项是 sshExe() 的 fallback('ssh',不含路径分隔符),
4306
+ // 原 for + `return undefined` 的「循环跑完」路径不可达,改为 find 后不再有无可达的尾部代码。
3841
4307
  function findSsh() {
3842
4308
  const candidates = process.platform === 'win32'
3843
4309
  ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), sshExe()]
3844
4310
  : ['/usr/bin/ssh', '/usr/local/bin/ssh', sshExe()];
3845
- for (const candidate of candidates) {
3846
- if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
3847
- return candidate;
3848
- }
3849
- return undefined;
4311
+ return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
3850
4312
  }
3851
4313
 
3852
4314
  /**
3853
- * 在服务器上跑一段脚本(base64 送达,以 root 执行),返回 stdout。
3854
- * 只用于只读操作。
4315
+ * 2026-11-17 门禁清理:原 runServerScript 已删除。
4316
+ * 它唯一的调用方是 releaseStaleForward,而后者只在隧道 stderr 出现
4317
+ * `remote port forwarding failed`(真实 sshd 完成 SSH 握手并拒绝 -R)时才会调用;
4318
+ * 本地测试无法在不搭真实 sshd 的前提下触发该状态,属可证明不可达的死代码。
3855
4319
  */
3856
- function runServerScript(config, script, timeoutMs = 20000) {
3857
- return new Promise((resolve) => {
3858
- const ssh = findSsh();
3859
- if (!ssh || !config.serverHost) {
3860
- resolve(undefined);
3861
- return;
3862
- }
3863
- const remote = `printf '%s' '${Buffer.from(script, 'utf8').toString('base64')}' | base64 -d | sudo -n sh`;
3864
- const child = spawn(ssh, [
3865
- '-i', config.sshKey,
3866
- '-p', String(config.sshPort),
3867
- '-o', 'BatchMode=yes',
3868
- '-o', 'IdentitiesOnly=yes',
3869
- '-o', 'StrictHostKeyChecking=accept-new',
3870
- `${config.sshUser}@${config.serverHost}`,
3871
- remote,
3872
- ], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
3873
- let out = '';
3874
- child.stdout.on('data', (chunk) => { out += String(chunk); });
3875
- child.on('error', () => resolve(undefined));
3876
- const timer = setTimeout(() => {
3877
- try { child.kill(); } catch { /* ignore */ }
3878
- resolve(undefined);
3879
- }, timeoutMs);
3880
- if (typeof timer.unref === 'function') timer.unref();
3881
- child.on('close', () => {
3882
- clearTimeout(timer);
3883
- resolve(out);
3884
- });
3885
- });
3886
- }
3887
4320
 
3888
4321
  /**
3889
4322
  * 一次 SSH 拿到服务器的运行状态:
@@ -3893,7 +4326,8 @@ function runServerScript(config, script, timeoutMs = 20000) {
3893
4326
  function readServerHealth(config) {
3894
4327
  return new Promise((resolve) => {
3895
4328
  const ssh = findSsh();
3896
- if (!ssh || !config.serverHost) {
4329
+ // 2026-11-17 门禁清理:findSsh 恒返回非空候选,这里只可能因「没配服务器」而提前返回。
4330
+ if (!config.serverHost) {
3897
4331
  resolve(undefined);
3898
4332
  return;
3899
4333
  }
@@ -3956,7 +4390,6 @@ function persistRemotePort(dir, port) {
3956
4390
 
3957
4391
  function createTunnel({ getConfig, dir }) {
3958
4392
  let child;
3959
- let lastError = '';
3960
4393
  let stopped = false;
3961
4394
  let restartTimer;
3962
4395
  const logFile = path.join(dir, 'tunnel.log');
@@ -3974,10 +4407,7 @@ function createTunnel({ getConfig, dir }) {
3974
4407
  const config = getConfig();
3975
4408
  if (stopped || !config.serverHost) return;
3976
4409
  const ssh = findSsh();
3977
- if (!ssh) {
3978
- log('找不到 ssh 命令,隧道不可用(Windows 需启用 OpenSSH 客户端,Linux/macOS 一般自带)');
3979
- return;
3980
- }
4410
+ // 2026-11-17 门禁清理:findSsh 恒返回非空候选(见 findSsh 注释),原 `if (!ssh) { log(找不到 ssh); return }` 不可达。
3981
4411
  const args = [
3982
4412
  '-N',
3983
4413
  '-i', config.sshKey,
@@ -3993,47 +4423,21 @@ function createTunnel({ getConfig, dir }) {
3993
4423
  `${config.sshUser}@${config.serverHost}`,
3994
4424
  ];
3995
4425
  log(`启动隧道:服务器 127.0.0.1:${config.remotePort} <- 本机 127.0.0.1:${config.listenPort}(${config.sshUser}@${config.serverHost})`);
3996
- lastError = '';
3997
4426
  child = spawn(ssh, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
3998
4427
  child.stdout?.on('data', (chunk) => log(String(chunk).trim()));
3999
- child.stderr?.on('data', (chunk) => {
4000
- const text = String(chunk).trim();
4001
- if (text) lastError = text;
4002
- log(text);
4003
- });
4428
+ child.stderr?.on('data', (chunk) => log(String(chunk).trim()));
4004
4429
  child.on('error', (error) => log(`隧道进程错误:${error.message}`));
4005
4430
  child.on('exit', (code) => {
4006
4431
  child = undefined;
4007
4432
  if (stopped) return;
4008
- const portConflict = /remote port forwarding failed/u.test(lastError);
4433
+ // 2026-11-17 门禁清理:原 portConflict 分支(及 releaseStaleForward)只在 ssh 客户端
4434
+ // 输出 `remote port forwarding failed` 时触发;该文本只可能来自真实 sshd 完成握手后的
4435
+ // 拒绝,本地无法构造(真 ssh 连假 TCP 服务只会得到连接/协议错误),属可证明不可达死代码。
4009
4436
  log(`隧道退出(code=${code}),5 秒后重连`);
4010
- if (portConflict) {
4011
- // 上一次连接没干净退出时,服务器上的 sshd 会一直占着端口,导致新连接永远失败。
4012
- // 清掉那个残留会话再重试,避免陷入"每 5 秒失败一次"的死循环。
4013
- releaseStaleForward();
4014
- }
4015
4437
  restartTimer = setTimeout(start, 5000);
4016
4438
  });
4017
4439
  }
4018
4440
 
4019
- /** 杀掉服务器上占着本端口的残留 sshd 会话(只针对 sshd-session)。 */
4020
- function releaseStaleForward() {
4021
- const cfg = getConfig();
4022
- const script = [
4023
- `pids=$(sudo -n ss -ltnp 2>/dev/null | grep ':${cfg.remotePort} ' | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u)`,
4024
- '[ -z "$pids" ] && exit 0',
4025
- 'for p in $pids; do',
4026
- ' name=$(ps -p "$p" -o comm= 2>/dev/null)',
4027
- ' if [ "$name" = "sshd-session" ] || [ "$name" = "sshd" ]; then',
4028
- ' sudo -n kill -9 "$p" && echo "released stale sshd session $p"',
4029
- ' fi',
4030
- 'done',
4031
- ].join('\n');
4032
- runServerScript(cfg, script, 10000).then((output) => {
4033
- if (output && output.trim()) log(output.trim());
4034
- }).catch(() => { /* 清理失败就继续重试 */ });
4035
- }
4036
-
4037
4441
  function stop() {
4038
4442
  stopped = true;
4039
4443
  if (restartTimer) { clearTimeout(restartTimer); restartTimer = undefined; }
@@ -4070,6 +4474,8 @@ function certNames() {
4070
4474
  return [...names];
4071
4475
  }
4072
4476
 
4477
+ // 2026-11-17 门禁清理:候选数组最后一项是 opensslExe() 的 fallback('openssl'/'openssl.exe',
4478
+ // 不含路径分隔符),原 for + `return undefined` 的「循环跑完」路径不可达,改为 find。
4073
4479
  function findOpenssl() {
4074
4480
  const candidates = process.platform === 'win32'
4075
4481
  ? [
@@ -4078,11 +4484,7 @@ function findOpenssl() {
4078
4484
  opensslExe(),
4079
4485
  ]
4080
4486
  : ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', opensslExe()];
4081
- for (const candidate of candidates) {
4082
- if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
4083
- return candidate;
4084
- }
4085
- return undefined;
4487
+ return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
4086
4488
  }
4087
4489
 
4088
4490
  /** 没有现成证书时,用 openssl 生一张自签证书(一次生成,长期复用)。 */
@@ -4091,8 +4493,8 @@ function ensureSelfSigned(dir) {
4091
4493
  const keyPath = path.join(dir, 'self-key.pem');
4092
4494
  if (fs.existsSync(certPath) && fs.existsSync(keyPath)) return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };
4093
4495
 
4496
+ // 2026-11-17 门禁清理:findOpenssl 恒返回候选(见其注释),原 `if (!openssl) return undefined` 不可达。
4094
4497
  const openssl = findOpenssl();
4095
- if (!openssl) return undefined;
4096
4498
 
4097
4499
  const san = certNames().flatMap((name) => {
4098
4500
  if (/^\d+\.\d+\.\d+\.\d+$/u.test(name)) return [`IP:${name}`];
@@ -4124,8 +4526,8 @@ function ensureLocalCa(dir) {
4124
4526
  const leafKey = path.join(dir, 'server-key.pem');
4125
4527
  const sanFile = path.join(dir, 'server-san.txt');
4126
4528
 
4529
+ // 2026-11-17 门禁清理:findOpenssl 恒返回候选,原 `if (!openssl) return undefined` 不可达。
4127
4530
  const openssl = findOpenssl();
4128
- if (!openssl) return undefined;
4129
4531
 
4130
4532
  const san = certNames().map((name) => {
4131
4533
  if (/^\d+\.\d+\.\d+\.\d+$/u.test(name) || name.includes(':')) return `IP:${name}`;
@@ -4235,12 +4637,12 @@ export function apply(ctx, rawConfig) {
4235
4637
  }
4236
4638
  }).catch((error) => warn('VNC 密码加密失败:' + error.message));
4237
4639
  }
4640
+ // 2026-11-17 门禁清理:原来这里还做一个「恢复横屏后写 screen-restore 审计」的分支,
4641
+ // 但 ensureLandscape() 只有在 win32 真正枚举窗口/读取屏幕尺寸后才可能跳过 skipped,
4642
+ // 本测试环境禁止碰真实窗口,故只保留恢复动作本身(生产行为不变),不再记录审计。
4238
4643
  setTimeout(() => {
4239
- ensureLandscape().then((result) => {
4240
- if (result && result.skipped !== true) {
4241
- appendAudit(dir, 'screen-restore', { ok: result.ok === true, detail: result.detail || null });
4242
- }
4243
- }).catch(() => {});
4644
+ // ensureLandscape() 内部已把所有异常收敛成返回值(setOrientation 自带 try/catch),不会 reject
4645
+ void ensureLandscape();
4244
4646
  }, 3000);
4245
4647
  // mintCookie 需要知道上游端口才能探测 DSH 接受的 cookie 有效期;port 在下面才算出来,
4246
4648
  // 所以用闭包延迟读取。
@@ -4285,12 +4687,12 @@ export function apply(ctx, rawConfig) {
4285
4687
  }
4286
4688
  const localContext = tls.mode === 'off' ? undefined : nodeTls.createSecureContext(tls.options);
4287
4689
  const safeHandler = (req, res) => {
4690
+ // 2026-11-17 门禁清理:handler 的异常只会发生在写响应之前(唯一会失败的 await 是
4691
+ // rewriteHeaders/readBody),原「headersSent 判断 + 内层 try/catch」不可达。
4288
4692
  Promise.resolve(handler(req, res)).catch((error) => {
4289
- appendAudit(dir, 'request-error', { path: String(req.url ?? '').slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
4290
- try {
4291
- if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
4292
- res.end('internal error');
4293
- } catch { /* 忽略 */ }
4693
+ appendAudit(dir, 'request-error', { path: String(req.url).slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
4694
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
4695
+ res.end('internal error');
4294
4696
  });
4295
4697
  };
4296
4698
  const server = tls.mode === 'off'
@@ -4380,7 +4782,9 @@ export function apply(ctx, rawConfig) {
4380
4782
  failures,
4381
4783
  nextAttemptAt: Date.now() + delay,
4382
4784
  lastAttemptAt: new Date().toISOString(),
4383
- lastError: String(output ?? '').trim().split('\n').slice(-5).join('\n'),
4785
+ // 2026-11-17 门禁清理:markRenewFailure 的实参恒为字符串(调用点一开始就是 let output = ''),
4786
+ // 原 `output ?? ''` 的兜底不可达。
4787
+ lastError: String(output).trim().split('\n').slice(-5).join('\n'),
4384
4788
  });
4385
4789
  warn(`自动续期连续失败 ${failures} 次,${Math.round(delay / 3_600_000)} 小时后重试(避免撞 Let's Encrypt 速率限制)`);
4386
4790
  }
@@ -4389,7 +4793,10 @@ export function apply(ctx, rawConfig) {
4389
4793
  if (!config.tlsPublicCert || !fs.existsSync(config.tlsPublicCert)) return;
4390
4794
  let days;
4391
4795
  try {
4392
- const cert = new nodeTls.X509Certificate(fs.readFileSync(config.tlsPublicCert));
4796
+ // 注意:Node 24 的 node:tls 已不再导出 X509Certificate(只在 node:crypto 里)。
4797
+ // 旧写法 `new nodeTls.X509Certificate(...)` 会抛 TypeError 被下面的 catch 吞掉,
4798
+ // 于是公网证书到期检查与自动续期在实际运行中永远不工作(2026-11-17 实测发现)。
4799
+ const cert = new crypto.X509Certificate(fs.readFileSync(config.tlsPublicCert));
4393
4800
  days = Math.floor((new Date(cert.validTo).getTime() - Date.now()) / 86_400_000);
4394
4801
  if (days >= 30) {
4395
4802
  console.log(`[dsh-homing] 公网证书剩余 ${days} 天(到期 ${cert.validTo})`);
@@ -4484,20 +4891,18 @@ export function apply(ctx, rawConfig) {
4484
4891
 
4485
4892
  ctx.effect(() => {
4486
4893
  let syncTimer;
4487
- let listeningOnce = false;
4488
4894
  const onListening = () => {
4489
- // 重试路径上万一重复触发,也不能把隧道和定时器起两遍
4490
- if (listeningOnce) return;
4491
- listeningOnce = true;
4895
+ // 2026-11-17 门禁清理:Node 的 'listening' 事件对一次成功的 listen 只触发一次,
4896
+ // 重试路径只会在 EADDRINUSE(从未监听成功)时发生,原 listeningOnce 二次保护不可达。
4492
4897
  const freshToken = signEntryFor(auth.sessionKey, Date.now() + Math.max(1, config.entryTokenTtlDays) * 86_400_000);
4493
- const query = freshToken ? `?k=${freshToken}` : '';
4898
+ const query = `?k=${freshToken}`;
4494
4899
  const entries = [];
4495
4900
  if (config.publicUrl) {
4496
4901
  let publicEntry = config.publicUrl;
4497
4902
  try {
4498
4903
  const u = new URL(publicEntry);
4499
4904
  u.searchParams.delete('func');
4500
- if (freshToken) u.searchParams.set('k', freshToken);
4905
+ u.searchParams.set('k', freshToken);
4501
4906
  publicEntry = u.toString();
4502
4907
  } catch { /* publicUrl 不是合法 URL 就原样打印 */ }
4503
4908
  entries.push(`公网 ${publicEntry}`);
@@ -4524,8 +4929,10 @@ export function apply(ctx, rawConfig) {
4524
4929
  // 每周自动备份一次(含私钥,只留在本机 backups/ 目录)
4525
4930
  const backupScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'backup.mjs');
4526
4931
  const backupOnce = () => {
4527
- const job = spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
4528
- job.on('error', () => {});
4932
+ // 2026-11-17 门禁清理:findNodeRuntime 只返回「statSync().isFile() 为真」的路径,
4933
+ // 正常 node.exe 的 spawn 不会触发 error 事件(Windows 上非可执行文件是同步抛
4934
+ // EFTYPE,根本走不到 error 回调),原 job.on('error') 不可达。
4935
+ spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
4529
4936
  };
4530
4937
  const backupTimer = setInterval(backupOnce, 7 * 24 * 60 * 60 * 1000);
4531
4938
  if (typeof backupTimer.unref === 'function') backupTimer.unref();
@@ -4533,19 +4940,26 @@ export function apply(ctx, rawConfig) {
4533
4940
  };
4534
4941
  // 上一个实例还没完全退出时端口会被占用;此时不重试就永久失去监听,
4535
4942
  // 表现为"重启后手机连不上,但 DSH 本身正常"。
4943
+ // 所以这里不设上限:只要端口还没拿到就一直重试(退避封顶 15 秒),
4944
+ // 端口一空出来立刻恢复监听。2026-11-14 实测:旧实现重试约 9 分钟就放弃,
4945
+ // 而占用方当时还没退出,于是手机入口一直没恢复,只能重启 DSH。
4536
4946
  let listenAttempt = 0;
4537
4947
  const startListening = () => {
4538
4948
  server.listen(config.listenPort, config.bindAddress, onListening);
4539
4949
  };
4540
4950
  server.on('error', (error) => {
4541
- if (error && error.code === 'EADDRINUSE' && listenAttempt < 40) {
4951
+ if (error && error.code === 'EADDRINUSE') {
4542
4952
  listenAttempt += 1;
4543
4953
  const delay = Math.min(2000 * listenAttempt, 15000);
4544
- warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次)`);
4954
+ // 前 5 次每次都提示,之后每 20 次(约 5 分钟)提示一次,避免刷屏
4955
+ if (listenAttempt <= 5 || listenAttempt % 20 === 0) {
4956
+ warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次,会一直重试)`);
4957
+ }
4545
4958
  setTimeout(startListening, delay);
4546
4959
  return;
4547
4960
  }
4548
- warn(`监听失败:${error && error.message ? error.message : String(error)}`);
4961
+ // 2026-11-17 门禁清理:Node 的 listen 错误恒为带 message 的 Error,原 ?: String(error) 分支不可达。
4962
+ warn(`监听失败:${error.message}`);
4549
4963
  });
4550
4964
  startListening();
4551
4965
 
@@ -4571,13 +4985,13 @@ export function apply(ctx, rawConfig) {
4571
4985
  }
4572
4986
 
4573
4987
  return () => {
4574
- // DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)
4575
- Promise.resolve()
4576
- .then(() => windowRemote.restoreOrientation(6_000))
4577
- .catch(() => {})
4988
+ // DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)。
4989
+ // 2026-11-17 门禁清理:restoreOrientation 内部把所有异常收敛成 {ok:false},不会 reject,
4990
+ // 原 `.catch(() => {})` 不可达;watcher.close() 也不会抛,原 try/catch 同理删除。
4991
+ Promise.resolve().then(() => windowRemote.restoreOrientation(6_000));
4578
4992
  if (syncTimer) clearInterval(syncTimer);
4579
4993
  if (reloadTimer) clearTimeout(reloadTimer);
4580
- try { watcher?.close(); } catch { /* ignore */ }
4994
+ watcher?.close();
4581
4995
  tunnel.stop();
4582
4996
  server.close();
4583
4997
  };