@andy.ian/dsh-homing 2.1.15 → 2.3.0

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 (51) hide show
  1. package/README.md +151 -110
  2. package/SECURITY.md +3 -0
  3. package/bin/restart-daemon.mjs +0 -0
  4. package/bin/restart.mjs +0 -0
  5. package/index.js +904 -601
  6. package/lib/app-proxy.mjs +262 -0
  7. package/lib/auth-guard.js +57 -0
  8. package/lib/client-report.js +168 -0
  9. package/lib/compress.mjs +3 -2
  10. package/lib/csrf.mjs +38 -0
  11. package/lib/debug-page.js +150 -0
  12. package/lib/exec-path.mjs +9 -1
  13. package/lib/files-page.mjs +3 -3
  14. package/lib/files.mjs +14 -15
  15. package/lib/format-age.mjs +32 -0
  16. package/lib/git.mjs +37 -19
  17. package/lib/idb-fallback.js +140 -0
  18. package/lib/local-apps-page.mjs +64 -0
  19. package/lib/local-apps.mjs +275 -0
  20. package/lib/markdown.mjs +6 -4
  21. package/lib/mobile-patch.mjs +429 -0
  22. package/lib/nav.mjs +1 -0
  23. package/lib/netdiag.js +211 -0
  24. package/lib/node-runtime.mjs +30 -13
  25. package/lib/office.mjs +42 -20
  26. package/lib/orientation.mjs +88 -53
  27. package/lib/pty.mjs +2 -9
  28. package/lib/recover.js +66 -0
  29. package/lib/secret.mjs +25 -9
  30. package/lib/shells.mjs +2 -2
  31. package/lib/vendor/vnc.bundle.js +189 -73
  32. package/lib/vnc-app.js +112 -23
  33. package/lib/vnc-auth-proxy.mjs +5 -2
  34. package/lib/vnc-boot.js +1 -1
  35. package/lib/vnc-keyboard.mjs +3 -3
  36. package/lib/vnc-page.mjs +34 -4
  37. package/lib/vnc-probe.mjs +46 -0
  38. package/lib/window-follow.mjs +66 -0
  39. package/lib/window-remote.mjs +266 -192
  40. package/lib/ws-bridge.mjs +6 -3
  41. package/package.json +2 -2
  42. package/permissions.json +7 -0
  43. package/restart/client.mjs +20 -1
  44. package/restart/daemon/README.md +22 -0
  45. package/restart/daemon/lib/detach.mjs +11 -5
  46. package/restart/daemon/lib/restart-flow.mjs +26 -12
  47. package/restart/daemon/lib/update-state.mjs +118 -1
  48. package/restart/daemon/main.mjs +68 -20
  49. package/restart/runner.mjs +9 -5
  50. package/restart/service.mjs +4 -3
  51. package/restart/watchdog.mjs +8 -2
