@andy.ian/dsh-homing 2.1.14 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -33,21 +33,27 @@ import { createRestartPolicy } from './restart/face.mjs';
33
33
  import * as compress from './lib/compress.mjs';
34
34
  import * as office from './lib/office.mjs';
35
35
  import * as markdown from './lib/markdown.mjs';
36
+ import { NAV_CSS, topNav } from './lib/nav.mjs';
36
37
  import * as windowRemote from './lib/window-remote.mjs';
37
38
  import { setOrientation, ensureLandscape } from './lib/orientation.mjs';
38
39
  import { protectSecret, unprotectSecret } from './lib/secret.mjs';
39
40
  import { startVncAuthProxy } from './lib/vnc-auth-proxy.mjs';
40
41
  import { renderWindowPage } from './lib/window-page.mjs';
41
42
  import * as vnc from './lib/vnc.mjs';
43
+ import { probeVnc } from './lib/vnc-probe.mjs';
42
44
  import { bridge as bridgeWebSocketToTcp } from './lib/ws-bridge.mjs';
43
45
  import { WebSocketServer } from './lib/vendor/ws/wrapper.mjs';
44
46
  import { renderVncPage } from './lib/vnc-page.mjs';
45
47
  import { customShells, detectShells, resolveShell, DEFAULT_SHELL } from './lib/shells.mjs';
46
48
  import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderCompressPage } from './lib/files-page.mjs';
47
- import { checkUnsafeOrigin } from './lib/csrf.mjs';
49
+ import { checkUnsafeOrigin, checkOwnPageWrite } from './lib/csrf.mjs';
48
50
  import { validateOpenPath } from './lib/guard.mjs';
49
51
  import { opensslExe, sshExe } from './lib/exec-path.mjs';
50
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';
51
57
 
52
58
  export const name = 'dsh-homing';
53
59
 
@@ -369,301 +375,10 @@ function createCookieMinter(credentials, getUpstreamPort) {
369
375
  }
370
376
 
371
377
  /* ------------------------------------------------------------------ *
372
- * 移动端补丁
378
+ * 移动端补丁:MOBILE_CSS / MOBILE_JS 在 lib/mobile-patch.mjs,单独成文件
379
+ * 以便用真实 DOM 桩做行为测试(见 test/unit.mobile-patch.test.mjs)。
373
380
  * ------------------------------------------------------------------ */
374
381
 
