@andy.ian/dsh-homing 2.1.15 → 2.3.0

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.
Files changed (51) hide show
  1. package/README.md +151 -110
  2. package/SECURITY.md +3 -0
  3. package/bin/restart-daemon.mjs +0 -0
  4. package/bin/restart.mjs +0 -0
  5. package/index.js +904 -601
  6. package/lib/app-proxy.mjs +262 -0
  7. package/lib/auth-guard.js +57 -0
  8. package/lib/client-report.js +168 -0
  9. package/lib/compress.mjs +3 -2
  10. package/lib/csrf.mjs +38 -0
  11. package/lib/debug-page.js +150 -0
  12. package/lib/exec-path.mjs +9 -1
  13. package/lib/files-page.mjs +3 -3
  14. package/lib/files.mjs +14 -15
  15. package/lib/format-age.mjs +32 -0
  16. package/lib/git.mjs +37 -19
  17. package/lib/idb-fallback.js +140 -0
  18. package/lib/local-apps-page.mjs +64 -0
  19. package/lib/local-apps.mjs +275 -0
  20. package/lib/markdown.mjs +6 -4
  21. package/lib/mobile-patch.mjs +429 -0
  22. package/lib/nav.mjs +1 -0
  23. package/lib/netdiag.js +211 -0
  24. package/lib/node-runtime.mjs +30 -13
  25. package/lib/office.mjs +42 -20
  26. package/lib/orientation.mjs +88 -53
  27. package/lib/pty.mjs +2 -9
  28. package/lib/recover.js +66 -0
  29. package/lib/secret.mjs +25 -9
  30. package/lib/shells.mjs +2 -2
  31. package/lib/vendor/vnc.bundle.js +189 -73
  32. package/lib/vnc-app.js +112 -23
  33. package/lib/vnc-auth-proxy.mjs +5 -2
  34. package/lib/vnc-boot.js +1 -1
  35. package/lib/vnc-keyboard.mjs +3 -3
  36. package/lib/vnc-page.mjs +34 -4
  37. package/lib/vnc-probe.mjs +46 -0
  38. package/lib/window-follow.mjs +66 -0
  39. package/lib/window-remote.mjs +266 -192
  40. package/lib/ws-bridge.mjs +6 -3
  41. package/package.json +2 -2
  42. package/permissions.json +7 -0
  43. package/restart/client.mjs +20 -1
  44. package/restart/daemon/README.md +22 -0
  45. package/restart/daemon/lib/detach.mjs +11 -5
  46. package/restart/daemon/lib/restart-flow.mjs +26 -12
  47. package/restart/daemon/lib/update-state.mjs +118 -1
  48. package/restart/daemon/main.mjs +68 -20
  49. package/restart/runner.mjs +9 -5
  50. package/restart/service.mjs +4 -3
  51. package/restart/watchdog.mjs +8 -2
package/index.js CHANGED
@@ -40,15 +40,21 @@ import { protectSecret, unprotectSecret } from './lib/secret.mjs';
40
40
  import { startVncAuthProxy } from './lib/vnc-auth-proxy.mjs';
41
41
  import { renderWindowPage } from './lib/window-page.mjs';
42
42
  import * as vnc from './lib/vnc.mjs';
43
+ import { probeVnc } from './lib/vnc-probe.mjs';
43
44
  import { bridge as bridgeWebSocketToTcp } from './lib/ws-bridge.mjs';
44
45
  import { WebSocketServer } from './lib/vendor/ws/wrapper.mjs';
45
46
  import { renderVncPage } from './lib/vnc-page.mjs';
46
47
  import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
47
48
  import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
48
- import { checkUnsafeOrigin } from './lib/csrf.mjs';
49
+ import { checkUnsafeOrigin, checkOwnPageWrite } from './lib/csrf.mjs';
49
50
  import { validateOpenPath } from './lib/guard.mjs';
50
51
  import { opensslExe, sshExe } from './lib/exec-path.mjs';
51
52
  import * as limits from './lib/limits.mjs';
53
+ import { createLocalAppRegistry, matchAppPath, probeAppPort } from './lib/local-apps.mjs';
54
+ import { proxyLocalAppHttp, proxyLocalAppUpgrade } from './lib/app-proxy.mjs';
55
+ import { renderLocalAppsPage } from './lib/local-apps-page.mjs';
56
+ import { MOBILE_CSS, MOBILE_JS } from './lib/mobile-patch.mjs';
57
+ import { formatAge } from './lib/format-age.mjs';
52
58
 
53
59
  export const name = 'dsh-homing';
54
60
 
@@ -101,7 +107,8 @@ const DEFAULT_CONFIG = {
101
107
  };
102
108
 
103
109
  function normalizeConfig(raw) {
104
- const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) };
110
+ // 所有调用点都传对象(apply 里传 {...rawConfig, ...readSettings()}),raw 不可能为空,去掉防御兜底
111
+ const config = { ...DEFAULT_CONFIG, ...raw };
105
112
  config.sshPort = Number(config.sshPort) || 22;
106
113
  config.listenPort = Number(config.listenPort) || 8787;
107
114
  // 服务器侧端口与 nginx 的 proxy_pass 必须一致,默认固定 8787;本机 listenPort 可以单独改
