@andy.ian/dsh-homing 2.1.4 → 2.1.5

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 (120) 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/renew-cert.mjs +2 -1
  6. package/index.js +686 -87
  7. package/lib/compress.mjs +29 -5
  8. package/lib/exec-path.mjs +85 -0
  9. package/lib/files-page.mjs +27 -2
  10. package/lib/files.mjs +3 -2
  11. package/lib/git.mjs +5 -2
  12. package/lib/guard.mjs +43 -0
  13. package/lib/local-socket.mjs +50 -0
  14. package/lib/log-file.mjs +50 -0
  15. package/lib/node-runtime.mjs +44 -0
  16. package/lib/office.mjs +133 -0
  17. package/lib/orientation.mjs +158 -0
  18. package/lib/pty.mjs +6 -3
  19. package/lib/secret.mjs +46 -0
  20. package/lib/shells.mjs +2 -1
  21. package/lib/term-page.mjs +2 -0
  22. package/lib/vendor/des-vnc.mjs +266 -0
  23. package/lib/vendor/novnc/LICENSE.txt +62 -0
  24. package/lib/vendor/novnc/core/base64.js +104 -0
  25. package/lib/vendor/novnc/core/crypto/aes.js +178 -0
  26. package/lib/vendor/novnc/core/crypto/bigint.js +34 -0
  27. package/lib/vendor/novnc/core/crypto/crypto.js +90 -0
  28. package/lib/vendor/novnc/core/crypto/des.js +330 -0
  29. package/lib/vendor/novnc/core/crypto/dh.js +55 -0
  30. package/lib/vendor/novnc/core/crypto/md5.js +82 -0
  31. package/lib/vendor/novnc/core/crypto/rsa.js +132 -0
  32. package/lib/vendor/novnc/core/decoders/copyrect.js +27 -0
  33. package/lib/vendor/novnc/core/decoders/h264.js +321 -0
  34. package/lib/vendor/novnc/core/decoders/hextile.js +181 -0
  35. package/lib/vendor/novnc/core/decoders/jpeg.js +161 -0
  36. package/lib/vendor/novnc/core/decoders/raw.js +59 -0
  37. package/lib/vendor/novnc/core/decoders/rre.js +44 -0
  38. package/lib/vendor/novnc/core/decoders/tight.js +393 -0
  39. package/lib/vendor/novnc/core/decoders/tightpng.js +27 -0
  40. package/lib/vendor/novnc/core/decoders/zlib.js +51 -0
  41. package/lib/vendor/novnc/core/decoders/zrle.js +185 -0
  42. package/lib/vendor/novnc/core/deflator.js +84 -0
  43. package/lib/vendor/novnc/core/display.js +578 -0
  44. package/lib/vendor/novnc/core/encodings.js +54 -0
  45. package/lib/vendor/novnc/core/inflator.js +65 -0
  46. package/lib/vendor/novnc/core/input/domkeytable.js +311 -0
  47. package/lib/vendor/novnc/core/input/fixedkeys.js +129 -0
  48. package/lib/vendor/novnc/core/input/gesturehandler.js +567 -0
  49. package/lib/vendor/novnc/core/input/keyboard.js +294 -0
  50. package/lib/vendor/novnc/core/input/keysym.js +616 -0
  51. package/lib/vendor/novnc/core/input/keysymdef.js +688 -0
  52. package/lib/vendor/novnc/core/input/util.js +191 -0
  53. package/lib/vendor/novnc/core/input/vkeys.js +116 -0
  54. package/lib/vendor/novnc/core/input/xtscancodes.js +173 -0
  55. package/lib/vendor/novnc/core/ra2.js +312 -0
  56. package/lib/vendor/novnc/core/rfb.js +3420 -0
  57. package/lib/vendor/novnc/core/util/browser.js +233 -0
  58. package/lib/vendor/novnc/core/util/cursor.js +249 -0
  59. package/lib/vendor/novnc/core/util/element.js +32 -0
  60. package/lib/vendor/novnc/core/util/events.js +138 -0
  61. package/lib/vendor/novnc/core/util/eventtarget.js +35 -0
  62. package/lib/vendor/novnc/core/util/int.js +15 -0
  63. package/lib/vendor/novnc/core/util/logging.js +56 -0
  64. package/lib/vendor/novnc/core/util/strings.js +28 -0
  65. package/lib/vendor/novnc/core/websock.js +369 -0
  66. package/lib/vendor/novnc/vendor/pako/LICENSE +21 -0
  67. package/lib/vendor/novnc/vendor/pako/README.md +6 -0
  68. package/lib/vendor/novnc/vendor/pako/lib/utils/common.js +45 -0
  69. package/lib/vendor/novnc/vendor/pako/lib/zlib/adler32.js +27 -0
  70. package/lib/vendor/novnc/vendor/pako/lib/zlib/constants.js +47 -0
  71. package/lib/vendor/novnc/vendor/pako/lib/zlib/crc32.js +36 -0
  72. package/lib/vendor/novnc/vendor/pako/lib/zlib/deflate.js +1846 -0
  73. package/lib/vendor/novnc/vendor/pako/lib/zlib/gzheader.js +35 -0
  74. package/lib/vendor/novnc/vendor/pako/lib/zlib/inffast.js +324 -0
  75. package/lib/vendor/novnc/vendor/pako/lib/zlib/inflate.js +1527 -0
  76. package/lib/vendor/novnc/vendor/pako/lib/zlib/inftrees.js +322 -0
  77. package/lib/vendor/novnc/vendor/pako/lib/zlib/messages.js +11 -0
  78. package/lib/vendor/novnc/vendor/pako/lib/zlib/trees.js +1195 -0
  79. package/lib/vendor/novnc/vendor/pako/lib/zlib/zstream.js +24 -0
  80. package/lib/vendor/vnc.bundle.js +14592 -0
  81. package/lib/vendor/ws/LICENSE +20 -0
  82. package/lib/vendor/ws/index.js +22 -0
  83. package/lib/vendor/ws/lib/buffer-util.js +142 -0
  84. package/lib/vendor/ws/lib/constants.js +19 -0
  85. package/lib/vendor/ws/lib/event-target.js +292 -0
  86. package/lib/vendor/ws/lib/extension.js +203 -0
  87. package/lib/vendor/ws/lib/limiter.js +55 -0
  88. package/lib/vendor/ws/lib/permessage-deflate.js +530 -0
  89. package/lib/vendor/ws/lib/receiver.js +743 -0
  90. package/lib/vendor/ws/lib/sender.js +610 -0
  91. package/lib/vendor/ws/lib/stream.js +161 -0
  92. package/lib/vendor/ws/lib/subprotocol.js +62 -0
  93. package/lib/vendor/ws/lib/validation.js +152 -0
  94. package/lib/vendor/ws/lib/websocket-server.js +562 -0
  95. package/lib/vendor/ws/lib/websocket.js +1426 -0
  96. package/lib/vendor/ws/package.json +74 -0
  97. package/lib/vendor/ws/wrapper.mjs +21 -0
  98. package/lib/vnc-app.js +567 -0
  99. package/lib/vnc-auth-proxy.mjs +179 -0
  100. package/lib/vnc-boot.js +45 -0
  101. package/lib/vnc-page.mjs +77 -0
  102. package/lib/vnc-pointer.mjs +17 -0
  103. package/lib/vnc.mjs +75 -0
  104. package/lib/window-app.js +155 -0
  105. package/lib/window-page.mjs +111 -0
  106. package/lib/window-remote.mjs +226 -0
  107. package/lib/ws-bridge.mjs +130 -0
  108. package/package.json +4 -2
  109. package/permissions.json +91 -0
  110. package/restart/client.mjs +85 -19
  111. package/restart/daemon/cli.mjs +55 -13
  112. package/restart/daemon/lib/detach.mjs +3 -2
  113. package/restart/daemon/lib/process-tree.mjs +17 -3
  114. package/restart/daemon/lib/restart-flow.mjs +36 -0
  115. package/restart/daemon/main.mjs +299 -80
  116. package/restart/engine.mjs +24 -8
  117. package/restart/port.mjs +88 -0
  118. package/restart/runner.mjs +4 -3
  119. package/restart/service.mjs +8 -5
  120. package/restart/watchdog.mjs +134 -0