375
- const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
376
- @media (max-width: 760px) {
377
- [class*="_frame"] { min-width: 0; }
378
- }
379
- `;
380
-
381
- const MOBILE_JS = `(() => {
382
- const narrow = () => window.innerWidth <= 760
383
- const root = document.documentElement
384
- const sidebar = () => document.querySelector('[class*="sidebarCol"]')
385
- // 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
386
- // 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
387
- const LAST_WS_KEY = 'dsh-homing:last-workspace'
388
- document.addEventListener('click', (event) => {
389
- const node = event.target
390
- if (node === null || typeof node.closest !== 'function') return
391
- const item = node.closest('[role="menuitem"]')
392
- const side = node.closest('[class*="sidebarCol"]')
393
- const candidate = item ?? (side === null ? null : node.closest('button, [role="treeitem"], [class*="session"], [class*="item"], div'))
394
- if (candidate === null) return
395
- const text = (candidate.textContent || '').replace(/\s+/g, ' ').trim()
396
- if (text === '' || text.length > 40) return
397
- // 排除操作类菜单项,只记看起来像工作区名字的
398
- if (/文件资源管理器|VS Code|Git Bash|添加工作区|新会话|搜索|设置|插件|自动化任务|更多|账号|退出/u.test(text)) return
399
- try { window.localStorage.setItem(LAST_WS_KEY, text) } catch { /* 隐私模式 */ }
400
- }, true)
401
-
402
- // 标题栏里那个「文件夹 + 小箭头」是分裂按钮:
403
- // 点箭头出菜单(我们已按文字拦截),点文件夹图标则直接在本机打开目录,手机上看不到。
404
- // 这里按结构识别:带 aria-haspopup 的按钮和文件夹图标在同一个父容器里,
405
- // 那么点这个容器里的任何按钮,都按"打开工作区目录"处理。
406
- const folderHost = () => {
407
- for (const node of document.querySelectorAll('[aria-haspopup]')) {
408
- const rect = node.getBoundingClientRect()
409
- if (rect.width === 0 || rect.height === 0) continue
410
- if (rect.top > 130) continue
411
- const host = node.parentElement
412
- if (host === null) continue
413
- const buttons = host.querySelectorAll('button, [role="button"]')
414
- if (buttons.length > 0 && buttons.length <= 3) return host
415
- }
416
- return null
417
- }
418
-
419
- // 当前会话标题:从标题栏(页面顶部、class 里带 title/tab/header 的元素)取最长的文本。
420
- // 用它去反查会话记录里的 cwd,就能打开"当前会话所属工作区"的目录。
421
- const currentSessionTitle = () => {
422
- let best = ''
423
- for (const node of document.querySelectorAll('div, span, h1, h2, header')) {
424
- const rect = node.getBoundingClientRect()
425
- if (rect.width === 0 || rect.height === 0) continue
426
- if (rect.top > 120 || rect.height > 44) continue
427
- const cls = String(node.className || '')
428
- if (!/title|tab|header|crumb|label/iu.test(cls)) continue
429
- const text = (node.textContent || '').trim()
430
- if (text.length < 2 || text.length > 60) continue
431
- if (text.length > best.length) best = text
432
- }
433
- return best
434
- }
435
-
436
- // 应用把"当前会话"存在 localStorage 里,直接读它 —— 这是确定值,不靠猜。
437
- const currentSessionId = () => {
438
- try {
439
- const raw = window.localStorage.getItem('dsh.sessions.current')
440
- if (raw === null) return ''
441
- const parsed = JSON.parse(raw)
442
- const id = parsed && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
443
- return /^session-[A-Za-z0-9-]+$/u.test(id) ? id : ''
444
- } catch {
445
- return ''
446
- }
447
- }
448
-
449
- const goFiles = () => {
450
- const session = currentSessionId()
451
- if (session !== '') {
452
- window.location.href = '/files?session=' + encodeURIComponent(session)
453
- return
454
- }
455
- let hint = ''
456
- try { hint = currentSessionTitle() || window.localStorage.getItem('dsh-homing:last-workspace') || '' } catch { hint = '' }
457
- window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
458
- }
459
-
460
- document.addEventListener('click', (event) => {
461
- const host = folderHost()
462
- if (host === null) return
463
- const target = event.target
464
- if (target === null || typeof target.closest !== 'function') return
465
- const button = target.closest('button, [role="button"]')
466
- if (button === null || !host.contains(button)) return
467
- // 带 aria-haspopup 的是那个小箭头:放行,让应用的菜单正常弹出。
468
- // 菜单里的「文件资源管理器」由另一段按文字拦截。
469
- if (button.hasAttribute('aria-haspopup')) return
470
- event.preventDefault()
471
- event.stopPropagation()
472
- goFiles()
473
- }, true)
474
-
475
- // 应用下拉里的「文件资源管理器 / VS Code / Git Bash」是在本机启动桌面程序,
476
- // 手机上看不到。这里把「文件资源管理器」接到我们的 /files 页面;
477
- // 另外两项给一条提示,避免点了没反应。
478
- const desktopOnly = (event) => {
479
- const node = event.target
480
- if (node === null || typeof node.closest !== 'function') return
481
- const item = node.closest('[role="menuitem"], button, li, div')
482
- const text = item === null ? '' : (item.textContent || '').trim()
483
- if (text === '') return
484
- if (text.includes('文件资源管理器')) {
485
- event.preventDefault()
486
- event.stopPropagation()
487
- // 尽量从属性里挖工作区路径,挖不到就让文件页自己决定默认目录
488
- let target = ''
489
- for (const holder of [item, ...(item.querySelectorAll('[data-path], [title]') || [])]) {
490
- if (holder === null) continue
491
- const dataPath = holder.getAttribute && holder.getAttribute('data-path')
492
- const title = holder.getAttribute && holder.getAttribute('title')
493
- if (dataPath) { target = dataPath; break }
494
- if (title && /^[A-Za-z]:[\\/]|^\//u.test(title)) { target = title; break }
495
- }
496
- // 带上当前选中的工作区名,服务端会映射成路径;映射不到就落到默认工作区
497
- let remembered = ''
498
- try { remembered = window.localStorage.getItem(LAST_WS_KEY) || '' } catch { /* 隐私模式 */ }
499
- const selected = remembered !== '' ? remembered : (() => {
500
- const side = document.querySelector('[class*="sidebarCol"]')
501
- if (side === null) return ''
502
- let best = ''
503
- for (const node of side.querySelectorAll('[class*="selected"], [class*="active"], [aria-current]')) {
504
- const text = (node.textContent || '').trim()
505
- if (text === '' || text.length > 40) continue
506
- if (best === '' || text.length < best.length) best = text
507
- }
508
- return best
509
- })()
510
- const session = currentSessionId()
511
- const query = target ? '?path=' + encodeURIComponent(target)
512
- : session !== '' ? '?session=' + encodeURIComponent(session)
513
- : '?hint=' + encodeURIComponent(currentSessionTitle() || selected || '')
514
- window.location.href = '/files' + query
515
- return
516
- }
517
- if (text.includes('VS Code')) {
518
- // 手机上用文件页 + 编辑功能代替(点文件旁的 ✏️ 可改可存)
519
- event.preventDefault()
520
- event.stopPropagation()
521
- const session = currentSessionId()
522
- window.location.href = '/files' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
523
- return
524
- }
525
- if (text.includes('Git Bash')) {
526
- // 手机上用 /git 页代替:可执行任意 git 命令
527
- event.preventDefault()
528
- event.stopPropagation()
529
- const session = currentSessionId()
530
- window.location.href = '/term' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
531
- return
532
- }
533
- }
534
- document.addEventListener('click', desktopOnly, true)
535
-
536
- let lastRight = 0
537
- const closeRightBar = () => {
538
- if (!narrow()) return
539
- if (document.querySelector('[data-rightbar-collapsed="false"]') === null) return
540
- if (Date.now() - lastRight < 2500) return
541
- const button = document.querySelector('[aria-label="收起右侧边栏"]')
542
- if (button === null) return
543
- lastRight = Date.now()
544
- button.click()
545
- }
546
-
547
- const start = () => {
548
- closeRightBar()
549
- }
550
-
551
- /* ---------- SESSION_MENU_ITEMS ----------
552
- * 在 DSH 会话「…」菜单里追加两项:
553
- * - 下载工作区文件:跳到文件页(可逐个文件下载)
554
- * - 重启 DSH / 守护进程:跳到重启页
555
- * 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
556
- * 每轮先清掉旧项,并全局 prune,保证每项最多一个。
557
- */
558
- const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
559
- 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"/>'
560
- 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"/>'
561
- let menuTimer = null
562
-
563
- const textNodeMatching = (node, pattern) => {
564
- const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
565
- for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
566
- if (pattern.test(current.nodeValue || '')) return current
567
- }
568
- return null
569
- }
570
-
571
- const buildMenuItem = (template, label, icon, action) => {
572
- const link = template.cloneNode(true)
573
- link.setAttribute('role', 'menuitem')
574
- link.setAttribute('href', '#')
575
- link.style.textDecoration = 'none'
576
- const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
577
- if (textNode !== null) textNode.nodeValue = label
578
- else link.textContent = label
579
- const svg = link.querySelector('svg')
580
- if (svg !== null) {
581
- svg.innerHTML = icon
582
- svg.setAttribute('viewBox', '0 0 24 24')
583
- svg.setAttribute('fill', 'none')
584
- svg.setAttribute('stroke', 'currentColor')
585
- svg.setAttribute('stroke-width', '2')
586
- svg.setAttribute('stroke-linecap', 'round')
587
- svg.setAttribute('stroke-linejoin', 'round')
588
- }
589
- link.addEventListener('click', (event) => {
590
- event.preventDefault()
591
- event.stopPropagation()
592
- action()
593
- }, true)
594
- return link
595
- }
596
-
597
- const enhanceMenus = () => {
598
- const done = new Set()
599
- for (const item of document.querySelectorAll('[role="menuitem"]')) {
600
- const menu = item.closest('[role="menu"]') ?? item.parentElement
601
- if (menu === null || done.has(menu)) continue
602
- if (!MENU_HINT.test(menu.textContent || '')) continue
603
- done.add(menu)
604
-
605
- for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
606
-
607
- const items = [...menu.querySelectorAll('[role="menuitem"]')]
608
- const template = items.find((node) => node.querySelector('svg')) ?? items[0]
609
- if (!template) continue
610
-
611
- const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
612
- download.setAttribute('data-dsh-homing-download', '1')
613
- const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
614
- restart.setAttribute('data-dsh-homing-restart', '1')
615
-
616
- menu.appendChild(download)
617
- menu.appendChild(restart)
618
- }
619
- }
620
-
621
- // 兜底:无论菜单容器怎么嵌套,每类最多保留一个
622
- const pruneMenuItems = () => {
623
- for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
624
- const all = [...document.querySelectorAll(selector)]
625
- for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
626
- }
627
- }
628
-
629
- const menuObserver = new MutationObserver(() => {
630
- if (menuTimer) return
631
- menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
632
- })
633
- menuObserver.observe(document.body, { childList: true, subtree: true })
634
-
635
- /* ---------- ALIVE_BEACON ----------
636
- * 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
637
- * 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
638
- * 节流 2 秒,页面隐藏时不发(后台标签页不算活跃)。
639
- */
640
- const ALIVE_INTERVAL = 2000
641
- let aliveAt = 0
642
- const alive = () => {
643
- const now = Date.now()
644
- if (now - aliveAt < ALIVE_INTERVAL) return
645
- aliveAt = now
646
- try {
647
- if (document.visibilityState === 'hidden') return
648
- const body = JSON.stringify({ at: now, path: location.pathname })
649
- if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
650
- else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
651
- } catch (error) {
652
- /* 忽略 */
653
- }
654
- }
655
- document.addEventListener('keydown', alive, true)
656
- document.addEventListener('pointerdown', alive, true)
657
- document.addEventListener('input', alive, true)
658
- document.addEventListener('compositionstart', alive, true)
659
- window.addEventListener('focus', alive, true)
660
-
661
- if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
662
- else start()
663
- })();
664
-
665
- `;
666
-
667
382
  const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
668
383
 
669
384
  // 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
@@ -846,11 +561,12 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
846
561
 
847
562
  const policy = restartPolicy.status()
848
563
  const cfg = policy?.config ?? {}
849
- const nav = '<div class="nav"><a href="/">← 返回 DSH</a><a href="/files">文件</a><a href="/git">Git</a><a href="/term">终端</a><a href="/debug">调试</a></div>'
564
+ const nav = topNav()
850
565
 
851
566
  return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
852
567
  + '<meta name="viewport" content="width=device-width,initial-scale=1">'
853
568
  + '<title>重启 DSH</title><style>'
569
+ + NAV_CSS
854
570
  + 'body{background:#12161d;color:#dbe2ea;font:14px/1.45 system-ui,-apple-system,"Noto Sans SC",sans-serif;margin:0 auto;padding:10px 12px 20px;max-width:620px}'
855
571
  + 'h1{font-size:17px;margin:0}.sub{color:#8b93a1;font-size:12px;margin:2px 0 8px}'
856
572
  + '.nav{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 10px}'
@@ -916,7 +632,7 @@ const DEBUG_HTML = `<!doctype html>
916
632
  <html lang="zh-CN"><head><meta charset="utf-8">