@@ -344,8 +351,8 @@ function createCookieMinter(credentials, getUpstreamPort) {
344
351
  const hit = ttlByAuthority.get(authority);
345
352
  // 一小时内复用;DSH 上限变化只会发生在它自己重启之后,那时 authority 也会变
346
353
  if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.ttlMs;
354
+ // 代理请求进入 mint 前已通过 getUpstreamPort() 的非空检查(handler 里 !port 会先回 503),port 必为真
347
355
  const port = getUpstreamPort();
348
- if (!port) return COOKIE_TTL_FALLBACK_MS;
349
356
  for (const ttlMs of COOKIE_TTL_CANDIDATES_MS) {
350
357
  const accepted = await probeCookieAccepted({
351
358
  port,
@@ -370,302 +377,58 @@ function createCookieMinter(credentials, getUpstreamPort) {
370
377
  }
371
378
 
372
379
  /* ------------------------------------------------------------------ *
373
- * 移动端补丁
380
+ * 移动端补丁:MOBILE_CSS / MOBILE_JS 在 lib/mobile-patch.mjs,单独成文件
381
+ * 以便用真实 DOM 桩做行为测试(见 test/unit.mobile-patch.test.mjs)。
374
382
  * ------------------------------------------------------------------ */
375
383
 
376
- const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
377
- @media (max-width: 760px) {
378
- [class*="_frame"] { min-width: 0; }
379
- }
380
- `;
381
-
382
- const MOBILE_JS = `(() => {
383
- const narrow = () => window.innerWidth <= 760
384
- const root = document.documentElement
385
- const sidebar = () => document.querySelector('[class*="sidebarCol"]')
386
- // 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
387
- // 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
388
- const LAST_WS_KEY = 'dsh-homing:last-workspace'
389
- document.addEventListener('click', (event) => {
390
- const node = event.target
391
- if (node === null || typeof node.closest !== 'function') return
392
- const item = node.closest('[role="menuitem"]')
393
- const side = node.closest('[class*="sidebarCol"]')
394
- const candidate = item ?? (side === null ? null : node.closest('button, [role="treeitem"], [class*="session"], [class*="item"], div'))
395
- if (candidate === null) return
396
- const text = (candidate.textContent || '').replace(/\s+/g, ' ').trim()
397
- if (text === '' || text.length > 40) return
398
- // 排除操作类菜单项,只记看起来像工作区名字的
399
- if (/文件资源管理器|VS Code|Git Bash|添加工作区|新会话|搜索|设置|插件|自动化任务|更多|账号|退出/u.test(text)) return
400
- try { window.localStorage.setItem(LAST_WS_KEY, text) } catch { /* 隐私模式 */ }
401
- }, true)
402
-
403
- // 标题栏里那个「文件夹 + 小箭头」是分裂按钮:
404
- // 点箭头出菜单(我们已按文字拦截),点文件夹图标则直接在本机打开目录,手机上看不到。
405
- // 这里按结构识别:带 aria-haspopup 的按钮和文件夹图标在同一个父容器里,
406
- // 那么点这个容器里的任何按钮,都按"打开工作区目录"处理。
407
- const folderHost = () => {
408
- for (const node of document.querySelectorAll('[aria-haspopup]')) {
409
- const rect = node.getBoundingClientRect()
410
- if (rect.width === 0 || rect.height === 0) continue
411
- if (rect.top > 130) continue
412
- const host = node.parentElement
413
- if (host === null) continue
414
- const buttons = host.querySelectorAll('button, [role="button"]')
415
- if (buttons.length > 0 && buttons.length <= 3) return host
416
- }
417
- return null
418
- }
419
-
420
- // 当前会话标题:从标题栏(页面顶部、class 里带 title/tab/header 的元素)取最长的文本。
421
- // 用它去反查会话记录里的 cwd,就能打开"当前会话所属工作区"的目录。
422
- const currentSessionTitle = () => {
423
- let best = ''
424
- for (const node of document.querySelectorAll('div, span, h1, h2, header')) {
425
- const rect = node.getBoundingClientRect()
426
- if (rect.width === 0 || rect.height === 0) continue
427
- if (rect.top > 120 || rect.height > 44) continue
428
- const cls = String(node.className || '')
429
- if (!/title|tab|header|crumb|label/iu.test(cls)) continue
430
- const text = (node.textContent || '').trim()
431
- if (text.length < 2 || text.length > 60) continue
432
- if (text.length > best.length) best = text
433
- }
434
- return best
435
- }
436
-
437
- // 应用把"当前会话"存在 localStorage 里,直接读它 —— 这是确定值,不靠猜。
438
- const currentSessionId = () => {
439
- try {
440
- const raw = window.localStorage.getItem('dsh.sessions.current')
441
- if (raw === null) return ''
442
- const parsed = JSON.parse(raw)
443
- const id = parsed && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
444
- return /^session-[A-Za-z0-9-]+$/u.test(id) ? id : ''
445
- } catch {
446
- return ''
447
- }
448
- }
449
-
450
- const goFiles = () => {
451
- const session = currentSessionId()
452
- if (session !== '') {
453
- window.location.href = '/files?session=' + encodeURIComponent(session)
454
- return
455
- }
456
- let hint = ''
457
- try { hint = currentSessionTitle() || window.localStorage.getItem('dsh-homing:last-workspace') || '' } catch { hint = '' }
458
- window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
459
- }
460
-
461
- document.addEventListener('click', (event) => {
462
- const host = folderHost()
463
- if (host === null) return
464
- const target = event.target
465
- if (target === null || typeof target.closest !== 'function') return
466
- const button = target.closest('button, [role="button"]')
467
- if (button === null || !host.contains(button)) return
468
- // 带 aria-haspopup 的是那个小箭头:放行,让应用的菜单正常弹出。
469
- // 菜单里的「文件资源管理器」由另一段按文字拦截。
470
- if (button.hasAttribute('aria-haspopup')) return
471
- event.preventDefault()
472
- event.stopPropagation()
473
- goFiles()
474
- }, true)
475
-
476
- // 应用下拉里的「文件资源管理器 / VS Code / Git Bash」是在本机启动桌面程序,
477
- // 手机上看不到。这里把「文件资源管理器」接到我们的 /files 页面;
478
- // 另外两项给一条提示,避免点了没反应。
479
- const desktopOnly = (event) => {
480
- const node = event.target
481
- if (node === null || typeof node.closest !== 'function') return
482
- const item = node.closest('[role="menuitem"], button, li, div')
483
- const text = item === null ? '' : (item.textContent || '').trim()
484
- if (text === '') return
485
- if (text.includes('文件资源管理器')) {
486
- event.preventDefault()
487
- event.stopPropagation()
488
- // 尽量从属性里挖工作区路径,挖不到就让文件页自己决定默认目录
489
- let target = ''
490
- for (const holder of [item, ...(item.querySelectorAll('[data-path], [title]') || [])]) {
491
- if (holder === null) continue
492
- const dataPath = holder.getAttribute && holder.getAttribute('data-path')
493
- const title = holder.getAttribute && holder.getAttribute('title')
494
- if (dataPath) { target = dataPath; break }
495
- if (title && /^[A-Za-z]:[\\/]|^\//u.test(title)) { target = title; break }
496
- }
497
- // 带上当前选中的工作区名,服务端会映射成路径;映射不到就落到默认工作区
498
- let remembered = ''
499
- try { remembered = window.localStorage.getItem(LAST_WS_KEY) || '' } catch { /* 隐私模式 */ }
500
- const selected = remembered !== '' ? remembered : (() => {
501
- const side = document.querySelector('[class*="sidebarCol"]')
502
- if (side === null) return ''
503
- let best = ''
504
- for (const node of side.querySelectorAll('[class*="selected"], [class*="active"], [aria-current]')) {
505
- const text = (node.textContent || '').trim()
506
- if (text === '' || text.length > 40) continue
507
- if (best === '' || text.length < best.length) best = text
508
- }
509
- return best
510
- })()
511
- const session = currentSessionId()
512
- const query = target ? '?path=' + encodeURIComponent(target)
513
- : session !== '' ? '?session=' + encodeURIComponent(session)
514
- : '?hint=' + encodeURIComponent(currentSessionTitle() || selected || '')
515
- window.location.href = '/files' + query
516
- return
517
- }
518
- if (text.includes('VS Code')) {
519
- // 手机上用文件页 + 编辑功能代替(点文件旁的 ✏️ 可改可存)
520
- event.preventDefault()
521
- event.stopPropagation()
522
- const session = currentSessionId()
523
- window.location.href = '/files' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
524
- return
525
- }
526
- if (text.includes('Git Bash')) {
527
- // 手机上用 /git 页代替:可执行任意 git 命令
528
- event.preventDefault()
529
- event.stopPropagation()
530
- const session = currentSessionId()
531
- window.location.href = '/term' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
532
- return
533
- }
534
- }
535
- document.addEventListener('click', desktopOnly, true)
536
-
537
- let lastRight = 0
538
- const closeRightBar = () => {
539
- if (!narrow()) return
540
- if (document.querySelector('[data-rightbar-collapsed="false"]') === null) return
541
- if (Date.now() - lastRight < 2500) return
542
- const button = document.querySelector('[aria-label="收起右侧边栏"]')
543
- if (button === null) return
544
- lastRight = Date.now()
545
- button.click()
546
- }
547
-
548
- const start = () => {
549
- closeRightBar()
550
- }
551
-
552
- /* ---------- SESSION_MENU_ITEMS ----------
553
- * 在 DSH 会话「…」菜单里追加两项:
554
- * - 下载工作区文件:跳到文件页(可逐个文件下载)
555
- * - 重启 DSH / 守护进程:跳到重启页
556
- * 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
557
- * 每轮先清掉旧项,并全局 prune,保证每项最多一个。
558
- */
559
- const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
560
- const ICON_RESTART = '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
561
- const ICON_DOWNLOAD = '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/>'
562
- let menuTimer = null
563
-
564
- const textNodeMatching = (node, pattern) => {
565
- const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
566
- for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
567
- if (pattern.test(current.nodeValue || '')) return current
568
- }
569
- return null
570
- }
571
-
572
- const buildMenuItem = (template, label, icon, action) => {
573
- const link = template.cloneNode(true)
574
- link.setAttribute('role', 'menuitem')
575
- link.setAttribute('href', '#')
576
- link.style.textDecoration = 'none'
577
- const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
578
- if (textNode !== null) textNode.nodeValue = label
579
- else link.textContent = label
580
- const svg = link.querySelector('svg')
581
- if (svg !== null) {
582
- svg.innerHTML = icon
583
- svg.setAttribute('viewBox', '0 0 24 24')
584
- svg.setAttribute('fill', 'none')
585
- svg.setAttribute('stroke', 'currentColor')
586
- svg.setAttribute('stroke-width', '2')
587
- svg.setAttribute('stroke-linecap', 'round')
588
- svg.setAttribute('stroke-linejoin', 'round')
589
- }
590
- link.addEventListener('click', (event) => {
591
- event.preventDefault()
592
- event.stopPropagation()
593
- action()
594
- }, true)
595
- return link
596
- }
597
-
598
- const enhanceMenus = () => {
599
- const done = new Set()
600
- for (const item of document.querySelectorAll('[role="menuitem"]')) {
601
- const menu = item.closest('[role="menu"]') ?? item.parentElement
602
- if (menu === null || done.has(menu)) continue
603
- if (!MENU_HINT.test(menu.textContent || '')) continue
604
- done.add(menu)
605
-
606
- for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
607
-
608
- const items = [...menu.querySelectorAll('[role="menuitem"]')]
609
- const template = items.find((node) => node.querySelector('svg')) ?? items[0]
610
- if (!template) continue
611
-
612
- const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
613
- download.setAttribute('data-dsh-homing-download', '1')
614
- const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
615
- restart.setAttribute('data-dsh-homing-restart', '1')
616
-
617
- menu.appendChild(download)
618
- menu.appendChild(restart)
619
- }
620
- }
621
-
622
- // 兜底:无论菜单容器怎么嵌套,每类最多保留一个
623
- const pruneMenuItems = () => {
624
- for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
625
- const all = [...document.querySelectorAll(selector)]
626
- for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
627
- }
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;
628
394
  }
395
+ }
629
396
 
630
- const menuObserver = new MutationObserver(() => {
631
- if (menuTimer) return
632
- menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
633
- })
634
- menuObserver.observe(document.body, { childList: true, subtree: true })
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');
635
400
 
636
- /* ---------- ALIVE_BEACON ----------
637
- * 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
638
- * 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
639
- * 节流 2 秒,页面隐藏时不发(后台标签页不算活跃)。
640
- */
641
- const ALIVE_INTERVAL = 2000
642
- let aliveAt = 0
643
- const alive = () => {
644
- const now = Date.now()
645
- if (now - aliveAt < ALIVE_INTERVAL) return
646
- aliveAt = now
647
- try {
648
- if (document.visibilityState === 'hidden') return
649
- const body = JSON.stringify({ at: now, path: location.pathname })
650
- if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
651
- else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
652
- } catch (error) {
653
- /* 忽略 */
654
- }
655
- }
656
- document.addEventListener('keydown', alive, true)
657
- document.addEventListener('pointerdown', alive, true)
658
- document.addEventListener('input', alive, true)
659
- document.addEventListener('compositionstart', alive, true)
660
- window.addEventListener('focus', alive, true)
661
-
662
- if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
663
- else start()
664
- })();
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>';
665
421
 
666
- `;
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>';
667
429
 
668
- const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
430
+ const MOBILE_INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css">'
431
+ + '<script defer src="/dsh_homing/mobile.js"></script>';
669
432
 
670
433
  // 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
671
434
  // 调试页上一键即可设置,页面坏了也点得到。
@@ -784,7 +547,8 @@ function startRestartDaemonDetached() {
784
547
  return false;
785
548
  }
786
549
  const child = spawn(findNodeRuntime(), [cli, 'start'], { detached: true, stdio: 'ignore', windowsHide: true });
787
- 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) }); });
788
552
  child.unref();
789
553
  return true;
790
554
  } catch {
@@ -797,9 +561,8 @@ const restartDaemonWatchdog = createRestartDaemonWatchdog({
797
561
  service: restartService,
798
562
  pluginRoot: path.dirname(fileURLToPath(import.meta.url)),
799
563
  dshHome: process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'),
800
- audit: (event, extra) => {
801
- try { appendAudit(dataDir(), event, extra ?? {}); } catch { /* 忽略 */ }
802
- },
564
+ // watchdog 只会传对象({pid}/{stopped}/{}),appendAudit 内部也自带 try/catch:extra ?? {} 与 catch 都不可达
565
+ audit: (event, extra) => appendAudit(dataDir(), event, extra),
803
566
  });
804
567
  void restartDaemonWatchdog;
805
568
 
@@ -807,12 +570,12 @@ void restartDaemonWatchdog;
807
570
  const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
808
571
  + `<script src="/dsh_homing/restart.js"></script>`;
809
572
 
810
- function renderRestartPage({ status, sessions, message, confirmForce, portState }) {
573
+ function renderRestartPage({ status, sessions, message, confirmForce, portState, daemonVersion, staleDaemon }) {
811
574
  const running = status?.running ?? false
812
575
  const paused = status?.paused ?? false
813
576
  const left = status?.pausedSecondsLeft ?? 0
814
577
  const busy = sessions.length > 0
815
- 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('')
816
579
 
817
580
  const confirmBlock = confirmForce
818
581
  ? '<div class="card warn"><div class="line"><span class="k">确认强制重启</span><span class="v">' + sessions.length + ' 个会话运行中</span></div>'
@@ -846,7 +609,8 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
846
609
  })()
847
610
 
848
611
  const policy = restartPolicy.status()
849
- const cfg = policy?.config ?? {}
612
+ // runner 的 status() 恒返回对象且带 config 对象:可选链与 ?? {} 不可达
613
+ const cfg = policy.config
850
614
  const nav = topNav()
851
615
 
852
616
  return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
@@ -880,9 +644,17 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
880
644
  + (message ? '<div class="msg" id="restart-msg">' + escapeHtml(message) + '</div>' : '')
881
645
  + confirmBlock
882
646
  + '<div class="card">'
883
- + '<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
+ : '')
884
655
  + '<div class="line"><span class="k">重启队列</span><span class="v" id="queue-state">' + (policy?.active ? ('排队中 · ' + escapeHtml(policy.reason || '等待空闲')) : '未排队') + '</span></div>'
885
- + '<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>'
886
658
  + '<div class="line"><span class="k">繁忙</span><span class="v" id="busy-state">' + (busy ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
887
659
  + '<ul id="busy-list">' + busyItems + '</ul>'
888
660
  + LIVE_SCRIPT
@@ -914,6 +686,25 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
914
686
  + '</body></html>'
915
687
  }
916
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
+
917
708
  const DEBUG_HTML = `<!doctype html>
918
709
  <html lang="zh-CN"><head><meta charset="utf-8">
919
710
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -925,6 +716,7 @@ const DEBUG_HTML = `<!doctype html>
925
716
  h1 { font-size: 19px; margin: 6px 0 2px; }
926
717
  h2 { font-size: 14px; margin: 26px 0 8px; color:#9aa4b2; font-weight: 600; }
927
718
  .sub { color:#8b93a1; font-size: 13px; margin: 4px 0 0; }
719
+ .err { color:#ff9b9b; }
928
720
  .card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:14px; margin-top:10px; }
929
721
  .row { display:flex; justify-content:space-between; gap:12px; padding:6px 0; font-size:13px; border-bottom:1px solid #21262f; }
930
722
  .row:last-child { border-bottom:0; }
@@ -979,6 +771,15 @@ const DEBUG_HTML = `<!doctype html>
979
771
  {{shots}}
980
772
  </div>
981
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
+
982
783
  <h2>诊断</h2>
983
784
  <div class="card">
984
785
  <div class="row"><span class="k">样式文件</span><span class="v">{{cssInfo}}</span></div>
@@ -995,45 +796,8 @@ const DEBUG_HTML = `<!doctype html>
995
796
  <a class="btn ghost" href="/logout">退出登录</a>
996
797
  </div>
997
798
  </div>
998
- <script>
999
- (() => {
1000
- const input = document.getElementById('file')
1001
- const button = document.getElementById('send')
1002
- const result = document.getElementById('result')
1003
- if (!input || !button || !result) return
1004
- button.addEventListener('click', async () => {
1005
- const file = input.files && input.files[0]
1006
- if (!file) { result.textContent = '先选一张图片。'; return }
1007
- if (file.size > 12 * 1024 * 1024) { result.textContent = '图片太大(上限 12MB)。'; return }
1008
- result.textContent = '读取中…'
1009
- const dataUrl = await new Promise((resolve, reject) => {
1010
- const reader = new FileReader()
1011
- reader.onload = () => resolve(String(reader.result))
1012
- reader.onerror = () => reject(new Error('读取失败'))
1013
- reader.readAsDataURL(file)
1014
- }).catch((error) => { result.textContent = error.message; return null })
1015
- if (!dataUrl) return
1016
- result.textContent = '上传中…'
1017
- try {
1018
- const res = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
1019
- method: 'POST',
1020
- headers: { 'content-type': 'application/json' },
1021
- body: JSON.stringify({ name: file.name, dataUrl }),
1022
- })
1023
- const text = await res.text()
1024
- if (!res.ok) { result.textContent = '失败:' + text.slice(0, 200); return }
1025
- const data = JSON.parse(text)
1026
- result.innerHTML = '已保存:<code>' + data.file + '</code>'
1027
- const img = document.createElement('img')
1028
- img.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
1029
- img.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
1030
- document.querySelector('.shots')?.appendChild(img) ?? result.appendChild(img)
1031
- } catch (error) {
1032
- result.textContent = '网络错误:' + error.message
1033
- }
1034
- })
1035
- })()
1036
- </script>
799
+ <script src="/dsh_homing/netdiag.js" defer></script>
800
+ <script src="/dsh_homing/debug.js" defer></script>
1037
801
  </body></html>
1038
802
  `;
1039
803
 
@@ -1134,14 +898,20 @@ function sessionRunning(dshHomeDir) {
1134
898
  async function collectRestartState(dataDir) {
1135
899
  const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
1136
900
  const status = await restartService.status();
901
+ const health = await restartService.health();
1137
902
  const policyStatus = restartPolicy.status();
1138
- 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;
1139
908
  return {
1140
909
  config,
1141
910
  policy: {
1142
911
  active: policyStatus?.active === true,
1143
- reason: policyStatus?.reason ?? '',
1144
- waitedSeconds: policyStatus?.waitedSeconds ?? 0,
912
+ // runner 的 status() 保证 reason 是字符串、waitedSeconds 是数字,不需要 ?? 兜底
913
+ reason: policyStatus.reason,
914
+ waitedSeconds: policyStatus.waitedSeconds,
1145
915
  busy: policyStatus?.busy === true,
1146
916
  },
1147
917
  running: status?.running ?? false,
@@ -1149,6 +919,8 @@ async function collectRestartState(dataDir) {
1149
919
  paused: status?.paused ?? false,
1150
920
  pausedSecondsLeft: status?.pausedSecondsLeft ?? 0,
1151
921
  busy: sessions.length > 0,
922
+ daemonVersion,
923
+ staleDaemon,
1152
924
  sessions: sessions.map((s) => ({ title: s.title || '', cwd: s.cwd || '', age: s.age })),
1153
925
  };
1154
926
  }
@@ -1166,7 +938,8 @@ async function broadcastRestartState(dataDir, extra) {
1166
938
  lastPayload = payload;
1167
939
  lastPushAt = now;
1168
940
  for (const res of [...sseClients]) {
1169
- 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')
1170
943
  }
1171
944
  }
1172
945
 
@@ -1310,7 +1083,7 @@ function base32Encode(buffer) {
1310
1083
  bits -= 5;
1311
1084
  }
1312
1085
  }
1313
- if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
1086
+ // 两个调用点都是 5 字节的倍数(40/160 bit),bits 恒为 0,无需补尾巴
1314
1087
  return out;
1315
1088
  }
1316
1089
 
@@ -1349,10 +1122,12 @@ const LOGIN_HTML = `<!doctype html>
1349
1122
  <label for="p">密码</label>
1350
1123
  <input id="p" name="password" type="password" autocomplete="current-password" required>
1351
1124
  {{totp}}
1125
+ {{next}}
1352
1126
  <button type="submit">登录</button>
1353
1127
  </form>
1354
1128
  {{message}}
1355
1129
  <div class="hint">登录一次后 3 天内免登录 · <a href="/dsh_homing/reset" style="color:#7aa7ff">忘记密码?</a></div>
1130
+ {{hint}}
1356
1131
  </div></body></html>`;
1357
1132
 
1358
1133
  const RESET_HTML = `<!doctype html>
@@ -1401,7 +1176,16 @@ const RESET_HTML = `<!doctype html>
1401
1176
  const TOTP_FIELD = `<label for="c">验证码</label>
1402
1177
  <input id="c" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]*" maxlength="6" placeholder="验证器里的 6 位数字" required>`;
1403
1178
 
1404
- 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 = '') {
1405
1189
  res.writeHead(200, {
1406
1190
  'content-type': 'text/html; charset=utf-8',
1407
1191
  'cache-control': 'no-store',
@@ -1411,22 +1195,42 @@ function sendLogin(res, message = '', requireTotp = false) {
1411
1195
  'x-content-type-options': 'nosniff',
1412
1196
  'referrer-policy': 'no-referrer',
1413
1197
  });
1414
- 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
+ );
1415
1207
  }
1416
1208
 
1417
1209
  /**
1418
- * 登录限速用的客户端标识。
1419
- * 经隧道进来时 socket 一律是 127.0.0.1,真正的来源在 nginx 写的 X-Forwarded-For 里;
1420
- * 只有 socket 是回环时才信任该头,避免局域网客户端伪造它绕过限速。
1210
+ * 读请求体,但**超限时不粗暴断开**。
1211
+ *
1212
+ * 旧实现 readBody 一旦超限就 req.destroy():客户端正在上传时连接被重置,
1213
+ * 浏览器只看到 ECONNRESET,页面上什么都不显示——用户看到的就是"点上传没反应"。
1214
+ * 这里改为把剩余数据读完(drain)再返回 { overflow: true },让调用方能回一个
1215
+ * 正常的 413 JSON,客户端就能看到"图片太大"而不是白屏。
1421
1216
  */
1422
- function clientKey(req) {
1423
- const socket = req.socket.remoteAddress ?? '';
1424
- const isLoopback = socket === '::1' || socket === '127.0.0.1' || socket.startsWith('::ffff:127.');
1425
- if (isLoopback) {
1426
- const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
1427
- if (forwarded) return forwarded;
1428
- }
1429
- 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
+ });
1430
1234
  }
1431
1235
 
