@andy.ian/dsh-homing 2.1.4 → 2.1.6

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 (122) hide show
  1. package/README.md +42 -0
  2. package/SECURITY.md +90 -0
  3. package/bin/backup.mjs +3 -2
  4. package/bin/bootstrap-server.mjs +2 -1
  5. package/bin/inbox.mjs +46 -0
  6. package/bin/renew-cert.mjs +2 -1
  7. package/bin/window-agent-daemon.mjs +268 -0
  8. package/index.js +686 -87
  9. package/lib/compress.mjs +29 -5
  10. package/lib/exec-path.mjs +85 -0
  11. package/lib/files-page.mjs +27 -2
  12. package/lib/files.mjs +3 -2
  13. package/lib/git.mjs +5 -2
  14. package/lib/guard.mjs +43 -0
  15. package/lib/local-socket.mjs +50 -0
  16. package/lib/log-file.mjs +50 -0
  17. package/lib/node-runtime.mjs +44 -0
  18. package/lib/office.mjs +133 -0
  19. package/lib/orientation.mjs +158 -0
  20. package/lib/pty.mjs +6 -3
  21. package/lib/secret.mjs +46 -0
  22. package/lib/shells.mjs +2 -1
  23. package/lib/term-page.mjs +2 -0
  24. package/lib/vendor/des-vnc.mjs +266 -0
  25. package/lib/vendor/novnc/LICENSE.txt +62 -0
  26. package/lib/vendor/novnc/core/base64.js +104 -0
  27. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  28. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  29. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  30. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  31. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  32. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  33. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  34. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  35. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  36. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  37. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  38. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  39. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  40. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  41. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  42. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  43. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  44. package/lib/vendor/novnc/core/deflator.js +84 -0
  45. package/lib/vendor/novnc/core/display.js +578 -0
  46. package/lib/vendor/novnc/core/encodings.js +54 -0
  47. package/lib/vendor/novnc/core/inflator.js +65 -0
  48. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  49. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  50. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  51. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  52. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  53. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  54. package/lib/vendor/novnc/core/input/util.js +191 -0
  55. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  56. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  57. package/lib/vendor/novnc/core/ra2.js +312 -0
  58. package/lib/vendor/novnc/core/rfb.js +3420 -0
  59. package/lib/vendor/novnc/core/util/browser.js +233 -0
  60. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  61. package/lib/vendor/novnc/core/util/element.js +32 -0
  62. package/lib/vendor/novnc/core/util/events.js +138 -0
  63. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  64. package/lib/vendor/novnc/core/util/int.js +15 -0
  65. package/lib/vendor/novnc/core/util/logging.js +56 -0
  66. package/lib/vendor/novnc/core/util/strings.js +28 -0
  67. package/lib/vendor/novnc/core/websock.js +369 -0
  68. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  69. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  80. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  81. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  82. package/lib/vendor/vnc.bundle.js +14592 -0
  83. package/lib/vendor/ws/LICENSE +20 -0
  84. package/lib/vendor/ws/index.js +22 -0
  85. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  86. package/lib/vendor/ws/lib/constants.js +19 -0
  87. package/lib/vendor/ws/lib/event-target.js +292 -0
  88. package/lib/vendor/ws/lib/extension.js +203 -0
  89. package/lib/vendor/ws/lib/limiter.js +55 -0
  90. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  91. package/lib/vendor/ws/lib/receiver.js +743 -0
  92. package/lib/vendor/ws/lib/sender.js +610 -0
  93. package/lib/vendor/ws/lib/stream.js +161 -0
  94. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  95. package/lib/vendor/ws/lib/validation.js +152 -0
  96. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  97. package/lib/vendor/ws/lib/websocket.js +1426 -0
  98. package/lib/vendor/ws/package.json +74 -0
  99. package/lib/vendor/ws/wrapper.mjs +21 -0
  100. package/lib/vnc-app.js +567 -0
  101. package/lib/vnc-auth-proxy.mjs +179 -0
  102. package/lib/vnc-boot.js +45 -0
  103. package/lib/vnc-page.mjs +77 -0
  104. package/lib/vnc-pointer.mjs +17 -0
  105. package/lib/vnc.mjs +75 -0
  106. package/lib/window-app.js +155 -0
  107. package/lib/window-page.mjs +111 -0
  108. package/lib/window-remote.mjs +227 -0
  109. package/lib/ws-bridge.mjs +130 -0
  110. package/package.json +6 -2
  111. package/permissions.json +91 -0
  112. package/restart/client.mjs +85 -19
  113. package/restart/daemon/cli.mjs +55 -13
  114. package/restart/daemon/lib/detach.mjs +3 -2
  115. package/restart/daemon/lib/process-tree.mjs +17 -3
  116. package/restart/daemon/lib/restart-flow.mjs +36 -0
  117. package/restart/daemon/main.mjs +299 -80
  118. package/restart/engine.mjs +24 -8
  119. package/restart/port.mjs +88 -0
  120. package/restart/runner.mjs +4 -3
  121. package/restart/service.mjs +8 -5
  122. package/restart/watchdog.mjs +134 -0
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "ws",
3
+ "version": "8.22.1",
4
+ "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js",
5
+ "keywords": [
6
+ "HyBi",
7
+ "Push",
8
+ "RFC-6455",
9
+ "WebSocket",
10
+ "WebSockets",
11
+ "real-time"
12
+ ],
13
+ "homepage": "https://github.com/websockets/ws",
14
+ "bugs": "https://github.com/websockets/ws/issues",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/websockets/ws.git"
18
+ },
19
+ "author": "Einar Otto Stangvik <einaros@gmail.com> (http://2x.io)",
20
+ "license": "MIT",
21
+ "main": "index.js",
22
+ "exports": {
23
+ ".": {
24
+ "browser": "./browser.js",
25
+ "import": "./wrapper.mjs",
26
+ "require": "./index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "browser": "browser.js",
31
+ "engines": {
32
+ "node": ">=10.0.0"
33
+ },
34
+ "files": [
35
+ "browser.js",
36
+ "index.js",
37
+ "lib/*.js",
38
+ "wrapper.mjs"
39
+ ],
40
+ "scripts": {
41
+ "test": "nyc --reporter=lcov --reporter=text mocha --throw-deprecation test/*.test.js",
42
+ "integration": "mocha --throw-deprecation test/*.integration.js",
43
+ "lint": "eslint . && prettier --check --ignore-path .gitignore \"**/*.{json,md,yaml,yml}\""
44
+ },
45
+ "peerDependencies": {
46
+ "bufferutil": "^4.0.1",
47
+ "utf-8-validate": ">=5.0.2"
48
+ },
49
+ "peerDependenciesMeta": {
50
+ "bufferutil": {
51
+ "optional": true
52
+ },
53
+ "utf-8-validate": {
54
+ "optional": true
55
+ }
56
+ },
57
+ "devDependencies": {
58
+ "@eslint/js": "^10.0.1",
59
+ "benchmark": "^2.1.4",
60
+ "bufferutil": "^4.0.1",
61
+ "eslint": "^10.0.1",
62
+ "eslint-config-prettier": "^10.0.1",
63
+ "eslint-plugin-prettier": "^5.0.0",
64
+ "globals": "^17.0.0",
65
+ "mocha": "^8.4.0",
66
+ "nyc": "^15.0.0",
67
+ "prettier": "^3.0.0",
68
+ "utf-8-validate": "^6.0.0"
69
+ },
70
+ "allowScripts": {
71
+ "bufferutil": true,
72
+ "utf-8-validate": true
73
+ }
74
+ }
@@ -0,0 +1,21 @@
1
+ import createWebSocketStream from './lib/stream.js';
2
+ import extension from './lib/extension.js';
3
+ import PerMessageDeflate from './lib/permessage-deflate.js';
4
+ import Receiver from './lib/receiver.js';
5
+ import Sender from './lib/sender.js';
6
+ import subprotocol from './lib/subprotocol.js';
7
+ import WebSocket from './lib/websocket.js';
8
+ import WebSocketServer from './lib/websocket-server.js';
9
+
10
+ export {
11
+ createWebSocketStream,
12
+ extension,
13
+ PerMessageDeflate,
14
+ Receiver,
15
+ Sender,
16
+ subprotocol,
17
+ WebSocket,
18
+ WebSocketServer
19
+ };
20
+
21
+ export default WebSocket;
package/lib/vnc-app.js ADDED
@@ -0,0 +1,567 @@
1
+ /**
2
+ * /vnc 页面的浏览器入口:noVNC + 移动端工具栏。
3
+ *
4
+ * 工具栏能力:
5
+ * - 视图:适合宽度 / 整屏 / 原始 / 全屏重置
6
+ * - 关窗:列出 PC 窗口 → 选一个发 WM_CLOSE
7
+ * - 退出程序:列出窗口 → 选一个结束其进程(二次确认)
8
+ * - 自动切换:点击后若弹出新窗口,自动把视图切到那个窗口
9
+ */
10
+ import RFB from './vendor/novnc/core/rfb.js'
11
+
12
+ const statusEl = document.getElementById('status')
13
+ const passwordEl = document.getElementById('password')
14
+ const connectBtn = document.getElementById('connect')
15
+ const disconnectBtn = document.getElementById('disconnect')
16
+ const screenEl = document.getElementById('screen')
17
+
18
+ const KEYS = {
19
+ alt: 0xffe9,
20
+ ctrl: 0xffe3,
21
+ shift: 0xffe0,
22
+ super: 0xffeb,
23
+ f4: 0xffc1,
24
+ tab: 0xff09,
25
+ esc: 0xff1b,
26
+ enter: 0xff0d,
27
+ d: 0x64,
28
+ }
29
+
30
+ let rfb = null
31
+ let connected = false
32
+ let autoSwitch = false
33
+ let screenSize = null
34
+ let autoTried = false
35
+ let lastClickAt = 0
36
+ let pollTimer = null
37
+ let knownWindows = new Set()
38
+ let windowView = null
39
+ let lastForeground = null
40
+ let clickBaseForeground = null
41
+ let pendingForeground = null
42
+
43
+
44
+ /** noVNC(KasmVNC fork) 需要一个真实输入元素承接键盘与输入法 */
45
+ function ensureImeInput() {
46
+ let ime = document.getElementById('vnc-ime')
47
+ if (ime) return ime
48
+ ime = document.createElement('textarea')
49
+ ime.id = 'vnc-ime'
50
+ ime.setAttribute('autocorrect', 'off')
51
+ ime.setAttribute('autocapitalize', 'off')
52
+ ime.setAttribute('autocomplete', 'off')
53
+ ime.setAttribute('spellcheck', 'false')
54
+ ime.setAttribute('aria-hidden', 'true')
55
+ ime.style.cssText = 'position:fixed;left:-9999px;top:0;width:1px;height:1px;opacity:0;pointer-events:none'
56
+ document.body.append(ime)
57
+ return ime
58
+ }
59
+
60
+ function report(kind, message, extra) {
61
+ try {
62
+ const body = JSON.stringify({ kind, message: String(message ?? '').slice(0, 400), extra: extra ?? null })
63
+ if (navigator.sendBeacon) navigator.sendBeacon('/vnc/report', new Blob([body], { type: 'application/json' }))
64
+ else fetch('/vnc/report', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
65
+ } catch { /* 忽略 */ }
66
+ }
67
+
68
+ window.__dshReport = (kind, message) => {
69
+ try { report(kind, message) } catch { /* 忽略 */ }
70
+ }
71
+
72
+ function setStatus(text, tone = '') {
73
+ statusEl.textContent = text
74
+ statusEl.className = tone
75
+ }
76
+
77
+ const wsUrl = () => (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/vnc/ws'
78
+
79
+ function sendCombo(modifier, key) {
80
+ if (rfb === null) return
81
+ try {
82
+ rfb.sendKey(KEYS[modifier], null, true)
83
+ rfb.sendKey(KEYS[key], null, true)
84
+ rfb.sendKey(KEYS[key], null, false)
85
+ rfb.sendKey(KEYS[modifier], null, false)
86
+ } catch (error) {
87
+ setStatus('发送按键失败:' + (error?.message ?? error), 'bad')
88
+ }
89
+ }
90
+
91
+ const canvasOf = () => screenEl.querySelector('canvas')
92
+ const layerOf = () => rfb?._screen ?? null
93
+
94
+ function clearTransform() {
95
+ const layer = layerOf()
96
+ if (layer) {
97
+ layer.style.removeProperty('transform')
98
+ layer.style.removeProperty('transform-origin')
99
+ layer.style.removeProperty('width')
100
+ layer.style.removeProperty('height')
101
+ }
102
+ const canvas = canvasOf()
103
+ if (canvas) {
104
+ canvas.style.removeProperty('transform')
105
+ canvas.style.removeProperty('transform-origin')
106
+ canvas.style.removeProperty('width')
107
+ canvas.style.removeProperty('height')
108
+ }
109
+ screenEl.style.overflow = 'hidden'
110
+ windowView = null
111
+ }
112
+
113
+ /** 视图:width=铺满宽度可竖滚;screen=整屏;native=1:1 可平移 */
114
+ function setViewMode(mode) {
115
+ clearTransform()
116
+ exitFocusUi()
117
+ if (rfb !== null) {
118
+ rfb.scaleViewport = mode === 'screen'
119
+ rfb.clipViewport = mode === 'screen'
120
+ }
121
+ const canvas = canvasOf()
122
+ if (mode === 'width') {
123
+ // 关键:布局尺寸保持帧缓冲尺寸,只用 transform 缩小,
124
+ // 否则元素坐标 ≠ 帧缓冲坐标,点击会落到左上角
125
+ const fbW = canvas?.width || 1920
126
+ const fbH = canvas?.height || 1080
127
+ const scale = screenEl.clientWidth / fbW
128
+ const layer = layerOf() ?? canvas
129
+ if (layer) {
130
+ layer.style.setProperty('width', fbW + 'px', 'important')
131
+ layer.style.setProperty('height', fbH + 'px', 'important')
132
+ layer.style.setProperty('transform-origin', '0 0', 'important')
133
+ layer.style.setProperty('transform', 'scale(' + scale + ')', 'important')
134
+ }
135
+ const spacer = document.getElementById('vnc-spacer') ?? (() => {
136
+ const node = document.createElement('div')
137
+ node.id = 'vnc-spacer'
138
+ screenEl.append(node)
139
+ return node
140
+ })()
141
+ spacer.style.cssText = 'width:1px;height:' + Math.round(fbH * scale) + 'px;pointer-events:none'
142
+ screenEl.style.overflowY = 'auto'
143
+ screenEl.style.overflowX = 'hidden'
144
+ } else if (mode === 'native') {
145
+ screenEl.style.overflow = 'auto'
146
+ }
147
+ setStatus('视图:' + ({ width: '适合宽度', screen: '整屏', native: '原始大小' }[mode] ?? mode))
148
+ }
149
+
150
+ /** 把视图裁剪/缩放到指定窗口矩形(自动切窗时用) */
151
+ /** 让目标窗口置前:否则裁剪区域可能被上层窗口盖住,看起来像切错窗口 */
152
+ function raiseWindow(hwnd) {
153
+ fetch('/remote/input', {
154
+ method: 'POST',
155
+ headers: { 'content-type': 'application/json' },
156
+ body: JSON.stringify({ kind: 'focus', hwnd: String(hwnd) }),
157
+ }).catch(() => {})
158
+ }
159
+
160
+ function enterFocusUi() {
161
+ document.body.classList.add('vnc-focus')
162
+ const header = document.querySelector('header, .topbar, .top-bar, .nav, nav')
163
+ if (header) header.style.display = 'none'
164
+ const bar = document.getElementById('vnc-toolbar')
165
+ if (bar) bar.classList.add('compact')
166
+ const style = document.getElementById('vnc-focus-style') ?? (() => {
167
+ const node = document.createElement('style')
168
+ node.id = 'vnc-focus-style'
169
+ node.textContent = '#vnc-toolbar.compact button[data-secondary]{display:none}#vnc-toolbar.compact{padding:4px 6px;gap:4px}#vnc-toolbar.compact button{padding:4px 8px;font-size:11px}'
170
+ document.head.append(node)
171
+ return node
172
+ })()
173
+ style.textContent = style.textContent
174
+ }
175
+
176
+ function exitFocusUi() {
177
+ document.body.classList.remove('vnc-focus')
178
+ const header = document.querySelector('header, .topbar, .top-bar, .nav, nav')
179
+ if (header) header.style.display = ''
180
+ }
181
+
182
+ function focusWindowRect(win) {
183
+ const canvas = canvasOf()
184
+ if (!canvas || !win || !win.width || !win.height) return
185
+ clearTransform()
186
+ if (win.foreground !== true) raiseWindow(win.hwnd)
187
+ if (rfb !== null) {
188
+ rfb.scaleViewport = false
189
+ rfb.clipViewport = false
190
+ }
191
+ // 窗口矩形和 VNC 帧缓冲可能不是同一坐标系(DPI 缩放),先按屏幕尺寸换算
192
+ const fbW = canvas.width || 1920
193
+ const fbH = canvas.height || 1080
194
+ const sx = screenSize && screenSize.width > 0 ? fbW / screenSize.width : 1
195
+ const sy = screenSize && screenSize.height > 0 ? fbH / screenSize.height : 1
196
+ let x = (win.x ?? 0) * sx
197
+ let y = (win.y ?? 0) * sy
198
+ let w = win.width * sx
199
+ let h = win.height * sy
200
+ // 越界(窗口比帧缓冲还大 / 坐标为负)时回退到整屏,避免裁出空白
201
+ if (w <= 0 || h <= 0 || w > fbW * 1.2 || h > fbH * 1.2) {
202
+ setViewMode('width')
203
+ setStatus('窗口尺寸异常,已显示整屏')
204
+ return
205
+ }
206
+ x = Math.max(0, Math.min(x, fbW - 1))
207
+ y = Math.max(0, Math.min(y, fbH - 1))
208
+ w = Math.min(w, fbW - x)
209
+ h = Math.min(h, fbH - y)
210
+ // 等比缩放到"完整可见",同时尽量占满手机可用区域
211
+ const scale = Math.min(screenEl.clientWidth / w, screenEl.clientHeight / h)
212
+ const offsetX = (screenEl.clientWidth - w * scale) / 2
213
+ const offsetY = (screenEl.clientHeight - h * scale) / 2
214
+ // 关键:让画布的 CSS 布局尺寸等于帧缓冲尺寸,
215
+ // 这样 clientToElement 的换算比例才正确(否则点击会偏移)
216
+ const layer = layerOf() ?? canvas
217
+ layer.style.setProperty('width', fbW + 'px', 'important')
218
+ layer.style.setProperty('height', fbH + 'px', 'important')
219
+ layer.style.setProperty('transform-origin', '0 0', 'important')
220
+ layer.style.setProperty('transform', `translate(${offsetX - x * scale}px, ${offsetY - y * scale}px) scale(${scale})`, 'important')
221
+ screenEl.style.overflow = 'hidden'
222
+ screenEl.scrollTop = 0
223
+ screenEl.scrollLeft = 0
224
+ windowView = win
225
+ enterFocusUi()
226
+ setStatus('已切换到:' + (win.title ?? '').slice(0, 24))
227
+ }
228
+
229
+ async function fetchWindows() {
230
+ const response = await fetch('/remote/windows', { cache: 'no-store' })
231
+ const data = await response.json()
232
+ if (!data.ok) throw new Error(data.error || '列窗口失败')
233
+ if (data.screenWidth > 0 && data.screenHeight > 0) {
234
+ screenSize = { width: data.screenWidth, height: data.screenHeight }
235
+ }
236
+ return data.windows || []
237
+ }
238
+
239
+ /**
240
+ * 轮询窗口列表并决定是否切窗。规则(宁可少切,不可切错):
241
+ * 1. 只认"前台窗口发生变化",不认"出现新窗口"
242
+ * 2. 变化必须发生在用户点击后的 5 秒内
243
+ * 3. 新前台窗口要连续两次轮询保持稳定(~1.2s),排除一闪而过的辅助窗口
244
+ * 4. 新前台不能等于点击前的前台(说明没切换)
245
+ * 5. 不能等于当前已聚焦窗口;尺寸必须正常
246
+ */
247
+ /** 已聚焦的窗口如果移动/改尺寸,重新对齐裁剪(WPS 打开文档会改变窗口大小) */
248
+ function refreshWindowView(windows) {
249
+ if (!windowView || !autoSwitch) return
250
+ const match = windows.find((w) => String(w.hwnd) === String(windowView.hwnd))
251
+ if (!match) return
252
+ const changed = match.x !== windowView.x || match.y !== windowView.y
253
+ || match.width !== windowView.width || match.height !== windowView.height
254
+ if (changed) focusWindowRect(match)
255
+ }
256
+
257
+ async function pollWindows() {
258
+ if (!connected) return
259
+ try {
260
+ const windows = await fetchWindows()
261
+ const ids = new Set(windows.map((w) => w.hwnd))
262
+ const fg = windows.find((w) => w.foreground === true) ?? null
263
+
264
+ if (fg !== null) {
265
+ if (String(fg.hwnd) !== String(lastForeground)) {
266
+ pendingForeground = { hwnd: fg.hwnd, since: Date.now() }
267
+ }
268
+ lastForeground = fg.hwnd
269
+ }
270
+
271
+ if (autoSwitch && lastClickAt > 0 && fg !== null && pendingForeground !== null) {
272
+ const now = Date.now()
273
+ const stable = now - pendingForeground.since >= 1200
274
+ const fresh = Date.now() - lastClickAt <= 5000
275
+ const changed = !knownWindows.has(fg.hwnd)
276
+ const notCurrent = !windowView || String(windowView.hwnd) !== String(fg.hwnd)
277
+ const sane = (fg.width ?? 0) > 80 && (fg.height ?? 0) > 80 && String(fg.title ?? '').trim() !== ''
278
+ if (stable && fresh && changed && notCurrent && sane) {
279
+ lastClickAt = 0
280
+ pendingForeground = null
281
+ focusWindowRect(fg)
282
+ }
283
+ }
284
+ if (Date.now() - lastClickAt > 5000) pendingForeground = null
285
+
286
+ knownWindows = ids
287
+ } catch { /* 忽略轮询错误 */ }
288
+ }
289
+
290
+ /** 等窗口真正成为前台,最多 timeout 毫秒 */
291
+ async function waitForeground(hwnd, timeout = 3000) {
292
+ const deadline = Date.now() + timeout
293
+ while (Date.now() < deadline) {
294
+ try {
295
+ const windows = await fetchWindows()
296
+ const target = windows.find((w) => String(w.hwnd) === String(hwnd))
297
+ if (target && target.foreground === true) return true
298
+ } catch { /* 忽略 */ }
299
+ await new Promise((resolve) => setTimeout(resolve, 200))
300
+ }
301
+ return false
302
+ }
303
+
304
+ async function focusByHwnd(hwnd, attempts = 8) {
305
+ for (let i = 0; i < attempts; i += 1) {
306
+ try {
307
+ const windows = await fetchWindows()
308
+ const target = windows.find((w) => String(w.hwnd) === String(hwnd))
309
+ if (target) {
310
+ if (target.foreground !== true) {
311
+ raiseWindow(target.hwnd)
312
+ const ok = await waitForeground(target.hwnd)
313
+ if (!ok) {
314
+ setViewMode('width')
315
+ setStatus('窗口置前失败,已显示桌面')
316
+ return false
317
+ }
318
+ }
319
+ const latest = (await fetchWindows()).find((w) => String(w.hwnd) === String(hwnd)) ?? target
320
+ focusWindowRect(latest)
321
+ return true
322
+ }
323
+ } catch { /* 稍后重试 */ }
324
+ await new Promise((resolve) => setTimeout(resolve, 600))
325
+ }
326
+ return false
327
+ }
328
+
329
+ function startPolling() {
330
+ stopPolling()
331
+ pollTimer = setInterval(pollWindows, 1200)
332
+ pollWindows()
333
+ }
334
+
335
+ function stopPolling() {
336
+ if (pollTimer !== null) {
337
+ clearInterval(pollTimer)
338
+ pollTimer = null
339
+ }
340
+ }
341
+
342
+ async function pickWindowAction(kind) {
343
+ try {
344
+ const windows = await fetchWindows()
345
+ showPicker(windows, kind)
346
+ } catch (error) {
347
+ setStatus('列窗口失败:' + (error?.message ?? error), 'bad')
348
+ }
349
+ }
350
+
351
+ function showPicker(windows, kind) {
352
+ const mask = document.createElement('div')
353
+ mask.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.72);z-index:9999;display:flex;flex-direction:column;padding:12px;gap:8px;overflow:auto'
354
+ const title = document.createElement('div')
355
+ title.textContent = kind === 'kill' ? '选择要结束的程序(会强制结束进程)' : '选择要关闭的窗口'
356
+ title.style.cssText = 'color:#e6e8ee;font-size:14px;padding:4px'
357
+ mask.append(title)
358
+ for (const item of windows) {
359
+ const row = document.createElement('button')
360
+ row.type = 'button'
361
+ row.textContent = item.title + ' · ' + (item.process || '')
362
+ row.style.cssText = 'text-align:left;padding:10px 12px;border-radius:8px;border:1px solid #333a46;background:#1b2029;color:#cfd5df;font-size:13px'
363
+ row.addEventListener('click', async () => {
364
+ mask.remove()
365
+ if (kind === 'kill') {
366
+ const yes = window.confirm('强制结束「' + item.title + '」?未保存的内容会丢失。')
367
+ if (!yes) return
368
+ }
369
+ try {
370
+ const res = await fetch('/remote/input', {
371
+ method: 'POST',
372
+ headers: { 'content-type': 'application/json' },
373
+ body: JSON.stringify({ kind, hwnd: item.hwnd }),
374
+ })
375
+ const body = await res.json()
376
+ setStatus(body.ok ? (kind === 'kill' ? '已结束:' : '已关闭:') + item.title : '操作失败:' + (body.error || ''), body.ok ? 'ok' : 'bad')
377
+ } catch (error) {
378
+ setStatus('操作失败:' + (error?.message ?? error), 'bad')
379
+ }
380
+ })
381
+ mask.append(row)
382
+ }
383
+ const cancel = document.createElement('button')
384
+ cancel.type = 'button'
385
+ cancel.textContent = '取消'
386
+ cancel.style.cssText = 'padding:10px 12px;border-radius:8px;border:1px solid #54303a;background:#3a2226;color:#f0b6bf;font-size:13px'
387
+ cancel.addEventListener('click', () => mask.remove())
388
+ mask.append(cancel)
389
+ document.body.append(mask)
390
+ }
391
+
392
+ /** 切换电脑屏幕方向;旋转后帧缓冲尺寸变化,重连一次以适配 */
393
+ async function rotateDesktop(mode) {
394
+ setStatus(mode === 'portrait' ? '正在切竖屏…' : '正在切横屏…')
395
+ try {
396
+ const response = await fetch('/remote/input', {
397
+ method: 'POST',
398
+ headers: { 'content-type': 'application/json' },
399
+ body: JSON.stringify({ kind: 'rotate', mode }),
400
+ })
401
+ const data = await response.json()
402
+ if (!data.ok) {
403
+ setStatus('切换失败:' + (data.detail || '未知原因'), 'bad')
404
+ return
405
+ }
406
+ try {
407
+ if (mode === 'portrait') localStorage.setItem('dsh-vnc-portrait', '1')
408
+ else localStorage.removeItem('dsh-vnc-portrait')
409
+ } catch { /* 忽略 */ }
410
+ setStatus(mode === 'portrait' ? '已切竖屏,重连中…' : '已切横屏,重连中…', 'ok')
411
+ setTimeout(() => {
412
+ try { cleanup(); connect() } catch { /* 忽略 */ }
413
+ }, 1200)
414
+ } catch (error) {
415
+ setStatus('切换失败:' + (error?.message ?? error), 'bad')
416
+ }
417
+ }
418
+
419
+ function setupToolbar() {
420
+ if (document.getElementById('vnc-toolbar')) return
421
+ const bar = document.createElement('div')
422
+ bar.id = 'vnc-toolbar'
423
+ bar.style.cssText = 'flex:0 0 auto;display:flex;gap:6px;flex-wrap:wrap;padding:6px 8px;background:#141920;border-top:1px solid #262b35'
424
+
425
+ const button = (label, onClick) => {
426
+ const node = document.createElement('button')
427
+ node.type = 'button'
428
+ node.textContent = label
429
+ node.style.cssText = 'padding:6px 10px;border-radius:6px;border:1px solid #333a46;background:#232a35;color:#cfd5df;font-size:12px'
430
+ node.addEventListener('click', onClick)
431
+ return node
432
+ }
433
+
434
+ const autoBtn = button('自动切窗:关', () => {
435
+ autoSwitch = !autoSwitch
436
+ autoBtn.textContent = '自动切窗:' + (autoSwitch ? '开' : '关')
437
+ if (autoSwitch) { clickBaseForeground = lastForeground; pendingForeground = null; lastClickAt = 0 }
438
+ })
439
+
440
+ bar.append(
441
+ button('适合宽度', () => setViewMode('width')),
442
+ button('整屏', () => setViewMode('screen')),
443
+ button('全屏', () => setViewMode('screen')),
444
+ autoBtn,
445
+ button('关闭窗口', () => pickWindowAction('close')),
446
+ button('退出程序', () => pickWindowAction('kill')),
447
+ button('Alt+F4', () => sendCombo('alt', 'f4')),
448
+ button('切换窗口', () => sendCombo('alt', 'tab')),
449
+ button('电脑竖屏', () => rotateDesktop('portrait')),
450
+ button('电脑横屏', () => rotateDesktop('landscape')),
451
+ button('返回文件', () => { location.href = '/files' }),
452
+ )
453
+ screenEl.parentElement.insertBefore(bar, screenEl.nextSibling)
454
+ }
455
+
456
+ /** 用户点击画面 = 可能触发新窗口,记录时间供轮询检测 */
457
+ function markClick(event) {
458
+ lastClickAt = Date.now()
459
+ clickBaseForeground = lastForeground
460
+ pendingForeground = null
461
+ }
462
+
463
+ canvasOfGuard()
464
+
465
+ function canvasOfGuard() {
466
+ // 画布由 noVNC 创建,这里只挂事件委托
467
+ screenEl.addEventListener('pointerdown', markClick, true)
468
+
469
+ for (const type of ['pointerup', 'mouseup', 'click']) {
470
+ screenEl.addEventListener(type, (event) => {
471
+ if (Date.now() < handledUntil) {
472
+ event.stopPropagation()
473
+ event.preventDefault()
474
+ }
475
+ }, true)
476
+ }
477
+ }
478
+
479
+ function cleanup() {
480
+ if (rfb !== null) {
481
+ try { rfb.disconnect() } catch { /* 已断开 */ }
482
+ rfb = null
483
+ }
484
+ connected = false
485
+ stopPolling()
486
+ clearTransform()
487
+ connectBtn.disabled = false
488
+ disconnectBtn.disabled = true
489
+ passwordEl.disabled = false
490
+ }
491
+
492
+ function connect() {
493
+ if (rfb !== null) cleanup()
494
+ setStatus('连接中…')
495
+ connectBtn.disabled = true
496
+ try {
497
+ // 密码由服务端代认证(lib/vnc-auth-proxy.mjs),浏览器不持有密码
498
+ rfb = new RFB(screenEl, wsUrl(), {
499
+ wsProtocols: ['binary'],
500
+ })
501
+ } catch (error) {
502
+ setStatus('创建连接失败:' + (error?.message ?? error), 'bad')
503
+ cleanup()
504
+ return
505
+ }
506
+
507
+ rfb.scaleViewport = false
508
+ rfb.clipViewport = false
509
+ rfb.showDotCursor = false
510
+ rfb.focusOnClick = true
511
+ setViewMode('width')
512
+
513
+ rfb.addEventListener('connect', () => {
514
+ connected = true
515
+ report('connect-ok', 'ok')
516
+ disconnectBtn.disabled = false
517
+ passwordEl.disabled = true
518
+ setStatus('已连接', 'ok')
519
+ startPolling()
520
+ const focus = new URLSearchParams(location.search).get('focus')
521
+ if (focus !== null && focus !== '') {
522
+ setStatus('正在定位窗口…')
523
+ focusByHwnd(focus).then((found) => { if (!found) setStatus('未找到对应窗口,已显示整屏') })
524
+ }
525
+ })
526
+ rfb.addEventListener('disconnect', (event) => {
527
+ const clean = event.detail?.clean ?? false
528
+ report('disconnect', clean ? 'clean' : 'dirty', { detail: event.detail ?? null, reason: rfb?._lastFailReason ?? null })
529
+ setStatus(clean ? '已断开' : '连接中断', clean ? '' : 'bad')
530
+ cleanup()
531
+ })
532
+ rfb.addEventListener('securityfailure', (event) => {
533
+ setStatus('认证失败:' + (event.detail?.reason ?? '密码错误'), 'bad')
534
+ cleanup()
535
+ })
536
+ }
537
+
538
+ connectBtn.addEventListener('click', connect)
539
+ disconnectBtn.addEventListener('click', () => {
540
+ cleanup()
541
+ setStatus('已断开')
542
+ })
543
+
544
+ window.addEventListener('pagehide', () => {
545
+ // 离开页面时如果竖屏是我们切的,恢复横屏,避免把 PC 留在竖屏
546
+ try {
547
+ if (localStorage.getItem('dsh-vnc-portrait') === '1') {
548
+ localStorage.removeItem('dsh-vnc-portrait')
549
+ const body = new Blob([JSON.stringify({ kind: 'rotate', mode: 'landscape' })], { type: 'application/json' })
550
+ if (navigator.sendBeacon) navigator.sendBeacon('/remote/input', body)
551
+ else fetch('/remote/input', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: 'rotate', mode: 'landscape' }), keepalive: true }).catch(() => {})
552
+ }
553
+ } catch { /* 忽略 */ }
554
+ if (rfb !== null) { try { rfb.disconnect() } catch { /* 忽略 */ } }
555
+ })
556
+
557
+ setupToolbar()
558
+
559
+ function autoConnect() {
560
+ if (autoTried) return
561
+ autoTried = true
562
+ if (passwordEl) passwordEl.style.display = 'none'
563
+ setStatus('用已登录账号自动连接…')
564
+ connect()
565
+ }
566
+
567
+ autoConnect()