@@ -0,0 +1,429 @@
1
+ /**
2
+ * 手机端补丁:index.js 把它注入到 DSH 页面(/dsh_homing/mobile.js、mobile.css)。
3
+ *
4
+ * 只做「手机上明显做不到、或做了也白做」的事:
5
+ * - 页头「文件夹 + 小箭头」分体按钮 = 在 DSH 那台电脑上打开工作区目录。
6
+ * 你人不在那台电脑前,手机上点它只会收到「已在其它设备打开」,什么也看不到;
7
+ * 这里统一接到本插件的文件页 /files。
8
+ * - 应用菜单里只能在电脑上启动的项(资源管理器 / VS Code / Git Bash / 终端)
9
+ * 同样接到对应网页(文件页 / 终端页)。
10
+ * - 窄屏自动收起右侧栏、记住最后点过的工作区、上报活跃信标。
11
+ *
12
+ * 定位按钮不靠易变的 class 名:优先用 DSH 的稳定标记 data-open-target,
13
+ * 老版本没有标记时退回结构判断。细节见下面 splitHost 的注释。
14
+ */
15
+
16
+ export const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
17
+ @media (max-width: 760px) {
18
+ [class*="_frame"] { min-width: 0; }
19
+ }
20
+ `;
21
+
22
+ /**
23
+ * 计算把浮层拉回视口所需的位移(像素,四舍五入)。
24
+ *
25
+ * 手机上的浮层(额度面板、菜单、对话框)常以「相对按钮定位」的方式出现,
26
+ * 在窄屏上会有一部分跑到屏幕左侧或右侧外面,内容被裁掉。这里只算位移,
27
+ * 由调用方用 CSS `translate`(独立于 transform,不会破坏原有动画)施加。
28
+ *
29
+ * @param {{left:number, top:number, right:number, bottom:number, width:number, height:number}} rect
30
+ * @param {{width:number, height:number}} viewport
31
+ * @param {number} [margin] 距视口边缘留白
32
+ * @returns {{dx:number, dy:number}}
33
+ */
34
+ export function clampPopoverOffset(rect, viewport, margin = 8) {
35
+ const offset = { dx: 0, dy: 0 };
36
+ if (!rect || !viewport) return offset;
37
+ const width = Number(viewport.width) || 0;
38
+ const height = Number(viewport.height) || 0;
39
+ if (width <= 0 || height <= 0) return offset;
40
+ const left = Number(rect.left) || 0;
41
+ const top = Number(rect.top) || 0;
42
+ const boxWidth = Number(rect.width) || 0;
43
+ const boxHeight = Number(rect.height) || 0;
44
+ if (boxWidth <= 0 || boxHeight <= 0) return offset;
45
+
46
+ // 水平:比视口还宽时贴左边缘(否则怎么移都会裁),否则把越界的一侧推回来
47
+ if (boxWidth > width - margin * 2) offset.dx = margin - left;
48
+ else if (left < margin) offset.dx = margin - left;
49
+ else if (left + boxWidth > width - margin) offset.dx = width - margin - (left + boxWidth);
50
+
51
+ // 垂直:同理
52
+ if (boxHeight > height - margin * 2) offset.dy = margin - top;
53
+ else if (top < margin) offset.dy = margin - top;
54
+ else if (top + boxHeight > height - margin) offset.dy = height - margin - (top + boxHeight);
55
+
56
+ return { dx: Math.round(offset.dx), dy: Math.round(offset.dy) };
57
+ }
58
+
59
+
60
+ export const MOBILE_JS = String.raw`(() => {
61
+ const clampPopoverOffset = ${clampPopoverOffset.toString()}
62
+ const narrow = () => window.innerWidth <= 760
63
+ // 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
64
+ // 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
65
+ const LAST_WS_KEY = 'dsh-homing:last-workspace'
66
+ document.addEventListener('click', (event) => {
67
+ const node = event.target
68
+ if (node === null || typeof node.closest !== 'function') return
69
+ const item = node.closest('[role="menuitem"]')
70
+ const side = node.closest('[class*="sidebarCol"]')
71
+ const candidate = item ?? (side === null ? null : node.closest('button, [role="treeitem"], [class*="session"], [class*="item"], div'))
72
+ if (candidate === null) return
73
+ const text = (candidate.textContent || '').replace(/\s+/g, ' ').trim()
74
+ if (text === '' || text.length > 40) return
75
+ // 排除操作类菜单项,只记看起来像工作区名字的
76
+ if (/文件资源管理器|VS Code|Git Bash|添加工作区|新会话|搜索|设置|插件|自动化任务|更多|账号|退出/u.test(text)) return
77
+ try { window.localStorage.setItem(LAST_WS_KEY, text) } catch { /* 隐私模式 */ }
78
+ }, true)
79
+
80
+ // 当前会话标题:从标题栏(页面顶部、class 里带 title/tab/header 的元素)取最长的文本。
81
+ // 用它去反查会话记录里的 cwd,就能打开"当前会话所属工作区"的目录。
82
+ const currentSessionTitle = () => {
83
+ let best = ''
84
+ for (const node of document.querySelectorAll('div, span, h1, h2, header')) {
85
+ const rect = node.getBoundingClientRect()
86
+ if (rect.width === 0 || rect.height === 0) continue
87
+ if (rect.top > 120 || rect.height > 44) continue
88
+ const cls = String(node.className || '')
89
+ if (!/title|tab|header|crumb|label/iu.test(cls)) continue
90
+ const text = (node.textContent || '').trim()
91
+ if (text.length < 2 || text.length > 60) continue
92
+ if (text.length > best.length) best = text
93
+ }
94
+ return best
95
+ }
96
+
97
+ // 应用把"当前会话"存在 localStorage 里,直接读它 —— 这是确定值,不靠猜。
98
+ const currentSessionId = () => {
99
+ try {
100
+ const raw = window.localStorage.getItem('dsh.sessions.current')
101
+ if (raw === null) return ''
102
+ const parsed = JSON.parse(raw)
103
+ const id = parsed && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
104
+ return /^session-[A-Za-z0-9-]+$/u.test(id) ? id : ''
105
+ } catch {
106
+ return ''
107
+ }
108
+ }
109
+
110
+ const goFiles = () => {
111
+ const session = currentSessionId()
112
+ if (session !== '') {
113
+ window.location.href = '/files?session=' + encodeURIComponent(session)
114
+ return
115
+ }
116
+ let hint = ''
117
+ try { hint = currentSessionTitle() || window.localStorage.getItem(LAST_WS_KEY) || '' } catch { hint = '' }
118
+ window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
119
+ }
120
+
121
+ /* ---------- 页头「文件夹 + 小箭头」分体按钮 ----------
122
+ * 它做的事是在 DSH 所在的电脑上启动程序(资源管理器 / VS Code / Git Bash)。
123
+ * 手机上没有那台电脑的屏幕,点了只会收到「已在其它设备打开」——纯噪音。
124
+ * 这里把它(主按钮和小箭头都算)接到文件页 /files。
125
+ *
126
+ * 定位必须稳:页头里还有子智能体面板、更多菜单等 aria-haspopup 控件,而且
127
+ * 它们排在分体按钮前面。「找第一个 aria-haspopup 的父容器」会认成子智能体
128
+ * 那个容器,于是点分体按钮时判定不命中、补丁失效(手机端历史 bug)。
129
+ * 所以:
130
+ * 1. 优先用 DSH 的稳定标记 data-open-target="directory"(分体按钮容器);
131
+ * 2. 老版本没有标记时退回结构判断 —— 同一容器里恰好两个按钮,一个带
132
+ * aria-haspopup="menu"(小箭头),另一个是纯图标主按钮(里面是应用图标)。
133
+ */
134
+ const splitHost = (node) => {
135
+ if (node === null || node === undefined || typeof node.closest !== 'function') return null
136
+ const marked = node.closest('[data-open-target="directory"]')
137
+ if (marked !== null) return marked
138
+ const button = node.closest('button, [role="button"]')
139
+ if (button === null) return null
140
+ const host = button.parentElement
141
+ if (host === null) return null
142
+ const buttons = host.querySelectorAll('button, [role="button"]')
143
+ if (buttons.length !== 2) return null
144
+ let main = null
145
+ let chevron = null
146
+ for (const item of buttons) {
147
+ if (item.hasAttribute('aria-haspopup')) chevron = item
148
+ else main = item
149
+ }
150
+ if (main === null || chevron === null) return null
151
+ if (chevron.getAttribute('aria-haspopup') !== 'menu') return null
152
+ if ((main.textContent || '').trim() !== '') return null
153
+ if (main.querySelector('img, svg') === null) return null
154
+ const rect = chevron.getBoundingClientRect()
155
+ if (rect.width === 0 || rect.height === 0) return null
156
+ if (rect.top > 200) return null
157
+ return host
158
+ }
159
+
160
+ document.addEventListener('click', (event) => {
161
+ const node = event.target
162
+ if (node === null || typeof node.closest !== 'function') return
163
+ const host = splitHost(node)
164
+ if (host === null) return
165
+ event.preventDefault()
166
+ event.stopPropagation()
167
+ goFiles()
168
+ }, true)
169
+
170
+ /* ---------- 只能在本机启动的菜单项 ----------
171
+ * 应用下拉里的「文件资源管理器 / VS Code / Git Bash / 终端」全是在 DSH 那台
172
+ * 电脑上启动桌面程序。这里接到对应网页:文件类 → /files,终端类 → /term。
173
+ * 只在 role=menuitem / role=option 上生效,避免误伤正文里的同名文字。
174
+ */
175
+ const openFilesFromMenu = (item) => {
176
+ // 尽量从属性里挖工作区路径,挖不到就让文件页自己决定默认目录
177
+ let target = ''
178
+ for (const holder of [item, ...(item.querySelectorAll('[data-path], [title]') || [])]) {
179
+ if (holder === null) continue
180
+ const dataPath = holder.getAttribute && holder.getAttribute('data-path')
181
+ const title = holder.getAttribute && holder.getAttribute('title')
182
+ if (dataPath) { target = dataPath; break }
183
+ if (title && /^[A-Za-z]:[\\/]|^\//u.test(title)) { target = title; break }
184
+ }
185
+ // 带上最后选中的工作区名,服务端会映射成路径;映射不到就落到默认工作区
186
+ let remembered = ''
187
+ try { remembered = window.localStorage.getItem(LAST_WS_KEY) || '' } catch { /* 隐私模式 */ }
188
+ const selected = remembered !== '' ? remembered : (() => {
189
+ const side = document.querySelector('[class*="sidebarCol"]')
190
+ if (side === null) return ''
191
+ let best = ''
192
+ for (const node of side.querySelectorAll('[class*="selected"], [class*="active"], [aria-current]')) {
193
+ const text = (node.textContent || '').trim()
194
+ if (text === '' || text.length > 40) continue
195
+ if (best === '' || text.length < best.length) best = text
196
+ }
197
+ return best
198
+ })()
199
+ const session = currentSessionId()
200
+ const query = target ? '?path=' + encodeURIComponent(target)
201
+ : session !== '' ? '?session=' + encodeURIComponent(session)
202
+ : '?hint=' + encodeURIComponent(currentSessionTitle() || selected || '')
203
+ window.location.href = '/files' + query
204
+ }
205
+
206
+ const openTermFromMenu = () => {
207
+ const session = currentSessionId()
208
+ window.location.href = '/term' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
209
+ }
210
+
211
+ document.addEventListener('click', (event) => {
212
+ const node = event.target
213
+ if (node === null || typeof node.closest !== 'function') return
214
+ const item = node.closest('[role="menuitem"], [role="option"]')
215
+ if (item === null) return
216
+ const text = (item.textContent || '').replace(/\s+/g, ' ').trim()
217
+ if (text === '' || text.length > 60) return
218
+ if (/文件资源管理器|文件管理器|访达|显示文件位置|在文件夹显示|在访达显示|VS Code|Visual Studio Code/u.test(text)) {
219
+ event.preventDefault()
220
+ event.stopPropagation()
221
+ openFilesFromMenu(item)
222
+ return
223
+ }
224
+ if (/Git Bash|终端|Terminal|PowerShell|命令提示符/u.test(text)) {
225
+ event.preventDefault()
226
+ event.stopPropagation()
227
+ openTermFromMenu()
228
+ }
229
+ }, true)
230
+
231
+ let lastRight = 0
232
+ const closeRightBar = () => {
233
+ if (!narrow()) return
234
+ if (document.querySelector('[data-rightbar-collapsed="false"]') === null) return
235
+ if (Date.now() - lastRight < 2500) return
236
+ const button = document.querySelector('[aria-label="收起右侧边栏"]')
237
+ if (button === null) return
238
+ lastRight = Date.now()
239
+ button.click()
240
+ }
241
+
242
+ const start = () => {
243
+ closeRightBar()
244
+ }
245
+
246
+ /* ---------- SESSION_MENU_ITEMS ----------
247
+ * 在 DSH 会话「…」菜单里追加两项:
248
+ * - 下载工作区文件:跳到文件页(可逐个文件下载)
249
+ * - 重启 DSH / 守护进程:跳到重启页
250
+ * 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
251
+ * 每轮先清掉旧项,并全局 prune,保证每项最多一个。
252
+ */
253
+ const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
254
+ 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"/>'
255
+ 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"/>'
256
+ let menuTimer = null
257
+
258
+ const textNodeMatching = (node, pattern) => {
259
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
260
+ for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
261
+ if (pattern.test(current.nodeValue || '')) return current
262
+ }
263
+ return null
264
+ }
265
+
266
+ const buildMenuItem = (template, label, icon, action) => {
267
+ const link = template.cloneNode(true)
268
+ link.setAttribute('role', 'menuitem')
269
+ link.setAttribute('href', '#')
270
+ link.style.textDecoration = 'none'
271
+ const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
272
+ if (textNode !== null) textNode.nodeValue = label
273
+ else link.textContent = label
274
+ const svg = link.querySelector('svg')
275
+ if (svg !== null) {
276
+ svg.innerHTML = icon
277
+ svg.setAttribute('viewBox', '0 0 24 24')
278
+ svg.setAttribute('fill', 'none')
279
+ svg.setAttribute('stroke', 'currentColor')
280
+ svg.setAttribute('stroke-width', '2')
281
+ svg.setAttribute('stroke-linecap', 'round')
282
+ svg.setAttribute('stroke-linejoin', 'round')
283
+ }
284
+ link.addEventListener('click', (event) => {
285
+ event.preventDefault()
286
+ event.stopPropagation()
287
+ action()
288
+ }, true)
289
+ return link
290
+ }
291
+
292
+ const enhanceMenus = () => {
293
+ const done = new Set()
294
+ for (const item of document.querySelectorAll('[role="menuitem"]')) {
295
+ const menu = item.closest('[role="menu"]') ?? item.parentElement
296
+ if (menu === null || done.has(menu)) continue
297
+ if (!MENU_HINT.test(menu.textContent || '')) continue
298
+ done.add(menu)
299
+
300
+ for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
301
+
302
+ const items = [...menu.querySelectorAll('[role="menuitem"]')]
303
+ const template = items.find((node) => node.querySelector('svg')) ?? items[0]
304
+ if (!template) continue
305
+
306
+ const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
307
+ download.setAttribute('data-dsh-homing-download', '1')
308
+ const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
309
+ restart.setAttribute('data-dsh-homing-restart', '1')
310
+
311
+ menu.appendChild(download)
312
+ menu.appendChild(restart)
313
+ }
314
+ }
315
+
316
+ // 兜底:无论菜单容器怎么嵌套,每类最多保留一个
317
+ const pruneMenuItems = () => {
318
+ for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
319
+ const all = [...document.querySelectorAll(selector)]
320
+ for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
321
+ }
322
+ }
323
+
324
+ const menuObserver = new MutationObserver(() => {
325
+ if (menuTimer) return
326
+ menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems(); scheduleClamp() }, 80)
327
+ })
328
+ menuObserver.observe(document.body, { childList: true, subtree: true })
329
+
330
+ /* ---------- 浮层不越出屏幕 ----------
331
+ * 额度面板、菜单、对话框大多按「相对触发按钮」定位,窄屏上会有一部分落到
332
+ * 屏幕左侧/右侧外面,文字被裁掉(手机上实测:额度面板左边整块看不见)。
333
+ * 这里在浮层出现后把它平移回视口内:
334
+ * - 只处理 position: fixed/absolute 且 z-index >= 100 的可见元素;
335
+ * - 用 CSS translate 属性(不是 transform),不与原动画/居中冲突;
336
+ * - 每次重新计算前先复位,避免位移叠加。
337
+ */
338
+ const floatingStyleOf = (node) => {
339
+ try {
340
+ if (typeof window.getComputedStyle === 'function') return window.getComputedStyle(node)
341
+ if (typeof getComputedStyle === 'function') return getComputedStyle(node)
342
+ } catch (error) {
343
+ /* 忽略 */
344
+ }
345
+ return null
346
+ }
347
+
348
+ const clampPopovers = () => {
349
+ try {
350
+ const viewport = {
351
+ width: Number(window.innerWidth) || Number(document.documentElement && document.documentElement.clientWidth) || 0,
352
+ height: Number(window.innerHeight) || Number(document.documentElement && document.documentElement.clientHeight) || 0,
353
+ }
354
+ if (viewport.width <= 0 || viewport.height <= 0) return 0
355
+ const selector = 'body > div, body > div > div, [role="dialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]'
356
+ const nodes = document.querySelectorAll ? document.querySelectorAll(selector) : []
357
+ let moved = 0
358
+ for (const node of nodes) {
359
+ if (node === null || typeof node.getBoundingClientRect !== 'function') continue
360
+ const computed = floatingStyleOf(node)
361
+ const position = String((computed && computed.position) || '')
362
+ if (position !== 'fixed' && position !== 'absolute') continue
363
+ const zIndex = Number.parseInt(String((computed && computed.zIndex) || '0'), 10)
364
+ if (!Number.isFinite(zIndex) || zIndex < 100) continue
365
+ if (computed && (computed.visibility === 'hidden' || computed.display === 'none')) continue
366
+ if (computed && Number(computed.opacity) === 0) continue
367
+ const style = node.style
368
+ if (style === null || style === undefined) continue
369
+ // 复位上一次的位移,再按当前(未平移)位置计算
370
+ if ('translate' in style) style.translate = ''
371
+ const rect = node.getBoundingClientRect()
372
+ if (rect === null || Number(rect.width) <= 0 || Number(rect.height) <= 0) continue
373
+ const offset = clampPopoverOffset(rect, viewport)
374
+ if (offset.dx === 0 && offset.dy === 0) continue
375
+ if ('translate' in style) {
376
+ style.translate = offset.dx + 'px ' + offset.dy + 'px'
377
+ moved += 1
378
+ }
379
+ }
380
+ return moved
381
+ } catch (error) {
382
+ return 0
383
+ }
384
+ }
385
+
386
+ let clampTimer = null
387
+ const scheduleClamp = () => {
388
+ if (clampTimer !== null) return
389
+ const run = () => { clampTimer = null; clampPopovers() }
390
+ if (typeof setTimeout === 'function') clampTimer = setTimeout(run, 120)
391
+ else run()
392
+ }
393
+ document.addEventListener('pointerup', scheduleClamp, true)
394
+ document.addEventListener('click', scheduleClamp, true)
395
+ window.addEventListener('resize', scheduleClamp)
396
+ // 调试/测试入口:也可手动触发一次
397
+ if (window.__dshHomingClampPopovers === undefined) window.__dshHomingClampPopovers = clampPopovers
398
+
399
+ /* ---------- ALIVE_BEACON ----------
400
+ * 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
401
+ * 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
402
+ * 节流 2 秒,页面隐藏时不发(后台标签页不算活跃)。
403
+ */
404
+ const ALIVE_INTERVAL = 2000
405
+ let aliveAt = 0
406
+ const alive = () => {
407
+ const now = Date.now()
408
+ if (now - aliveAt < ALIVE_INTERVAL) return
409
+ aliveAt = now
410
+ try {
411
+ if (document.visibilityState === 'hidden') return
412
+ const body = JSON.stringify({ at: now, path: location.pathname })
413
+ if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
414
+ else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
415
+ } catch (error) {
416
+ /* 忽略 */
417
+ }
418
+ }
419
+ document.addEventListener('keydown', alive, true)
420
+ document.addEventListener('pointerdown', alive, true)
421
+ document.addEventListener('input', alive, true)
422
+ document.addEventListener('compositionstart', alive, true)
423
+ window.addEventListener('focus', alive, true)
424
+
425
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
426
+ else start()
427
+ })();
428
+
429
+ `;
package/lib/nav.mjs CHANGED
@@ -24,6 +24,7 @@ const LINKS = [
24
24
  ['/term', '终端', ''],
25
25
  ['/remote', '窗口', ''],
26
26
  ['/vnc', '桌面', ''],
27
+ ['/dsh_homing/apps', '应用', ''],
27
28
  ['/debug', '调试', ''],
28
29
  ['/dsh_homing/account', '账户', ''],
29
30
  ]
package/lib/netdiag.js ADDED
@@ -0,0 +1,211 @@
1
+ /**
2
+ * 网络自检脚本(v5,2026-11-15)
3
+ *
4
+ * 可以在两个地方用:
5
+ * 1. /debug 调试页:有 #netdiag-run 按钮,点一下才跑,输出到 #netdiag-out
6
+ * 2. /dsh_homing/netdiag 独立页:没有按钮,加载即自动跑,输出到 #out
7
+ *
8
+ * 设计要点:
9
+ * - 每步都有硬超时(华为浏览器里 caches.keys()/getRegistrations() 可能永不返回)
10
+ * - 每完成一步就追加一行,页面实时可见
11
+ * - **先把结果回传服务端**再显示结论:页面截不全也能从审计里拿到完整证据
12
+ * - 测真正的 RPC 通道 /api/remote.mux(不是根路径),并附带根路径作参考
13
+ * - 用于匹配资源引用的 HTML 片段要足够长(v4 只取 400 字符,导致误报"找不到入口脚本")
14
+ */
15
+ (() => {
16
+ const debugButton = document.getElementById('netdiag-run')
17
+ const out = document.getElementById('netdiag-out') ?? document.getElementById('out')
18
+ const copyButton = document.getElementById('netdiag-copy') ?? document.getElementById('copy')
19
+ const autoRun = !debugButton
20
+
21
+ const lines = []
22
+ const started = Date.now()
23
+
24
+ function render() {
25
+ if (out) out.textContent = lines.join('\n')
26
+ }
27
+ function line(text) {
28
+ lines.push(text)
29
+ render()
30
+ }
31
+
32
+ function withTimeout(promise, ms, label) {
33
+ return Promise.race([
34
+ promise.catch((error) => ({ error: String(error && error.message ? error.message : error) })),
35
+ new Promise((resolve) => setTimeout(() => resolve({ error: label + ' 超时(' + ms + 'ms)' }), ms)),
36
+ ])
37
+ }
38
+
39
+ async function httpProbe(url, { timeoutMs = 8000, method = 'GET', body = null, headers = {} } = {}) {
40
+ const begin = Date.now()
41
+ const controller = new AbortController()
42
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
43
+ try {
44
+ const response = await fetch(url, {
45
+ method, body, cache: 'no-store', credentials: 'same-origin',
46
+ signal: controller.signal, headers: { accept: '*/*', ...headers },
47
+ })
48
+ const text = await response.text()
49
+ return {
50
+ status: response.status, bytes: text.length, ms: Date.now() - begin,
51
+ cacheControl: response.headers.get('cache-control') ?? '',
52
+ head: text.slice(0, 400),
53
+ // 用于在完整 HTML 里匹配资源引用(head 只有 400 字符,不能拿来匹配)
54
+ rawLength: text.length,
55
+ assetScript: /\/assets\/index-[A-Za-z0-9_-]+\.js/u.exec(text)?.[0] ?? '',
56
+ }
57
+ } catch (error) {
58
+ const aborted = error && (error.name === 'AbortError' || error.name === 'TimeoutError')
59
+ return { status: aborted ? 'TIMEOUT' : 'ERR', ms: Date.now() - begin, error: String(error && error.message ? error.message : error) }
60
+ } finally {
61
+ clearTimeout(timer)
62
+ }
63
+ }
64
+
65
+ function wsProbe(pathName, timeoutMs = 6000) {
66
+ return new Promise((resolve) => {
67
+ let socket = null
68
+ let settled = false
69
+ const done = (value) => {
70
+ if (settled) return
71
+ settled = true
72
+ try { socket && socket.close() } catch (error) { /* 忽略 */ }
73
+ resolve(value)
74
+ }
75
+ const timer = setTimeout(() => done({ ok: false, detail: '超时(' + timeoutMs + 'ms)' }), timeoutMs)
76
+ try {
77
+ const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:'
78
+ socket = new WebSocket(`${scheme}//${location.host}${pathName}`)
79
+ socket.onopen = () => { clearTimeout(timer); done({ ok: true, detail: '101 已建立' }) }
80
+ socket.onerror = () => { clearTimeout(timer); done({ ok: false, detail: 'error 事件(握手被拒或连接被断)' }) }
81
+ socket.onclose = (event) => { clearTimeout(timer); done({ ok: false, detail: '被关闭 code=' + event.code + (event.reason ? ' ' + event.reason : '') }) }
82
+ } catch (error) {
83
+ clearTimeout(timer)
84
+ done({ ok: false, detail: '抛出:' + String(error && error.message ? error.message : error) })
85
+ }
86
+ })
87
+ }
88
+
89
+ async function cacheProbe() {
90
+ const result = { caches: null, serviceWorkers: null }
91
+ try {
92
+ if (typeof caches !== 'undefined' && caches.keys) {
93
+ const names = await withTimeout(caches.keys(), 3000, 'caches.keys')
94
+ result.caches = Array.isArray(names) ? names : null
95
+ } else {
96
+ result.caches = 'unsupported'
97
+ }
98
+ } catch (error) { result.caches = 'error' }
99
+ try {
100
+ if (navigator.serviceWorker && navigator.serviceWorker.getRegistrations) {
101
+ const list = await withTimeout(navigator.serviceWorker.getRegistrations(), 3000, 'getRegistrations')
102
+ result.serviceWorkers = Array.isArray(list) ? list.length : null
103
+ } else {
104
+ result.serviceWorkers = 'unsupported'
105
+ }
106
+ } catch (error) { result.serviceWorkers = 'error' }
107
+ return result
108
+ }
109
+
110
+ async function run() {
111
+ lines.length = 0
112
+ line('开始检测 ' + new Date().toLocaleTimeString())
113
+ line('地址: ' + location.href)
114
+ line('UA: ' + navigator.userAgent)
115
+ line('')
116
+
117
+ line('① 首页 HTML')
118
+ const home = await httpProbe('/')
119
+ line(home.error
120
+ ? ' ✗ ' + home.error
121
+ : ' HTTP ' + home.status + ' · ' + home.bytes + 'B · ' + home.ms + 'ms · ' + (home.cacheControl || '无 cache-control'))
122
+
123
+ line('② 鉴权状态')
124
+ const authState = await httpProbe('/dsh_homing/auth-state', { headers: { accept: 'application/json' } })
125
+ line(authState.error ? ' ✗ ' + authState.error : ' HTTP ' + authState.status + ' · ' + authState.head.slice(0, 160))
126
+
127
+ line('③ 入口脚本')
128
+ let assetPath = home.assetScript ?? ''
129
+ let asset = { status: '(跳过)' }
130
+ if (home.error) {
131
+ line(' ✗ 取首页失败:' + home.error)
132
+ } else if (assetPath === '') {
133
+ line(' ✗ 首页里找不到 /assets/index-*.js(HTML ' + home.bytes + 'B)')
134
+ } else {
135
+ asset = await httpProbe(assetPath)
136
+ line(' ' + assetPath)
137
+ line(asset.error ? ' ✗ ' + asset.error : ' HTTP ' + asset.status + ' · ' + asset.bytes + 'B · ' + asset.ms + 'ms')
138
+ }
139
+
140
+ line('④ RPC 通道 /api/remote.mux(应用真正用的)')
141
+ const mux = await wsProbe('/api/remote.mux')
142
+ line(' ' + (mux.ok ? '✓ ' + mux.detail : '✗ ' + mux.detail))
143
+
144
+ line('⑤ 根路径 WebSocket(仅参考,应用不用它)')
145
+ const rootWs = await wsProbe('/')
146
+ line(' ' + (rootWs.ok ? '✓ ' + rootWs.detail : '✗ ' + rootWs.detail))
147
+
148
+ line('⑥ 缓存 / Service Worker')
149
+ const cache = await cacheProbe()
150
+ line(' Cache Storage: ' + (Array.isArray(cache.caches) ? (cache.caches.length ? cache.caches.join(', ') : '空') : String(cache.caches)))
151
+ line(' Service Worker: ' + (typeof cache.serviceWorkers === 'number' ? cache.serviceWorkers + ' 个' : String(cache.serviceWorkers)))
152
+
153
+ const payload = {
154
+ at: new Date().toISOString(),
155
+ href: location.href,
156
+ ua: navigator.userAgent,
157
+ elapsedMs: Date.now() - started,
158
+ home, authState, asset, mux, rootWs, cache,
159
+ viewport: { width: innerWidth, height: innerHeight, dpr: devicePixelRatio },
160
+ }
161
+
162
+ const sent = await httpProbe('/dsh_homing/netdiag/report', {
163
+ method: 'POST',
164
+ body: JSON.stringify(payload),
165
+ headers: { 'content-type': 'application/json' },
166
+ timeoutMs: 10000,
167
+ })
168
+ line('')
169
+ line(sent.error ? '✗ 回传失败:' + sent.error : '✓ 结果已回传(HTTP ' + sent.status + ',电脑端查审计)')
170
+ line('耗时 ' + (Date.now() - started) + 'ms')
171
+ }
172
+
173
+ if (copyButton) {
174
+ copyButton.addEventListener('click', () => {
175
+ const text = lines.join('\n')
176
+ if (navigator.clipboard && navigator.clipboard.writeText) {
177
+ navigator.clipboard.writeText(text).then(
178
+ () => { copyButton.textContent = '已复制' },
179
+ () => { copyButton.textContent = '复制失败' },
180
+ )
181
+ } else {
182
+ // 没有 clipboard API 时退化为选中文本,用户长按复制
183
+ copyButton.textContent = '请长按选中文本复制'
184
+ if (out && window.getSelection) {
185
+ const range = document.createRange()
186
+ range.selectNodeContents(out)
187
+ const selection = window.getSelection()
188
+ selection.removeAllRanges()
189
+ selection.addRange(range)
190
+ }
191
+ }
192
+ })
193
+ }
194
+
195
+ if (debugButton) {
196
+ debugButton.addEventListener('click', () => {
197
+ debugButton.disabled = true
198
+ debugButton.textContent = '检测中…'
199
+ if (out) out.textContent = '开始检测…'
200
+ run()
201
+ .catch((error) => line('✗ 自检脚本出错:' + String(error && error.message ? error.message : error)))
202
+ .finally(() => {
203
+ debugButton.disabled = false
204
+ debugButton.textContent = '重新检测'
205
+ })
206
+ })
207
+ if (out) out.textContent = '(点「开始检测」运行)'
208
+ } else if (autoRun) {
209
+ run().catch((error) => line('✗ 自检脚本出错:' + String(error && error.message ? error.message : error)))
210
+ }
211
+ })()