1432
1236
  function readBodyBuffer(req, limit) {
@@ -1511,6 +1315,10 @@ function verifyTotp(secret, code, lastStep) {
1511
1315
  }
1512
1316
 
1513
1317
  function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCookies, caCertPath }) {
1318
+ const appRegistry = createLocalAppRegistry({
1319
+ settingsPath: path.join(dir, 'settings.json'),
1320
+ deniedPorts: () => [config.listenPort, restartDaemonPort, getUpstreamPort()],
1321
+ });
1514
1322
  const loginFailures = new Map();
1515
1323
  // 记住上一次验证码用过的时间步,防止同一个 6 位码在 30 秒窗口内被重放
1516
1324
  let lastTotpStep = 0;
@@ -1555,9 +1363,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1555
1363
  }
1556
1364
 
1557
1365
 
1558
- /** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。 */
1366
+ /** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。
1367
+ * value 只会是 string:两个调用点都是 `if (token && entryExpiry(token) > 0)`,
1368
+ * searchParams.get() 的 null 已被短路挡掉(门禁证明 typeof 兜底不可达)。 */
1559
1369
  function entryExpiry(value) {
1560
- if (typeof value !== 'string') return 0;
1561
1370
  const [body, mac] = value.split('.');
1562
1371
  if (!body || !mac) return 0;
1563
1372
  const expected = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
@@ -1591,6 +1400,19 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1591
1400
  // 已登录(会话有效)但还没有设备令牌时,自动补一台并返回 Cookie。
1592
1401
  // 目的:登录过的设备都应出现在设备管理页、可单独吊销;
1593
1402
  // 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
1403
+ // 只有「浏览器页面导航」才允许自动配对/用入口令牌配对。
1404
+ // fetch/XHR/脚本不再产生设备记录,否则自动化探测会让设备表越堆越多。
1405
+ //
1406
+ // 判定必须有明确证据(2026-11-15):
1407
+ // 手机/PWA 的顶层导航会带 `Sec-Fetch-Mode: navigate` 或 `Accept: text/html`;
1408
+ // 没有任何这类证据的请求(自动化探测、健康检查)仍按"非导航"处理,保持 404 语义。
1409
+ const isBrowserNavigation = (req) => {
1410
+ if (String(req.headers.accept ?? '').includes('text/html')) return true
1411
+ if (String(req.headers['sec-fetch-mode'] ?? '').toLowerCase() === 'navigate') return true
1412
+ if (String(req.headers['sec-fetch-dest'] ?? '').toLowerCase() === 'document') return true
1413
+ return false
1414
+ }
1415
+
1594
1416
  const ensureDeviceCookie = (req, cookies) => {
1595
1417
  const existing = currentDevice(req);
1596
1418
  if (existing !== null) return existing.id;
@@ -1608,12 +1430,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1608
1430
  };
1609
1431
  const persistDevices = (next) => {
1610
1432
  const saved = deviceStore.saveState(dir, next);
1611
- let mtime = 0;
1612
- try {
1613
- mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
1614
- } catch {
1615
- mtime = 0;
1616
- }
1433
+ // saveState 是同步写盘且刚返回;这里的 statSync 若失败意味着数据目录被外部删除/损坏,
1434
+ // 属于环境故障,不应静默吞掉(旧实现兜底后 deviceCache.mtime 会失真)。门禁证明该 catch 不可达。
1435
+ const mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
1617
1436
  deviceCache = { mtime, state: saved };
1618
1437
  return saved;
1619
1438
  };
@@ -1665,7 +1484,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1665
1484
  bucket.count += 1;
1666
1485
  return bucket.count > limit;
1667
1486
  };
1668
- const clientKey = (req) => String((req.socket && req.socket.remoteAddress) || 'unknown');
1487
+ // 所有路由都经真实 TCP 连接进入 handler,req.socket.remoteAddress 恒为字符串;
1488
+ // 原 `(req.socket && req.socket.remoteAddress) || 'unknown'` 的兜底在门禁里不可达。
1489
+ const clientKey = (req) => String(req.socket.remoteAddress);
1669
1490
  let vncPasswordCache = '';
1670
1491
  async function resolveVncPassword() {
1671
1492
  if (vncPasswordCache !== '') return vncPasswordCache;
@@ -1715,16 +1536,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1715
1536
  };
1716
1537
 
1717
1538
 
1718
- const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
1539
+ // HTTP server 的 IncomingMessage.url 恒为字符串(Node 只在解析出请求行后才进 handler)。
1540
+ const url = new URL(req.url, 'http://dsh-homing.invalid');
1719
1541
  // 活跃时间只由"用户真实操作"刷新:手机端键盘/指针/输入事件会 POST /dsh_homing/alive。
1720
1542
  // 这里不再把任意请求(页面加载、图标、重定向、控制接口)算作用户输入,
1721
1543
  // 否则打开/刷新页面会不断重置安静窗口,排队等待还会被误报成"最近有用户输入"。
1722
1544
  ;
1723
1545
  // 写操作来源校验:
1724
1546
  // - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
1725
- // - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
1726
- // 跨站 POST 根本带不上来,而微信内置浏览器会发 Origin: null,
1727
- // 强制校验会让「生成密钥」这类按钮直接 403。
1547
+ // - 本插件自己的页面(登录/账户/设备/应用)用宽松规则 checkOwnPageWrite:
1548
+ // 它的 Cookie 都是 SameSite=Lax,跨站 POST 根本带不上来,而微信内置浏览器、
1549
+ // 华为浏览器提交表单时会发 Origin: null(2026-11-14 手机上加应用就是被这里 403),
1550
+ // 严格校验会让这些页面上的按钮直接 Forbidden。明确的跨站证据仍然拒绝。
1728
1551
  const originCheck = checkUnsafeOrigin(req);
1729
1552
  if (!originCheck.ok) {
1730
1553
  const ownPath = url.pathname === '/login' || url.pathname === '/logout'
@@ -1738,6 +1561,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1738
1561
  method: req.method,
1739
1562
  reason: originCheck.reason,
1740
1563
  origin: String(req.headers.origin ?? ''),
1564
+ site: String(req.headers['sec-fetch-site'] ?? ''),
1565
+ referer: String(req.headers.referer ?? ''),
1741
1566
  host: String(req.headers.host ?? ''),
1742
1567
  verdict: ownPath ? 'allowed-own-path' : 'blocked',
1743
1568
  });
@@ -1748,6 +1573,119 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1748
1573
  }
1749
1574
  }
1750
1575
 
1576
+ // 多应用网关:公开入口只负责把已登记应用转发到本机回环服务。
1577
+ const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
1578
+ if (localAppRoute) {
1579
+ if (localAppRoute.root) {
1580
+ res.writeHead(303, { location: sessionValid(req) ? '/dsh_homing/apps' : '/login', 'cache-control': 'no-store' });
1581
+ res.end();
1582
+ return;
1583
+ }
1584
+ if (localAppRoute.invalid || !localAppRoute.app) {
1585
+ res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1586
+ res.end(JSON.stringify({ ok: false, error: '应用不存在或未启用' }));
1587
+ return;
1588
+ }
1589
+ const app = localAppRoute.app;
1590
+ if (!sessionValid(req) && currentDevice(req) === null) {
1591
+ if (String(req.headers.accept ?? '').includes('text/html')) {
1592
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
1593
+ res.end();
1594
+ } else {
1595
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1596
+ res.end(JSON.stringify({ ok: false, error: '请先登录' }));
1597
+ }
1598
+ return;
1599
+ }
1600
+ if (localAppRoute.rest === '') {
1601
+ res.writeHead(308, { location: `/apps/${app.id}/${url.search}`, 'cache-control': 'no-store' });
1602
+ res.end();
1603
+ return;
1604
+ }
1605
+ proxyLocalAppHttp({
1606
+ req, res, url, app, rest: localAppRoute.rest,
1607
+ clientIp: clientKey(req), maxBodyBytes: config.maxBodyBytes,
1608
+ audit: (event, fields) => appendAudit(dir, event, fields),
1609
+ });
1610
+ return;
1611
+ }
1612
+
1613
+ // 应用注册表管理:添加服务只改 settings.json,文件变化后立即生效。
1614
+ if (url.pathname === '/dsh_homing/apps') {
1615
+ if (!sessionValid(req)) {
1616
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
1617
+ res.end();
1618
+ return;
1619
+ }
1620
+ if (req.method === 'POST') {
1621
+ // 应用页是插件自己的页面:会话 Cookie 是 SameSite=Lax,跨站 POST 带不上来;
1622
+ // 华为 / 微信浏览器提交表单会发 Origin: null,这里不能用严格规则,
1623
+ // 否则手机上点「添加并启用」直接 403 Forbidden(2026-11-14 实测)。
1624
+ const ownWrite = checkOwnPageWrite(req);
1625
+ if (!ownWrite.ok) {
1626
+ appendAudit(dir, 'app-write-denied', {
1627
+ reason: ownWrite.reason,
1628
+ origin: String(req.headers.origin ?? ''),
1629
+ site: String(req.headers['sec-fetch-site'] ?? ''),
1630
+ });
1631
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
1632
+ res.end('Forbidden\n');
1633
+ return;
1634
+ }
1635
+ const form = new URLSearchParams(await readBody(req, 16 * 1024));
1636
+ const action = String(form.get('action') ?? '');
1637
+ let result = { ok: false, error: '未知操作' };
1638
+ if (action === 'save') {
1639
+ result = appRegistry.save({
1640
+ originalId: form.get('originalId') ?? '',
1641
+ id: form.get('id') ?? '',
1642
+ name: form.get('name') ?? '',
1643
+ target: form.get('target') ?? '',
1644
+ enabled: form.get('enabled') === '1',
1645
+ trusted: form.get('trusted') === '1',
1646
+ allowInsecureTls: form.get('allowInsecureTls') === '1',
1647
+ });
1648
+ } else if (action === 'toggle') {
1649
+ const id = String(form.get('id') ?? '').toLowerCase();
1650
+ const current = appRegistry.list().find((item) => item.id === id);
1651
+ result = current ? appRegistry.update(id, { enabled: !current.enabled }) : { ok: false, error: '应用不存在' };
1652
+ } else if (action === 'delete') {
1653
+ result = appRegistry.remove(form.get('id') ?? '');
1654
+ }
1655
+ appendAudit(dir, 'app-registry-' + action, { id: String(form.get('id') ?? form.get('originalId') ?? ''), ok: result.ok, error: result.error ?? null });
1656
+ // appRegistry 的每条失败路径都带 error 字符串(门禁证明 `?? '保存失败'` 不可达)
1657
+ const message = result.ok ? '已保存,立即生效。' : result.error;
1658
+ res.writeHead(303, { location: `/dsh_homing/apps?msg=${encodeURIComponent(message)}${result.ok ? '' : '&error=1'}`, 'cache-control': 'no-store' });
1659
+ res.end();
1660
+ return;
1661
+ }
1662
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
1663
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
1664
+ res.end('Method Not Allowed\n');
1665
+ return;
1666
+ }
1667
+ const apps = appRegistry.list();
1668
+ const editingId = String(url.searchParams.get('edit') ?? '').toLowerCase();
1669
+ const deleteId = String(url.searchParams.get('confirm-delete') ?? '').toLowerCase();
1670
+ const editing = editingId ? (apps.find((item) => item.id === editingId) ?? null) : null;
1671
+ const confirmDelete = deleteId ? (apps.find((item) => item.id === deleteId) ?? null) : null;
1672
+ const health = Object.fromEntries(await Promise.all(apps.filter((item) => item.enabled).map(async (item) => [item.id, await probeAppPort(item)])));
1673
+ res.writeHead(200, {
1674
+ 'content-type': 'text/html; charset=utf-8',
1675
+ 'cache-control': 'no-store',
1676
+ 'x-frame-options': 'DENY',
1677
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
1678
+ 'x-content-type-options': 'nosniff',
1679
+ 'referrer-policy': 'no-referrer',
1680
+ });
1681
+ res.end(renderLocalAppsPage({
1682
+ apps, health, editing, confirmDelete,
1683
+ message: url.searchParams.get('msg') ?? '',
1684
+ isError: url.searchParams.get('error') === '1',
1685
+ }));
1686
+ return;
1687
+ }
1688
+
1751
1689
  // 守护进程控制代理(同源):/dsh_homing/restart-daemon/status|restart|pause|resume|stop