917
633
  <meta name="viewport" content="width=device-width, initial-scale=1">
918
634
  <title>调试 · DSH 手机入口</title>
919
- <style>
635
+ <style>${NAV_CSS}
920
636
  :root { color-scheme: dark; }
921
637
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
922
638
  .wrap { max-width: 620px; margin: 0 auto; padding: 20px 16px 60px; }
@@ -942,7 +658,7 @@ const DEBUG_HTML = `<!doctype html>
942
658
  .shots img { width:88px; height:88px; object-fit:cover; border-radius:8px; border:1px solid #262b36; }
943
659
  code { background:#1d2229; padding:1px 5px; border-radius:4px; font-size:12px; }
944
660
  </style></head>
945
- <body><div class="wrap">
661
+ <body><div class="wrap">${topNav({ current: '/debug' })}
946
662
  <h1>调试页</h1>
947
663
  <p class="sub">这一页不依赖移动端样式,界面被改坏时也能打开。</p>
948
664
  <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
@@ -1043,7 +759,7 @@ const ACCOUNT_HTML = `<!doctype html>
1043
759
  <html lang="zh-CN"><head><meta charset="utf-8">
1044
760
  <meta name="viewport" content="width=device-width, initial-scale=1">
1045
761
  <title>账户 · DSH 手机入口</title>
