@andy.ian/dsh-homing 2.1.15 → 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
@@ -40,15 +40,20 @@ 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';
52
57
 
53
58
  export const name = 'dsh-homing';
54
59
 
@@ -370,301 +375,10 @@ function createCookieMinter(credentials, getUpstreamPort) {
370
375
  }
371
376
 
372
377
  /* ------------------------------------------------------------------ *
373
- * 移动端补丁
378
+ * 移动端补丁:MOBILE_CSS / MOBILE_JS 在 lib/mobile-patch.mjs,单独成文件
379
+ * 以便用真实 DOM 桩做行为测试(见 test/unit.mobile-patch.test.mjs)。
374
380
  * ------------------------------------------------------------------ */
375
381
 
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
- }
628
- }
629
-
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 })
635
-
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
- })();
665
-
666
- `;
667
-
668
382
  const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
669
383
 
670
384
  // 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
@@ -1511,6 +1225,10 @@ function verifyTotp(secret, code, lastStep) {
1511
1225
  }
1512
1226
 
1513
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
+ });
1514
1232
  const loginFailures = new Map();
1515
1233
  // 记住上一次验证码用过的时间步,防止同一个 6 位码在 30 秒窗口内被重放
1516
1234
  let lastTotpStep = 0;
@@ -1591,6 +1309,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1591
1309
  // 已登录(会话有效)但还没有设备令牌时,自动补一台并返回 Cookie。
1592
1310
  // 目的:登录过的设备都应出现在设备管理页、可单独吊销;
1593
1311
  // 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
1312
+ // 只有「浏览器页面导航」才允许自动配对/用入口令牌配对。
1313
+ // fetch/XHR/脚本(Accept 不含 text/html)不再产生设备记录,
1314
+ // 否则自动化探测会让设备表越堆越多。
1315
+ const isBrowserNavigation = (req) => String(req.headers.accept ?? '').includes('text/html')
1316
+
1594
1317
  const ensureDeviceCookie = (req, cookies) => {
1595
1318
  const existing = currentDevice(req);
1596
1319
  if (existing !== null) return existing.id;
@@ -1722,9 +1445,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1722
1445
  ;
1723
1446
  // 写操作来源校验:
1724
1447
  // - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
1725
- // - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
1726
- // 跨站 POST 根本带不上来,而微信内置浏览器会发 Origin: null,
1727
- // 强制校验会让「生成密钥」这类按钮直接 403。
1448
+ // - 本插件自己的页面(登录/账户/设备/应用)用宽松规则 checkOwnPageWrite:
1449
+ // 它的 Cookie 都是 SameSite=Lax,跨站 POST 根本带不上来,而微信内置浏览器、
1450
+ // 华为浏览器提交表单时会发 Origin: null(2026-11-14 手机上加应用就是被这里 403),
1451
+ // 严格校验会让这些页面上的按钮直接 Forbidden。明确的跨站证据仍然拒绝。
1728
1452
  const originCheck = checkUnsafeOrigin(req);
1729
1453
  if (!originCheck.ok) {
1730
1454
  const ownPath = url.pathname === '/login' || url.pathname === '/logout'
@@ -1738,6 +1462,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1738
1462
  method: req.method,
1739
1463
  reason: originCheck.reason,
1740
1464
  origin: String(req.headers.origin ?? ''),
1465
+ site: String(req.headers['sec-fetch-site'] ?? ''),
1466
+ referer: String(req.headers.referer ?? ''),
1741
1467
  host: String(req.headers.host ?? ''),
1742
1468
  verdict: ownPath ? 'allowed-own-path' : 'blocked',
1743
1469
  });
@@ -1748,6 +1474,118 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
1748
1474
  }
1749
1475
  }
1750
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
+
1751
1589
  // 守护进程控制代理(同源):/dsh_homing/restart-daemon/status|restart|pause|resume|stop
1752
1590
  if (url.pathname.startsWith('/dsh_homing/restart-daemon/')) {
1753
1591
  const rest = url.pathname.slice('/dsh_homing/restart-daemon/'.length);
@@ -2724,6 +2562,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2724
2562
 
2725
2563
  if (url.pathname === '/vnc' && req.method === 'GET') {
2726
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;
2727
2567
  sendVnc(200, {
2728
2568
  'content-type': 'text/html; charset=utf-8',
2729
2569
  'x-frame-options': 'DENY',
@@ -2734,6 +2574,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
2734
2574
  host: os.hostname(),
2735
2575
  target: target.host + ':' + target.port,
2736
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(),
2737
2595
  }));
2738
2596
  return;
2739
2597
  }
@@ -3320,6 +3178,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
3320
3178
  if (action === 'revoke') result = deviceStore.revokeDevice(devices(), id);
3321
3179
  else if (action === 'remove') result = deviceStore.removeDevice(devices(), id);
3322
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
+ }
3323
3186
  if (result.changed) {
3324
3187
  persistDevices(result.state);
3325
3188
  appendAudit(dir, `device-${action}`, { id, ip: clientKey(req) });
@@ -3381,7 +3244,7 @@ a{color:#8ab4f8}
3381
3244
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
3382
3245
  <table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
3383
3246
  <tbody>${activeRows}</tbody></table>
3384
- ${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>` : ''}
3385
3248
  <p class="sub" style="margin-top:26px">要新增设备:把带 <code>?k=</code> 的入口链接发到那台手机,打开一次即完成配对。<br>