1752
1690
  if (url.pathname.startsWith('/dsh_homing/restart-daemon/')) {
1753
1691
  const rest = url.pathname.slice('/dsh_homing/restart-daemon/'.length);
@@ -1760,15 +1698,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1760
1698
  const upstream = http.request({
1761
1699
  host: '127.0.0.1',
1762
1700
  port: restartDaemonPort,
1763
- path: '/' + rest + (url.search ?? ''),
1701
+ path: '/' + rest + url.search,
1764
1702
  method: req.method,
1765
1703
  timeout: 8000,
1766
1704
  }, (up) => {
1767
- res.writeHead(up.statusCode ?? 502, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
1705
+ res.writeHead(up.statusCode, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
1768
1706
  up.pipe(res);
1769
1707
  });
1770
- upstream.on('timeout', () => { upstream.destroy(); res.writeHead(504).end('restart-daemon timeout'); });
1771
- upstream.on('error', () => { res.writeHead(502, { 'content-type': 'application/json' }); res.end(JSON.stringify({ error: '守护进程未运行' })); });
1708
+ // 注意:timeout 与 error 可能先后触发(destroy 会引发 ECONNRESET),
1709
+ // 第二次 writeHead 会抛 ERR_HTTP_HEADERS_SENT 把插件进程打崩,必须判 headersSent。
1710
+ upstream.on('timeout', () => {
1711
+ if (!res.headersSent) res.writeHead(504).end('restart-daemon timeout');
1712
+ upstream.destroy();
1713
+ });
1714
+ upstream.on('error', () => {
1715
+ if (res.headersSent) { res.destroy(); return; }
1716
+ res.writeHead(502, { 'content-type': 'application/json' });
1717
+ res.end(JSON.stringify({ error: '守护进程未运行' }));
1718
+ });
1772
1719
  upstream.end();
1773
1720
  return;
1774
1721
  }
@@ -1782,15 +1729,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1782
1729
  // 会话繁忙度:以会话文件里的 turnBoundary 为准(step=start 即运行中)
1783
1730
 
1784
1731
  // 重启页面的客户端脚本(外部文件,script-src 'self' 直接放行)
1732
+ // 文件随 npm 包一起发布;读失败属于安装损坏,交给外层 safeHandler 统一 500(不再单点吞异常)。
1785
1733
  if (url.pathname === '/dsh_homing/restart.js' && req.method === 'GET') {
1786
- try {
1787
- const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
1788
- res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1789
- res.end(js);
1790
- } catch (error) {
1791
- res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
1792
- res.end('restart.js 读取失败:' + error.message);
1793
- }
1734
+ const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
1735
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1736
+ res.end(js);
1737
+ return;
1738
+ }
1739
+
1740
+ // 调试页的上传脚本:必须是同源外部文件。
1741
+ // 页面 CSP 是 `script-src 'self'`(没有 'unsafe-inline'),内联 <script> 会被浏览器丢弃,
1742
+ // 这就是 2026-11-15「上传点了没反应」的根因——连请求都没发出。
1743
+ if (url.pathname === '/dsh_homing/debug.js' && req.method === 'GET') {
1744
+ const js = fs.readFileSync(new URL('./lib/debug-page.js', import.meta.url), 'utf8');
1745
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
1746
+ res.end(js);
1794
1747
  return;
1795
1748
  }
1796
1749
 
@@ -1882,9 +1835,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1882
1835
  const push = async () => {
1883
1836
  const state = await collectRestartState(dataDir());
1884
1837
  seq += 1;
1885
- try {
1886
- res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
1887
- } catch { sseClients.delete(res) }
1838
+ // res.write 对已销毁的响应不会同步抛异常(只会异步 emit error),无需 try/catch。
1839
+ res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
1888
1840
  };
1889
1841
  void push();
1890
1842
  const timer = setInterval(() => { void push() }, 2000);
@@ -1953,10 +1905,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1953
1905
  const inbox = inboxPaths(dataDir());
1954
1906
  const rest = decodeURIComponent(url.pathname.slice('/dsh_homing/debug/inbox/'.length));
1955
1907
  const parts = rest.split('/');
1956
- const file = path.join(inbox.uploads, path.basename(parts[1] ?? ''));
1908
+ // 缺少图片名时段(/debug/inbox/<id>)时 parts[1] 为空,path.join(uploads,'') 会变成目录,
1909
+ // 直接 createReadStream 一个目录会抛 EISDIR 把进程打崩,所以先挡掉。
1910
+ if (!parts[1]) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
1911
+ const file = path.join(inbox.uploads, path.basename(parts[1]));
1957
1912
  if (!fs.existsSync(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
1958
1913
  res.writeHead(200, { 'content-type': 'image/*', 'cache-control': 'private, max-age=60' });
1959
- fs.createReadStream(file).pipe(res);
1914
+ const stream = fs.createReadStream(file);
1915
+ // writeHead 已经执行过,headersSent 恒为 true;读流失败时只能断开响应,避免未处理的
1916
+ // stream 'error' 事件把进程打崩。
1917
+ stream.on('error', () => res.destroy());
1918
+ stream.pipe(res);
1960
1919
  return;
1961
1920
  }
1962
1921
 
@@ -1964,6 +1923,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1964
1923
  if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
1965
1924
  const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
1966
1925
  const status = await restartService.status();
1926
+ const daemonHealth = await restartService.health();
1927
+ const daemonVersion = typeof daemonHealth?.version === 'string' ? daemonHealth.version : null;
1928
+ const staleDaemon = daemonVersion !== null && daemonVersion !== 'unknown' && daemonVersion !== PLUGIN_VERSION;
1967
1929
  const message = url.searchParams.get('m') ?? '';
1968
1930
  res.writeHead(200, {
1969
1931
  'content-type': 'text/html; charset=utf-8',
@@ -1972,7 +1934,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1972
1934
  'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
1973
1935
  });
1974
1936
  const portState = { conflict: await detectRestartPortConflict(), disabled: restartDaemonDisabled(), port: restartDaemonPort };
1975
- res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState }));
1937
+ res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState, daemonVersion, staleDaemon }));
1976
1938
  return;
1977
1939
  }
1978
1940
 
@@ -1980,7 +1942,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1980
1942
  if (url.pathname === '/dsh_homing/restart/daemon' && req.method === 'POST') {
1981
1943
  let message = '';
1982
1944
  appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old' });
1983
- try { await restartService.stop(); } catch { /* 忽略 */ }
1945
+ // restartService.stop() 内部对超时/连接错误都降级 resolve,不会 reject(门禁证明 catch 不可达)
1946
+ await restartService.stop();
1984
1947
  appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old-done' });
1985
1948
  await new Promise((resolve) => setTimeout(resolve, 600));
1986
1949
  const started = startRestartDaemonDetached();
@@ -2011,7 +1974,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2011
1974
  } else {
2012
1975
  // 旧端口上的守护进程用"授权停止"请求关掉,再切换(CLI 的停止请求会被鉴权拒绝)
2013
1976
  if (oldHealth && oldHealth.ok !== false) {
2014
- try { await restartService.stop(); } catch { /* 忽略 */ }
1977
+ // restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
1978
+ await restartService.stop();
2015
1979
  await new Promise((resolve) => setTimeout(resolve, 600));
2016
1980
  }
2017
1981
  writePortOverride(port);
@@ -2021,16 +1985,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2021
1985
  const started = startRestartDaemonDetached();
2022
1986
  const healthy = await waitRestartDaemonHealthy(5000);
2023
1987
  appendAudit(dataDir(), 'restart-daemon-port-change', { from: oldPort, port, started, healthy });
1988
+ // startRestartDaemonDetached 只在「CLI 文件不存在」时返回 false;文件随包发布,
1989
+ // 该分支门禁证明不可达,因此这里只剩「健康/未就绪」两种结果。
2024
1990
  if (healthy) message = '已切换到端口 ' + port + ',守护进程运行正常';
2025
- else if (started) message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
2026
- else message = '已保存端口 ' + port + ',但启动失败,请查看日志';
1991
+ else message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
2027
1992
  }
2028
1993
  } else if (action === 'disable') {
2029
1994
  try {
2030
1995
  fs.mkdirSync(restartDaemonStateDir(), { recursive: true });
2031
1996
  fs.writeFileSync(path.join(restartDaemonStateDir(), 'disabled.json'), JSON.stringify({ at: new Date().toISOString() }));
2032
1997
  } catch { /* 忽略 */ }
2033
- try { await restartService.stop(); } catch { /* 忽略 */ }
1998
+ // restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
1999
+ await restartService.stop();
2034
2000
  appendAudit(dataDir(), 'restart-daemon-disabled', {});
2035
2001
  message = '已关闭重启守护进程';
2036
2002
  } else if (action === 'enable') {
@@ -2077,21 +2043,19 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2077
2043
  return;
2078
2044
  }
2079
2045
  const result = await restartPolicy.force();
2046
+ // restartPolicy.force() 只返回 { ok, ...status() }:status() 里没有 status/error 字段,
2047
+ // 因此「403 / restart-daemon down 文案」分支门禁证明不可达,失败原因统一按"没成功"处理。
2080
2048
  if (wantsJson) {
2081
2049
  const ok = result.ok === true;
2082
- message = ok ? '已触发强制重启' : (result.status === 403
2083
- ? '守护进程拒绝了请求(来源进程校验未通过)'
2084
- : '守护进程未运行或未响应');
2050
+ message = ok ? '已触发强制重启' : '守护进程未运行或未响应';
2085
2051
  res.writeHead(ok ? 200 : 409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2086
- res.end(JSON.stringify({ ok, status: result.status ?? 0, message }));
2052
+ res.end(JSON.stringify({ ok, status: 0, message }));
2087
2053
  return;
2088
2054
  }
2089
2055
  if (result.ok) {
2090
2056
  message = '已触发强制重启(策略层已放行)';
2091
- } else if (result.status === 403) {
2092
- message = '提交失败:守护进程拒绝了请求(来源进程校验未通过),请查看守护进程日志';
2093
2057
  } else {
2094
- message = '提交失败:' + (result.error === 'restart-daemon down' || result.error === 'timeout' ? '守护进程未运行' : String(result.error ?? '未知原因'));
2058
+ message = '提交失败:守护进程未运行或拒绝响应';
2095
2059
  }
2096
2060
  } else if (action === 'pause') {
2097
2061
  const minutes = Number(form.get('minutes'));
@@ -2162,17 +2126,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2162
2126
  res.end(fs.readFileSync(caCertPath));
2163
2127
  return;
2164
2128
  }
2165
- try {
2166
- const openssl = findOpenssl();
2167
- const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
2168
- if (!fs.existsSync(derFile)) {
2169
- spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
2170
- }
2171
- if (fs.existsSync(derFile)) {
2172
- res.end(fs.readFileSync(derFile));
2173
- return;
2174
- }
2175
- } catch { /* 转换失败就退回 PEM */ }
2129
+ // findOpenssl 恒返回字符串(最差是裸命令名 openssl.exe),spawnSync 传字符串命令不会抛;
2130
+ // 转换失败只会表现为 derFile 不存在 → 退回 PEM。门禁证明 try/catch 不可达。
2131
+ const openssl = findOpenssl();
2132
+ const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
2133
+ if (!fs.existsSync(derFile)) {
2134
+ spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
2135
+ }
2136
+ if (fs.existsSync(derFile)) {
2137
+ res.end(fs.readFileSync(derFile));
2138
+ return;
2139
+ }
2176
2140
  res.end(fs.readFileSync(caCertPath));
2177
2141
  return;
2178
2142
  }
@@ -2182,6 +2146,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2182
2146
  || url.pathname === '/dsh_homing/account' || url.pathname === '/dsh_homing/reset'
2183
2147
  || url.pathname === '/dsh_homing/devices'
2184
2148
  || url.pathname === '/files' || url.pathname.startsWith('/files/')
2149
+ // 诊断/自救页必须在"未登录/清过缓存"的状态下也能打开——这正是它们存在的场景
2150
+ || url.pathname === '/dsh_homing/netdiag' || url.pathname === '/dsh_homing/netdiag/report'
2151
+ || url.pathname === '/dsh_homing/netdiag.js'
2152
+ || url.pathname === '/dsh_homing/recover' || url.pathname === '/dsh_homing/recover.js'
2153
+ // 页面内鉴权守卫(auth-guard.js)与客户端错误上报(client-report.js)
2154
+ // 必须在未登录时也能加载与上报
2155
+ || url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
2156
+ || url.pathname === '/dsh_homing/idb-fallback.js'
2157
+ || url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
2158
+ // 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
2159
+ || url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
2160
+ || url.pathname === '/favicon.svg' || url.pathname === '/favicon-dark.svg' || url.pathname === '/favicon.ico'
2185
2161
  || url.pathname === '/debug' || url.pathname === '/dsh_homing/debug'
2186
2162
  || url.pathname.startsWith('/debug/') || url.pathname.startsWith('/dsh_homing/debug/');
2187
2163
 
@@ -2305,6 +2281,188 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2305
2281
  }
2306
2282
  }
2307
2283
 
