@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,150 @@
1
+ /**
2
+ * 调试页的上传脚本(外部文件,不是内联脚本)。
3
+ *
4
+ * 为什么必须放在外部文件里(2026-11-15 事故):
5
+ * 页面响应头带 `Content-Security-Policy: ... script-src 'self'`,没有 'unsafe-inline'。
6
+ * 所以写在 HTML 里的 <script>…</script> 会被浏览器直接丢弃——按钮没有监听器,
7
+ * 点了完全没反应,连请求都不会发出(审计日志里一条记录都没有)。
8
+ * 改成同源外部脚本(script-src 'self' 允许)后才会真正执行。
9
+ *
10
+ * 逻辑:
11
+ * 1. 选图后先在本机压缩(长边 ≤1600 / JPEG 0.85),手机 4K 截图从几 MB 降到几百 KB
12
+ * 2. 用 dataURL 交给 /debug/upload,服务端落盘到 debug/shots/
13
+ * 3. 每一步都给可见回执:读取中 / 上传中(XKB) / 已保存(XKB·Yms) / 失败(HTTP 状态+原因)
14
+ * 4. 30 秒超时兜底,上传期间禁用按钮防重复点击
15
+ */
16
+ (() => {
17
+ const input = document.getElementById('file')
18
+ const button = document.getElementById('send')
19
+ const result = document.getElementById('result')
20
+ if (!input || !button || !result) return
21
+
22
+ const MAX_EDGE = 1600
23
+ const MAX_BYTES = 12 * 1024 * 1024
24
+ const TIMEOUT_MS = 30000
25
+
26
+ const info = (message) => {
27
+ result.className = 'sub'
28
+ result.textContent = message
29
+ }
30
+ const fail = (message) => {
31
+ result.className = 'sub err'
32
+ result.textContent = '失败:' + message
33
+ }
34
+
35
+ /** 缩到长边 1600 的 JPEG;失败就退回原图(宁可能传,也别因为压缩失败卡住) */
36
+ function shrink(file) {
37
+ return new Promise((resolve) => {
38
+ const reader = new FileReader()
39
+ reader.onerror = () => resolve(null)
40
+ reader.onload = () => {
41
+ const original = String(reader.result)
42
+ const image = new Image()
43
+ image.onerror = () => resolve(original)
44
+ image.onload = () => {
45
+ try {
46
+ const longest = Math.max(image.width, image.height)
47
+ const scale = Math.min(1, MAX_EDGE / longest)
48
+ if (scale === 1 && file.size <= 1.5 * 1024 * 1024) {
49
+ resolve(original)
50
+ return
51
+ }
52
+ const canvas = document.createElement('canvas')
53
+ canvas.width = Math.max(1, Math.round(image.width * scale))
54
+ canvas.height = Math.max(1, Math.round(image.height * scale))
55
+ const context = canvas.getContext('2d')
56
+ if (!context) {
57
+ resolve(original)
58
+ return
59
+ }
60
+ context.drawImage(image, 0, 0, canvas.width, canvas.height)
61
+ resolve(canvas.toDataURL('image/jpeg', 0.85))
62
+ } catch (error) {
63
+ resolve(original)
64
+ }
65
+ }
66
+ image.src = original
67
+ }
68
+ reader.readAsDataURL(file)
69
+ })
70
+ }
71
+
72
+ button.addEventListener('click', async () => {
73
+ const file = input.files && input.files[0]
74
+ if (!file) {
75
+ fail('先选一张图片。')
76
+ return
77
+ }
78
+ if (file.size > MAX_BYTES) {
79
+ fail('图片太大(上限 12MB)。')
80
+ return
81
+ }
82
+
83
+ button.disabled = true
84
+ const startedAt = Date.now()
85
+ try {
86
+ info('读取中…')
87
+ const dataUrl = await shrink(file)
88
+ if (!dataUrl) {
89
+ fail('这个文件读不出来,换一张试试(或重新截一次图)。')
90
+ return
91
+ }
92
+ const kb = Math.round((dataUrl.length * 3) / 4 / 1024)
93
+ info('上传中…(' + kb + 'KB)')
94
+
95
+ const controller = new AbortController()
96
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS)
97
+ let response
98
+ try {
99
+ response = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
100
+ method: 'POST',
101
+ headers: { 'content-type': 'application/json' },
102
+ body: JSON.stringify({ name: file.name, dataUrl }),
103
+ signal: controller.signal,
104
+ })
105
+ } catch (error) {
106
+ const aborted = error && (error.name === 'AbortError' || error.name === 'TimeoutError')
107
+ if (aborted) fail('等了 30 秒没有响应(已传 ' + kb + 'KB),可能是隧道/反代截断了请求体。')
108
+ else fail('请求没发出去或连接被断开(' + (error && error.message ? error.message : error) + ',' + kb + 'KB)。')
109
+ return
110
+ } finally {
111
+ clearTimeout(timer)
112
+ }
113
+
114
+ const text = await response.text()
115
+ const elapsed = Date.now() - startedAt
116
+ if (!response.ok) {
117
+ let reason = text.slice(0, 200)
118
+ try {
119
+ const parsedError = JSON.parse(text)
120
+ if (parsedError && parsedError.error) reason = parsedError.error
121
+ } catch (error) {
122
+ // 保留原文
123
+ }
124
+ fail('HTTP ' + response.status + ' · ' + reason + '(' + elapsed + 'ms)')
125
+ return
126
+ }
127
+
128
+ let data = null
129
+ try {
130
+ data = JSON.parse(text)
131
+ } catch (error) {
132
+ data = null
133
+ }
134
+ if (!data || !data.file) {
135
+ fail('服务端返回看不懂:' + text.slice(0, 160))
136
+ return
137
+ }
138
+
139
+ info('已保存:' + data.file + '(' + kb + 'KB / ' + elapsed + 'ms)')
140
+ const image = document.createElement('img')
141
+ image.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
142
+ image.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
143
+ const gallery = document.querySelector('.shots')
144
+ if (gallery) gallery.appendChild(image)
145
+ else result.appendChild(image)
146
+ } finally {
147
+ button.disabled = false
148
+ }
149
+ })
150
+ })()
package/lib/exec-path.mjs CHANGED
@@ -11,7 +11,15 @@
11
11
  import fs from 'node:fs'