1046
- <style>
762
+ <style>${NAV_CSS}
1047
763
  :root { color-scheme: dark; }
1048
764
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
1049
765
  .wrap { max-width: 640px; margin: 0 auto; padding: 24px 18px 48px; }
@@ -1060,7 +776,7 @@ const ACCOUNT_HTML = `<!doctype html>
1060
776
  ul { padding-left:18px; margin:8px 0 0; font-size:13px; color:#9aa4b2; }
1061
777
  a { color:#7aa7ff; }
1062
778
  </style></head>
1063
- <body><div class="wrap">
779
+ <body><div class="wrap">${topNav({ current: '/dsh_homing/account' })}
1064
780
  <h1>账户设置</h1>
1065
781
  <p class="sub"><a href="/dsh_homing/devices">设备管理(吊销/删除已配对设备)→</a></p>
1066
782
  <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
@@ -1318,7 +1034,7 @@ const LOGIN_HTML = `<!doctype html>
1318
1034
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
1319
1035
  <meta name="robots" content="noindex, nofollow">
1320
1036
  <title>登录 · DSH</title>
1321
- <style>
1037
+ <style>${NAV_CSS}
1322
1038
  :root { color-scheme: dark; }
1323
1039
  * { box-sizing: border-box; }
1324
1040
  body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