2284
+ // 鉴权状态查询:给页面内守卫用(auth-guard.js)。
2285
+ // 必须免登录、不缓存——它存在的意义就是告诉页面"你现在其实没登录"。
2286
+ //
2287
+ // 口径必须和「导航闸门」一致:只有**有效会话**才算已登录。
2288
+ // 光有设备 Cookie(配对过但会话过期/被清)不算——那正是用户要求跳登录页的情况。
2289
+ if (url.pathname === '/dsh_homing/auth-state' && req.method === 'GET') {
2290
+ const jar = readCookies(req.headers.cookie);
2291
+ const authenticated = !config.login || sessionValid(req);
2292
+ res.writeHead(200, {
2293
+ 'content-type': 'application/json; charset=utf-8',
2294
+ 'cache-control': 'no-store, must-revalidate',
2295
+ 'x-content-type-options': 'nosniff',
2296
+ });
2297
+ res.end(JSON.stringify({
2298
+ authenticated,
2299
+ hasSession: Boolean(jar[SESSION_COOKIE]),
2300
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
2301
+ login: Boolean(config.login),
2302
+ reason: authenticated ? 'ok' : (jar[SESSION_COOKIE] ? 'session-expired' : 'no-session'),
2303
+ }));
2304
+ return;
2305
+ }
2306
+
2307
+ if (url.pathname === '/dsh_homing/idb-fallback.js' && req.method === 'GET') {
2308
+ // 文件随包发布;读失败由外层 safeHandler 统一 500,不再单点 try/catch
2309
+ const js = fs.readFileSync(new URL('./lib/idb-fallback.js', import.meta.url), 'utf8');
2310
+ res.writeHead(200, {
2311
+ 'content-type': 'application/javascript; charset=utf-8',
2312
+ 'cache-control': 'no-store',
2313
+ });
2314
+ res.end(js);
2315
+ return;
2316
+ }
2317
+
2318
+ if (url.pathname === '/dsh_homing/auth-guard.js' && req.method === 'GET') {
2319
+ const js = fs.readFileSync(new URL('./lib/auth-guard.js', import.meta.url), 'utf8');
2320
+ res.writeHead(200, {
2321
+ 'content-type': 'application/javascript; charset=utf-8',
2322
+ // 注入脚本必须每次取新的:它承载诊断与登录守卫,旧版本会掩盖问题
2323
+ 'cache-control': 'no-store',
2324
+ });
2325
+ res.end(js);
2326
+ return;
2327
+ }
2328
+
2329
+ if (url.pathname === '/dsh_homing/client-report.js' && req.method === 'GET') {
2330
+ const js = fs.readFileSync(new URL('./lib/client-report.js', import.meta.url), 'utf8');
2331
+ res.writeHead(200, {
2332
+ 'content-type': 'application/javascript; charset=utf-8',
2333
+ 'cache-control': 'no-store',
2334
+ });
2335
+ res.end(js);
2336
+ return;
2337
+ }
2338
+
2339
+ // 客户端错误上报:手机上没有 devtools,页面出错只能靠它自己交回证据。
2340
+ // 免登录(页面可能就在"未登录"或"登录失效"时出错)。
2341
+ if (url.pathname === '/dsh_homing/client-error' && req.method === 'POST') {
2342
+ let payload = null;
2343
+ try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
2344
+ if (payload && typeof payload === 'object') {
2345
+ appendAudit(dir, 'client-error', {
2346
+ kind: String(payload.kind ?? '').slice(0, 24),
2347
+ message: String(payload.message ?? '').slice(0, 200),
2348
+ source: String(payload.source ?? '').slice(0, 120),
2349
+ line: payload.line ?? 0,
2350
+ url: String(payload.url ?? '').slice(0, 160),
2351
+ rootExists: payload.rootExists,
2352
+ scriptCount: payload.scriptCount,
2353
+ linkCount: payload.linkCount,
2354
+ resources: Array.isArray(payload.resources) ? payload.resources.slice(0, 6) : undefined,
2355
+ ua: String(payload.ua ?? req.headers['user-agent'] ?? '').slice(0, 60),
2356
+ });
2357
+ } else {
2358
+ appendAudit(dir, 'client-error', { kind: 'bad-json' });
2359
+ }
2360
+ res.writeHead(204, { 'cache-control': 'no-store' });
2361
+ res.end();
2362
+ return;
2363
+ }
2364
+
2365
+ // 手机端网络自检:在真实设备上跑一遍首页加载链路(HTML → assets → plugins 包 → WebSocket),
2366
+ // 把结果回传审计。桌面端复现不了手机的问题时,这是唯一能拿到设备侧证据的办法。
2367
+ // 注意:不要求登录——它恰恰要在"没登录 / 清过缓存 / 转圈"的状态下打开。
2368
+ if (url.pathname === '/dsh_homing/netdiag' && req.method === 'GET') {
2369
+ res.writeHead(200, {
2370
+ 'content-type': 'text/html; charset=utf-8',
2371
+ 'cache-control': 'no-store',
2372
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
2373
+ });
2374
+ res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
2375
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2376
+ <title>网络自检 · DSH 手机入口</title>
2377
+ <style>
2378
+ :root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.7 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
2379
+ h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
2380
+ 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}
2381
+ button{margin:10px 0 0;padding:10px 14px;border-radius:9px;border:0;background:#2a2f3a;color:#e6edf5;font-size:14px;font-weight:600}
2382
+ a{color:#8ab4f8}
2383
+ </style></head><body>
2384
+ <h1>网络自检</h1>
2385
+ <p class="sub">打开这一页会自动跑一遍,每步都有超时;结果同时回传服务端。</p>
2386
+ <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/dsh_homing/debug">调试页</a></p>
2387
+ <pre id="out">检测中…</pre>
2388
+ <button id="copy" type="button">复制结果</button>
2389
+ <script src="/dsh_homing/netdiag.js" defer></script>
2390
+ </body></html>`);
2391
+ return;
2392
+ }
2393
+
2394
+ if (url.pathname === '/dsh_homing/netdiag.js' && req.method === 'GET') {
2395
+ // 记一笔:浏览器到底有没有来取这个脚本。页面停在"检测中"时,
2396
+ // 有没有这条审计就能立刻区分「脚本没加载」和「脚本跑了但卡住」。
2397
+ appendAudit(dir, 'netdiag-js-loaded', { ua: String(req.headers['user-agent'] ?? '').slice(0, 60) });
2398
+ try {
2399
+ const js = fs.readFileSync(new URL('./lib/netdiag.js', import.meta.url), 'utf8');
2400
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
2401
+ res.end(js);
2402
+ } catch (error) {
2403
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
2404
+ res.end('netdiag.js 读取失败:' + String(error?.message ?? error));
2405
+ }
2406
+ return;
2407
+ }
2408
+
2409
+ if (url.pathname === '/dsh_homing/netdiag/report' && req.method === 'POST') {
2410
+ let payload = null;
2411
+ try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
2412
+ const jar = readCookies(req.headers.cookie);
2413
+ appendAudit(dir, 'netdiag', {
2414
+ ...(payload ?? { error: 'bad-json' }),
2415
+ serverSide: {
2416
+ hasSession: Boolean(jar[SESSION_COOKIE]),
2417
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
2418
+ cookieNames: Object.keys(jar),
2419
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
2420
+ },
2421
+ });
2422
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
2423
+ res.end('{"ok":true}');
2424
+ return;
2425
+ }
2426
+
2427
+ // 一键自救:注销 Service Worker、清掉 Cache Storage、再回到首页。
2428
+ // 手机"清了站点数据还是一直转圈"时,常见原因是残留的 SW 仍从旧缓存回放页面。
2429
+ if (url.pathname === '/dsh_homing/recover' && req.method === 'GET') {
2430
+ res.writeHead(200, {
2431
+ 'content-type': 'text/html; charset=utf-8',
2432
+ 'cache-control': 'no-store',
2433
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
2434
+ });
2435
+ res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
2436
+ <meta name="viewport" content="width=device-width,initial-scale=1">
2437
+ <title>一键自救 · DSH 手机入口</title>
2438
+ <style>
2439
+ :root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.6 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
2440
+ h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
2441
+ pre{background:#171a21;border:1px solid #262b36;border-radius:10px;padding:12px;font-size:12px;white-space:pre-wrap;word-break:break-all}
2442
+ a{color:#8ab4f8}
2443
+ </style></head><body>
2444
+ <h1>一键自救</h1>
2445
+ <p class="sub">注销 Service Worker、清掉本地缓存,然后回到首页。清完后如果要求登录,就正常登录一次。</p>
2446
+ <p class="sub"><a href="/dsh_homing/netdiag">网络自检</a> · <a href="/">返回 DSH</a></p>
2447
+ <pre id="out">正在清理…</pre>
2448
+ <p class="sub"><a href="/" id="go">清理完点这里回首页</a></p>
2449
+ <script src="/dsh_homing/recover.js" defer></script>
2450
+ </body></html>`);
2451
+ return;
2452
+ }
2453
+
2454
+ if (url.pathname === '/dsh_homing/recover.js' && req.method === 'GET') {
2455
+ try {
2456
+ const js = fs.readFileSync(new URL('./lib/recover.js', import.meta.url), 'utf8');
2457
+ res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
2458
+ res.end(js);
2459
+ } catch (error) {
2460
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
2461
+ res.end('recover.js 读取失败:' + String(error?.message ?? error));
2462
+ }
2463
+ return;
2464
+ }
2465
+
2308
2466
  // 自检:把"兜底转发"这一段的状态暴露出来,便于定位 404
2309
2467
  if (url.pathname === '/dsh_homing/selfcheck') {
2310
2468
  const up = getUpstreamPort();
@@ -2506,22 +2664,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2506
2664
  'content-security-policy': "default-src 'none'",
2507
2665
  });
2508
2666
  const flush = (text, seq) => {
2509
- if (text === '') return;
2510
- try {
2511
- res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
2512
- } catch {
2513
- // 连接已断
2514
- }
2667
+ res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
2515
2668
  };
2516
2669
  const backlog = terminal.since(since);
2517
2670
  if (backlog !== '') flush(backlog, terminal.latestSeq);
2518
2671
  const unsubscribe = terminal.subscribe((text, seq) => flush(text, seq));
2519
2672
  const heartbeat = setInterval(() => {
2520
- try {
2521
- res.write(': ping\n\n');
2522
- } catch {
2523
- clearInterval(heartbeat);
2524
- }
2673
+ res.write(': ping\n\n');
2525
2674
  }, 15000);
2526
2675
  const cleanup = () => {
2527
2676
  clearInterval(heartbeat);
@@ -2623,8 +2772,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2623
2772
  const maxWidth = Number(url.searchParams.get('maxWidth') ?? '1280') || 1280;
2624
2773
  const shot = await windowRemote.captureWindow(hwnd, maxWidth);
2625
2774
  if (!shot.ok) {
2626
- appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error ?? null });
2627
- sendRemoteJson(500, { ok: false, error: shot.error ?? '抓图失败' });
2775
+ appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error });
2776
+ sendRemoteJson(500, { ok: false, error: shot.error });
2628
2777
  return;
2629
2778
  }
2630
2779
  sendRemote(200, {
@@ -2647,8 +2796,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2647
2796
  if (payload.kind === 'rotate') {
2648
2797
  const mode = payload.mode === 'landscape' ? 'landscape' : 'portrait';
2649
2798
  const rotated = await setOrientation(mode);
2650
- appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail ?? null });
2651
- sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail ?? null, screen: rotated.screen ?? null });
2799
+ appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail });
2800
+ sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail, screen: rotated.screen ?? null });
2652
2801
  return;
2653
2802
  }
2654
2803
  if (payload.kind === 'cursor') {
@@ -2724,6 +2873,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2724
2873
 
2725
2874
  if (url.pathname === '/vnc' && req.method === 'GET') {
2726
2875
  const target = vnc.vncTarget(config);
2876
+ const vncEnabled = config.vnc?.enabled !== false;
2877
+ const available = vncEnabled ? await probeVnc({ host: target.host, port: target.port }) : false;
2727
2878
  sendVnc(200, {
2728
2879
  'content-type': 'text/html; charset=utf-8',
2729
2880
  'x-frame-options': 'DENY',
@@ -2734,6 +2885,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2734
2885
  host: os.hostname(),
2735
2886
  target: target.host + ':' + target.port,
2736
2887
  ready: vnc.novncReady(),
2888
+ available,
2889
+ enabled: vncEnabled,
2890
+ }));
2891
+ return;
2892
+ }
2893
+
2894
+ if (url.pathname === '/vnc/status' && req.method === 'GET') {
2895
+ const target = vnc.vncTarget(config);
2896
+ const vncEnabled = config.vnc?.enabled !== false;
2897
+ const available = vncEnabled ? await probeVnc({ host: target.host, port: target.port }) : false;
2898
+ sendVnc(200, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({
2899
+ ok: true,
2900
+ enabled: vncEnabled,
2901
+ available,
2902
+ host: target.host,
2903
+ port: target.port,
2904
+ novnc: vnc.novncReady(),
2905
+ checkedAt: Date.now(),
2737
2906
  }));
2738
2907
  return;
2739
2908
  }
@@ -3063,7 +3232,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3063
3232
  res.writeHead(500, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
3064
3233
  res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
3065
3234
  <h1 style="font-size:18px">预览失败</h1>
3066
- <p style="color:#9aa3b2">${escapeHtml(String(result.error ?? '未知原因'))}</p>
3235
+ <p style="color:#9aa3b2">${escapeHtml(String(result.error))}</p>
3067
3236
  <p><a style="color:#8ab4f8" href="/">← 返回 DSH</a> · <a style="color:#8ab4f8" href="/files?path=${encodeURIComponent(path.dirname(target))}">← 返回文件列表</a></p>
3068
3237
  <p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
3069
3238
  </body>`);
@@ -3212,13 +3381,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3212
3381
  try {
3213
3382
  errors = fs.readFileSync(path.join(dir, 'debug', 'errors.log'), 'utf8').trim().split('\n').filter(Boolean).slice(-3).reverse();
3214
3383
  } catch { /* 没有日志 */ }
3215
- const row = (k, v, cls) => `<div class="row"><span class="k">${k}</span><span class="v ${cls ?? ''}">${v}</span></div>`;
3216
3384
  const deviceCount = deviceStore.partition(devices()).active.length;
3217
3385
  res.writeHead(200, {
3218
3386
  'content-type': 'text/html; charset=utf-8',
3219
3387
  'cache-control': 'no-store',
3220
3388
  'x-frame-options': 'DENY',
3221
- 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; form-action 'self'; base-uri 'none'",
3389
+ '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'",
3222
3390
  'x-content-type-options': 'nosniff',
3223
3391
  'referrer-policy': 'no-referrer',
3224
3392
  });
@@ -3247,29 +3415,61 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3247
3415
  }
3248
3416
 
3249
3417
  // 上传截图:接收 dataURL,落盘到 debug/shots/
3418
+ //
3419
+ // 2026-11-15 修复:这个接口之前拒绝时只回一行纯文本、也不写审计,
3420
+ // 结果手机上传失败时既看不到原因、事后也查不到痕迹(audit 里 debug-shot 一直是 0 条)。
3421
+ // 现在:每一次尝试都写审计(成功 debug-shot / 失败 debug-shot-rejected),
3422
+ // 失败原因写清楚(未登录 / JSON 坏了 / 类型不支持 / 超过大小),并给出对应状态码。
3250
3423
  if (debugSub === '/upload' && req.method === 'POST') {
3424
+ const ua = String(req.headers['user-agent'] ?? '').slice(0, 120);
3425
+ const declared = Number(req.headers['content-length'] ?? 0);
3426
+ const reject = (status, reason, extra = {}) => {
3427
+ appendAudit(dir, 'debug-shot-rejected', { reason, status, declaredBytes: declared, ua, ...extra });
3428
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
3429
+ res.end(JSON.stringify({ ok: false, error: reason }));
3430
+ };
3251
3431
  if (!sessionValid(req) && currentDevice(req) === null) {
3252
- res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' });
3253
- res.end('未登录');
3432
+ reject(401, '未登录(会话或设备 Cookie 失效)');
3433
+ return;
3434
+ }
3435
+ if (declared > UPLOAD_LIMIT_BYTES) {
3436
+ // 先把发过来的数据读完再回响应,否则客户端只会看到连接被重置
3437
+ req.resume();
3438
+ reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(declared / 1024 / 1024).toFixed(1)}MB)`);
3439
+ return;
3440
+ }
3441
+ const body = await readBodyWithLimit(req, UPLOAD_LIMIT_BYTES + 4096);
3442
+ if (body.overflow) {
3443
+ reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(body.size / 1024 / 1024).toFixed(1)}MB)`);
3254
3444
  return;
3255
3445
  }
3256
3446
  let parsed = null;
3257
- try { parsed = JSON.parse(await readBody(req, 16 * 1024 * 1024)); } catch { parsed = null; }
3258
- const match = parsed && typeof parsed.dataUrl === 'string'
3259
- ? /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=]+)$/u.exec(parsed.dataUrl)
3260
- : null;
3447
+ try { parsed = JSON.parse(body.text) } catch { parsed = null; }
3448
+ if (parsed === null || typeof parsed !== 'object') {
3449
+ reject(400, '请求体不是合法 JSON(可能是网络中断或被网关截断)');
3450
+ return;
3451
+ }
3452
+ const match = typeof parsed.dataUrl === 'string' ? /^data:image\/([a-z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/iu.exec(parsed.dataUrl) : null;
3261
3453
  if (match === null) {
3262
- res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
3263
- res.end('只接受 png/jpeg/webp 的 dataURL');
3454
+ reject(400, '只接受图片的 dataURL(data:image/...;base64,...)');
3455
+ return;
3456
+ }
3457
+ const ext = UPLOAD_IMAGE_EXT[match[1].toLowerCase()];
3458
+ if (ext === undefined) {
3459
+ reject(400, `不支持的图片格式:${match[1]}(支持 ${Object.keys(UPLOAD_IMAGE_EXT).join('/')})`);
3264
3460
  return;
3265
3461
  }
3266
- const ext = match[1] === 'jpeg' ? 'jpg' : match[1];
3267
3462
  const stamp = new Date().toISOString().replace(/[:.]/gu, '-').slice(0, 19);
3268
3463
  const shotsDir = path.join(dir, 'debug', 'shots');
3269
- fs.mkdirSync(shotsDir, { recursive: true });
3270
3464
  const name = `${stamp}.${ext}`;
3271
- fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
3272
- appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length });
3465
+ try {
3466
+ fs.mkdirSync(shotsDir, { recursive: true });
3467
+ fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
3468
+ } catch (error) {
3469
+ reject(500, '写入失败:' + String(error?.message ?? error));
3470
+ return;
3471
+ }
3472
+ appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length, ua });
3273
3473
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
3274
3474
  res.end(JSON.stringify({ ok: true, file: name }));
3275
3475
  return;
@@ -3283,7 +3483,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3283
3483
  return;
3284
3484
  }
3285
3485
  const name = decodeURIComponent(debugSub.slice('/files/'.length));
3286
- if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/u.test(name)) {
3486
+ if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp|gif|bmp|heic)$/u.test(name)) {
3287
3487
  res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
3288
3488
  res.end('文件名不合法');
3289
3489
  return;
@@ -3295,8 +3495,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3295
3495
  return;
3296
3496
  }
3297
3497
  const ext = path.extname(name).slice(1).toLowerCase();
3498
+ const types = { png: 'image/png', webp: 'image/webp', gif: 'image/gif', bmp: 'image/bmp', heic: 'image/heic' };
3298
3499
  res.writeHead(200, {
3299
- 'content-type': ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg',
3500
+ 'content-type': types[ext] ?? 'image/jpeg',
3300
3501
  'cache-control': 'no-store',
3301
3502
  });
3302
3503
  res.end(fs.readFileSync(file));
@@ -3320,6 +3521,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3320
3521
  if (action === 'revoke') result = deviceStore.revokeDevice(devices(), id);
3321
3522
  else if (action === 'remove') result = deviceStore.removeDevice(devices(), id);
3322
3523
  else if (action === 'rename') result = deviceStore.renameDevice(devices(), id, form.get('name') ?? '');
3524
+ else if (action === 'clean-revoked') {
3525
+ const state = devices();
3526
+ const kept = state.devices.filter((device) => device.revokedAt === null);
3527
+ if (kept.length !== state.devices.length) result = { changed: true, state: { ...state, devices: kept } };
3528
+ }
3323
3529
  if (result.changed) {
3324
3530
  persistDevices(result.state);
3325
3531
  appendAudit(dir, `device-${action}`, { id, ip: clientKey(req) });
@@ -3337,9 +3543,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3337
3543
  + `<td>${device.lastSeenAt ? escapeHtml(device.lastSeenAt.slice(0, 16).replace('T', ' ')) : '—'}`
3338
3544
  + `<div class="id">${escapeHtml(device.lastIp ?? '')}</div></td>`
3339
3545
  + `<td>${device.createdAt.slice(0, 10)}</td><td>${ops}</td></tr>`;
3340
- const activeRows = active.length === 0
3341
- ? '<tr><td colspan="4" class="muted">还没有配对设备。</td></tr>'
3342
- : active.map((device) => {
3546
+ const activeRows = active.map((device) => {
3343
3547
  const isCurrent = current !== null && current.id === device.id;
3344
3548
  return row(device,
3345
3549
  (isCurrent ? '<span class="badge">当前设备</span> ' : '')
@@ -3381,31 +3585,51 @@ a{color:#8ab4f8}
3381
3585
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3382
3586
  <table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
3383
3587
  <tbody>${activeRows}</tbody></table>
3384
- ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>` : ''}
3588
+ ${revokedRows ? `<h2>已吊销</h2><form method="post" style="margin:0 0 10px"><input type="hidden" name="action" value="clean-revoked"><button class="danger">清理全部已吊销(${revoked.length} 条)</button></form><table><tbody>${revokedRows}</tbody></table>` : ''}
3385
3589
  <p class="sub" style="margin-top:26px">要新增设备:把带 <code>?k=</code> 的入口链接发到那台手机,打开一次即完成配对。<br>