3386
3249
  入口链接:在电脑上运行 <code>node bin/entry-link.mjs</code>。</p>`);
3387
3250
  return;
@@ -3417,7 +3280,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3417
3280
  // (令牌不进地址栏/历史;之后靠 dsh-homing-device Cookie 长期放行)
3418
3281
  if (!isLoginPath && config.entryGate !== false) {
3419
3282
  const token = url.searchParams.get('k');
3420
- if (token && entryExpiry(token) > 0 && currentDevice(req) === null) {
3283
+ if (token && entryExpiry(token) > 0 && currentDevice(req) === null && isBrowserNavigation(req)) {
3421
3284
  const activeCount = deviceStore.partition(devices()).active.length;
3422
3285
  const maxDevices = Number(config.maxDevices) > 0 ? Number(config.maxDevices) : 20;
3423
3286
  if (activeCount >= maxDevices) {
@@ -3539,7 +3402,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3539
3402
  }
3540
3403
  if (sessionValid(req)) {
3541
3404
  const cookies = [];
3542
- ensureDeviceCookie(req, cookies);
3405
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, cookies);
3543
3406
  res.writeHead(303, {
3544
3407
  location: '/',
3545
3408
  'cache-control': 'no-store',
@@ -3748,7 +3611,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3748
3611
  }).join('')
3749
3612
  : '<li>暂无记录</li>');
3750
3613
  const deviceCookies = [];
3751
- ensureDeviceCookie(req, deviceCookies);
3614
+ if (isBrowserNavigation(req)) ensureDeviceCookie(req, deviceCookies);
3752
3615
  res.writeHead(200, {
3753
3616
  'content-type': 'text/html; charset=utf-8',
3754
3617
  'cache-control': 'no-store',
@@ -3868,6 +3731,28 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3868
3731
  const onUpgrade = async (req, socket, head) => {
3869
3732
  const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
3870
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
+
3871
3756
  // 桌面 WebSocket:鉴权后通过 ws 库完成握手,再桥接本机 VNC 的 TCP
3872
3757
  if (url.pathname === '/vnc/ws') {
3873
3758
  if (!sessionValid(req) && currentDevice(req) === null) {
@@ -3875,6 +3760,20 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
3875
3760
  return;
3876
3761
  }
3877
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
+ }
3878
3777
  try {
3879
3778
  vncWss.handleUpgrade(req, socket, head, (ws) => {
3880
3779
  appendAudit(dir, 'vnc-connect', { host: target.host, port: target.port });