@@ -1338,7 +1054,7 @@ const LOGIN_HTML = `<!doctype html>
1338
1054
  border: 1px solid rgba(255,80,80,.35); color: #ff9b9b; font-size: 13px; }
1339
1055
  .hint { margin-top: 18px; color: #6b7383; font-size: 12px; text-align: center; }
1340
1056
  </style></head>
1341
- <body><div class="card">
1057
+ <body><div class="card">${topNav()}
1342
1058
  <h1>DeepSeek Harness</h1>
1343
1059
  <p class="sub">请输入本机设置的账号密码</p>
1344
1060
  <form method="post" action="/login">
@@ -1357,7 +1073,7 @@ const RESET_HTML = `<!doctype html>
1357
1073
  <html lang="zh-CN"><head><meta charset="utf-8">
1358
1074
  <meta name="viewport" content="width=device-width, initial-scale=1">
1359
1075
  <title>重置密码 · DSH 手机入口</title>
1360
- <style>
1076
+ <style>${NAV_CSS}
1361
1077
  :root { color-scheme: dark; }
1362
1078
  body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
1363
1079
  .wrap { max-width: 460px; margin: 0 auto; padding: 32px 18px; }
@@ -1370,7 +1086,7 @@ const RESET_HTML = `<!doctype html>
1370
1086
  .msg { background:#2a2618; border:1px solid #514a2a; color:#e8d99a; padding:10px 12px; border-radius:9px; margin:12px 0 0; font-size:14px; }
1371
1087
  a { color:#7aa7ff; }
1372
1088
  </style></head>
1373
- <body><div class="wrap">
1089
+ <body><div class="wrap">${topNav()}
1374
1090
  <h1>重置密码</h1>
1375
1091
  <p>重置需要在<strong>运行 DSH 的那台电脑</strong>上取一个重置码——这确保只有能碰到这台机器的人才能重置。</p>
1376
1092
  {{message}}
@@ -1509,6 +1225,10 @@ function verifyTotp(secret, code, lastStep) {
1509
1225
  }
1510
1226
 
1511
1227
  function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCookies, caCertPath }) {
1228
+ const appRegistry = createLocalAppRegistry({
1229
+ settingsPath: path.join(dir, 'settings.json'),
1230
+ deniedPorts: () => [config.listenPort, restartDaemonPort, getUpstreamPort()],
1231
+ });
1512
1232
  const loginFailures = new Map();
1513
1233
  // 记住上一次验证码用过的时间步,防止同一个 6 位码在 30 秒窗口内被重放
1514
1234
  let lastTotpStep = 0;
@@ -1589,6 +1309,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1589
1309
  // 已登录(会话有效)但还没有设备令牌时,自动补一台并返回 Cookie。
1590
1310
  // 目的:登录过的设备都应出现在设备管理页、可单独吊销;
1591
1311
  // 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
1312
+ // 只有「浏览器页面导航」才允许自动配对/用入口令牌配对。
1313
+ // fetch/XHR/脚本(Accept 不含 text/html)不再产生设备记录,
1314
+ // 否则自动化探测会让设备表越堆越多。
1315
+ const isBrowserNavigation = (req) => String(req.headers.accept ?? '').includes('text/html')
1316
+
1592
1317
  const ensureDeviceCookie = (req, cookies) => {
1593
1318
  const existing = currentDevice(req);
1594
1319
  if (existing !== null) return existing.id;
@@ -1720,9 +1445,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1720
1445
  ;
1721
1446
  // 写操作来源校验:
1722
1447
  // - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
1723
- // - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
1724
- // 跨站 POST 根本带不上来,而微信内置浏览器会发 Origin: null,
1725
- // 强制校验会让「生成密钥」这类按钮直接 403。
1448
+ // - 本插件自己的页面(登录/账户/设备/应用)用宽松规则 checkOwnPageWrite:
1449
+ // 它的 Cookie 都是 SameSite=Lax,跨站 POST 根本带不上来,而微信内置浏览器、
1450
+ // 华为浏览器提交表单时会发 Origin: null(2026-11-14 手机上加应用就是被这里 403),
1451
+ // 严格校验会让这些页面上的按钮直接 Forbidden。明确的跨站证据仍然拒绝。
1726
1452
  const originCheck = checkUnsafeOrigin(req);
1727
1453
  if (!originCheck.ok) {
1728
1454
  const ownPath = url.pathname === '/login' || url.pathname === '/logout'
@@ -1736,6 +1462,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1736
1462
  method: req.method,
1737
1463
  reason: originCheck.reason,
1738
1464
  origin: String(req.headers.origin ?? ''),
1465
+ site: String(req.headers['sec-fetch-site'] ?? ''),
1466
+ referer: String(req.headers.referer ?? ''),
1739
1467
  host: String(req.headers.host ?? ''),
1740
1468
  verdict: ownPath ? 'allowed-own-path' : 'blocked',
1741
1469
  });
@@ -1746,6 +1474,118 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1746
1474
  }
1747
1475
  }
1748
1476
 
1477
+ // 多应用网关:公开入口只负责把已登记应用转发到本机回环服务。
1478
+ const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
1479
+ if (localAppRoute) {
1480
+ if (localAppRoute.root) {
1481
+ res.writeHead(303, { location: sessionValid(req) ? '/dsh_homing/apps' : '/login', 'cache-control': 'no-store' });
1482
+ res.end();
1483
+ return;
1484
+ }
1485
+ if (localAppRoute.invalid || !localAppRoute.app) {
1486
+ res.writeHead(404, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1487
+ res.end(JSON.stringify({ ok: false, error: '应用不存在或未启用' }));
1488
+ return;
1489
+ }
1490
+ const app = localAppRoute.app;
1491
+ if (!sessionValid(req) && currentDevice(req) === null) {
1492
+ if (String(req.headers.accept ?? '').includes('text/html')) {
1493
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
1494
+ res.end();
1495
+ } else {
1496
+ res.writeHead(401, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
1497
+ res.end(JSON.stringify({ ok: false, error: '请先登录' }));
1498
+ }
1499
+ return;
1500
+ }
1501
+ if (localAppRoute.rest === '') {
1502
+ res.writeHead(308, { location: `/apps/${app.id}/${url.search}`, 'cache-control': 'no-store' });
1503
+ res.end();
1504
+ return;
1505
+ }
1506
+ proxyLocalAppHttp({
1507
+ req, res, url, app, rest: localAppRoute.rest,
1508
+ clientIp: clientKey(req), maxBodyBytes: config.maxBodyBytes,
1509
+ audit: (event, fields) => appendAudit(dir, event, fields),
1510
+ });
1511
+ return;
1512
+ }
1513
+
1514
+ // 应用注册表管理:添加服务只改 settings.json,文件变化后立即生效。
1515
+ if (url.pathname === '/dsh_homing/apps') {
1516
+ if (!sessionValid(req)) {
1517
+ res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
1518
+ res.end();
1519
+ return;
1520
+ }
1521
+ if (req.method === 'POST') {
1522
+ // 应用页是插件自己的页面:会话 Cookie 是 SameSite=Lax,跨站 POST 带不上来;
1523
+ // 华为 / 微信浏览器提交表单会发 Origin: null,这里不能用严格规则,
1524
+ // 否则手机上点「添加并启用」直接 403 Forbidden(2026-11-14 实测)。
1525
+ const ownWrite = checkOwnPageWrite(req);
1526
+ if (!ownWrite.ok) {
1527
+ appendAudit(dir, 'app-write-denied', {
1528
+ reason: ownWrite.reason,
1529
+ origin: String(req.headers.origin ?? ''),
1530
+ site: String(req.headers['sec-fetch-site'] ?? ''),
1531
+ });
1532
+ res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
1533
+ res.end('Forbidden\n');
1534
+ return;
1535
+ }
1536
+ const form = new URLSearchParams(await readBody(req, 16 * 1024));
1537
+ const action = String(form.get('action') ?? '');
1538
+ let result = { ok: false, error: '未知操作' };
1539
+ if (action === 'save') {
1540
+ result = appRegistry.save({
1541
+ originalId: form.get('originalId') ?? '',
1542
+ id: form.get('id') ?? '',
1543
+ name: form.get('name') ?? '',
1544
+ target: form.get('target') ?? '',
1545
+ enabled: form.get('enabled') === '1',
1546
+ trusted: form.get('trusted') === '1',
1547
+ allowInsecureTls: form.get('allowInsecureTls') === '1',
1548
+ });
1549
+ } else if (action === 'toggle') {
1550
+ const id = String(form.get('id') ?? '').toLowerCase();
1551
+ const current = appRegistry.list().find((item) => item.id === id);
1552
+ result = current ? appRegistry.update(id, { enabled: !current.enabled }) : { ok: false, error: '应用不存在' };
1553
+ } else if (action === 'delete') {
1554
+ result = appRegistry.remove(form.get('id') ?? '');
1555
+ }
1556
+ appendAudit(dir, 'app-registry-' + action, { id: String(form.get('id') ?? form.get('originalId') ?? ''), ok: result.ok, error: result.error ?? null });
1557
+ const message = result.ok ? '已保存,立即生效。' : (result.error ?? '保存失败');
1558
+ res.writeHead(303, { location: `/dsh_homing/apps?msg=${encodeURIComponent(message)}${result.ok ? '' : '&error=1'}`, 'cache-control': 'no-store' });
1559
+ res.end();
1560
+ return;
1561
+ }
1562
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
1563
+ res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
1564
+ res.end('Method Not Allowed\n');
1565
+ return;
1566
+ }
1567
+ const apps = appRegistry.list();
1568
+ const editingId = String(url.searchParams.get('edit') ?? '').toLowerCase();
1569
+ const deleteId = String(url.searchParams.get('confirm-delete') ?? '').toLowerCase();
1570
+ const editing = editingId ? (apps.find((item) => item.id === editingId) ?? null) : null;
1571
+ const confirmDelete = deleteId ? (apps.find((item) => item.id === deleteId) ?? null) : null;
1572
+ const health = Object.fromEntries(await Promise.all(apps.filter((item) => item.enabled).map(async (item) => [item.id, await probeAppPort(item)])));
1573
+ res.writeHead(200, {
1574
+ 'content-type': 'text/html; charset=utf-8',
1575
+ 'cache-control': 'no-store',
1576
+ 'x-frame-options': 'DENY',
1577
+ '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:",
1578
+ 'x-content-type-options': 'nosniff',
1579
+ 'referrer-policy': 'no-referrer',
1580
+ });
1581
+ res.end(renderLocalAppsPage({
1582
+ apps, health, editing, confirmDelete,
1583
+ message: url.searchParams.get('msg') ?? '',
1584
+ isError: url.searchParams.get('error') === '1',
1585
+ }));
1586
+ return;
1587
+ }
1588
+
1749
1589
  // 守护进程控制代理(同源):/dsh_homing/restart-daemon/status|restart|pause|resume|stop
1750
1590
  if (url.pathname.startsWith('/dsh_homing/restart-daemon/')) {
1751
1591
  const rest = url.pathname.slice('/dsh_homing/restart-daemon/'.length);
@@ -2722,6 +2562,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2722
2562
 
2723
2563
  if (url.pathname === '/vnc' && req.method === 'GET') {
2724
2564
  const target = vnc.vncTarget(config);
2565
+ const vncEnabled = config.vnc?.enabled !== false;
2566
+ const available = vncEnabled ? await probeVnc({ host: target.host, port: target.port }) : false;
2725
2567
  sendVnc(200, {
2726
2568
  'content-type': 'text/html; charset=utf-8',
2727
2569
  'x-frame-options': 'DENY',
@@ -2732,6 +2574,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2732
2574
  host: os.hostname(),
2733
2575
  target: target.host + ':' + target.port,
2734
2576
  ready: vnc.novncReady(),
2577
+ available,
2578
+ enabled: vncEnabled,
2579
+ }));
2580
+ return;
2581
+ }
2582
+
2583
+ if (url.pathname === '/vnc/status' && req.method === 'GET') {
2584
+ const target = vnc.vncTarget(config);
2585
+ const vncEnabled = config.vnc?.enabled !== false;
2586
+ const available = vncEnabled ? await probeVnc({ host: target.host, port: target.port }) : false;
2587
+ sendVnc(200, { 'content-type': 'application/json; charset=utf-8' }, JSON.stringify({
2588
+ ok: true,
2589
+ enabled: vncEnabled,
2590
+ available,
2591
+ host: target.host,
2592
+ port: target.port,
2593
+ novnc: vnc.novncReady(),
2594
+ checkedAt: Date.now(),
2735
2595
  }));
2736
2596
  return;
2737
2597
  }
@@ -3062,6 +2922,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3062
2922
  res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
3063
2923
  <h1 style="font-size:18px">预览失败</h1>
3064
2924
  <p style="color:#9aa3b2">${escapeHtml(String(result.error ?? '未知原因'))}</p>
2925
+ <p><a style="color:#8ab4f8" href="/">← 返回 DSH</a> · <a style="color:#8ab4f8" href="/files?path=${encodeURIComponent(path.dirname(target))}">← 返回文件列表</a></p>
3065
2926
  <p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
3066
2927
  </body>`);