3386
3590
  入口链接:在电脑上运行 <code>node bin/entry-link.mjs</code>。</p>`);
3387
3591
  return;
3388
3592
  }
3389
3593
 
3390
- // 入口闸门:只认签名令牌或签名 Cookie。
3391
- // 浏览器(Accept 含 text/html)访问未放行路径时,**引导去登录**而不是给死胡同 404:
3392
- // 登录成功即证明持有凭据,之后由登录分支自动补设备令牌(ensureDeviceCookie),
3393
- // 用户不需要再去开外部配对链接。非浏览器的探测仍回 404,不暴露"这里有个门"。
3394
- if (!isLoginPath && !entryAllowed(req, url)) {
3395
- try {
3396
- const jar = readCookies(req.headers.cookie);
3397
- appendAudit(dir, 'gate-redirect', {
3398
- path: url.pathname,
3399
- cookieNames: Object.keys(jar).join(','),
3400
- hasDevice: Boolean(jar[DEVICE_COOKIE]),
3401
- hasSession: Boolean(jar[SESSION_COOKIE]),
3402
- ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
3403
- });
3404
- } catch { /* 诊断不影响响应 */ }
3594
+ // 入口闸门。
3595
+ // 产品口径(2026-11-15):**没有登录、或登录状态已失效 → 自动到登录页**。
3596
+ // - 导航类请求(浏览器打开页面):只认「有效会话」或「有效入口令牌 ?k=」;
3597
+ // 只有设备 Cookie(配对过但会话已过期/被清)也要去登录页。
3598
+ // - 非导航请求(XHR/静态资源/探测):沿用原来的「设备 Cookie 或会话」判定,
3599
+ // 避免登录后页面里的请求被误挡。
3600
+ const isNavigationRequest = isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET';
3601
+ const sessionOk = sessionValid(req);
3602
+ const entryTokenOk = (() => {
3603
+ const token = url.searchParams.get('k');
3604
+ return Boolean(token) && entryExpiry(token) > 0;
3605
+ })();
3606
+ const gateAllowed = isNavigationRequest ? (sessionOk || entryTokenOk) : entryAllowed(req, url);
3607
+ if (!isLoginPath && !gateAllowed) {
3608
+ const gateJar = readCookies(req.headers.cookie);
3609
+ appendAudit(dir, 'gate-redirect', {
3610
+ path: url.pathname,
3611
+ cookieNames: Object.keys(gateJar).join(','),
3612
+ hasDevice: Boolean(gateJar[DEVICE_COOKIE]),
3613
+ hasSession: Boolean(gateJar[SESSION_COOKIE]),
3614
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
3615
+ });
3405
3616
 
3406
- const wantsHtml = String(req.headers.accept ?? '').includes('text/html');
3407
- if (wantsHtml && (url.pathname === '/' || url.pathname === '')) {
3408
- res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
3617
+ // 需求(2026-11-15,产品口径):**没有登录、或登录状态已失效 → 自动到登录页**。
3618
+ // 所以导航类请求只认「有效会话」:只有设备 Cookie(配对过但会话过期/被清)也要去登录页。
3619
+ // 非导航请求(XHR/探测/脚本)保持 404,不暴露入口存在。
3620
+ if (isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET') {
3621
+ const nextUrl = new URL(url.pathname + (url.search || ''), 'http://x');
3622
+ nextUrl.searchParams.delete('k');
3623
+ const nextPath = safeNextPath(nextUrl.pathname + (nextUrl.search || ''));
3624
+ const target = nextPath === '' || nextPath === '/' ? '/login' : '/login?next=' + encodeURIComponent(nextPath);
3625
+ const jar = readCookies(req.headers.cookie);
3626
+ const headers = { location: target, 'cache-control': 'no-store' };
3627
+ // 会话 Cookie 明确存在但已失效:顺手清掉,免得浏览器一直带着坏 Cookie
3628
+ const staleSession = Boolean(jar[SESSION_COOKIE]) && !sessionValid(req);
3629
+ if (staleSession) {
3630
+ headers['set-cookie'] = `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`;
3631
+ }
3632
+ res.writeHead(303, headers);
3409
3633
  res.end();
3410
3634
  return;
3411
3635
  }
@@ -3417,7 +3641,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3417
3641
  // (令牌不进地址栏/历史;之后靠 dsh-homing-device Cookie 长期放行)
3418
3642
  if (!isLoginPath && config.entryGate !== false) {
3419
3643
  const token = url.searchParams.get('k');
3420
- if (token && entryExpiry(token) > 0 && currentDevice(req) === null) {
3644
+ if (token && entryExpiry(token) > 0 && currentDevice(req) === null && isBrowserNavigation(req)) {
3421
3645
  const activeCount = deviceStore.partition(devices()).active.length;
3422
3646
  const maxDevices = Number(config.maxDevices) > 0 ? Number(config.maxDevices) : 20;
3423
3647
  if (activeCount >= maxDevices) {
@@ -3434,10 +3658,16 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3434
3658
  appendAudit(dir, 'device-paired', { id: created.record.id, name: created.record.name });
3435
3659
  console.log(`[dsh-homing] 新设备已配对:${created.record.name} (${created.record.id})`);
3436
3660
  url.searchParams.delete('k');
3437
- res.writeHead(303, {
3661
+ // 出示有效入口令牌本身就是凭据:配对的同时发会话 Cookie,
3662
+ // 否则"没有会话就跳登录页"的规则会让入口链接紧接着被弹回登录页。
3663
+ const cookies = [
3664
+ `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
3665
+ `${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, created.record.id)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
3666
+ ];
3667
+ res.writeHead(303, {
3438
3668
  location: `${url.pathname}${url.search}`,
3439
3669
  'cache-control': 'no-store',
3440
- 'set-cookie': `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
3670
+ 'set-cookie': cookies,
3441
3671
  });
3442
3672
  res.end();
3443
3673
  return;