@@ -0,0 +1,179 @@
1
+ /**
2
+ * 服务端 VNC 认证代理。
3
+ *
4
+ * 目的:让浏览器永远拿不到 VNC 密码。
5
+ *
6
+ * 做法:本模块先以自己的身份和 VNC 服务端完成 RFB 握手(含 VNC 认证的
7
+ * DES 挑战应答),成功后与浏览器之间伪造一段"无认证"的握手:
8
+ *
9
+ * browser ← RFB 003.008
10
+ * browser → RFB 003.008
11
+ * browser ← [1] 安全类型:None
12
+ * browser → [1] 选择 None
13
+ * browser ← SecurityResult = 0
14
+ * browser → ClientInit
15
+ * browser ← 真实的 ServerInit(从上游读到的)
16
+ * ←→ 之后双向原样转发
17
+ *
18
+ * 浏览器(noVNC)看到的是一个不需要密码的普通 VNC 服务端。
19
+ */
20
+ import net from 'node:net'
21
+ import DES from './vendor/des-vnc.mjs'
22
+
23
+ class ByteQueue {
24
+ constructor(name) {
25
+ this.name = name
26
+ this.buf = Buffer.alloc(0)
27
+ this.waiters = []
28
+ this.sink = null
29
+ this.ended = false
30
+ this.error = null
31
+ }
32
+
33
+ push(chunk) {
34
+ if (this.sink !== null) {
35
+ this.sink(chunk)
36
+ return
37
+ }
38
+ this.buf = Buffer.concat([this.buf, chunk])
39
+ this.flush()
40
+ }
41
+
42
+ read(n) {
43
+ if (this.ended) return Promise.reject(this.error ?? new Error(this.name + ' closed'))
44
+ return new Promise((resolve, reject) => {
45
+ this.waiters.push({ n, resolve, reject })
46
+ this.flush()
47
+ })
48
+ }
49
+
50
+ flush() {
51
+ while (this.waiters.length > 0 && this.buf.length >= this.waiters[0].n) {
52
+ const waiter = this.waiters.shift()
53
+ const out = this.buf.subarray(0, waiter.n)
54
+ this.buf = this.buf.subarray(waiter.n)
55
+ waiter.resolve(out)
56
+ }
57
+ }
58
+
59
+ pipeTo(sink) {
60
+ this.sink = sink
61
+ if (this.buf.length > 0) {
62
+ const rest = this.buf
63
+ this.buf = Buffer.alloc(0)
64
+ sink(rest)
65
+ }
66
+ }
67
+
68
+ end(error) {
69
+ if (this.ended) return
70
+ this.ended = true
71
+ this.error = error ?? null
72
+ for (const waiter of this.waiters) waiter.reject(this.error ?? new Error(this.name + ' closed'))
73
+ this.waiters = []
74
+ }
75
+ }
76
+
77
+ function sendBinary(ws, buffer) {
78
+ try {
79
+ ws.send(buffer, { binary: true })
80
+ } catch {
81
+ // 连接已断开,忽略
82
+ }
83
+ }
84
+
85
+ function buildDesResponse(password, challenge) {
86
+ const key = []
87
+ for (const ch of String(password)) key.push(ch.charCodeAt(0) & 0xff)
88
+ while (key.length < 8) key.push(0)
89
+ const des = new DES(key.slice(0, 8))
90
+ return Buffer.from(des.encrypt([...challenge]))
91
+ }
92
+
93
+ /**
94
+ * 接管一条已升级的 WebSocket,完成"服务端认证 + 浏览器无认证"的桥接。
95
+ * @param {object} options
96
+ * @param {import('ws').WebSocket} options.ws
97
+ * @param {string} options.host
98
+ * @param {number} options.port
99
+ * @param {() => Promise<string>} options.getPassword
100
+ * @param {(error: Error) => void} [options.onError]
101
+ */
102
+ export function startVncAuthProxy({ ws, host, port, getPassword, onError }) {
103
+ const client = new ByteQueue('client')
104
+ const upstream = new ByteQueue('upstream')
105
+ const tcp = net.connect({ host, port })
106
+ let closed = false
107
+
108
+ const finish = (error) => {
109
+ if (closed) return
110
+ closed = true
111
+ client.end(error)
112
+ upstream.end(error)
113
+ try { tcp.destroy() } catch { /* 忽略 */ }
114
+ try {
115
+ if (error) ws.close(1011, 'vnc auth proxy failed')
116
+ else ws.close()
117
+ } catch { /* 忽略 */ }
118
+ if (error && typeof onError === 'function') onError(error)
119
+ }
120
+
121
+ tcp.on('data', (chunk) => upstream.push(chunk))
122
+ tcp.on('error', (error) => finish(error))
123
+ tcp.on('close', () => finish(null))
124
+ ws.on('message', (data) => client.push(Buffer.isBuffer(data) ? data : Buffer.from(data)))
125
+ ws.on('close', () => {
126
+ closed = true
127
+ client.end(new Error('browser closed'))
128
+ upstream.end(new Error('browser closed'))
129
+ try { tcp.destroy() } catch { /* 忽略 */ }
130
+ })
131
+ ws.on('error', () => finish(null))
132
+
133
+ const handshake = async () => {
134
+ await new Promise((resolve, reject) => {
135
+ tcp.once('connect', resolve)
136
+ tcp.once('error', reject)
137
+ })
138
+
139
+ // ---- 对浏览器:伪造无认证握手 ----
140
+ sendBinary(ws, Buffer.from('RFB 003.008\n', 'latin1'))
141
+ const clientVersion = await client.read(12)
142
+ if (clientVersion.toString('latin1').slice(0, 4) !== 'RFB ') {
143
+ throw new Error('client version invalid')
144
+ }
145
+ sendBinary(ws, Buffer.from([1, 1])) // 1 种安全类型:None
146
+ const selection = await client.read(1)
147
+ if (selection[0] !== 1) throw new Error('client rejected None security')
148
+ sendBinary(ws, Buffer.from([0, 0, 0, 0])) // SecurityResult OK
149
+ await client.read(1) // ClientInit
150
+
151
+ // ---- 对上游:真实 VNC 认证 ----
152
+ const serverVersion = await upstream.read(12)
153
+ tcp.write(serverVersion)
154
+ const typeCount = (await upstream.read(1))[0]
155
+ const types = await upstream.read(typeCount)
156
+ if (![...types].includes(2)) throw new Error('server does not offer VNC auth')
157
+ tcp.write(Buffer.from([2]))
158
+ const challenge = await upstream.read(16)
159
+ const password = await getPassword()
160
+ if (typeof password !== 'string' || password === '') throw new Error('VNC password not configured')
161
+ tcp.write(buildDesResponse(password, challenge))
162
+ const result = await upstream.read(4)
163
+ if (result.readUInt32BE(0) !== 0) throw new Error('VNC authentication failed')
164
+ tcp.write(Buffer.from([1])) // ClientInit(shared)
165
+ const header = await upstream.read(24)
166
+ const nameLength = header.readUInt32BE(20)
167
+ const name = nameLength > 0 ? await upstream.read(nameLength) : Buffer.alloc(0)
168
+ sendBinary(ws, Buffer.concat([header, name]))
169
+
170
+ // ---- 进入透传 ----
171
+ upstream.pipeTo((chunk) => sendBinary(ws, chunk))
172
+ client.pipeTo((chunk) => {
173
+ try { tcp.write(chunk) } catch { /* 忽略 */ }
174
+ })
175
+ }
176
+
177
+ handshake().catch((error) => finish(error))
178
+ return { close: () => finish(null) }
179
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * /vnc 启动脚本(经典脚本):
3
+ * - 安装错误上报
4
+ * - 用普通 <script> 加载打包好的单文件 bundle(不再用 ES module 动态 import)
5
+ *
6
+ * 为什么改成单文件:noVNC 的模块图在部分手机浏览器上会被
7
+ * CSP/缓存/模块解析问题打断,打包成 IIFE 后只有一个请求,最稳定。
8
+ */
9
+ (() => {
10
+ const report = (kind, message, extra) => {
11
+ try {
12
+ const body = JSON.stringify({ kind, message: String(message ?? '').slice(0, 500), extra: extra ?? null })
13
+ if (navigator.sendBeacon) navigator.sendBeacon('/vnc/report', new Blob([body], { type: 'application/json' }))
14
+ else fetch('/vnc/report', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
15
+ } catch { /* 上报失败就算了 */ }
16
+ }
17
+
18
+ window.addEventListener('error', (event) => {
19
+ report('error', event.message, { filename: event.filename, line: event.lineno })
20
+ })
21
+ window.addEventListener('unhandledrejection', (event) => {
22
+ report('rejection', event.reason?.message ?? event.reason)
23
+ })
24
+ document.addEventListener('securitypolicyviolation', (event) => {
25
+ report('csp', event.violatedDirective + ' blocked ' + (event.blockedURI ?? ''), { source: event.sourceFile })
26
+ })
27
+
28
+ const status = document.getElementById('status')
29
+ const boot = (text) => {
30
+ if (status) status.textContent = text
31
+ }
32
+
33
+ const script = document.createElement('script')
34
+ script.type = 'module'
35
+ script.src = '/vnc/bundle.js?v=40'
36
+ script.onload = () => {
37
+ boot('就绪,点连接')
38
+ report('bundle-loaded', 'ok')
39
+ }
40
+ script.onerror = () => {
41
+ boot('脚本加载失败:bundle.js')
42
+ report('bundle-load-failed', 'script error')
43
+ }
44
+ document.body.append(script)
45
+ })()
@@ -0,0 +1,77 @@
1
+ /**
2
+ * /vnc 页面:浏览器里的 VNC 客户端(noVNC)。
3
+ *
4
+ * 页面本身很薄,真正的协议在 /vnc/static/core/rfb.js 里;
5
+ * 连接地址固定为同源的 /vnc/ws(由插件代理到本机 VNC 服务端)。
6
+ */
7
+ const escapeHtml = (value) => String(value ?? '')
8
+ .replaceAll('&', '&amp;')
9
+ .replaceAll('<', '&lt;')
10
+ .replaceAll('>', '&gt;')
11
+ .replaceAll('"', '&quot;')
12
+
13
+ const STYLE = `
14
+ :root { color-scheme: dark; }
15
+ * { box-sizing: border-box; }
16
+ html, body { height: 100%; margin: 0; }
17
+ body {
18
+ background: #0c0c0c; color: #e6e8ee; display: flex; flex-direction: column;
19
+ font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 13px;
20
+ overflow: hidden;
21
+ }
22
+ .bar {
23
+ flex: 0 0 auto; display: flex; gap: 10px; align-items: center;
24
+ padding: 6px 10px; background: #181c23; border-bottom: 1px solid #262b35;
25
+ font-size: 12px; color: #9aa3b2; white-space: nowrap; overflow-x: auto;
26
+ }
27
+ .bar a { color: #8ab4f8; text-decoration: none; }
28
+ .bar .spacer { flex: 1; }
29
+ #status { color: #7a8394; }
30
+ #status.bad { color: #ff8f8f; }
31
+ #status.ok { color: #8ff0a4; }
32
+ #screen { flex: 1 1 auto; min-height: 0; background: #000; overflow: hidden; }
33
+ #screen canvas { outline: none; }
34
+ .connect {
35
+ flex: 0 0 auto; display: flex; gap: 6px; align-items: center;
36
+ padding: 8px 10px; background: #161a20; border-top: 1px solid #262b35;
37
+ }
38
+ .connect input {
39
+ flex: 1 1 auto; min-width: 0; padding: 8px 10px; border-radius: 6px;
40
+ border: 1px solid #333a46; background: #0f1218; color: #e6e8ee; font-size: 14px;
41
+ }
42
+ .connect button {
43
+ flex: 0 0 auto; padding: 8px 14px; border-radius: 6px;
44
+ border: 1px solid #3f5f84; background: #2f4a68; color: #dce9f7; font-size: 13px;
45
+ }
46
+ .connect button:disabled { opacity: .5; }
47
+ .tip { padding: 0 10px 8px; color: #7a8394; font-size: 11px; background: #161a20; }
48
+ `
49
+
50
+ export function renderVncPage({ host = '', user = '', target = '127.0.0.1:5900', ready = true } = {}) {
51
+ return `<!doctype html>
52
+ <html lang="zh-CN"><head>
53
+ <meta charset="utf-8">
54
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
55
+ <title>桌面 · DSH</title>
56
+ <style>${STYLE}</style>
57
+ </head>
58
+ <body>
59
+ <div class="bar">
60
+ <a href="/">DSH</a>
61
+ <a href="/files">文件</a>
62
+ <a href="/term">终端</a>
63
+ <a href="/remote">窗口</a>
64
+ <span class="spacer"></span>
65
+ <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
66
+ <span id="status">${ready ? '未连接' : 'noVNC 资源缺失'}</span>
67
+ </div>
68
+ <div id="screen"></div>
69
+ <div class="connect">
70
+ <input id="password" type="password" placeholder="VNC 密码(未设密码可留空)" autocomplete="off">
71
+ <button type="button" id="connect" ${ready ? '' : 'disabled'}>连接</button>
72
+ <button type="button" id="disconnect" disabled>断开</button>
73
+ </div>
74
+ <div class="tip">目标:${escapeHtml(target)}(只在本机回环,经插件代理)</div>
75
+ <script src="/vnc/boot.js"></script>
76
+ </body></html>`
77
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * VNC 指针坐标归一化(纯函数,便于单测)。
3
+ *
4
+ * 背景:noVNC 的 _sendMouse 收到的是"元素坐标",而当画布被 CSS 缩放
5
+ * (显示宽度 != 帧缓冲宽度)时,必须先按比例换算成帧缓冲坐标,
6
+ * 否则服务端光标会落在左上角区域。
7
+ */
8
+ export function normalizePointer(x, y, canvasWidth, canvasHeight, rectWidth, rectHeight) {
9
+ const cw = Number(canvasWidth) || 0
10
+ const ch = Number(canvasHeight) || 0
11
+ const rw = Number(rectWidth) || 0
12
+ const rh = Number(rectHeight) || 0
13
+ if (cw <= 0 || ch <= 0 || rw <= 0 || rh <= 0) return { x, y }
14
+ // 尺寸一致时不动,避免无意义的浮点误差
15
+ if (Math.abs(cw - rw) <= 1 && Math.abs(ch - rh) <= 1) return { x, y }
16
+ return { x: x * (cw / rw), y: y * (ch / rh) }
17
+ }
package/lib/vnc.mjs ADDED
@@ -0,0 +1,75 @@
1
+ /**
2
+ * VNC 接入的辅助逻辑(跨平台):
3
+ * - 解析配置里的 VNC 目标(默认 127.0.0.1:5900)
4
+ * - WebSocket 握手需要的 Sec-WebSocket-Accept
5
+ * - noVNC 静态资源的路径安全与 MIME
6
+ */
7
+ import crypto from 'node:crypto'
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+ import { fileURLToPath } from 'node:url'
11
+
12
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
13
+ export const NOVNC_ROOT = path.join(HERE, 'vendor', 'novnc')
14
+ const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
15
+
16
+ /** 从 settings 的 vnc 段取目标;非法值回落到默认 */
17
+ export function vncTarget(config) {
18
+ const section = (config && typeof config.vnc === 'object' && config.vnc !== null) ? config.vnc : {}
19
+ const host = typeof section.host === 'string' && section.host.trim() !== '' ? section.host.trim() : '127.0.0.1'
20
+ const port = Number.isFinite(Number(section.port)) && Number(section.port) > 0 ? Number(section.port) : 5900
21
+ return { host, port }
22
+ }
23
+
24
+ /** WebSocket 握手应答值 */
25
+ export function acceptKey(key) {
26
+ return crypto.createHash('sha1').update(String(key) + WS_GUID, 'utf8').digest('base64')
27
+ }
28
+
29
+ const MIME = new Map([
30
+ ['.js', 'text/javascript; charset=utf-8'],
31
+ ['.mjs', 'text/javascript; charset=utf-8'],
32
+ ['.css', 'text/css; charset=utf-8'],
33
+ ['.html', 'text/html; charset=utf-8'],
34
+ ['.json', 'application/json; charset=utf-8'],
35
+ ['.png', 'image/png'],
36
+ ['.svg', 'image/svg+xml'],
37
+ ['.woff2', 'font/woff2'],
38
+ ['.txt', 'text/plain; charset=utf-8'],
39
+ ['.wasm', 'application/wasm'],
40
+ ])
41
+
42
+ export const mimeOf = (file) => MIME.get(path.extname(file).toLowerCase()) ?? 'application/octet-stream'
43
+
44
+ /**
45
+ * 把 /vnc/static/xxx 映射到 vendored 目录内的文件;越界或不存在返回 null。
46
+ */
47
+ export function resolveStatic(pathname) {
48
+ const prefix = '/vnc/static/'
49
+ if (!pathname.startsWith(prefix)) return null
50
+ let rest = ''
51
+ try {
52
+ rest = decodeURIComponent(pathname.slice(prefix.length))
53
+ } catch {
54
+ return null
55
+ }
56
+ if (rest.includes('\0') || rest.includes('..')) return null
57
+ const file = path.resolve(NOVNC_ROOT, rest)
58
+ const root = path.resolve(NOVNC_ROOT) + path.sep
59
+ if (!file.startsWith(root)) return null
60
+ try {
61
+ if (!fs.statSync(file).isFile()) return null
62
+ } catch {
63
+ return null
64
+ }
65
+ return file
66
+ }
67
+
68
+ /** noVNC 资源是否就位 */
69
+ export function novncReady() {
70
+ try {
71
+ return fs.statSync(path.join(NOVNC_ROOT, 'core', 'rfb.js')).isFile()
72
+ } catch {
73
+ return false
74
+ }
75
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * /remote 页面的浏览器脚本:拉窗口列表、轮询画面、把点击/文字/按键发给服务器。
3
+ *
4
+ * 关键点:
5
+ * - 画面用 canvas 绘制;点击坐标按"显示尺寸 → 原始窗口尺寸"换算;
6
+ * - 轮询不复用请求:上一帧没回来就不再发,避免堆积;
7
+ * - 所有输入都是 POST JSON,服务端再转给 PowerShell 代理。
8
+ */
9
+ (() => {
10
+ const $ = (id) => document.getElementById(id)
11
+ const listEl = $('list')
12
+ const shareEl = $('share')
13
+ const canvas = $('screen')
14
+ const ctx = canvas.getContext('2d')
15
+ const statusEl = $('status')
16
+ const textEl = $('text')
17
+
18
+ let current = null
19
+ let winWidth = 0
20
+ let winHeight = 0
21
+ let polling = false
22
+ let lastPoint = null
23
+
24
+ const setStatus = (text, bad = false) => {
25
+ statusEl.textContent = text
26
+ statusEl.classList.toggle('bad', bad)
27
+ }
28
+
29
+ async function api(path, options) {
30
+ const response = await fetch(path, options)
31
+ if (!response.ok) throw new Error('HTTP ' + response.status)
32
+ return response
33
+ }
34
+
35
+ async function loadWindows() {
36
+ try {
37
+ setStatus('加载窗口列表…')
38
+ const response = await api('/remote/windows')
39
+ const data = await response.json()
40
+ if (!data.ok) throw new Error(data.error || '列出窗口失败')
41
+ listEl.innerHTML = ''
42
+ if (data.windows.length === 0) {
43
+ listEl.innerHTML = '<div class="meta" style="padding:16px">没有可共享的窗口</div>'
44
+ setStatus('没有窗口')
45
+ return
46
+ }
47
+ for (const item of data.windows) {
48
+ const card = document.createElement('div')
49
+ card.className = 'win'
50
+ const title = document.createElement('div')
51
+ title.className = 'title'
52
+ title.textContent = item.title
53
+ const meta = document.createElement('div')
54
+ meta.className = 'meta'
55
+ meta.textContent = [item.process, item.width + 'x' + item.height, item.foreground ? '● 当前窗口' : ''].filter(Boolean).join(' · ')
56
+ if (item.foreground) meta.classList.add('fg')
57
+ card.append(title, meta)
58
+ card.addEventListener('click', () => startShare(item))
59
+ listEl.append(card)
60
+ }
61
+ setStatus('共 ' + data.windows.length + ' 个窗口')
62
+ } catch (error) {
63
+ setStatus('列出窗口失败:' + error.message, true)
64
+ }
65
+ }
66
+
67
+ async function fetchFrame() {
68
+ if (current === null) return
69
+ try {
70
+ const response = await api('/remote/frame?hwnd=' + encodeURIComponent(current.hwnd) + '&maxWidth=1280')
71
+ const blob = await response.blob()
72
+ winWidth = Number(response.headers.get('x-window-width')) || winWidth
73
+ winHeight = Number(response.headers.get('x-window-height')) || winHeight
74
+ const bitmap = await createImageBitmap(blob)
75
+ canvas.width = bitmap.width
76
+ canvas.height = bitmap.height
77
+ ctx.drawImage(bitmap, 0, 0)
78
+ bitmap.close?.()
79
+ setStatus((current.title || '').slice(0, 30) + ' · ' + winWidth + 'x' + winHeight)
80
+ } catch (error) {
81
+ setStatus('画面获取失败:' + error.message, true)
82
+ await new Promise((resolve) => setTimeout(resolve, 1200))
83
+ }
84
+ }
85
+
86
+ async function loop() {
87
+ polling = true
88
+ while (current !== null) {
89
+ await fetchFrame()
90
+ await new Promise((resolve) => setTimeout(resolve, 450))
91
+ }
92
+ polling = false
93
+ }
94
+
95
+ function startShare(item) {
96
+ current = item
97
+ winWidth = item.width
98
+ winHeight = item.height
99
+ listEl.style.display = 'none'
100
+ shareEl.classList.add('on')
101
+ setStatus('共享:' + item.title)
102
+ if (!polling) loop()
103
+ }
104
+
105
+ function stopShare() {
106
+ current = null
107
+ shareEl.classList.remove('on')
108
+ listEl.style.display = ''
109
+ loadWindows()
110
+ }
111
+
112
+ const post = (payload) => api('/remote/input', {
113
+ method: 'POST',
114
+ headers: { 'content-type': 'application/json' },
115
+ body: JSON.stringify({ hwnd: current.hwnd, ...payload }),
116
+ }).catch((error) => setStatus('操作失败:' + error.message, true))
117
+
118
+ canvas.addEventListener('pointerdown', (event) => {
119
+ if (current === null) return
120
+ const rect = canvas.getBoundingClientRect()
121
+ const x = Math.round(((event.clientX - rect.left) / rect.width) * winWidth)
122
+ const y = Math.round(((event.clientY - rect.top) / rect.height) * winHeight)
123
+ lastPoint = { x, y }
124
+ post({ kind: 'click', x, y, button: 'left' })
125
+ })
126
+
127
+ $('sendText').addEventListener('click', () => {
128
+ const text = textEl.value
129
+ if (text === '' || current === null) return
130
+ post({ kind: 'key', text })
131
+ textEl.value = ''
132
+ })
133
+ textEl.addEventListener('keydown', (event) => {
134
+ if (event.key === 'Enter') $('sendText').click()
135
+ })
136
+
137
+ for (const button of document.querySelectorAll('[data-key]')) {
138
+ button.addEventListener('click', () => {
139
+ if (current === null) return
140
+ post({ kind: 'key', keys: [button.getAttribute('data-key')] })
141
+ })
142
+ }
143
+
144
+ $('refresh').addEventListener('click', () => fetchFrame())
145
+ $('back').addEventListener('click', () => stopShare())
146
+ $('wheelUp').addEventListener('click', () => current !== null && post({ kind: 'wheel', delta: 120 }))
147
+ $('wheelDown').addEventListener('click', () => current !== null && post({ kind: 'wheel', delta: -120 }))
148
+ $('focus').addEventListener('click', () => current !== null && post({ kind: 'focus' }))
149
+ $('rightClick').addEventListener('click', () => {
150
+ if (current === null || lastPoint === null) return
151
+ post({ kind: 'click', x: lastPoint.x, y: lastPoint.y, button: 'right' })
152
+ })
153
+
154
+ loadWindows()
155
+ })()
@@ -0,0 +1,111 @@
1
+ /**
2
+ * /remote 页面:窗口共享(手机上看/操作 PC 上的任意窗口)。
3
+ *
4
+ * 页面只负责渲染;抓图与输入由 /remote/frame、/remote/input 完成。
5
+ */
6
+ const escapeHtml = (value) => String(value ?? '')
7
+ .replaceAll('&', '&amp;')
8
+ .replaceAll('<', '&lt;')
9
+ .replaceAll('>', '&gt;')
10
+ .replaceAll('"', '&quot;')
11
+
12
+ const STYLE = `
13
+ :root { color-scheme: dark; }
14
+ * { box-sizing: border-box; }
15
+ html, body { height: 100%; margin: 0; }
16
+ body {
17
+ background: #101318; color: #e6e8ee; display: flex; flex-direction: column;
18
+ font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; font-size: 14px;
19
+ overflow: hidden;
20
+ }
21
+ .bar {
22
+ flex: 0 0 auto; display: flex; gap: 10px; align-items: center;
23
+ padding: 8px 10px; background: #181c23; border-bottom: 1px solid #262b35;
24
+ font-size: 12px; color: #9aa3b2; white-space: nowrap; overflow-x: auto;
25
+ }
26
+ .bar a { color: #8ab4f8; text-decoration: none; }
27
+ .bar .spacer { flex: 1; }
28
+ #status { color: #7a8394; font-size: 12px; }
29
+ #status.bad { color: #ff8f8f; }
30
+ .list { flex: 1 1 auto; overflow-y: auto; padding: 10px; }
31
+ .win {
32
+ display: flex; flex-direction: column; gap: 4px;
33
+ padding: 12px 14px; margin-bottom: 8px; border-radius: 10px;
34
+ background: #1b2029; border: 1px solid #2a313d; cursor: pointer;
35
+ }
36
+ .win:active { background: #232a35; }
37
+ .win .title { font-size: 14px; line-height: 1.4; word-break: break-all; }
38
+ .win .meta { font-size: 11px; color: #7a8394; display: flex; gap: 8px; flex-wrap: wrap; }
39
+ .win .fg { color: #8ff0a4; }
40
+ .share { flex: 1 1 auto; display: none; flex-direction: column; min-height: 0; }
41
+ .share.on { display: flex; }
42
+ #wrap { flex: 1 1 auto; overflow: auto; padding: 6px; display: flex; align-items: flex-start; justify-content: center; }
43
+ #screen { max-width: 100%; height: auto; background: #000; border-radius: 6px; touch-action: manipulation; }
44
+ .keys {
45
+ flex: 0 0 auto; display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px;
46
+ padding: 6px 8px calc(6px + env(safe-area-inset-bottom));
47
+ background: #161a20; border-top: 1px solid #262b35;
48
+ }
49
+ .keys button, .keys .send {
50
+ width: 100%; min-width: 0; padding: 9px 4px; border-radius: 6px;
51
+ border: 1px solid #333a46; background: #232a35; color: #cfd5df; font: inherit; font-size: 12px;
52
+ }
53
+ .keys button.warn { border-color: #5a2a2a; color: #f0b6bf; }
54
+ .textrow {
55
+ flex: 0 0 auto; display: flex; gap: 6px; padding: 6px 8px;
56
+ background: #161a20; border-top: 1px solid #262b35;
57
+ }
58
+ .textrow input {
59
+ flex: 1 1 auto; min-width: 0; padding: 8px 10px; border-radius: 6px;
60
+ border: 1px solid #333a46; background: #0f1218; color: #e6e8ee; font-size: 14px;
61
+ }
62
+ .textrow button {
63
+ flex: 0 0 auto; padding: 8px 14px; border-radius: 6px;
64
+ border: 1px solid #333a46; background: #2f4a68; color: #dce9f7; font-size: 13px;
65
+ }
66
+ `
67
+
68
+ export function renderWindowPage({ host = '', user = '', supported = true, agent = false } = {}) {
69
+ return `<!doctype html>
70
+ <html lang="zh-CN"><head>
71
+ <meta charset="utf-8">
72
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
73
+ <title>窗口共享 · DSH</title>
74
+ <style>${STYLE}</style>
75
+ </head>
76
+ <body>
77
+ <div class="bar">
78
+ <a href="/">DSH</a>
79
+ <a href="/files">文件</a>
80
+ <a href="/term">终端</a>
81
+ <a href="/vnc">桌面</a>
82
+ <span class="spacer"></span>
83
+ <span>${escapeHtml(user)}@${escapeHtml(host)}</span>
84
+ <span id="status">${supported ? (agent ? '代理已启动' : '代理未启动') : '仅支持 Windows'}</span>
85
+ </div>
86
+
87
+ <div class="list" id="list"><div class="meta" style="padding:16px">加载窗口列表…</div></div>
88
+
89
+ <div class="share" id="share">
90
+ <div id="wrap"><canvas id="screen"></canvas></div>
91
+ <div class="textrow">
92
+ <input id="text" placeholder="输入文字(可中文),点发送" autocomplete="off">
93
+ <button type="button" id="sendText">发送</button>
94
+ </div>
95
+ <div class="keys">
96
+ <button type="button" id="back">← 列表</button>
97
+ <button type="button" id="refresh">刷新画面</button>
98
+ <button type="button" data-key="enter">回车</button>
99
+ <button type="button" data-key="backspace">退格</button>
100
+ <button type="button" data-key="esc">Esc</button>
101
+ <button type="button" data-key="tab">Tab</button>
102
+ <button type="button" id="rightClick">右键</button>
103
+ <button type="button" id="wheelUp">滚轮↑</button>
104
+ <button type="button" id="wheelDown">滚轮↓</button>
105
+ <button type="button" id="focus">激活窗口</button>
106
+ </div>
107
+ </div>
108
+
109
+ <script src="/remote/app.js"></script>
110
+ </body></html>`
111
+ }