3067
2928
  return;
@@ -3317,6 +3178,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3317
3178
  if (action === 'revoke') result = deviceStore.revokeDevice(devices(), id);
3318
3179
  else if (action === 'remove') result = deviceStore.removeDevice(devices(), id);
3319
3180
  else if (action === 'rename') result = deviceStore.renameDevice(devices(), id, form.get('name') ?? '');
3181
+ else if (action === 'clean-revoked') {
3182
+ const state = devices();
3183
+ const kept = state.devices.filter((device) => device.revokedAt === null);
3184
+ if (kept.length !== state.devices.length) result = { changed: true, state: { ...state, devices: kept } };
3185
+ }
3320
3186
  if (result.changed) {
3321
3187
  persistDevices(result.state);
3322
3188
  appendAudit(dir, `device-${action}`, { id, ip: clientKey(req) });
@@ -3373,12 +3239,12 @@ button.danger{background:#3a2226;border-color:#54303a;color:#f0b6bf}
3373
3239
  a{color:#8ab4f8}
3374
3240
  </style>
3375
3241
  <h1>设备管理</h1>
3376
- <p class="sub"><a href="/dsh_homing/account">← 返回账户设置</a></p>
3242
+ <p class="sub"><a href="/">← 返回 DSH</a> · <a href="/dsh_homing/account">← 返回账户设置</a></p>
3377
3243
  <p class="sub">每台配对过的手机/浏览器各占一条。吊销后它的下一次请求立即失效,不用改密码、不用重启。</p>
3378
3244
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3379
3245
  <table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
3380
3246
  <tbody>${activeRows}</tbody></table>
3381
- ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>` : ''}
3247
+ ${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>` : ''}
3382
3248
  <p class="sub" style="margin-top:26px">要新增设备:把带 <code>?k=</code> 的入口链接发到那台手机,打开一次即完成配对。<br>
3383
3249
  入口链接:在电脑上运行 <code>node bin/entry-link.mjs</code>。</p>`);
3384
3250
  return;
@@ -3414,7 +3280,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3414
3280
  // (令牌不进地址栏/历史;之后靠 dsh-homing-device Cookie 长期放行)
3415
3281
  if (!isLoginPath && config.entryGate !== false) {
3416
3282
  const token = url.searchParams.get('k');
3417
- if (token && entryExpiry(token) > 0 && currentDevice(req) === null) {
3283
+ if (token && entryExpiry(token) > 0 && currentDevice(req) === null && isBrowserNavigation(req)) {
3418
3284
  const activeCount = deviceStore.partition(devices()).active.length;
3419
3285
  const maxDevices = Number(config.maxDevices) > 0 ? Number(config.maxDevices) : 20;
3420
3286
  if (activeCount >= maxDevices) {
@@ -3536,7 +3402,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3536
3402
  }
3537
3403
  if (sessionValid(req)) {
3538
3404
  const cookies = [];
3539
- ensureDeviceCookie(req, cookies);
3405
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, cookies);
3540
3406
  res.writeHead(303, {
3541
3407
  location: '/',
3542
3408
  'cache-control': 'no-store',
@@ -3745,7 +3611,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3745
3611
  }).join('')
3746
3612
  : '<li>暂无记录</li>');
3747
3613
  const deviceCookies = [];
3748
- ensureDeviceCookie(req, deviceCookies);
3614
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, deviceCookies);
3749
3615
  res.writeHead(200, {
3750
3616
  'content-type': 'text/html; charset=utf-8',
3751
3617
  'cache-control': 'no-store',
@@ -3865,6 +3731,28 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3865
3731
  const onUpgrade = async (req, socket, head) => {
3866
3732
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
3867
3733
 
3734
+ // 多应用 WebSocket:与普通请求共用应用注册表和登录/设备鉴权。
3735
+ const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
3736
+ if (localAppRoute) {
3737
+ if (localAppRoute.invalid || localAppRoute.root || !localAppRoute.app) {
3738
+ socket.end('HTTP/1.1 404 Not Found\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
3739
+ return;
3740
+ }
3741
+ if (!sessionValid(req) && currentDevice(req) === null) {
3742
+ socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
3743
+ return;
3744
+ }
3745
+ if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
3746
+ socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\nconnection: close\r\n\r\n');
3747
+ return;
3748
+ }
3749
+ proxyLocalAppUpgrade({
3750
+ req, socket, head, url, app: localAppRoute.app, rest: localAppRoute.rest,
3751
+ clientIp: clientKey(req), audit: (event, fields) => appendAudit(dir, event, fields),
3752
+ });
3753
+ return;
3754
+ }
3755
+
3868
3756
  // 桌面 WebSocket:鉴权后通过 ws 库完成握手,再桥接本机 VNC 的 TCP
3869
3757
  if (url.pathname === '/vnc/ws') {
3870
3758
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -3872,6 +3760,20 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3872
3760
  return;
3873
3761
  }
3874
3762
  const target = vnc.vncTarget(config);
3763
+ const vncEnabled = config.vnc?.enabled !== false;
3764
+ if (!vncEnabled) {
3765
+ appendAudit(dir, 'vnc-unavailable', { host: target.host, port: target.port, reason: 'disabled' });
3766
+ const disabledText = '桌面共享未启用(vnc.enabled=false)';
3767
+ 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);
3768
+ return;
3769
+ }
3770
+ const vncReady = await probeVnc({ host: target.host, port: target.port });
3771
+ if (!vncReady) {
3772
+ appendAudit(dir, 'vnc-unavailable', { host: target.host, port: target.port, reason: 'connect-failed' });
3773
+ const missingText = '未检测到 VNC 服务端(无法连接目标地址)';
3774
+ 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);
3775
+ return;
3776
+ }
3875
3777
  try {
3876
3778
  vncWss.handleUpgrade(req, socket, head, (ws) => {
3877
3779
  appendAudit(dir, 'vnc-connect', { host: target.host, port: target.port });