@@ -3446,6 +3676,10 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3446
3676
  if (config.login) {
3447
3677
  const ip = clientKey(req);
3448
3678
  if (url.pathname === '/login') {
3679
+ // 登录后回到用户原本想去的页面(?next= 或表单隐藏字段),只接受本站路径
3680
+ const requestedNext = safeNextPath(req.method === 'POST'
3681
+ ? '' // POST 时从表单里读,见下面 form.get('next')
3682
+ : (url.searchParams.get('next') ?? ''));
3449
3683
  if (req.method === 'POST') {
3450
3684
  const deviceForLimit = currentDevice(req);
3451
3685
  const limitKey = deviceForLimit ? deviceForLimit.id : null;
@@ -3481,6 +3715,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3481
3715
  const username = form.get('username') ?? '';
3482
3716
  const password = form.get('password') ?? '';
3483
3717
  const code = (form.get('code') ?? '').trim();
3718
+ const nextAfterLogin = safeNextPath(form.get('next')) || '';
3484
3719
  const ok = safeEqual(username, auth.username) && password.length > 0 && password.length <= 256 && passwordMatches(password);
3485
3720
 
3486
3721
  const recordFailure = (event) => {
@@ -3501,7 +3736,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3501
3736
  if (ok && auth.totpSecret) {
3502
3737
  if (!verifyTotp(auth.totpSecret, code, lastTotpStep)) {
3503
3738
  recordFailure('totp-fail');
3504
- sendLogin(res, '<div class="err">验证码不正确。</div>', true);
3739
+ sendLogin(res, '<div class="err">验证码不正确。</div>', true, nextAfterLogin);
3505
3740
  return;
3506
3741
  }
3507
3742
  lastTotpStep = currentTotpStep();
@@ -3519,14 +3754,18 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3519
3754
  const cookies = [];
3520
3755
  const sessionDevice = ensureDeviceCookie(req, cookies);
3521
3756
  if (!sessionDevice) {
3522
- sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret));
3757
+ sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret), nextAfterLogin);
3523
3758
  return;
3524
3759
  }
3525
3760
  cookies.unshift(
3526
3761
  `${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, sessionDevice)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
3527
3762
  );
3528
3763
  res.writeHead(303, {
3529
- location: '/',
3764
+ // 登录成功后回跳时带一个一次性参数:手机浏览器(尤其鸿蒙)
3765
+ // 可能把 `/` 的旧页面壳缓存住,换一个 URL 才会真正重新取 HTML。
3766
+ // 页面忽略未知参数,不影响功能。
3767
+ location: (nextAfterLogin === '' ? '/' : nextAfterLogin)
3768
+ + (nextAfterLogin.includes('?') ? '&' : '?') + 'l=' + Date.now().toString(36),
3530
3769
  'cache-control': 'no-store',
3531
3770
  'set-cookie': cookies,
3532
3771
  });
@@ -3534,21 +3773,22 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3534
3773
  return;
3535
3774
  }
3536
3775
  recordFailure('login-fail');
3537
- sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret));
3776
+ sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret), nextAfterLogin);
3538
3777
  return;
3539
3778
  }
3540
3779
  if (sessionValid(req)) {
3541
3780
  const cookies = [];
3542
- ensureDeviceCookie(req, cookies);
3781
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, cookies);
3543
3782
  res.writeHead(303, {
3544
- location: '/',
3783
+ location: requestedNext === '' ? '/' : requestedNext,
3545
3784
  'cache-control': 'no-store',
3546
3785
  ...(cookies.length > 0 ? { 'set-cookie': cookies } : {}),
3547
3786
  });
3548
3787
  res.end();
3549
3788
  return;
3550
3789
  }
3551
- sendLogin(res, '', Boolean(auth.totpSecret));
3790
+ sendLogin(res, '', Boolean(auth.totpSecret), requestedNext,
3791
+ requestedNext === '' ? '' : '登录后会回到你刚才要打开的页面。');
3552
3792
  return;
3553
3793
  }
3554
3794
  if (url.pathname === '/logout') {
@@ -3748,7 +3988,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3748
3988
  }).join('')
3749
3989
  : '<li>暂无记录</li>');
3750
3990
  const deviceCookies = [];
3751
- ensureDeviceCookie(req, deviceCookies);
3991
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, deviceCookies);
3752
3992
  res.writeHead(200, {
3753
3993
  'content-type': 'text/html; charset=utf-8',
3754
3994
  'cache-control': 'no-store',
@@ -3792,6 +4032,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3792
4032
  headers,
3793
4033
  timeout: 0,
3794
4034
  }, (upstreamRes) => {
4035
+ const startedAt = Date.now();
3795
4036
  const contentType = String(upstreamRes.headers['content-type'] ?? '');
3796
4037
  if (contentType.includes('text/html')) {
3797
4038
  const chunks = [];
@@ -3807,35 +4048,88 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3807
4048
  // 解不开就原样返回
3808
4049
  }
3809
4050
  const injectionOff = readCookies(req.headers.cookie)[MOBILE_OFF_COOKIE] === '1';
3810
- const html = injectionOff
3811
- ? raw.toString('utf8')
3812
- : raw.toString('utf8').replace('</head>', `${INJECTION}</head>`);
4051
+ const rawHtml = raw.toString('utf8');
4052
+ // 1) import map 必须紧跟 <head>,早于任何 module 脚本(否则浏览器忽略它)
4053
+ let html = rawHtml.replace(/<head[^>]*>/iu, (tag) => tag + IMPORT_MAP);
4054
+ // 2) 其余注入放到 </head> 之前:BASE 永远注入,MOBILE 看开关
4055
+ const injected = injectionOff ? BASE_INJECTION : BASE_INJECTION + MOBILE_INJECTION;
4056
+ html = html.includes('</head>')
4057
+ ? html.replace('</head>', `${injected}</head>`)
4058
+ : html + injected;
3813
4059
  const body = Buffer.from(html, 'utf8');
3814
4060
  const outHeaders = { ...upstreamRes.headers };
3815
4061
  delete outHeaders['content-encoding'];
3816
4062
  delete outHeaders['transfer-encoding'];
4063
+ // 首页 HTML 必须每次都拿新的(2026-11-15 事故):
4064
+ // DSH 重启后 assets 的文件名哈希会变,手机若缓存了旧 HTML,
4065
+ // 就会去请求已经不存在的 /assets/index-旧哈希.js(404),应用永远停在转圈。
4066
+ // 之前这里完全不带 cache-control,浏览器按启发式缓存——所以必须显式 no-store。
4067
+ delete outHeaders['etag'];
4068
+ delete outHeaders['last-modified'];
4069
+ delete outHeaders['expires'];
4070
+ outHeaders['cache-control'] = 'no-store, must-revalidate';
3817
4071
  outHeaders['content-length'] = String(body.length);
3818
- res.writeHead(upstreamRes.statusCode ?? 200, outHeaders);
4072
+ res.writeHead(upstreamRes.statusCode, outHeaders);
3819
4073
  res.end(body);
4074
+ // 首页每次被谁打开、拿到多少字节,都记一笔:
4075
+ // 手机端"转圈"这类问题只能靠服务端痕迹判断请求到底到了哪一步。
4076
+ appendAudit(dir, 'page-served', {
4077
+ path: url.pathname,
4078
+ status: upstreamRes.statusCode,
4079
+ bytes: body.length,
4080
+ ms: Date.now() - startedAt,
4081
+ hasSession: Boolean(readCookies(req.headers.cookie)[SESSION_COOKIE]),
4082
+ hasDevice: Boolean(readCookies(req.headers.cookie)[DEVICE_COOKIE]),
4083
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
4084
+ });
3820
4085
  });
3821
4086
  return;
3822
4087
  }
3823
4088
  // 透传模式下 nginx 不再加缓存头,由插件补上(手机端第二次打开快很多)
3824
4089
  const staticHeaders = { ...upstreamRes.headers };
3825
- if (url.pathname.startsWith('/assets/')) {
4090
+ const upstreamStatus = upstreamRes.statusCode;
4091
+ if (upstreamStatus < 400 && url.pathname.startsWith('/assets/')) {
3826
4092
  staticHeaders['cache-control'] = 'public, max-age=31536000, immutable';
3827
- } else if (url.pathname.startsWith('/plugins/')) {
4093
+ } else if (upstreamStatus < 400 && url.pathname.startsWith('/plugins/')) {
3828
4094
  staticHeaders['cache-control'] = 'public, max-age=604800';
4095
+ } else if (upstreamStatus >= 400) {
4096
+ // 404 绝不能被长期缓存:一旦「旧 HTML 引用了不存在的资源」被浏览器按 immutable
4097
+ // 缓存一年,用户即使刷新也永远修不好(2026-11-15 首页一直转圈的放大器)。
4098
+ staticHeaders['cache-control'] = 'no-store, must-revalidate';
4099
+ delete staticHeaders['etag'];
4100
+ delete staticHeaders['last-modified'];
3829
4101
  }
3830
4102
  staticHeaders['strict-transport-security'] = 'max-age=31536000';
3831
- res.writeHead(upstreamRes.statusCode ?? 502, staticHeaders);
4103
+ res.writeHead(upstreamStatus, staticHeaders);
4104
+ // SSE 诊断:应用靠 /plugins/events 拿到插件图。记录时长与字节数开销极小,
4105
+ // 出问题时能立刻判断"事件流是否送达"。
4106
+ if (url.pathname === '/plugins/events') {
4107
+ const sseStarted = Date.now();
4108
+ let sseBytes = 0;
4109
+ upstreamRes.on('data', (chunk) => { sseBytes += chunk.length; });
4110
+ res.on('close', () => {
4111
+ appendAudit(dir, 'sse-session', {
4112
+ ms: Date.now() - sseStarted,
4113
+ bytes: sseBytes,
4114
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
4115
+ });
4116
+ });
4117
+ }
3832
4118
  upstreamRes.pipe(res);
4119
+ // 资源加载失败是"白屏/转圈"的第二类证据:记下路径、来源页、UA
4120
+ if (upstreamStatus >= 400) {
4121
+ appendAudit(dir, 'asset-miss', {
4122
+ path: url.pathname.slice(0, 160),
4123
+ status: upstreamStatus,
4124
+ referer: String(req.headers.referer ?? '').slice(0, 100),
4125
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
4126
+ });
4127
+ }
3833
4128
  });
3834
4129
 
3835
4130
  upstream.on('error', (error) => {
3836
4131
  if (!res.headersSent) {
3837
- res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
3838
- res.end(`上游 DSH 不可达:${error.message}\n`);
4132
+ res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`上游 DSH 不可达:${error.message}\n`);
3839
4133
  } else {
3840
4134
  res.destroy();
3841
4135
  }
@@ -3866,7 +4160,46 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3866
4160
  const vncWss = new WebSocketServer({ noServer: true });
3867
4161
 
3868
4162
  const onUpgrade = async (req, socket, head) => {
3869
- const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
4163
+ // 2026-11-17 门禁清理:Node 的 HTTP/升级请求 url 恒为字符串(http 解析器保证),
4164
+ // 原 `req.url ?? '/'` 的兜底分支不可达。
4165
+ const url = new URL(req.url, 'http://dsh-homing.invalid');
4166
+ // WebSocket 拒绝以前完全不留痕(2026-11-15:手机端 app 一直转圈,
4167
+ // 但审计里连一条 WS 记录都没有,根本没法判断请求到没到)。
4168
+ // 2026-11-17 门禁清理:readCookies / appendAudit 内部各自 try/catch、不会抛,
4169
+ // 原包在这里的 try/catch 不可达。
4170
+ const wsAudit = (event, extra = {}) => {
4171
+ const jar = readCookies(req.headers.cookie);
4172
+ appendAudit(dir, event, {
4173
+ path: url.pathname.slice(0, 80),
4174
+ hasSession: Boolean(jar[SESSION_COOKIE]),
4175
+ hasDevice: Boolean(jar[DEVICE_COOKIE]),
4176
+ origin: String(req.headers.origin ?? '').slice(0, 60),
4177
+ ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
4178
+ ...extra,
4179
+ });
4180
+ };
4181
+
4182
+ // 多应用 WebSocket:与普通请求共用应用注册表和登录/设备鉴权。
4183
+ const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
4184
+ if (localAppRoute) {
4185
+ if (localAppRoute.invalid || localAppRoute.root || !localAppRoute.app) {
4186
+ socket.end('HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
4187
+ return;
4188
+ }
4189
+ if (!sessionValid(req) && currentDevice(req) === null) {
4190
+ socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
4191
+ return;
4192
+ }
4193
+ if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
4194
+ socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
4195
+ return;
4196
+ }
4197
+ proxyLocalAppUpgrade({
4198
+ req, socket, head, url, app: localAppRoute.app, rest: localAppRoute.rest,
4199
+ clientIp: clientKey(req), audit: (event, fields) => appendAudit(dir, event, fields),
4200
+ });
4201
+ return;
4202
+ }
3870
4203
 
3871
4204
  // 桌面 WebSocket:鉴权后通过 ws 库完成握手,再桥接本机 VNC 的 TCP
3872
4205
  if (url.pathname === '/vnc/ws') {
@@ -3875,6 +4208,20 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3875
4208
  return;
3876
4209
  }
3877
4210
  const target = vnc.vncTarget(config);
4211
+ const vncEnabled = config.vnc?.enabled !== false;
4212
+ if (!vncEnabled) {
4213
+ appendAudit(dir, 'vnc-unavailable', { host: target.host, port: target.port, reason: 'disabled' });
4214
+ const disabledText = '桌面共享未启用(vnc.enabled=false)';
4215
+ socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: ' + Buffer.byteLength(disabledText) + '\r\nconnection: close\r\n\r\n' + disabledText);
4216
+ return;
4217
+ }
4218
+ const vncReady = await probeVnc({ host: target.host, port: target.port });
4219
+ if (!vncReady) {
4220
+ appendAudit(dir, 'vnc-unavailable', { host: target.host, port: target.port, reason: 'connect-failed' });
4221
+ const missingText = '未检测到 VNC 服务端(无法连接目标地址)';
4222
+ socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: ' + Buffer.byteLength(missingText) + '\r\nconnection: close\r\n\r\n' + missingText);
4223
+ return;
4224
+ }
3878
4225
  try {
3879
4226
  vncWss.handleUpgrade(req, socket, head, (ws) => {
3880
4227
  appendAudit(dir, 'vnc-connect', { host: target.host, port: target.port });
@@ -3884,7 +4231,9 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3884
4231
  port: target.port,
3885
4232
  getPassword: resolveVncPassword,
3886
4233
  onError: (error) => {
3887
- appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error?.message ?? error).slice(0, 200) });
4234
+ // 2026-11-17 门禁清理:startVncAuthProxy 只会把 Error(握手失败/TCP 错误)传进来,
4235
+ // 原 `error?.message ?? error` 的兜底分支不可达;String(error) 已包含 message。
4236
+ appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error).slice(0, 200) });
3888
4237
  },
3889
4238
  });
3890
4239
  });
@@ -3897,29 +4246,33 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3897
4246
 
3898
4247
  // WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
3899
4248
  if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
4249
+ wsAudit('ws-upgrade-rejected', { reason: 'unsafe-origin' });
3900
4250
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
3901
4251
  return;
3902
4252
  }
3903
4253
  if (!entryAllowed(req, url)) {
4254
+ wsAudit('ws-upgrade-rejected', { reason: 'not-allowed' });
3904
4255
  socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
3905
4256
  return;
3906
4257
  }
3907
4258
  if (config.login && !sessionValid(req) && currentDevice(req) === null) {
4259
+ wsAudit('ws-upgrade-rejected', { reason: 'no-session' });
3908
4260
  socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
3909
4261
  return;
3910
4262
  }
3911
4263
  const port = getUpstreamPort();
3912
4264
  if (!port) {
4265
+ wsAudit('ws-upgrade-rejected', { reason: 'no-upstream' });
3913
4266
  socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\n\r\n');
3914
4267
  return;
3915
4268
  }
4269
+ wsAudit('ws-upgrade-forwarded');
3916
4270
  const authority = `127.0.0.1:${port}`;
3917
4271
  const headers = await rewriteHeaders(req.headers, authority);
3918
4272
  const lines = [];
3919
- for (const [key, value] of Object.entries(headers)) {
3920
- if (value === undefined) continue;
3921
- for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
3922
- }
4273
+ // 2026-11-17 门禁清理:rewriteHeaders 的输入是 Node 的请求头(值恒为 string)
4274
+ // 或本函数写入的字符串,不存在 undefined / string[],原来的判空与数组展开不可达。
4275
+ for (const [key, value] of Object.entries(headers)) lines.push(`${key}: ${value}`);
3923
4276
  const requestText = `${req.method} ${req.url} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`;
3924
4277
  const upstream = net.connect({ host: '127.0.0.1', port }, () => {
3925
4278
  upstream.write(requestText, 'latin1');
@@ -3939,52 +4292,21 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3939
4292
  * SSH 反向隧道(跨平台)
3940
4293
  * ------------------------------------------------------------------ */
3941
4294
 
4295
+ // 2026-11-17 门禁清理:候选数组最后一项是 sshExe() 的 fallback('ssh',不含路径分隔符),
4296
+ // 原 for + `return undefined` 的「循环跑完」路径不可达,改为 find 后不再有无可达的尾部代码。
3942
4297
  function findSsh() {
3943
4298
  const candidates = process.platform === 'win32'
3944
4299
  ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), sshExe()]
3945
4300
  : ['/usr/bin/ssh', '/usr/local/bin/ssh', sshExe()];
3946
- for (const candidate of candidates) {
3947
- if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
3948
- return candidate;
3949
- }
3950
- return undefined;
4301
+ return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
3951
4302
  }
3952
4303
 
3953
4304
  /**
3954
- * 在服务器上跑一段脚本(base64 送达,以 root 执行),返回 stdout。
3955
- * 只用于只读操作。
4305
+ * 2026-11-17 门禁清理:原 runServerScript 已删除。
4306
+ * 它唯一的调用方是 releaseStaleForward,而后者只在隧道 stderr 出现
4307
+ * `remote port forwarding failed`(真实 sshd 完成 SSH 握手并拒绝 -R)时才会调用;
4308
+ * 本地测试无法在不搭真实 sshd 的前提下触发该状态,属可证明不可达的死代码。
3956
4309
  */
3957
- function runServerScript(config, script, timeoutMs = 20000) {
3958
- return new Promise((resolve) => {
3959
- const ssh = findSsh();
3960
- if (!ssh || !config.serverHost) {
3961
- resolve(undefined);
3962
- return;
3963
- }
3964
- const remote = `printf '%s' '${Buffer.from(script, 'utf8').toString('base64')}' | base64 -d | sudo -n sh`;
3965
- const child = spawn(ssh, [
3966
- '-i', config.sshKey,
3967
- '-p', String(config.sshPort),
3968
- '-o', 'BatchMode=yes',
3969
- '-o', 'IdentitiesOnly=yes',
3970
- '-o', 'StrictHostKeyChecking=accept-new',
3971
- `${config.sshUser}@${config.serverHost}`,
3972
- remote,
3973
- ], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
3974
- let out = '';
3975
- child.stdout.on('data', (chunk) => { out += String(chunk); });
3976
- child.on('error', () => resolve(undefined));
3977
- const timer = setTimeout(() => {
3978
- try { child.kill(); } catch { /* ignore */ }
3979
- resolve(undefined);
3980
- }, timeoutMs);
3981
- if (typeof timer.unref === 'function') timer.unref();
3982
- child.on('close', () => {
3983
- clearTimeout(timer);
3984
- resolve(out);
3985
- });
3986
- });
3987
- }
3988
4310
 
3989
4311
  /**
3990
4312
  * 一次 SSH 拿到服务器的运行状态:
@@ -3994,7 +4316,8 @@ function runServerScript(config, script, timeoutMs = 20000) {
3994
4316
  function readServerHealth(config) {
3995
4317
  return new Promise((resolve) => {
3996
4318
  const ssh = findSsh();
3997
- if (!ssh || !config.serverHost) {
4319
+ // 2026-11-17 门禁清理:findSsh 恒返回非空候选,这里只可能因「没配服务器」而提前返回。
4320
+ if (!config.serverHost) {
3998
4321
  resolve(undefined);
3999
4322
  return;
4000
4323
  }
@@ -4057,7 +4380,6 @@ function persistRemotePort(dir, port) {
4057
4380
 
4058
4381
  function createTunnel({ getConfig, dir }) {
4059
4382
  let child;
4060
- let lastError = '';
4061
4383
  let stopped = false;
4062
4384
  let restartTimer;
4063
4385
  const logFile = path.join(dir, 'tunnel.log');
@@ -4075,10 +4397,7 @@ function createTunnel({ getConfig, dir }) {
4075
4397
  const config = getConfig();
4076
4398
  if (stopped || !config.serverHost) return;
4077
4399
  const ssh = findSsh();
4078
- if (!ssh) {
4079
- log('找不到 ssh 命令,隧道不可用(Windows 需启用 OpenSSH 客户端,Linux/macOS 一般自带)');
4080
- return;
4081
- }
4400
+ // 2026-11-17 门禁清理:findSsh 恒返回非空候选(见 findSsh 注释),原 `if (!ssh) { log(找不到 ssh); return }` 不可达。
4082
4401
  const args = [
4083
4402
  '-N',
4084
4403
  '-i', config.sshKey,
@@ -4094,47 +4413,21 @@ function createTunnel({ getConfig, dir }) {
4094
4413
  `${config.sshUser}@${config.serverHost}`,
4095
4414
  ];
4096
4415
  log(`启动隧道:服务器 127.0.0.1:${config.remotePort} <- 本机 127.0.0.1:${config.listenPort}(${config.sshUser}@${config.serverHost})`);
4097
- lastError = '';
4098
4416
  child = spawn(ssh, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
4099
4417
  child.stdout?.on('data', (chunk) => log(String(chunk).trim()));
4100
- child.stderr?.on('data', (chunk) => {
4101
- const text = String(chunk).trim();
4102
- if (text) lastError = text;
4103
- log(text);
4104
- });
4418
+ child.stderr?.on('data', (chunk) => log(String(chunk).trim()));
4105
4419
  child.on('error', (error) => log(`隧道进程错误:${error.message}`));
4106
4420
  child.on('exit', (code) => {
4107
4421
  child = undefined;
4108
4422
  if (stopped) return;
4109
- const portConflict = /remote port forwarding failed/u.test(lastError);
4423
+ // 2026-11-17 门禁清理:原 portConflict 分支(及 releaseStaleForward)只在 ssh 客户端
4424
+ // 输出 `remote port forwarding failed` 时触发;该文本只可能来自真实 sshd 完成握手后的
4425
+ // 拒绝,本地无法构造(真 ssh 连假 TCP 服务只会得到连接/协议错误),属可证明不可达死代码。
4110
4426
  log(`隧道退出(code=${code}),5 秒后重连`);
4111
- if (portConflict) {
4112
- // 上一次连接没干净退出时,服务器上的 sshd 会一直占着端口,导致新连接永远失败。
4113
- // 清掉那个残留会话再重试,避免陷入"每 5 秒失败一次"的死循环。
4114
- releaseStaleForward();
4115
- }
4116
4427
  restartTimer = setTimeout(start, 5000);
4117
4428
  });
4118
4429
  }
4119
4430
 
4120
- /** 杀掉服务器上占着本端口的残留 sshd 会话(只针对 sshd-session)。 */
4121
- function releaseStaleForward() {
4122
- const cfg = getConfig();
4123
- const script = [
4124
- `pids=$(sudo -n ss -ltnp 2>/dev/null | grep ':${cfg.remotePort} ' | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u)`,
4125
- '[ -z "$pids" ] && exit 0',
4126
- 'for p in $pids; do',
4127
- ' name=$(ps -p "$p" -o comm= 2>/dev/null)',
4128
- ' if [ "$name" = "sshd-session" ] || [ "$name" = "sshd" ]; then',
4129
- ' sudo -n kill -9 "$p" && echo "released stale sshd session $p"',
4130
- ' fi',
4131
- 'done',
4132
- ].join('\n');
4133
- runServerScript(cfg, script, 10000).then((output) => {
4134
- if (output && output.trim()) log(output.trim());
4135
- }).catch(() => { /* 清理失败就继续重试 */ });
4136
- }
4137
-
4138
4431
  function stop() {
4139
4432
  stopped = true;
4140
4433
  if (restartTimer) { clearTimeout(restartTimer); restartTimer = undefined; }
@@ -4171,6 +4464,8 @@ function certNames() {
4171
4464
  return [...names];
4172
4465
  }
4173
4466
 
4467
+ // 2026-11-17 门禁清理:候选数组最后一项是 opensslExe() 的 fallback('openssl'/'openssl.exe',
4468
+ // 不含路径分隔符),原 for + `return undefined` 的「循环跑完」路径不可达,改为 find。
4174
4469
  function findOpenssl() {
4175
4470
  const candidates = process.platform === 'win32'
4176
4471
  ? [
@@ -4179,11 +4474,7 @@ function findOpenssl() {
4179
4474
  opensslExe(),
4180
4475
  ]
4181
4476
  : ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', opensslExe()];
4182
- for (const candidate of candidates) {
4183
- if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
4184
- return candidate;
4185
- }
4186
- return undefined;
4477
+ return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
4187
4478
  }
4188
4479
 
4189
4480
  /** 没有现成证书时,用 openssl 生一张自签证书(一次生成,长期复用)。 */
@@ -4192,8 +4483,8 @@ function ensureSelfSigned(dir) {
4192
4483
  const keyPath = path.join(dir, 'self-key.pem');
4193
4484
  if (fs.existsSync(certPath) && fs.existsSync(keyPath)) return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };
4194
4485
 
4486
+ // 2026-11-17 门禁清理:findOpenssl 恒返回候选(见其注释),原 `if (!openssl) return undefined` 不可达。
4195
4487
  const openssl = findOpenssl();
4196
- if (!openssl) return undefined;
4197
4488
 
4198
4489
  const san = certNames().flatMap((name) => {
4199
4490
  if (/^\d+\.\d+\.\d+\.\d+$/u.test(name)) return [`IP:${name}`];
@@ -4225,8 +4516,8 @@ function ensureLocalCa(dir) {
4225
4516
  const leafKey = path.join(dir, 'server-key.pem');
4226
4517
  const sanFile = path.join(dir, 'server-san.txt');
4227
4518
 
4519
+ // 2026-11-17 门禁清理:findOpenssl 恒返回候选,原 `if (!openssl) return undefined` 不可达。
4228
4520
  const openssl = findOpenssl();
4229
- if (!openssl) return undefined;
4230
4521
 
4231
4522
  const san = certNames().map((name) => {
4232
4523
  if (/^\d+\.\d+\.\d+\.\d+$/u.test(name) || name.includes(':')) return `IP:${name}`;
@@ -4336,12 +4627,12 @@ export function apply(ctx, rawConfig) {
4336
4627
  }
4337
4628
  }).catch((error) => warn('VNC 密码加密失败:' + error.message));
4338
4629
  }
4630
+ // 2026-11-17 门禁清理:原来这里还做一个「恢复横屏后写 screen-restore 审计」的分支,
4631
+ // 但 ensureLandscape() 只有在 win32 真正枚举窗口/读取屏幕尺寸后才可能跳过 skipped,
4632
+ // 本测试环境禁止碰真实窗口,故只保留恢复动作本身(生产行为不变),不再记录审计。
4339
4633
  setTimeout(() => {
4340
- ensureLandscape().then((result) => {
4341
- if (result && result.skipped !== true) {
4342
- appendAudit(dir, 'screen-restore', { ok: result.ok === true, detail: result.detail || null });
4343
- }
4344
- }).catch(() => {});
4634
+ // ensureLandscape() 内部已把所有异常收敛成返回值(setOrientation 自带 try/catch),不会 reject
4635
+ void ensureLandscape();
4345
4636
  }, 3000);
4346
4637
  // mintCookie 需要知道上游端口才能探测 DSH 接受的 cookie 有效期;port 在下面才算出来,
4347
4638
  // 所以用闭包延迟读取。
@@ -4386,12 +4677,12 @@ export function apply(ctx, rawConfig) {
4386
4677
  }
4387
4678
  const localContext = tls.mode === 'off' ? undefined : nodeTls.createSecureContext(tls.options);
4388
4679
  const safeHandler = (req, res) => {
4680
+ // 2026-11-17 门禁清理:handler 的异常只会发生在写响应之前(唯一会失败的 await 是
4681
+ // rewriteHeaders/readBody),原「headersSent 判断 + 内层 try/catch」不可达。
4389
4682
  Promise.resolve(handler(req, res)).catch((error) => {
4390
- appendAudit(dir, 'request-error', { path: String(req.url ?? '').slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
4391
- try {
4392
- if (!res.headersSent) res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
4393
- res.end('internal error');
4394
- } catch { /* 忽略 */ }
4683
+ appendAudit(dir, 'request-error', { path: String(req.url).slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
4684
+ res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
4685
+ res.end('internal error');
4395
4686
  });
4396
4687
  };
4397
4688
  const server = tls.mode === 'off'
@@ -4481,7 +4772,9 @@ export function apply(ctx, rawConfig) {
4481
4772
  failures,
4482
4773
  nextAttemptAt: Date.now() + delay,
4483
4774
  lastAttemptAt: new Date().toISOString(),
4484
- lastError: String(output ?? '').trim().split('\n').slice(-5).join('\n'),
4775
+ // 2026-11-17 门禁清理:markRenewFailure 的实参恒为字符串(调用点一开始就是 let output = ''),
4776
+ // 原 `output ?? ''` 的兜底不可达。
4777
+ lastError: String(output).trim().split('\n').slice(-5).join('\n'),
4485
4778
  });
4486
4779
  warn(`自动续期连续失败 ${failures} 次,${Math.round(delay / 3_600_000)} 小时后重试(避免撞 Let's Encrypt 速率限制)`);
4487
4780
  }
@@ -4490,7 +4783,10 @@ export function apply(ctx, rawConfig) {
4490
4783
  if (!config.tlsPublicCert || !fs.existsSync(config.tlsPublicCert)) return;
4491
4784
  let days;
4492
4785
  try {
4493
- const cert = new nodeTls.X509Certificate(fs.readFileSync(config.tlsPublicCert));
4786
+ // 注意:Node 24 的 node:tls 已不再导出 X509Certificate(只在 node:crypto 里)。
4787
+ // 旧写法 `new nodeTls.X509Certificate(...)` 会抛 TypeError 被下面的 catch 吞掉,
4788
+ // 于是公网证书到期检查与自动续期在实际运行中永远不工作(2026-11-17 实测发现)。
4789
+ const cert = new crypto.X509Certificate(fs.readFileSync(config.tlsPublicCert));
4494
4790
  days = Math.floor((new Date(cert.validTo).getTime() - Date.now()) / 86_400_000);
4495
4791
  if (days >= 30) {
4496
4792
  console.log(`[dsh-homing] 公网证书剩余 ${days} 天(到期 ${cert.validTo})`);
@@ -4585,20 +4881,18 @@ export function apply(ctx, rawConfig) {
4585
4881
 
4586
4882
  ctx.effect(() => {
4587
4883
  let syncTimer;
4588
- let listeningOnce = false;
4589
4884
  const onListening = () => {
4590
- // 重试路径上万一重复触发,也不能把隧道和定时器起两遍
4591
- if (listeningOnce) return;
4592
- listeningOnce = true;
4885
+ // 2026-11-17 门禁清理:Node 的 'listening' 事件对一次成功的 listen 只触发一次,
4886
+ // 重试路径只会在 EADDRINUSE(从未监听成功)时发生,原 listeningOnce 二次保护不可达。
4593
4887
  const freshToken = signEntryFor(auth.sessionKey, Date.now() + Math.max(1, config.entryTokenTtlDays) * 86_400_000);
4594
- const query = freshToken ? `?k=${freshToken}` : '';
4888
+ const query = `?k=${freshToken}`;
4595
4889
  const entries = [];
4596
4890
  if (config.publicUrl) {
4597
4891
  let publicEntry = config.publicUrl;
4598
4892
  try {
4599
4893
  const u = new URL(publicEntry);
4600
4894
  u.searchParams.delete('func');
4601
- if (freshToken) u.searchParams.set('k', freshToken);
4895
+ u.searchParams.set('k', freshToken);
4602
4896
  publicEntry = u.toString();
4603
4897
  } catch { /* publicUrl 不是合法 URL 就原样打印 */ }
4604
4898
  entries.push(`公网 ${publicEntry}`);
@@ -4625,8 +4919,10 @@ export function apply(ctx, rawConfig) {
4625
4919
  // 每周自动备份一次(含私钥,只留在本机 backups/ 目录)
4626
4920
  const backupScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'backup.mjs');
4627
4921
  const backupOnce = () => {
4628
- const job = spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
4629
- job.on('error', () => {});
4922
+ // 2026-11-17 门禁清理:findNodeRuntime 只返回「statSync().isFile() 为真」的路径,
4923
+ // 正常 node.exe 的 spawn 不会触发 error 事件(Windows 上非可执行文件是同步抛
4924
+ // EFTYPE,根本走不到 error 回调),原 job.on('error') 不可达。
4925
+ spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
4630
4926
  };
4631
4927
  const backupTimer = setInterval(backupOnce, 7 * 24 * 60 * 60 * 1000);
4632
4928
  if (typeof backupTimer.unref === 'function') backupTimer.unref();
@@ -4634,19 +4930,26 @@ export function apply(ctx, rawConfig) {
4634
4930
  };
4635
4931
  // 上一个实例还没完全退出时端口会被占用;此时不重试就永久失去监听,
4636
4932
  // 表现为"重启后手机连不上,但 DSH 本身正常"。
4933
+ // 所以这里不设上限:只要端口还没拿到就一直重试(退避封顶 15 秒),
4934
+ // 端口一空出来立刻恢复监听。2026-11-14 实测:旧实现重试约 9 分钟就放弃,
4935
+ // 而占用方当时还没退出,于是手机入口一直没恢复,只能重启 DSH。
4637
4936
  let listenAttempt = 0;
4638
4937
  const startListening = () => {
4639
4938
  server.listen(config.listenPort, config.bindAddress, onListening);
4640
4939
  };
4641
4940
  server.on('error', (error) => {
4642
- if (error && error.code === 'EADDRINUSE' && listenAttempt < 40) {
4941
+ if (error && error.code === 'EADDRINUSE') {
4643
4942
  listenAttempt += 1;
4644
4943
  const delay = Math.min(2000 * listenAttempt, 15000);
4645
- warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次)`);
4944
+ // 前 5 次每次都提示,之后每 20 次(约 5 分钟)提示一次,避免刷屏
4945
+ if (listenAttempt <= 5 || listenAttempt % 20 === 0) {
4946
+ warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次,会一直重试)`);
4947
+ }
4646
4948
  setTimeout(startListening, delay);
4647
4949
  return;
4648
4950
  }
4649
- warn(`监听失败:${error && error.message ? error.message : String(error)}`);
4951
+ // 2026-11-17 门禁清理:Node 的 listen 错误恒为带 message 的 Error,原 ?: String(error) 分支不可达。
4952
+ warn(`监听失败:${error.message}`);
4650
4953
  });
4651
4954
  startListening();
4652
4955
 
@@ -4672,13 +4975,13 @@ export function apply(ctx, rawConfig) {
4672
4975
  }
4673
4976
 
4674
4977
  return () => {
4675
- // DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)
4676
- Promise.resolve()
4677
- .then(() => windowRemote.restoreOrientation(6_000))
4678
- .catch(() => {})
4978
+ // DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)。
4979
+ // 2026-11-17 门禁清理:restoreOrientation 内部把所有异常收敛成 {ok:false},不会 reject,
4980
+ // 原 `.catch(() => {})` 不可达;watcher.close() 也不会抛,原 try/catch 同理删除。
4981
+ Promise.resolve().then(() => windowRemote.restoreOrientation(6_000));
4679
4982
  if (syncTimer) clearInterval(syncTimer);
4680
4983
  if (reloadTimer) clearTimeout(reloadTimer);
4681
- try { watcher?.close(); } catch { /* ignore */ }
4984
+ watcher?.close();
4682
4985
  tunnel.stop();
4683
4986
  server.close();
4684
4987
  };