12
12
  import path from 'node:path'
13
13
 
14
- const SYSTEM_ROOT = process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows'
14
+ /**
15
+ * Windows 系统目录:SystemRoot 优先,其次 WINDIR,最后回退 C:\Windows。
16
+ * 单独成函数便于测试三种取值(真实 Windows 上 SystemRoot 总是存在)。
17
+ */
18
+ export function systemRoot(env = process.env) {
19
+ return env.SystemRoot ?? env.WINDIR ?? 'C:\\Windows'
20
+ }
21
+
22
+ const SYSTEM_ROOT = systemRoot()
15
23
 
16
24
  function firstExisting(candidates, fallback) {
17
25
  for (const candidate of candidates) {
@@ -271,7 +271,7 @@ export function renderListing({ info, message, isError, home, dataDir, workspace
271
271
  ${entry.dir || !TEXT_FILE_RE.test(entry.name) ? '' : `<a class="mi" role="menuitem" data-act="edit" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u270F\uFE0F</span>编辑</a>`}
272
272
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="openpc" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F5A5}\uFE0F</span>在电脑打开</a>`}
273
273
  ${entry.dir ? '' : `<a class="mi" role="menuitem" data-act="download" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u2B07\uFE0F</span>下载</a>`}
274
- ${/\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name) ? `<a class="mi" role="menuitem" data-act="preview" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F441}\uFE0F</span>预览</a>` : ''}
274
+ ${/\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name) ? `<a class="mi" role="menuitem" data-act="preview" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F441}\uFE0F</span>预览</a>` : ''}
275
275
  <a class="mi" role="menuitem" data-act="compress" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u{1F512}</span>加密压缩</a>
276
276
  ${entry.runnable ? `<a class="mi" role="menuitem" data-act="run" data-path="${escapeHtml(entry.path)}" href="#"><span class="ico">\u25B6\uFE0F</span>执行</a>` : ''}
277
277
  <a class="mi" role="menuitem" data-act="rename" data-path="${escapeHtml(entry.path)}" data-name="${escapeHtml(entry.name)}" href="#"><span class="ico">\u{1F3F7}\uFE0F</span>重命名</a>
@@ -288,7 +288,7 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
288
288
  const rows = info.entries.map((entry) => {
289
289
  const label = escapeHtml(entry.name);
290
290
  const icon = entry.dir ? '\u{1F4C1}' : (entry.runnable ? '\u2699\uFE0F' : '\u{1F4C4}');
291
- const previewable = /\\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name)
291
+ const previewable = /\.(docx?|xlsx?|pptx?|odt|ods|odp|rtf|pdf)$/iu.test(entry.name)
292
292
  const nameHtml = entry.dir
293
293
  ? `<a class="fname dir" href="/files?path=${encodeURIComponent(entry.path)}">${label}</a>`
294
294
  : previewable
@@ -434,7 +434,7 @@ export function renderFile({ info, message, isError, rendered = null }) {
434
434
  : '')
435
435
  const body = `
436
436
  <div class="bar">
437
- <h1>${escapeHtml(info.path.split(/[\\/]/u).pop() ?? info.path)}</h1>
437
+ <h1>${escapeHtml(info.path.split(/[\\/]/u).pop())}</h1>
438
438
  <div class="path">${escapeHtml(info.path)}</div>
439
439
  ${toggle}
440
440
  </div>
package/lib/files.mjs CHANGED
@@ -348,14 +348,13 @@ export function writeTextFile(absPath, text, limit = MAX_READ) {
348
348
 
349
349
  /** 判断命令是否可用(跨平台:Windows 查 where,其他查 PATH) */
350
350
  function commandExists(name) {
351
- try {
352
- const checker = process.platform === 'win32' ? systemExe('where') : systemExe('sh');
353
- const args = process.platform === 'win32' ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
354
- const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
355
- return out.status === 0 && String(out.stdout ?? '').trim().length > 0;
356
- } catch {
357
- return false;
358
- }
351
+ const isWindows = process.platform === 'win32';
352
+ const checker = isWindows ? systemExe('where') : systemExe('sh');
353
+ const args = isWindows ? [name] : ['-c', 'command -v ' + JSON.stringify(name)];
354
+ const out = spawnSync(checker, args, { encoding: 'utf8', windowsHide: true, timeout: 4000 });
355
+ // where / command -v 只有在找到命令时才以 0 退出(且 stdout 必有路径),
356
+ // spawnSync 对本函数的固定入参不会抛错,所以 status 就是唯一判据。
357
+ return out.status === 0;
359
358
  }
360
359
 
361
360
  /** 按类型执行文件,收集输出。不经过 shell 拼接(bat/ps1/sh 由解释器接手)。 */
@@ -454,13 +453,13 @@ export function runFile(absPath, args = '', { timeoutMs = 15_000, cwd } = {}) {
454
453
  };
455
454
 
456
455
  const timer = setTimeout(() => {
457
- try {
458
- if (process.platform === 'win32' && child.pid) {
459
- spawn(systemExe('taskkill'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
460
- } else {
461
- child.kill('SIGKILL');
462
- }
463
- } catch { /* 已退出 */ }
456
+ // 能走到这里说明子进程已成功拉起(pid 一定存在;拉起失败时 error 事件先于定时器触发)。
457
+ // Windows 用 taskkill 结束整棵进程树,其他平台发 SIGKILL;对已退出的子进程 kill 返回 false 而不抛错。
458
+ if (process.platform === 'win32') {
459
+ spawn(systemExe('taskkill'), ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
460
+ } else {
461
+ child.kill('SIGKILL');
462
+ }
464
463
  finish({ ok: true, code: null, output: decode(), truncated, timedOut: true });
465
464
  }, timeoutMs);
466
465
 
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 「距今多少秒」的显示文案。
3
+ *
4
+ * 背景:重启页原来直接拼 `30.6 秒前`,前面没有任何标签,放在红色列表里
5
+ * 会被读成「已经繁忙了 30.6 秒」。用户反馈看不懂,所以统一成带语义的短语,
6
+ * 由调用方补「最后活动」这类前缀。
7
+ *
8
+ * 浏览器端(restart/client.mjs)有一份等价的实现(那边不能 import ESM),
9
+ * 两边行为由 test/unit.format-age.test.mjs 的一致性用例守住。
10
+ */
11
+
12
+ /**
13
+ * @param {number} seconds 距今秒数(可以是小数)
14
+ * @returns {string} 例:'刚刚' / '30.6 秒前' / '2 分 5 秒前' / '1 小时 3 分前'
15
+ */
16
+ export function formatAge(seconds) {
17
+ const value = Number(seconds)
18
+ if (!Number.isFinite(value) || value < 0) return '未知'
19
+ if (value < 1) return '刚刚'
20
+ if (value < 60) return (Math.round(value * 10) / 10) + ' 秒前'
21
+ if (value < 3600) {
22
+ let minutes = Math.floor(value / 60)
23
+ let rest = Math.round(value % 60)
24
+ // 59.6 秒会被四舍五入成 60,必须进位,否则出现「1 分 60 秒前」
25
+ if (rest === 60) { minutes += 1; rest = 0 }
26
+ return rest === 0 ? (minutes + ' 分钟前') : (minutes + ' 分 ' + rest + ' 秒前')
27
+ }
28
+ const hours = Math.floor(value / 3600)
29
+ let minutes = Math.round((value % 3600) / 60)
30
+ if (minutes === 60) return ((hours + 1) + ' 小时前')
31
+ return minutes === 0 ? (hours + ' 小时前') : (hours + ' 小时 ' + minutes + ' 分前')
32
+ }
package/lib/git.mjs CHANGED
@@ -17,6 +17,18 @@ const GIT_EXE = gitExe()
17
17
  const TASKKILL = systemExe('taskkill')
18
18
  const MAX_OUTPUT = 64 * 1024
19
19
  const DEFAULT_TIMEOUT = 20_000
20
+ /** runGit 对"成功但没有任何输出"的占位符(页面直接展示时比空白友好) */
21
+ export const EMPTY_OUTPUT = '(无输出)'
22
+
23
+ /**
24
+ * 把输出里的占位符归一成空串:仓库概况字段不应该显示占位符。
25
+ * 调用点都先判 `result.ok`,而 runGit 成功(ok=true)时 output 必为字符串
26
+ * (close/timeout 分支都显式赋值),所以这里不需要 null/undefined 兜底。
27
+ */
28
+ const plainOutput = (value) => {
29
+ const text = String(value).trim()
30
+ return text === EMPTY_OUTPUT ? '' : text
31
+ }
20
32
 
21
33
  /** 是不是一个 git 仓库的根目录(有 .git 目录或 gitfile) */
22
34
  export function isRepo(dir) {
@@ -36,14 +48,21 @@ export async function repoSummary(dir) {
36
48
  runGit(dir, ['log', '-1', '--pretty=%h %ad %s', '--date=format:%m-%d %H:%M']),
37
49
  runGit(dir, ['branch', '-a', '--format=%(refname:short)']),
38
50
  ])
39
- const dirty = status.ok ? status.output.trim().split('\n').filter(Boolean) : []
51
+ // 注意:runGit 成功且无输出时会返回占位符,这里必须先归一成空串,
52
+ // 否则干净仓库会被算成"有 1 个脏文件"、无远端会被显示成"(无输出)"。
53
+ const statusText = status.ok ? plainOutput(status.output) : ''
54
+ const dirty = statusText === '' ? [] : statusText.split('\n').filter(Boolean)
55
+ const remoteText = remote.ok ? plainOutput(remote.output) : ''
40
56
  return {
41
- branch: branch.ok ? branch.output.trim() : '',
57
+ branch: branch.ok ? plainOutput(branch.output) : '',
42
58
  dirty,
43
- remote: remote.ok ? remote.output.trim().split('\n')[0] ?? '' : '',
44
- last: last.ok ? last.output.trim() : '',
59
+ remote: remoteText === '' ? '' : remoteText.split('\n')[0],
60
+ last: last.ok ? plainOutput(last.output) : '',
45
61
  branches: branches.ok
46
- ? branches.output.split('\n').map((line) => line.trim()).filter((line) => line !== '' && !line.includes('HEAD'))
62
+ ? plainOutput(branches.output)
63
+ .split('\n')
64
+ .map((line) => line.trim())
65
+ .filter((line) => line !== '' && !line.includes('HEAD'))
47
66
  : [],
48
67
  }
49
68
  }
@@ -90,25 +109,24 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
90
109
  child.stderr.on('data', collect)
91
110
 
92
111
  const decode = () => {
93
- // git 的输出基本都是 ASCII/UTF-8;路径在这种环境下也很少出现 GBK
112
+ // git 的输出基本都是 ASCII/UTF-8;路径在这种环境下也很少出现 GBK。
113
+ // DSH 自带运行时是 full ICU(已核实 small-icu: false),TextDecoder('gbk') 必然可用,
114
+ // 所以这里不需要 try/catch 兜底(少一个永不可达的分支)。
94
115
  const buffer = Buffer.concat(chunks).subarray(0, MAX_OUTPUT)
95
116
  const utf8 = buffer.toString('utf8')
96
117
  if (!utf8.includes('\uFFFD')) return utf8
97
- try {
98
- return new TextDecoder('gbk').decode(buffer)
99
- } catch {
100
- return utf8
101
- }
118
+ return new TextDecoder('gbk').decode(buffer)
102
119
  }
103
120
 
104
121
  const timer = setTimeout(() => {
105
- try {
106
- if (process.platform === 'win32' && child.pid) {
107
- spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
108
- } else {
109
- child.kill('SIGKILL')
110
- }
111
- } catch { /* 已退出 */ }
122
+ // 超时终止:Windows 用 taskkill 结束整个进程树(git 会派生子进程),
123
+ // 其它平台直接 SIGKILL。参数都是静态字符串、TASKKILL 是绝对路径,
124
+ // spawn 既不会同步抛错也不会异步失败(置为 ignore 的 stdio 也不会回传输出)。
125
+ if (process.platform === 'win32') {
126
+ spawn(TASKKILL, ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
127
+ } else {
128
+ child.kill('SIGKILL')
129
+ }
112
130
  finish({ ok: false, timeout: true, code: null, output: decode() + '\n(超时,已终止)' })
113
131
  }, timeoutMs)
114
132
 
@@ -119,7 +137,7 @@ export function runGit(cwd, args, { timeoutMs = DEFAULT_TIMEOUT } = {}) {
119
137
  child.on('close', (code) => {
120
138
  clearTimeout(timer)
121
139
  const output = decode()
122
- finish({ ok: code === 0, code, output: output === '' ? '(无输出)' : output })
140
+ finish({ ok: code === 0, code, output: output === '' ? EMPTY_OUTPUT : output })
123
141
  })
124
142
  })
125
143
  }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * IndexedDB 兜底(保险机制,2026-11-15)
3
+ *
4
+ * 背景:华为浏览器(ArkWeb)上观察到存储类 API 会**不回调**——
5
+ * caches.keys()、navigator.serviceWorker.getRegistrations() 实测超时返回 null。
6
+ * 排查首页卡死时曾经怀疑「IndexedDB open 挂死」,但后来证伪:
7
+ * 同一时刻 Aira 的 idb-probe 也超时,而它的应用照常加载;
8
+ * 最终确定首页卡死的真实原因是「缓存的旧页面壳」+「插件说明符无法解析」,
9
+ * 与 IndexedDB 无关(本兜底在修复后一次都没触发过)。
10
+ *
11
+ * 之所以仍然保留:如果用户环境里 IndexedDB 真的挂住(同一类 API 不回调的现象确实存在),
12
+ * 应用就会永远等下去。这里在 8 秒无回调时降级到内存实现,把「死等」变成「能启动」。
13
+ *
14
+ * 触发条件极窄,正常浏览器完全不受影响:先走真实实现,只有它一个回调都不给时才接管。
15
+ */
16
+ (() => {
17
+ if (typeof indexedDB === 'undefined') return
18
+ const real = indexedDB
19
+ const TIMEOUT_MS = 8000
20
+ const patched = new WeakSet()
21
+
22
+ function memoryStore() {
23
+ const map = new Map()
24
+ return {
25
+ _map: map,
26
+ get(key) { return wrapRequest(() => map.get(key)) },
27
+ getAll() { return wrapRequest(() => [...map.values()]) },
28
+ getAllKeys() { return wrapRequest(() => [...map.keys()]) },
29
+ count() { return wrapRequest(() => map.size) },
30
+ put(value, key) { return wrapRequest(() => { const k = key ?? value?.id ?? Math.random(); map.set(k, value); return k }) },
31
+ add(value, key) { return wrapRequest(() => { const k = key ?? value?.id ?? Math.random(); if (map.has(k)) throw new Error('ConstraintError'); map.set(k, value); return k }) },
32
+ delete(key) { return wrapRequest(() => { map.delete(key) }) },
33
+ clear() { return wrapRequest(() => { map.clear() }) },
34
+ openCursor() { return wrapRequest(() => null) },
35
+ createIndex() { return { name: 'index', get: (key) => wrapRequest(() => undefined), getAll: () => wrapRequest(() => []) } },
36
+ index() { return { name: 'index', get: (key) => wrapRequest(() => undefined), getAll: () => wrapRequest(() => []) } },
37
+ }
38
+ }
39
+
40
+ /** 最小 IDBRequest:异步回调,支持 onsuccess / onerror */
41
+ function wrapRequest(fn) {
42
+ const request = { result: undefined, error: null, onsuccess: null, onerror: null }
43
+ setTimeout(() => {
44
+ try {
45
+ request.result = fn()
46
+ if (typeof request.onsuccess === 'function') request.onsuccess({ target: request })
47
+ } catch (error) {
48
+ request.error = error
49
+ if (typeof request.onerror === 'function') request.onerror({ target: request })
50
+ }
51
+ }, 0)
52
+ return request
53
+ }
54
+
55
+ /** 内存版数据库:store 名称按需创建 */
56
+ function memoryDatabase(stores, version) {
57
+ const byName = new Map()
58
+ const names = {
59
+ length: stores.length,
60
+ contains: (name) => stores.includes(name),
61
+ item: (index) => stores[index] ?? null,
62
+ [Symbol.iterator]: function* iterate() { yield* stores },
63
+ }
64
+ const ensure = (name) => {
65
+ if (!byName.has(name)) byName.set(name, memoryStore())
66
+ return byName.get(name)
67
+ }
68
+ return {
69
+ name: 'memory',
70
+ version: version ?? 1,
71
+ objectStoreNames: names,
72
+ createObjectStore(name) { stores.push(name); return ensure(name) },
73
+ deleteObjectStore(name) { const at = stores.indexOf(name); if (at >= 0) stores.splice(at, 1) },
74
+ transaction(storeNames) {
75
+ const list = Array.isArray(storeNames) ? storeNames : [storeNames]
76
+ const tx = { oncomplete: null, onerror: null, onabort: null, error: null, mode: 'readwrite', objectStore: (name) => ensure(name), abort() {} }
77
+ setTimeout(() => { if (typeof tx.oncomplete === 'function') tx.oncomplete({ target: tx }) }, 0)
78
+ for (const name of list) ensure(name)
79
+ return tx
80
+ },
81
+ close() {},
82
+ onversionchange: null,
83
+ }
84
+ }
85
+
86
+ indexedDB.open = function patchedOpen(name, version) {
87
+ const request = { result: undefined, error: null, onsuccess: null, onerror: null, onupgradeneeded: null, onblocked: null }
88
+ let settled = false
89
+ const settle = () => { settled = true }
90
+
91
+ let realRequest = null
92
+ try {
93
+ realRequest = real.open(name, version)
94
+ } catch (error) {
95
+ // 真实实现直接抛错:立刻走内存兜底
96
+ }
97
+
98
+ if (realRequest) {
99
+ realRequest.onupgradeneeded = (event) => {
100
+ if (typeof request.onupgradeneeded === 'function') request.onupgradeneeded(event)
101
+ }
102
+ realRequest.onsuccess = (event) => {
103
+ settle()
104
+ request.result = realRequest.result
105
+ if (typeof request.onsuccess === 'function') request.onsuccess(event)
106
+ }
107
+ realRequest.onerror = (event) => {
108
+ settle()
109
+ request.error = realRequest.error
110
+ if (typeof request.onerror === 'function') request.onerror(event)
111
+ }
112
+ realRequest.onblocked = (event) => {
113
+ // blocked 不代表失败,但如果一直不前进也会挂住,交给下面的超时兜底
114
+ if (typeof request.onblocked === 'function') request.onblocked(event)
115
+ }
116
+ }
117
+
118
+ setTimeout(() => {
119
+ if (settled) return
120
+ // 8 秒没有任何回调:判定为挂死,用内存库接管
121
+ const stores = []
122
+ const db = memoryDatabase(stores, version)
123
+ console.warn('[dsh-homing] IndexedDB open 挂死超过 ' + TIMEOUT_MS + 'ms,改用内存实现:' + name)
124
+ try {
125
+ if (typeof request.onupgradeneeded === 'function') request.onupgradeneeded({ target: { result: db, oldVersion: 0, newVersion: version ?? 1 } })
126
+ } catch (error) { /* 忽略 */ }
127
+ request.result = db
128
+ try {
129
+ if (typeof request.onsuccess === 'function') request.onsuccess({ target: request })
130
+ } catch (error) { /* 忽略 */ }
131
+ try {
132
+ // 上报给服务端,便于确认兜底是否被触发
133
+ const body = JSON.stringify({ kind: 'idb-fallback', message: 'open 挂死,已启用内存实现', url: location.href.slice(0, 120), at: new Date().toISOString() })
134
+ fetch('/dsh_homing/client-error', { method: 'POST', headers: { 'content-type': 'application/json' }, body, cache: 'no-store', keepalive: true }).catch(() => {})
135
+ } catch (error) { /* 忽略 */ }
136
+ }, TIMEOUT_MS)
137
+
138
+ return request
139
+ }
140
+ })()
@@ -0,0 +1,64 @@
1
+ /** 本地应用管理页:只依赖原生表单,兼容手机浏览器。 */
2
+ import { NAV_CSS, topNav } from './nav.mjs'
3
+
4
+ const escapeHtml = (value) => String(value ?? '')
5
+ .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
6
+ .replaceAll('"', '&quot;').replaceAll("'", '&#39;')
7
+
8
+ const STYLE = `
9
+ :root{color-scheme:dark}*{box-sizing:border-box}body{margin:0;background:#0f1115;color:#e8eaed;font:14px/1.5 system-ui,-apple-system,"Noto Sans SC",sans-serif}
10
+ .wrap{max-width:980px;margin:0 auto;padding:10px 12px 50px}h1{font-size:20px;margin:6px 0}h2{font-size:15px;margin:20px 0 8px;color:#aab4c3}
11
+ .sub{color:#8b93a1;font-size:12px;margin:4px 0 12px}.card{background:#171a21;border:1px solid #262b36;border-radius:12px;padding:14px;margin:10px 0}
12
+ .app{border-bottom:1px solid #252b35;padding:10px 0}.app:last-child{border-bottom:0}.title{font-size:15px;font-weight:600;word-break:break-word}
13
+ .meta{color:#8b93a1;font-size:12px;word-break:break-all;margin-top:3px}.dot{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:5px;background:#596273}
14
+ .dot.on{background:#70d99a}.dot.off{background:#e5a06b}.ops{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
15
+ a{color:#8ab4f8;text-decoration:none}button,.btn{border:1px solid #3a4658;border-radius:7px;background:#263141;color:#dce9f7;padding:7px 11px;font-size:12px;cursor:pointer}
16
+ .btn{display:inline-block}.primary{background:#315cb4;border-color:#4c7bd0;color:#fff}.danger{background:#4a292d;border-color:#704047;color:#ffd4d7}.ghost{background:#232a34}
17
+ form{margin:0}label{display:block;margin:10px 0 4px;color:#9aa4b2;font-size:12px}input[type=text],input[type=url]{width:100%;padding:10px;border-radius:8px;border:1px solid #354052;background:#0f1319;color:#e6edf5;font-size:14px}
18
+ .check{display:flex;align-items:center;gap:7px;margin:9px 0}.check input{width:18px;height:18px}.grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}.msg{padding:10px 12px;border-radius:8px;background:#213d31;border:1px solid #315c45;color:#b5e6c7;margin:10px 0}
19
+ .err{background:#44272c;border-color:#6b3c43;color:#ffc9cf}.empty{padding:20px 4px;color:#8b93a1}.note{font-size:12px;color:#8b93a1;line-height:1.7}
20
+ @media(max-width:640px){.grid{grid-template-columns:1fr}.card{padding:12px}}
21
+ `
22
+
23
+ export function renderLocalAppsPage({ apps, health = {}, editing = null, confirmDelete = null, message = '', isError = false }) {
24
+ const formApp = editing ?? { id: '', name: '', target: 'http://127.0.0.1:', enabled: true, trusted: false, allowInsecureTls: false }
25
+ const rows = apps.length === 0
26
+ ? '<div class="empty">还没有本地应用。先在下方添加一个本机服务。</div>'
27
+ : apps.map((app) => {
28
+ const state = health[app.id]
29
+ const stateText = app.enabled ? (state === true ? '端口可达' : state === false ? '端口不可达' : '已启用') : '已停用'
30
+ const stateClass = app.enabled && state === true ? 'on' : 'off'
31
+ return `<div class="app"><div class="title"><span class="dot ${stateClass}"></span>${escapeHtml(app.name)}</div>
32
+ <div class="meta">ID <code>${escapeHtml(app.id)}</code> · ${escapeHtml(stateText)}${app.trusted ? ' · 已信任网页脚本' : ' · 仅安全内容'}<br>${escapeHtml(app.target)}</div>
33
+ <div class="ops">${app.enabled ? `<a class="btn primary" href="/apps/${app.id}/" target="_blank" rel="noopener noreferrer">打开</a>` : ''}
34
+ <a class="btn ghost" href="/dsh_homing/apps?edit=${encodeURIComponent(app.id)}">编辑</a>
35
+ <form method="post"><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="${escapeHtml(app.id)}"><button type="submit">${app.enabled ? '停用' : '启用'}</button></form>
36
+ <a class="btn danger" href="/dsh_homing/apps?confirm-delete=${encodeURIComponent(app.id)}">删除</a>
37
+ </div></div>`
38
+ }).join('')
39
+
40
+ const deleteCard = confirmDelete
41
+ ? `<div class="card"><h2>确认删除「${escapeHtml(confirmDelete.name)}」?</h2><p class="sub">只删除网关入口,不会停止或删除电脑上的服务。</p><div class="ops"><form method="post"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="${escapeHtml(confirmDelete.id)}"><button class="danger" type="submit">确认删除</button></form><a class="btn ghost" href="/dsh_homing/apps">取消</a></div></div>`
42
+ : ''
43
+
44
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>本地应用 · DSH</title><style>${STYLE}${NAV_CSS}</style></head><body><div class="wrap">
45
+ ${topNav({ current: '/dsh_homing/apps' })}
46
+ <h1>本地应用</h1><p class="sub">把本机回环服务接入同一个安全入口。每个应用独立启用,互不影响。</p>
47
+ ${message ? `<div class="msg${isError ? ' err' : ''}">${escapeHtml(message)}</div>` : ''}
48
+ ${deleteCard}
49
+ <div class="card"><h2>已登记应用(${apps.length})</h2>${rows}</div>
50
+ <div class="card"><h2>${editing ? '编辑应用' : '添加应用'}</h2>
51
+ <form method="post"><input type="hidden" name="action" value="save"><input type="hidden" name="originalId" value="${escapeHtml(editing?.id ?? '')}">
52
+ <div class="grid"><div><label for="app-id">应用 ID(小写字母、数字、中划线)</label><input id="app-id" name="id" type="text" required maxlength="32" pattern="[a-z0-9]([a-z0-9-]*[a-z0-9])?" value="${escapeHtml(formApp.id)}" placeholder="m0"></div>
53
+ <div><label for="app-name">显示名称</label><input id="app-name" name="name" type="text" required maxlength="60" value="${escapeHtml(formApp.name)}" placeholder="M0 决策弹窗"></div></div>
54
+ <label for="app-target">目标地址(仅允许 127.0.0.1 / ::1)</label><input id="app-target" name="target" type="url" required value="${escapeHtml(formApp.target)}" placeholder="http://127.0.0.1:8765">
55
+ <label class="check"><input name="enabled" type="checkbox" value="1"${formApp.enabled ? ' checked' : ''}>启用这个应用</label>
56
+ <label class="check"><input name="trusted" type="checkbox" value="1"${formApp.trusted ? ' checked' : ''}>我信任此应用的网页脚本(允许 HTML / JavaScript)</label>
57
+ <p class="note">默认只允许 JSON、文本、图片等安全内容。勾选前请确认应用代码可信:网页脚本与 DSH 同源,能发起 DSH 操作;不可信应用或存在 XSS 的应用不要勾选。</p>
58
+ <label class="check"><input name="allowInsecureTls" type="checkbox" value="1"${formApp.allowInsecureTls ? ' checked' : ''}>目标是 HTTPS 时允许自签名证书(仅在确有需要时开启)</label>
59
+ <div class="ops"><button class="primary" type="submit">${editing ? '保存修改' : '添加并启用'}</button>${editing ? '<a class="btn ghost" href="/dsh_homing/apps">取消编辑</a>' : ''}</div>
60
+ </form>
61
+ </div>
62
+ <div class="card"><h2>访问方式</h2><p class="note">保存后立即生效,无需重启 DSH。公开地址为 <code>/apps/应用ID/</code>。所有访问仍要求 DSH 登录或有效设备令牌;管理操作要求重新处于登录会话中。<br>只代理本机回环地址,不会把插件会话 Cookie 转发给你的服务。网页如果写死根路径,请使用支持 base path 的服务或后续独立域名模式。</p></div>
63
+ </div></body></html>`
64
+ }