@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/lib/vnc-app.js CHANGED
@@ -9,6 +9,15 @@
9
9
  */
10
10
  import RFB from './vendor/novnc/core/rfb.js'
11
11
  import { charToKey, inputTypeToKey, SPECIAL_KEYS } from './vnc-keyboard.mjs'
12
+ import {
13
+ autoFollowLabel,
14
+ isNewWindowSinceSnapshot,
15
+ POPUP_CLICK_WINDOW_MS,
16
+ readAutoFollowPreference,
17
+ shouldFollowPopupWindow,
18
+ snapshotWindowIds,
19
+ writeAutoFollowPreference,
20
+ } from './window-follow.mjs'
12
21
 
13
22
  const statusEl = document.getElementById('status')
14
23
  const passwordEl = document.getElementById('password')
@@ -28,14 +37,22 @@ const KEYS = {
28
37
  d: 0x64,
29
38
  }
30
39
 
40
+ const AUTO_FOLLOW_STORAGE_KEY = 'dsh-vnc-auto-follow-popup'
41
+
42
+ function initialAutoFollow() {
43
+ try { return readAutoFollowPreference(window.localStorage, AUTO_FOLLOW_STORAGE_KEY) } catch { return true }
44
+ }
45
+
31
46
  let rfb = null
32
47
  let connected = false
33
- let autoSwitch = false
48
+ // 默认跟随新弹窗;用户手动关闭后记住选择。
49
+ let autoSwitch = initialAutoFollow()
34
50
  let screenSize = null
35
51
  let autoTried = false
36
52
  let lastClickAt = 0
37
53
  let pollTimer = null
38
54
  let knownWindows = new Set()
55
+ let clickWindowSnapshot = null
39
56
  let windowView = null
40
57
  let viewMode = 'width'
41
58
  let lastFbSize = ''
@@ -253,12 +270,8 @@ async function fetchWindows() {
253
270
  }
254
271
 
255
272
  /**
256
- * 轮询窗口列表并决定是否切窗。规则(宁可少切,不可切错):
257
- * 1. 只认"前台窗口发生变化",不认"出现新窗口"
258
- * 2. 变化必须发生在用户点击后的 5 秒内
259
- * 3. 新前台窗口要连续两次轮询保持稳定(~1.2s),排除一闪而过的辅助窗口
260
- * 4. 新前台不能等于点击前的前台(说明没切换)
261
- * 5. 不能等于当前已聚焦窗口;尺寸必须正常
273
+ * 自动跟随新弹窗:用户在远程画面操作后,如果新建窗口成为前台且稳定,
274
+ * 自动裁切/放大到该窗口,方便手机阅读。已有窗口之间切换不会误触发。
262
275
  */
263
276
  /** 已聚焦的窗口如果移动/改尺寸,重新对齐裁剪(WPS 打开文档会改变窗口大小) */
