@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,262 @@
1
+ /**
2
+ * 通用本地应用代理:HTTP/流式响应 + WebSocket。
3
+ *
4
+ * 与 DSH 主代理分开:这里只转发登记过的 loopback 应用,不注入 DSH 登录态,
5
+ * 也不把插件会话 Cookie 泄露给第三方本地服务。
6
+ */
7
+ import http from 'node:http'
8
+ import https from 'node:https'
9
+ import net from 'node:net'
10
+ import tls from 'node:tls'
11
+ import {
12
+ rewriteLocation,
13
+ rewriteSetCookie,
14
+ scrubPluginCookies,
15
+ upstreamPath,
16
+ } from './local-apps.mjs'
17
+ import * as limits from './limits.mjs'
18
+
19
+ const HOP_HEADERS = [
20
+ 'connection', 'keep-alive', 'proxy-connection', 'proxy-authenticate',
21
+ 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade',
22
+ ]
23
+
24
+ function publicRequestHeaders(req, app, rest, url, clientIp) {
25
+ const target = new URL(app.target)
26
+ const headers = { ...req.headers }
27
+ for (const name of HOP_HEADERS) delete headers[name]
28
+ headers.host = target.host
29
+ const cookies = scrubPluginCookies(headers.cookie)
30
+ if (cookies) headers.cookie = cookies
31
+ else delete headers.cookie
32
+ headers['x-forwarded-host'] = String(req.headers.host ?? '')
33
+ headers['x-forwarded-proto'] = req.socket.encrypted ? 'https' : 'http'
34
+ headers['x-forwarded-prefix'] = `/apps/${app.id}`
35
+ if (clientIp) headers['x-forwarded-for'] = clientIp
36
+ if (headers.origin) headers.origin = target.origin
37
+ if (headers.referer) headers.referer = target.origin + upstreamPath(app, rest, url.search)
38
+ return headers
39
+ }
40
+
41
+ function publicResponseHeaders(headers, app, rest) {
42
+ const result = { ...headers }
43
+ for (const name of HOP_HEADERS) delete result[name]
44
+ if (result.location) result.location = rewriteLocation(result.location, app, rest)
45
+ if (result['set-cookie']) result['set-cookie'] = rewriteSetCookie(result['set-cookie'], app)
46
+ if (app.trusted !== true && !result['content-type']) {
47
+ // 上游未声明类型时,不信任应用只能下载,不能让浏览器按 HTML/JS sniff 执行。
48
+ result['content-type'] = 'application/octet-stream'
49
+ if (!result['content-disposition']) result['content-disposition'] = 'attachment'
50
+ }
51
+ result['x-content-type-options'] = 'nosniff'
52
+ return result
53
+ }
54
+
55
+ function escapeHtml(value) {
56
+ return String(value ?? '').replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;').replaceAll('"', '&quot;')
57
+ }
58
+
59
+ function sendProxyError(req, res, app, status, message) {
60
+ if (res.destroyed) return
61
+ if (res.headersSent) {
62
+ res.destroy()
63
+ return
64
+ }
65
+ const accept = String(req.headers.accept ?? '')
66
+ if (!accept.includes('text/html')) {
67
+ const body = JSON.stringify({ ok: false, app: app.id, error: message })
68
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', connection: 'close' })
69
+ res.end(body)
70
+ return
71
+ }
72
+ const body = `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>应用暂不可用</title><body style="margin:0;background:#0f1115;color:#e8eaed;font:16px/1.6 system-ui;padding:24px"><h1 style="font-size:20px">${escapeHtml(app.name)}</h1><p style="color:#9aa4b2">${escapeHtml(message)}</p><p><a style="color:#8ab4f8" href="/apps/${app.id}/">重试</a> · <a style="color:#8ab4f8" href="/dsh_homing/apps">返回本地应用</a></p></body></html>`
73
+ res.writeHead(status, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', connection: 'close' })
74
+ res.end(body)
75
+ }
76
+
77
+ const ACTIVE_CONTENT_RE = /(?:text\/html|application\/xhtml\+xml|javascript|ecmascript|image\/svg\+xml|(?:text|application)\/(?:[^/;]+\+)?xml\b|xslt|xsl|rss|atom)/iu
78
+
79
+ function shouldBlockActiveContent(app, contentType) {
80
+ // 默认同源 HTML/JS 不可信:防止本地应用的脚本借 DSH 同源 Cookie 调管理接口。
81
+ // 只有管理员明确标记 trusted 的应用才能返回可执行网页内容。
82
+ if (app.trusted === true) return false
83
+ const type = String(contentType ?? '').toLowerCase()
84
+ return ACTIVE_CONTENT_RE.test(type)
85
+ }
86
+
87
+ /** 转发一个已经鉴权的应用请求。 */
88
+ export function proxyLocalAppHttp({ req, res, url, app, rest, clientIp, maxBodyBytes, audit = () => {} }) {
89
+ const target = new URL(app.target)
90
+ const declared = limits.checkDeclaredLength(req.headers['content-length'], maxBodyBytes)
91
+ if (declared.over) {
92
+ audit('app-body-too-large', { app: app.id, declared: declared.declared, limit: declared.limit })
93
+ req.resume()
94
+ sendProxyError(req, res, app, 413, '请求体超过网关允许的大小')
95
+ return
96
+ }
97
+
98
+ const path = upstreamPath(app, rest, url.search)
99
+ const transport = target.protocol === 'https:' ? https : http
100
+ const upstream = transport.request({
101
+ protocol: target.protocol,
102
+ hostname: target.hostname.replace(/^\[|\]$/gu, ''),
103
+ port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)),
104
+ method: req.method,
105
+ path,
106
+ headers: publicRequestHeaders(req, app, rest, url, clientIp),
107
+ rejectUnauthorized: !app.allowInsecureTls,
108
+ agent: false,
109
+ }, (upstreamRes) => {
110
+ upstream.setTimeout(0)
111
+ if (shouldBlockActiveContent(app, upstreamRes.headers['content-type'])) {
112
+ audit('app-active-content-blocked', { app: app.id, contentType: String(upstreamRes.headers['content-type']).slice(0, 100) })
113
+ upstreamRes.destroy()
114
+ sendProxyError(req, res, app, 403, '此应用未开启「信任网页脚本」。API/文本仍可使用;如确认应用代码可信,请在应用管理中显式开启。')
115
+ return
116
+ }
117
+ res.writeHead(upstreamRes.statusCode ?? 502, publicResponseHeaders(upstreamRes.headers, app, rest))
118
+ upstreamRes.pipe(res)
119
+ upstreamRes.on('error', () => { if (!res.writableFinished) res.destroy() })
120
+ })
121
+
122
+ // 只限制等待首字节的时间;响应开始后可以长期流式下载/SSE。
123
+ upstream.setTimeout(5000, () => upstream.destroy(new Error('应用响应超时')))
124
+ upstream.on('error', (error) => {
125
+ audit('app-proxy-error', { app: app.id, error: String(error?.code ?? error?.message ?? error).slice(0, 160) })
126
+ sendProxyError(req, res, app, error?.message === '应用响应超时' ? 504 : 502, '无法连接应用。请确认服务已启动,且监听地址和端口正确。')
127
+ })
128
+
129
+ const counter = limits.createByteCounter(maxBodyBytes)
130
+ let overflow = false
131
+ req.on('data', (chunk) => {
132
+ if (overflow) return
133
+ if (!counter.add(chunk.length)) return
134
+ overflow = true
135
+ audit('app-body-too-large', { app: app.id, streamed: counter.total, limit: counter.limit })
136
+ upstream.destroy()
137
+ req.unpipe(upstream)
138
+ req.resume()
139
+ sendProxyError(req, res, app, 413, '请求体超过网关允许的大小')
140
+ })
141
+ req.on('aborted', () => upstream.destroy())
142
+ res.on('close', () => { if (!res.writableFinished) upstream.destroy() })
143
+ req.pipe(upstream)
144
+ audit('app-http', { app: app.id, method: req.method, path: rest || '/' })
145
+ }
146
+
147
+ function writeSocketError(socket, status, text) {
148
+ try {
149
+ socket.end(`HTTP/1.1 ${status}\r\ncontent-type: text/plain; charset=utf-8\r\ncontent-length: ${Buffer.byteLength(text)}\r\nconnection: close\r\n\r\n${text}`)
150
+ } catch { /* 对端已断开 */ }
151
+ }
152
+
153
+ /** 清洗 WS 握手响应头;101 之后的帧数据不在此函数处理。 */
154
+ export function sanitizeUpgradeResponse(headerText, app, rest = '/') {
155
+ const lines = String(headerText).split('\r\n')
156
+ const output = []
157
+ for (const line of lines) {
158
+ const colon = line.indexOf(':')
159
+ if (colon <= 0) {
160
+ output.push(line)
161
+ continue
162
+ }
163
+ const name = line.slice(0, colon).toLowerCase()
164
+ const value = line.slice(colon + 1).trim()
165
+ if (name === 'set-cookie') {
166
+ const rewritten = rewriteSetCookie([value], app)
167
+ if (rewritten.length > 0) output.push(`Set-Cookie: ${rewritten[0]}`)
168
+ } else if (name === 'location') {
169
+ output.push(`Location: ${rewriteLocation(value, app, rest)}`)
170
+ } else {
171
+ output.push(line)
172
+ }
173
+ }
174
+ return output.join('\r\n')
175
+ }
176
+
177
+ /** 转发一个已经鉴权的 WebSocket upgrade;保留服务自身的子协议与扩展协商。 */
178
+ export function proxyLocalAppUpgrade({ req, socket, head, url, app, rest, clientIp, audit = () => {} }) {
179
+ if (String(req.method).toUpperCase() !== 'GET') {
180
+ writeSocketError(socket, '405 Method Not Allowed', 'WebSocket 只支持 GET')
181
+ return
182
+ }
183
+ const target = new URL(app.target)
184
+ const path = upstreamPath(app, rest, url.search)
185
+ const headers = publicRequestHeaders(req, app, rest, url, clientIp)
186
+ // publicRequestHeaders 为普通 HTTP 去掉 hop header;WebSocket 必须恢复。
187
+ headers.connection = 'Upgrade'
188
+ headers.upgrade = 'websocket'
189
+ const lines = []
190
+ for (const [key, value] of Object.entries(headers)) {
191
+ if (value === undefined) continue
192
+ for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`)
193
+ }
194
+ const requestText = `GET ${path} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`
195
+ const options = {
196
+ host: target.hostname.replace(/^\[|\]$/gu, ''),
197
+ port: Number(target.port || (target.protocol === 'https:' ? 443 : 80)),
198
+ }
199
+ if (target.protocol === 'https:') options.rejectUnauthorized = !app.allowInsecureTls
200
+ const upstream = target.protocol === 'https:' ? tls.connect(options) : net.connect(options)
201
+ let connected = false
202
+ let handshakeDone = false
203
+ let closed = false
204
+ let buffer = Buffer.alloc(0)
205
+
206
+ const closeBoth = () => {
207
+ if (closed) return
208
+ closed = true
209
+ clearTimeout(handshakeTimer)
210
+ try { upstream.destroy() } catch { /* 已关闭 */ }
211
+ try { socket.destroy() } catch { /* 已关闭 */ }
212
+ }
213
+
214
+ // 完整握手总时限:不会被慢速分片重置。
215
+ const handshakeTimer = setTimeout(() => {
216
+ if (!handshakeDone) writeSocketError(socket, '504 Gateway Timeout', '应用 WebSocket 握手超时')
217
+ closeBoth()
218
+ }, 5000)
219
+ handshakeTimer.unref?.()
220
+
221
+ const onHandshakeData = (chunk) => {
222
+ if (closed || handshakeDone) return
223
+ buffer = Buffer.concat([buffer, chunk])
224
+ const end = buffer.indexOf('\r\n\r\n')
225
+ if (end < 0) {
226
+ if (buffer.length > 64 * 1024) {
227
+ writeSocketError(socket, '502 Bad Gateway', '应用 WebSocket 响应头过大')
228
+ closeBoth()
229
+ }
230
+ return
231
+ }
232
+ handshakeDone = true
233
+ clearTimeout(handshakeTimer)
234
+ const headerText = buffer.subarray(0, end + 4).toString('latin1')
235
+ const remainder = buffer.subarray(end + 4)
236
+ buffer = Buffer.alloc(0)
237
+ upstream.off('data', onHandshakeData)
238
+ try {
239
+ socket.write(sanitizeUpgradeResponse(headerText, app, rest), 'latin1')
240
+ if (remainder.length) socket.write(remainder)
241
+ upstream.pipe(socket)
242
+ audit('app-ws', { app: app.id, path: rest || '/' })
243
+ } catch {
244
+ closeBoth()
245
+ }
246
+ }
247
+
248
+ upstream.once(target.protocol === 'https:' ? 'secureConnect' : 'connect', () => {
249
+ connected = true
250
+ upstream.write(requestText, 'latin1')
251
+ if (head?.length) upstream.write(head)
252
+ upstream.on('data', onHandshakeData)
253
+ socket.pipe(upstream)
254
+ })
255
+ upstream.on('error', () => {
256
+ if (!handshakeDone) writeSocketError(socket, '502 Bad Gateway', connected ? '应用 WebSocket 握手失败' : '应用 WebSocket 不可达')
257
+ closeBoth()
258
+ })
259
+ upstream.on('close', closeBoth)
260
+ socket.on('error', closeBoth)
261
+ socket.on('close', closeBoth)
262
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * 页面加载守卫:每次页面加载都问一次「现在登录还成立吗」。
3
+ *
4
+ * 为什么必须存在(2026-11-15 事故):
5
+ * 手机把首页 HTML 缓存在本地后,浏览器根本不再请求 `/`(审计里只有图标请求、没有 `/`)。
6
+ * 于是服务端的「未登录 → 303 /login」永远不会触发:缓存里的旧页面壳照样启动,
7
+ * 它发起的 RPC/WebSocket 因为没有 Cookie 被拒,界面就永远停在转圈。
8
+ *
9
+ * 这个脚本跟着页面壳一起跑,在**每一次加载**时向服务端要一次真实状态(no-store,不可缓存):
10
+ * 未登录 / 会话已失效 → 立刻 replace 到 /login?next=当前页面。
11
+ *
12
+ * 注意:它必须是外部文件(页面 CSP 是 script-src 'self',内联脚本会被丢弃)。
13
+ */
14
+ (() => {
15
+ const CHECK_URL = '/dsh_homing/auth-state'
16
+ const LOOP_KEY = 'dsh-homing-auth-guard-at'
17
+
18
+ function toLogin(reason) {
19
+ // 防抖:10 秒内只跳一次,避免和浏览器自身的跳转打架造成闪烁
20
+ try {
21
+ const last = Number(sessionStorage.getItem(LOOP_KEY) ?? '0')
22
+ if (Number.isFinite(last) && Date.now() - last < 10_000) return
23
+ sessionStorage.setItem(LOOP_KEY, String(Date.now()))
24
+ } catch (error) {
25
+ // sessionStorage 不可用时也允许跳转
26
+ }
27
+ const here = location.pathname + location.search
28
+ const next = here.startsWith('/login') ? '' : here
29
+ const target = next === '' ? '/login' : '/login?next=' + encodeURIComponent(next)
30
+ console.warn('[dsh-homing] 未登录或会话已失效,前往登录页', reason ?? '')
31
+ location.replace(target)
32
+ }
33
+
34
+ async function check() {
35
+ // 已经在登录页 / 重置页就不用再检查,避免自己跳自己
36
+ if (location.pathname === '/login' || location.pathname === '/dsh_homing/reset') return
37
+ try {
38
+ const response = await fetch(CHECK_URL, {
39
+ cache: 'no-store',
40
+ credentials: 'same-origin',
41
+ headers: { accept: 'application/json' },
42
+ })
43
+ if (!response.ok) return // 服务端异常时不误伤,交给页面自身处理
44
+ const state = await response.json()
45
+ if (!state || state.authenticated !== false) return
46
+ toLogin(state.reason)
47
+ } catch (error) {
48
+ // 网络断了不要乱跳:此时跳登录页也没用
49
+ }
50
+ }
51
+
52
+ // 页面壳可能在 DOM 之前就渲染,尽早检查;同时等 DOMContentLoaded 再查一次兜底
53
+ void check()
54
+ if (document.readyState === 'loading') {
55
+ document.addEventListener('DOMContentLoaded', () => { void check() }, { once: true })
56
+ }
57
+ })()
@@ -0,0 +1,168 @@
1
+ /**
2
+ * 客户端错误上报(注入到 DSH 页面里)。
3
+ *
4
+ * 只做三件轻量的事(2026-11-15 排查结束后已删掉当时临时加的重负载探针):
5
+ *
6
+ * 1. 捕获 window.onerror / unhandledrejection / 资源加载失败 → 立即上报
7
+ * 2. 捕获 console.error / console.warn 的前 2 条(插件初始化失败常被应用
8
+ * try/catch 后写 logger,window.onerror 看不到)
9
+ * 3. 12 秒后若仍在启动页:先自动换 URL 重载一次,仍不行则显示自救提示
10
+ *
11
+ * 必须是外部文件(页面 CSP 只有 script-src 'self')。
12
+ */
13
+ (() => {
14
+ const REPORT_URL = '/dsh_homing/client-error'
15
+ const sent = new Set()
16
+
17
+ function report(payload) {
18
+ const key = (payload.kind ?? '') + '|' + String(payload.message ?? '').slice(0, 60)
19
+ if (sent.has(key)) return
20
+ sent.add(key)
21
+ try {
22
+ const body = JSON.stringify({
23
+ ...payload,
24
+ href: location.href,
25
+ ua: navigator.userAgent.slice(0, 120),
26
+ at: new Date().toISOString(),
27
+ })
28
+ fetch(REPORT_URL, {
29
+ method: 'POST',
30
+ headers: { 'content-type': 'application/json' },
31
+ body,
32
+ cache: 'no-store',
33
+ credentials: 'same-origin',
34
+ keepalive: true,
35
+ }).catch(() => {})
36
+ } catch (error) {
37
+ // 上报失败不影响页面
38
+ }
39
+ }
40
+
41
+ window.addEventListener('error', (event) => {
42
+ const target = event.target
43
+ if (target && target !== window && (target.src || target.href)) {
44
+ report({
45
+ kind: 'resource',
46
+ message: '资源加载失败',
47
+ url: String(target.src || target.href).slice(0, 200),
48
+ tag: target.tagName,
49
+ })
50
+ return
51
+ }
52
+ report({
53
+ kind: 'js-error',
54
+ message: String(event.message ?? '').slice(0, 300),
55
+ source: String(event.filename ?? '').slice(0, 200),
56
+ line: event.lineno ?? 0,
57
+ stack: event.error && event.error.stack ? String(event.error.stack).slice(0, 800) : '',
58
+ })
59
+ }, true)
60
+
61
+ window.addEventListener('unhandledrejection', (event) => {
62
+ const reason = event.reason
63
+ report({
64
+ kind: 'promise',
65
+ message: String((reason && (reason.message || reason)) ?? '').slice(0, 300),
66
+ stack: reason && reason.stack ? String(reason.stack).slice(0, 800) : '',
67
+ })
68
+ })
69
+
70
+ // 只拦 error / warn,每级 2 条:足够定位插件初始化失败,又不影响性能
71
+ for (const level of ['error', 'warn']) {
72
+ const original = console[level]
73
+ if (typeof original !== 'function') continue
74
+ let reported = 0
75
+ console[level] = function patched(...args) {
76
+ try {
77
+ if (reported < 2) {
78
+ reported += 1
79
+ report({
80
+ kind: 'console-' + level,
81
+ message: args.map((arg) => {
82
+ if (typeof arg === 'string') return arg
83
+ if (arg instanceof Error) return arg.message
84
+ try { return JSON.stringify(arg) } catch { return String(arg) }
85
+ }).join(' ').slice(0, 400),
86
+ })
87
+ }
88
+ } catch (error) { /* 忽略 */ }
89
+ return original.apply(console, args)
90
+ }
91
+ }
92
+
93
+ // 12 秒后检查应用是否挂载:仍在启动页或 #root 为空,
94
+ // 先自动换一个带随机参数的 URL 重载一次(破解缓存壳/浏览器进程中的旧状态),
95
+ // 再不行才显示自救提示。
96
+ setTimeout(() => {
97
+ try {
98
+ const root = document.getElementById('root')
99
+ const splash = document.querySelector('[data-dsh-boot]')
100
+ const mounted = Boolean(root && root.childElementCount > 0) && !splash
101
+ if (mounted) return
102
+ report({
103
+ kind: 'boot-timeout',
104
+ message: String(document.body?.innerText ?? '').replace(/\s+/g, ' ').slice(0, 400) || '(页面无文字)',
105
+ rootExists: Boolean(root),
106
+ splashPresent: Boolean(splash),
107
+ readyState: document.readyState,
108
+ })
109
+
110
+ // 自动重载:每次会话只尝试一次,避免死循环
111
+ let tried = false
112
+ try {
113
+ tried = sessionStorage.getItem('dsh-homing-boot-retry') === '1'
114
+ if (!tried) sessionStorage.setItem('dsh-homing-boot-retry', '1')
115
+ } catch (error) {
116
+ tried = true // 拿不到 sessionStorage 就不要再自动刷新
117
+ }
118
+ if (!tried) {
119
+ const url = new URL(location.href)
120
+ url.searchParams.set('_r', Date.now().toString(36))
121
+ location.replace(url.href)
122
+ return
123
+ }
124
+
125
+ showStuckOverlay()
126
+ } catch (error) {
127
+ // 忽略
128
+ }
129
+ }, 12000)
130
+
131
+ /**
132
+ * 启动卡住时给出可见的自救提示。
133
+ *
134
+ * 为什么需要(2026-11-15 实测):手机浏览器进程会积累坏状态(泄漏的 IndexedDB 连接等),
135
+ * 表现就是界面永远停在 "Loading plugins…",而**刷新、重开标签都没用**,
136
+ * 必须把浏览器从后台彻底关掉再打开才恢复。用户当时试了很多次都不知道这一点,
137
+ * 所以卡住时直接把这句话显示出来,配一个重新加载按钮。
138
+ */
139
+ function showStuckOverlay() {
140
+ if (document.getElementById('dsh-homing-stuck')) return
141
+ const box = document.createElement('div')
142
+ box.id = 'dsh-homing-stuck'
143
+ box.style.cssText = 'position:fixed;inset:auto 12px 12px 12px;z-index:2147483647;'
144
+ + 'background:#171a21;color:#e8eaed;border:1px solid #7a5a2c;border-radius:12px;'
145
+ + 'padding:14px;font:14px/1.6 system-ui,-apple-system,"Noto Sans SC",sans-serif;'
146
+ + 'box-shadow:0 8px 28px rgba(0,0,0,.5)'
147
+ const title = document.createElement('div')
148
+ title.textContent = 'DSH 启动卡住了'
149
+ title.style.cssText = 'font-weight:700;margin-bottom:6px'
150
+ const hint = document.createElement('div')
151
+ hint.style.cssText = 'color:#b7bec9;margin-bottom:10px'
152
+ hint.textContent = '请在手机的多任务里把这个浏览器彻底关掉(不是切后台),再重新打开。'
153
+ + '今天多次刷新都无效、只有彻底关掉浏览器才恢复,原因通常是浏览器进程里的旧状态没被清掉。'
154
+ const row = document.createElement('div')
155
+ row.style.cssText = 'display:flex;gap:8px'
156
+ const reload = document.createElement('button')
157
+ reload.textContent = '重新加载'
158
+ reload.style.cssText = 'flex:1;padding:10px;border:0;border-radius:8px;background:#4f7cff;color:#fff;font-weight:600'
159
+ reload.addEventListener('click', () => location.reload())
160
+ const diag = document.createElement('a')
161
+ diag.textContent = '诊断'
162
+ diag.href = '/dsh_homing/netdiag'
163
+ diag.style.cssText = 'flex:0 0 auto;padding:10px 14px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;text-align:center'
164
+ row.append(reload, diag)
165
+ box.append(title, hint, row)
166
+ document.body.appendChild(box)
167
+ }
168
+ })()
package/lib/compress.mjs CHANGED
@@ -134,14 +134,15 @@ function run(bin, args, { cwd, timeoutMs }) {
134
134
  /**
135
135
  * 把 target(文件或目录)压缩成加密归档,放在同级目录。
136
136
  * 返回 { ok, path, bytes, tool, strength, error }
137
+ * @param {{ target: string, password: string, timeoutMs?: number, backends?: Array }} options
138
+ * backends 默认按本机探测结果;显式传入只为测试可控(不改生产行为)
137
139
  */
138
- export function createEncryptedArchive({ target, password, timeoutMs = 10 * 60_000 }) {
140
+ export function createEncryptedArchive({ target, password, timeoutMs = 10 * 60_000, backends = availableBackends() }) {
139
141
  const passwordError = checkPassword(password)
140
142
  if (passwordError) return { ok: false, error: passwordError }
141
143
  if (typeof target !== 'string' || target.trim() === '') return { ok: false, error: '路径为空' }
142
144
  if (!fs.existsSync(target)) return { ok: false, error: '目标不存在' }
143
145
 
144
- const backends = availableBackends()
145
146
  if (backends.length === 0) {
146
147
  return {
147
148
  ok: false,
package/lib/csrf.mjs CHANGED
@@ -58,3 +58,41 @@ export function checkUnsafeOrigin(req) {
58
58
 
59
59
  return { ok: true }
60
60
  }
61
+
62
+ /**
63
+ * 插件自己页面上的写操作来源校验(登录、账户、设备、应用管理、文件页等)。
64
+ *
65
+ * 与 checkUnsafeOrigin 的区别:这些页面的会话 Cookie 是 SameSite=Lax,跨站 POST
66
+ * 根本带不上 Cookie,所以 Origin 缺失或为 `null` 不阻断 —— 微信内置浏览器、
67
+ * 华为浏览器提交表单时会发 `Origin: null`(2026-11-14 手机上加应用即因此 403)。
68
+ * 但仍然拒绝明确的跨站证据:
69
+ * - Origin 是真实来源且与 Host 不同源;
70
+ * - Sec-Fetch-Site 存在且不是 same-origin / none(这两个头跨站页面无法伪造)。
71
+ *
72
+ * @param {object} req - Node 的 IncomingMessage
73
+ * @returns {{ ok: boolean, reason?: string }}
74
+ */
75
+ export function checkOwnPageWrite(req) {
76
+ const method = String(req?.method ?? '').toUpperCase()
77
+ if (!UNSAFE_METHODS.has(method)) return { ok: true }
78
+
79
+ const hostHeader = typeof req.headers?.host === 'string' ? req.headers.host.toLowerCase() : ''
80
+
81
+ const origin = req.headers?.origin
82
+ if (typeof origin === 'string' && origin !== '' && origin !== 'null') {
83
+ const originHost = hostOf(origin)
84
+ if (originHost === '' || hostHeader === '' || originHost !== hostHeader) {
85
+ return { ok: false, reason: `origin-mismatch:${originHost || 'invalid'}!=${hostHeader || 'none'}` }
86
+ }
87
+ }
88
+
89
+ const site = req.headers?.['sec-fetch-site']
90
+ if (typeof site === 'string' && site !== '') {
91
+ const value = site.toLowerCase()
92
+ if (value !== 'same-origin' && value !== 'none') {
93
+ return { ok: false, reason: `sec-fetch-site:${value}` }
94
+ }
95
+ }
96
+
97
+ return { ok: true }
98
+ }