264
277
  function refreshWindowView(windows) {
@@ -277,30 +290,51 @@ async function pollWindows() {
277
290
  if (Date.now() < pollPausedUntil) return
278
291
  try {
279
292
  const windows = await fetchWindows()
280
- const ids = new Set(windows.map((w) => w.hwnd))
293
+ const ids = snapshotWindowIds(windows)
281
294
  const fg = windows.find((w) => w.foreground === true) ?? null
295
+ const now = Date.now()
282
296
 
283
297
  if (fg !== null) {
284
- if (String(fg.hwnd) !== String(lastForeground)) {
285
- pendingForeground = { hwnd: fg.hwnd, since: Date.now() }
298
+ const foregroundId = String(fg.hwnd)
299
+ if (foregroundId !== String(lastForeground ?? '')) {
300
+ // 在前台发生变化时锁存「是否在点击之后新建」。
301
+ // 不要在后续轮询里再用最新的 knownWindows 判断:那时新窗口已进入列表,
302
+ // 会把 changed 错误变成 false,导致弹窗永远无法被跟随。
303
+ pendingForeground = {
304
+ hwnd: foregroundId,
305
+ since: now,
306
+ openedAfterClick: isNewWindowSinceSnapshot(clickWindowSnapshot, foregroundId),
307
+ }
286
308
  }
287
- lastForeground = fg.hwnd
309
+ lastForeground = foregroundId
288
310
  }
289
311
 
290
- if (autoSwitch && lastClickAt > 0 && fg !== null && pendingForeground !== null) {
291
- const now = Date.now()
292
- const stable = now - pendingForeground.since >= 1200
293
- const fresh = Date.now() - lastClickAt <= 5000
294
- const changed = !knownWindows.has(fg.hwnd)
295
- const notCurrent = !windowView || String(windowView.hwnd) !== String(fg.hwnd)
296
- const sane = (fg.width ?? 0) > 80 && (fg.height ?? 0) > 80 && String(fg.title ?? '').trim() !== ''
297
- if (stable && fresh && changed && notCurrent && sane) {
312
+ if (fg !== null && pendingForeground !== null && pendingForeground.hwnd === String(fg.hwnd)) {
313
+ const shouldFollow = shouldFollowPopupWindow({
314
+ enabled: autoSwitch,
315
+ clickAt: lastClickAt,
316
+ now,
317
+ stableSince: pendingForeground.since,
318
+ openedAfterClick: pendingForeground.openedAfterClick,
319
+ hwnd: fg.hwnd,
320
+ baselineHwnd: clickBaseForeground,
321
+ currentHwnd: windowView?.hwnd,
322
+ width: fg.width,
323
+ height: fg.height,
324
+ title: fg.title,
325
+ })
326
+ if (shouldFollow) {
298
327
  lastClickAt = 0
328
+ clickWindowSnapshot = null
299
329
  pendingForeground = null
300
330
  focusWindowRect(fg)
301
331
  }
302
332
  }
303
- if (Date.now() - lastClickAt > 5000) pendingForeground = null
333
+ if (lastClickAt > 0 && now - lastClickAt > POPUP_CLICK_WINDOW_MS) {
334
+ lastClickAt = 0
335
+ clickWindowSnapshot = null
336
+ pendingForeground = null
337
+ }
304
338
 
305
339
  knownWindows = ids
306
340
  refreshFramebufferView()
@@ -540,11 +574,23 @@ function setupToolbar() {
540
574
  return node
541
575
  }
542
576
 
543
- const autoBtn = button('自动切窗:关', () => {
577
+ const autoBtn = button(autoFollowLabel(autoSwitch), () => {
544
578
  autoSwitch = !autoSwitch
545
- autoBtn.textContent = '自动切窗:' + (autoSwitch ? '开' : '关')
546
- if (autoSwitch) { clickBaseForeground = lastForeground; pendingForeground = null; lastClickAt = 0 }
579
+ writeAutoFollowPreference(autoSwitch, window.localStorage, AUTO_FOLLOW_STORAGE_KEY)
580
+ autoBtn.textContent = autoFollowLabel(autoSwitch)
581
+ autoBtn.title = '点电脑窗口后,新弹出的前台窗口会自动放大到手机画面'
582
+ if (autoSwitch) {
583
+ clickBaseForeground = lastForeground
584
+ clickWindowSnapshot = snapshotWindowIds([...knownWindows].map((hwnd) => ({ hwnd })))
585
+ pendingForeground = null
586
+ lastClickAt = 0
587
+ } else {
588
+ pendingForeground = null
589
+ clickWindowSnapshot = null
590
+ lastClickAt = 0
591
+ }
547
592
  })
593
+ autoBtn.title = '默认开启:点电脑窗口后,新弹出的前台窗口会自动放大到手机画面'
548
594
 
549
595
  bar.append(
550
596
  button('适合宽度', () => setViewMode('width')),
@@ -581,6 +627,8 @@ function setupToolbar() {
581
627
  function markClick(event) {
582
628
  lastClickAt = Date.now()
583
629
  clickBaseForeground = lastForeground
630
+ // 在用户操作发生时拍一份窗口快照;之后出现的新前台窗口才算弹窗。
631
+ clickWindowSnapshot = new Set(knownWindows)
584
632
  pendingForeground = null
585
633
  // 手机上点画面:顺手把隐藏输入框聚焦,软键盘才会出现
586
634
  if (event && event.pointerType && event.pointerType !== 'mouse') focusKeyboard()
@@ -612,6 +660,42 @@ function canvasOfGuard() {
612
660
  }
613
661
  }
614
662
 
663
+ // 页面渲染时服务端已探测过 VNC 是否可用;不可用就不要自动连接,改为轮询等待
664
+ function vncInitiallyAvailable() {
665
+ return screenEl?.dataset?.vncAvailable !== '0'
666
+ }
667
+
668
+ function vncEnabledByConfig() {
669
+ return screenEl?.dataset?.vncEnabled !== '0'
670
+ }
671
+
672
+ async function checkVncStatus() {
673
+ try {
674
+ const res = await fetch('/vnc/status', { headers: { accept: 'application/json' } })
675
+ if (!res.ok) return null
676
+ return await res.json()
677
+ } catch {
678
+ return null
679
+ }
680
+ }
681
+
682
+ /** 未检测到 VNC 服务端时每 3 秒探测一次,装好后自动启用「连接」并连上 */
683
+ function watchVncAvailability() {
684
+ if (vncInitiallyAvailable() || !vncEnabledByConfig()) return
685
+ const banner = document.getElementById('vnc-unavailable')
686
+ const timer = setInterval(async () => {
687
+ const status = await checkVncStatus()
688
+ if (status?.available !== true) return
689
+ clearInterval(timer)
690
+ banner?.remove()
691
+ screenEl.dataset.vncAvailable = '1'
692
+ if (connectBtn) connectBtn.disabled = false
693
+ setStatus('VNC 服务端已就绪', 'ok')
694
+ connect()
695
+ }, 3000)
696
+ timer.unref?.()
697
+ }
698
+
615
699
  let reconnectTimer = null
616
700
  let reconnectTries = 0
617
701
  let userClosed = false
@@ -733,6 +817,11 @@ function autoConnect() {
733
817
  if (autoTried) return
734
818
  autoTried = true
735
819
  if (passwordEl) passwordEl.style.display = 'none'
820
+ if (!vncInitiallyAvailable()) {
821
+ setStatus(vncEnabledByConfig() ? '未检测到 VNC 服务端' : '桌面共享未启用', 'bad')
822
+ watchVncAvailability()
823
+ return
824
+ }
736
825
  setStatus('用已登录账号自动连接…')
737
826
  connect()
738
827
  }
package/lib/vnc-boot.js CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
  const script = document.createElement('script')
34
34
  script.type = 'module'
35
- script.src = '/vnc/bundle.js?v=46'
35
+ script.src = '/vnc/bundle.js?v=48'
36
36
  script.onload = () => {
37
37
  boot('就绪,点连接')
38
38
  report('bundle-loaded', 'ok')
package/lib/vnc-page.mjs CHANGED
@@ -4,6 +4,8 @@
4
4
  * 页面本身很薄,真正的协议在 /vnc/static/core/rfb.js 里;
5
5
  * 连接地址固定为同源的 /vnc/ws(由插件代理到本机 VNC 服务端)。
6
6
  */
7
+ import { NAV_CSS, topNav } from './nav.mjs'
8
+
7
9
  const escapeHtml = (value) => String(value ?? '')
8
10
  .replaceAll('&', '&amp;')
9
11
  .replaceAll('<', '&lt;')
@@ -45,30 +47,57 @@ const STYLE = `
45
47
  }
46
48
  .connect button:disabled { opacity: .5; }
47
49
  .tip { padding: 0 10px 8px; color: #7a8394; font-size: 11px; background: #161a20; }
50
+ .vnc-warn { margin: 10px; padding: 12px 14px; border-radius: 10px; background: #1b1f27; border: 1px solid #3a4150; color: #cfd6e2; font-size: 13px; line-height: 1.6; overflow-y: auto; }
51
+ .vnc-warn h2 { margin: 0 0 8px; font-size: 15px; color: #f1c46b; }
52
+ .vnc-warn p { margin: 6px 0; }
53
+ .vnc-warn code { background: #11151c; border: 1px solid #2c333f; border-radius: 5px; padding: 1px 5px; font-size: 12px; }
54
+ .vnc-warn ul { margin: 6px 0; padding-left: 18px; }
55
+ .vnc-warn li { margin: 3px 0; }
56
+ .vnc-warn a { color: #8ab4f8; }
48
57
  `
49
58
 
50
- export function renderVncPage({ host = '', user = '', target = '127.0.0.1:5900', ready = true } = {}) {
59
+ export function renderVncPage({ host = '', user = '', target = '127.0.0.1:5900', ready = true, available = true, enabled = true } = {}) {
60
+ const usable = ready && enabled && available
61
+ const statusText = !enabled ? '桌面共享未启用' : (!available ? '未检测到 VNC 服务端' : (ready ? '未连接' : 'noVNC 资源缺失'))
62
+ const warning = !enabled
63
+ ? `<div class="vnc-warn" id="vnc-unavailable" data-kind="disabled">
64
+ <h2>桌面共享未启用</h2>
65
+ <p>settings.json 里 <code>vnc.enabled</code> 为 <code>false</code>,所以不会连接本机 VNC 服务端。</p>
66
+ <p>需要时把 <code>"vnc": { "enabled": true }</code> 改回来并保存即可(不用重启 DSH)。</p>
67
+ </div>`
68
+ : (!available
69
+ ? `<div class="vnc-warn" id="vnc-unavailable" data-kind="missing">
70
+ <h2>未检测到 VNC 服务端</h2>
71
+ <p>目标 <code>${escapeHtml(target)}</code> 无法连接。桌面共享需要在电脑上安装并启动 VNC 服务端:</p>
72
+ <ul>
73
+ <li><b>Windows</b>:安装 TightVNC / UltraVNC,设置密码,只监听 <code>127.0.0.1:5900</code></li>
74
+ <li><b>Linux(X11)</b>:<code>x11vnc -localhost -forever -shared -rfbauth ~/.vnc/passwd</code></li>
75
+ <li><b>Linux(Wayland)</b>:<code>wayvnc 127.0.0.1 5900</code></li>
76
+ <li><b>macOS</b>:系统设置 → 通用 → 共享 → 屏幕共享</li>
77
+ </ul>
78
+ <p>装好后本页会自动检测并启用「连接」;也可以 <a href="/vnc">手动刷新</a>。</p>
79
+ <p style="color:#8b93a1">不需要桌面共享可以忽略本页——其它功能(文件/终端/Git/窗口共享)不受影响。</p>
80
+ </div>`
81
+ : '')
51
82
  return `<!doctype html>
52
83
  <html lang="zh-CN"><head>
53
84
  <meta charset="utf-8">
54
85
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
55
86
  <title>桌面 · DSH</title>
56
- <style>${STYLE}</style>
87
+ <style>${STYLE}${NAV_CSS}</style>
57
88
  </head>
58
89
  <body>
90
+ ${topNav({ current: '/vnc' })}
59
91
  <div class="bar">
60
- <a href="/">DSH</a>
61
- <a href="/files">文件</a>
62
- <a href="/term">终端</a>
63
- <a href="/remote">窗口</a>
64
92
  <span class="spacer"></span>
65
93
  <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
66
- <span id="status">${ready ? '未连接' : 'noVNC 资源缺失'}</span>
94
+ <span id="status">${statusText}</span>
67
95
  </div>
68
- <div id="screen"></div>
96
+ ${warning}
97
+ <div id="screen" data-vnc-available="${usable ? '1' : '0'}" data-vnc-enabled="${enabled ? '1' : '0'}"></div>
69
98
  <div class="connect">
70
99
  <input id="password" type="password" placeholder="VNC 密码(未设密码可留空)" autocomplete="off">
71
- <button type="button" id="connect" ${ready ? '' : 'disabled'}>连接</button>
100
+ <button type="button" id="connect" ${usable ? '' : 'disabled'}>连接</button>
72
101
  <button type="button" id="disconnect" disabled>断开</button>
73
102
  </div>
74
103
  <div class="tip">目标:${escapeHtml(target)}(只在本机回环,经插件代理)</div>
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 检测本机 VNC 服务端是否可用。
3
+ *
4
+ * 用途:没装 VNC 时不把 /vnc 做成一打开就"连接中断"的黑屏页,
5
+ * 而是明确告诉用户"未检测到 VNC 服务端"并给出安装指引。
6
+ *
7
+ * 结果缓存 5 秒,避免页面轮询把探测打得太频繁。
8
+ */
9
+ import net from 'node:net'
10
+
11
+ const CACHE_MS = 5000
12
+ const cache = new Map()
13
+
14
+ export function clearVncProbeCache() {
15
+ cache.clear()
16
+ }
17
+
18
+ /**
19
+ * @param {{ host?: string, port?: number, timeoutMs?: number }} options
20
+ * @returns {Promise<boolean>}
21
+ */
22
+ export function probeVnc({ host = '127.0.0.1', port = 5900, timeoutMs = 600 } = {}) {
23
+ const key = host + ':' + port
24
+ const cached = cache.get(key)
25
+ if (cached && Date.now() - cached.at < CACHE_MS) return Promise.resolve(cached.ok)
26
+
27
+ return new Promise((resolve) => {
28
+ let settled = false
29
+ let timer = null
30
+ const socket = net.connect({ host, port })
31
+
32
+ const finish = (ok) => {
33
+ if (settled) return
34
+ settled = true
35
+ if (timer !== null) clearTimeout(timer)
36
+ try { socket.destroy() } catch { /* 忽略 */ }
37
+ cache.set(key, { ok, at: Date.now() })
38
+ resolve(ok)
39
+ }
40
+
41
+ timer = setTimeout(() => finish(false), timeoutMs)
42
+ timer.unref?.()
43
+ socket.once('connect', () => finish(true))
44
+ socket.once('error', () => finish(false))
45
+ socket.once('timeout', () => finish(false))
46
+ socket.setTimeout?.(timeoutMs)
47
+ })
48
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * 窗口弹出后自动跟随的纯决策逻辑。
3
+ *
4
+ * 只在用户刚刚操作远程画面、并且出现了新建的前台窗口且稳定一段时间后切换视图,
5
+ * 避免切到通知、菜单、闪一下的辅助窗或用户本来就在用的其他窗口。
6
+ */
7
+ export const POPUP_STABLE_MS = 1200
8
+ export const POPUP_CLICK_WINDOW_MS = 10_000
9
+
10
+ /**
11
+ * 判断候选窗口是否应该自动放大。
12
+ * @param {{enabled:boolean, clickAt:number, now:number, stableSince:number,
13
+ * openedAfterClick:boolean, hwnd:string|number, baselineHwnd?:string|number|null,
14
+ * currentHwnd?:string|number|null, width:number, height:number, title:string,
15
+ * stableMs?:number, clickWindowMs?:number}} input
16
+ */
17
+ export function shouldFollowPopupWindow(input) {
18
+ if (input.enabled !== true || input.openedAfterClick !== true) return false
19
+ const clickAt = Number(input.clickAt) || 0
20
+ const now = Number(input.now) || 0
21
+ const stableSince = Number(input.stableSince) || 0
22
+ if (clickAt <= 0 || now < clickAt || now - clickAt > (input.clickWindowMs ?? POPUP_CLICK_WINDOW_MS)) return false
23
+ if (stableSince <= 0 || now - stableSince < (input.stableMs ?? POPUP_STABLE_MS)) return false
24
+
25
+ const hwnd = String(input.hwnd ?? '')
26
+ if (hwnd === '') return false
27
+ if (input.baselineHwnd !== null && input.baselineHwnd !== undefined && String(input.baselineHwnd) === hwnd) return false
28
+ if (input.currentHwnd !== null && input.currentHwnd !== undefined && String(input.currentHwnd) === hwnd) return false
29
+
30
+ const width = Number(input.width) || 0
31
+ const height = Number(input.height) || 0
32
+ const title = String(input.title ?? '').trim()
33
+ if (width <= 80 || height <= 80 || title === '') return false
34
+ return true
35
+ }
36
+
37
+ /** 将设备列表转成点击时的快照,用于区分「新弹窗」与已有窗口的切换。 */
38
+ export function snapshotWindowIds(windows) {
39
+ return new Set((Array.isArray(windows) ? windows : []).map((window) => String(window?.hwnd ?? '')).filter(Boolean))
40
+ }
41
+
42
+ export function isNewWindowSinceSnapshot(snapshot, hwnd) {
43
+ if (!(snapshot instanceof Set)) return false
44
+ const id = String(hwnd ?? '')
45
+ return id !== '' && !snapshot.has(id)
46
+ }
47
+
48
+ /** 读取偏好;首次默认开启,用户可关闭并持久记忆。 */
49
+ export function readAutoFollowPreference(storage, key = 'dsh-vnc-auto-follow-popup') {
50
+ try {
51
+ return storage?.getItem(key) !== '0'
52
+ } catch {
53
+ return true
54
+ }
55
+ }
56
+
57
+ export function writeAutoFollowPreference(enabled, storage, key = 'dsh-vnc-auto-follow-popup') {
58
+ try { storage?.setItem(key, enabled ? '1' : '0') } catch { /* 隐私模式/存储禁用时退化为当前页设置 */ }
59
+ }
60
+
61
+ /** 自动跟随按钮文案 */
62
+ export function autoFollowLabel(enabled) {
63
+ return '跟随弹窗:' + (enabled ? '开' : '关')
64
+ }
65
+
66
+ export const AUTO_FOLLOW_HELP = '点电脑窗口后,新弹出的前台窗口会自动放大到手机画面;可随时关闭。'
@@ -3,6 +3,8 @@
3
3
  *
4
4
  * 页面只负责渲染;抓图与输入由 /remote/frame、/remote/input 完成。
5
5
  */
6
+ import { NAV_CSS, topNav } from './nav.mjs'
7
+
6
8
  const escapeHtml = (value) => String(value ?? '')
7
9
  .replaceAll('&', '&amp;')
8
10
  .replaceAll('<', '&lt;')
@@ -71,14 +73,11 @@ export function renderWindowPage({ host = '', user = '', supported = true, agent
71
73
  <meta charset="utf-8">
72
74
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
73
75
  <title>窗口共享 · DSH</title>
74
- <style>${STYLE}</style>
76
+ <style>${STYLE}${NAV_CSS}</style>
75
77
  </head>
76
78
  <body>
79
+ ${topNav({ current: '/remote' })}
77
80
  <div class="bar">
78
- <a href="/">DSH</a>
79
- <a href="/files">文件</a>
80
- <a href="/term">终端</a>
81
- <a href="/vnc">桌面</a>
82
81
  <span class="spacer"></span>
83
82
  <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
84
83
  <span id="status">${supported ? (agent ? '代理已启动' : '代理未启动') : '仅支持 Windows'}</span>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.14",
3
+ "version": "2.2.2",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -71,4 +71,4 @@
71
71
  "scripts": {
72
72
  "test": "node --test --test-concurrency=1"
73
73
  }
74
- }
74
+ }
package/permissions.json CHANGED
@@ -24,6 +24,13 @@
24
24
  "title": "出站网络",
25
25
  "detail": "仅连接用户配置的 SSH/服务器地址与端口;无遥测、无第三方上报。"
26
26
  },
27
+ {
28
+ "id": "network.local_app_proxy",
29
+ "level": "high",
30
+ "default": "user-configured",
31
+ "title": "本地应用网关",
32
+ "detail": "代理多个本机回环 HTTP 服务;仅允许 127.0.0.1/::1,禁止管理端口。主动 HTML/JS 默认拦截,只有显式信任的应用才允许执行,信任后应用脚本与 DSH 同源。"
33
+ },
27
34
  {
28
35
  "id": "filesystem.read_write",
29
36
  "level": "medium",