@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,275 @@
1
+ /**
2
+ * 本地应用注册表:多个 loopback 服务共用一套网关。
3
+ *
4
+ * 安全边界:只允许 http/https + 127.0.0.1 / ::1,且必须显式登记。
5
+ * 不接受请求里的目标 URL,避免变成内网开放代理。
6
+ */
7
+ import fs from 'node:fs'
8
+ import net from 'node:net'
9
+ import path from 'node:path'
10
+
11
+ export const APP_ID_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/u
12
+
13
+ export function normalizeAppId(value) {
14
+ return String(value ?? '').trim().toLowerCase()
15
+ }
16
+
17
+ export function appUrlError(value) {
18
+ let target
19
+ try {
20
+ target = new URL(String(value ?? '').trim())
21
+ } catch {
22
+ return '目标地址不是合法 URL'
23
+ }
24
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') return '目标只支持 http / https'
25
+ if (target.username || target.password) return '目标地址不能带用户名或密码'
26
+ const hostname = target.hostname.replace(/^\[|\]$/gu, '')
27
+ if (hostname !== '127.0.0.1' && hostname !== '::1') return '只允许代理本机回环地址(127.0.0.1 / ::1)'
28
+ if (target.search || target.hash) return '目标地址不能带查询参数或锚点'
29
+ const port = target.port === '' ? (target.protocol === 'https:' ? 443 : 80) : Number(target.port)
30
+ if (!Number.isInteger(port) || port < 1 || port > 65535) return '目标端口无效'
31
+ return ''
32
+ }
33
+
34
+ export function validateApp(input, deniedPorts = []) {
35
+ const id = normalizeAppId(input?.id)
36
+ const name = String(input?.name ?? '').trim().slice(0, 60)
37
+ const targetText = String(input?.target ?? '').trim()
38
+ if (!APP_ID_RE.test(id)) return { ok: false, error: '应用 ID 只能用小写字母、数字和中划线,长度 1–32 位' }
39
+ if (name === '') return { ok: false, error: '请填写应用名称' }
40
+ const targetError = appUrlError(targetText)
41
+ if (targetError) return { ok: false, error: targetError }
42
+ const target = new URL(targetText)
43
+ const port = Number(target.port || (target.protocol === 'https:' ? 443 : 80))
44
+ if (deniedPorts.map(Number).includes(port)) return { ok: false, error: `端口 ${port} 是插件或 DSH 的管理端口,不能代理` }
45
+ const basePath = target.pathname === '/' ? '' : target.pathname.replace(/\/+$/u, '')
46
+ // 注意:URL.hostname 对 IPv6 已经返回带方括号的形式([::1]),不能再包一层,
47
+ // 否则会得到 http://[[::1]]:9000 这种非法 URL(2026-11-17 实测发现)。
48
+ return {
49
+ ok: true,
50
+ app: {
51
+ id,
52
+ name,
53
+ target: `${target.protocol}//${target.hostname}:${port}${basePath}`,
54
+ enabled: input?.enabled !== false,
55
+ // 同源 HTML/JS 默认不受信。只有明确勾选后才允许返回可执行网页内容。
56
+ trusted: input?.trusted === true,
57
+ allowInsecureTls: input?.allowInsecureTls === true && target.protocol === 'https:',
58
+ },
59
+ }
60
+ }
61
+
62
+ function cloneApp(app) {
63
+ // 只会传入归一化后的对象(见 normalizedList / save 的调用点);
64
+ // 对象展开对 null/undefined 也是安全的(得到 {}),因此不需要不可达的判空分支。
65
+ return { ...app }
66
+ }
67
+
68
+ function readSettingsFile(file, { strict = false } = {}) {
69
+ try {
70
+ const value = JSON.parse(fs.readFileSync(file, 'utf8'))
71
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
72
+ } catch (error) {
73
+ if (strict && fs.existsSync(file)) throw error
74
+ return {}
75
+ }
76
+ }
77
+
78
+ function normalizedList(raw, deniedPorts = []) {
79
+ const list = Array.isArray(raw?.apps) ? raw.apps : []
80
+ const seen = new Set()
81
+ const result = []
82
+ for (const item of list) {
83
+ if (!item || typeof item !== 'object') continue
84
+ const id = normalizeAppId(item.id)
85
+ if (!APP_ID_RE.test(id) || seen.has(id)) continue
86
+ const app = validateApp({ ...item, id }, deniedPorts)
87
+ if (!app.ok) continue
88
+ seen.add(id)
89
+ result.push(app.app)
90
+ }
91
+ return result
92
+ }
93
+
94
+ /** URL /apps/<id>/<rest> 的解析;rest 保留原始编码。 */
95
+ export function matchAppPath(pathname, apps) {
96
+ if (pathname === '/apps' || pathname === '/apps/') return { root: true }
97
+ if (!pathname.startsWith('/apps/')) return null
98
+ const tail = pathname.slice('/apps/'.length)
99
+ const slash = tail.indexOf('/')
100
+ const id = normalizeAppId(slash < 0 ? tail : tail.slice(0, slash))
101
+ if (!APP_ID_RE.test(id)) return { invalid: true }
102
+ const rest = slash < 0 ? '' : tail.slice(slash)
103
+ const app = apps.find((item) => item.id === id && item.enabled === true) ?? null
104
+ return { id, app, rest }
105
+ }
106
+
107
+ export function upstreamPath(app, rest, search = '') {
108
+ const base = new URL(app.target).pathname.replace(/\/+$/u, '')
109
+ return (base || '') + (rest || '/') + (search || '')
110
+ }
111
+
112
+ function publicPathFromTarget(pathname, app) {
113
+ const base = new URL(app.target).pathname.replace(/\/+$/u, '')
114
+ // 唯一调用方传入的是 new URL(...).pathname,恒为以 / 开头的非空字符串,
115
+ // 因此不需要「空值兜底」和「补前导 /」这两个走不到的防御分支。
116
+ let rest = String(pathname)
117
+ if (base && rest === base) rest = '/'
118
+ else if (base && rest.startsWith(base + '/')) rest = rest.slice(base.length)
119
+ return `/apps/${app.id}${rest}`
120
+ }
121
+
122
+ /**
123
+ * 将上游 Location 映射回公开前缀。
124
+ * rest 是本次请求的上游相对路径,用于正确解析 Location: next 这类相对地址。
125
+ */
126
+ export function rewriteLocation(value, app, rest = '/') {
127
+ if (typeof value !== 'string' || value === '') return value
128
+ const prefix = `/apps/${app.id}`
129
+ if (value === prefix || value.startsWith(prefix + '/') || value.startsWith(prefix + '?') || value.startsWith(prefix + '#')) return value
130
+ try {
131
+ const source = new URL(app.target)
132
+ const current = source.origin + upstreamPath(app, rest)
133
+ const location = new URL(value, current)
134
+ if (location.origin !== source.origin) return value
135
+ if (location.pathname === prefix || location.pathname.startsWith(prefix + '/')) {
136
+ return location.pathname + location.search + location.hash
137
+ }
138
+ return publicPathFromTarget(location.pathname, app) + location.search + location.hash
139
+ } catch {
140
+ return value
141
+ }
142
+ }
143
+
144
+ /** Cookie 必须按应用隔离;同时不允许把插件会话 Cookie 发给本地服务。 */
145
+ export function scrubPluginCookies(header) {
146
+ const parts = String(header ?? '').split(';').map((item) => item.trim()).filter(Boolean)
147
+ return parts.filter((item) => {
148
+ const name = item.split('=', 1)[0].trim().toLowerCase()
149
+ return !name.startsWith('dsh-homing-')
150
+ && !name.startsWith('dsh-auth-')
151
+ && name !== 'dsh-entry'
152
+ && name !== 'dsh-device'
153
+ }).join('; ')
154
+ }
155
+
156
+ export function rewriteSetCookie(value, app) {
157
+ const values = Array.isArray(value) ? value : [value]
158
+ const base = new URL(app.target).pathname.replace(/\/+$/u, '')
159
+ return values.map((cookie) => {
160
+ const attributes = String(cookie ?? '').split(';').map((item) => item.trim()).filter(Boolean)
161
+ const name = String(attributes[0] ?? '').split('=', 1)[0].trim().toLowerCase()
162
+ // 应用绝不能覆盖或伪造插件的登录/设备凭据。
163
+ if (name.startsWith('dsh-homing-') || name.startsWith('dsh-auth-') || name === 'dsh-entry' || name === 'dsh-device') return null
164
+ const kept = []
165
+ let pathWritten = false
166
+ for (const attribute of attributes) {
167
+ const [key, rawValue] = attribute.split('=', 2)
168
+ if (key.toLowerCase() === 'domain') continue
169
+ if (key.toLowerCase() === 'path') {
170
+ let oldPath = rawValue || '/'
171
+ const publicPrefix = `/apps/${app.id}`
172
+ if (oldPath === publicPrefix || oldPath.startsWith(publicPrefix + '/')) {
173
+ // 已经是公开路径:保留,不能再次添加前缀。
174
+ kept.push(`Path=${oldPath}`)
175
+ pathWritten = true
176
+ continue
177
+ }
178
+ if (base && oldPath === base) oldPath = '/'
179
+ else if (base && oldPath.startsWith(base + '/')) oldPath = oldPath.slice(base.length)
180
+ kept.push(`Path=/apps/${app.id}${oldPath === '/' ? '/' : oldPath}`)
181
+ pathWritten = true
182
+ } else {
183
+ kept.push(attribute)
184
+ }
185
+ }
186
+ if (!pathWritten) kept.push(`Path=/apps/${app.id}/`)
187
+ return kept.join('; ')
188
+ }).filter((cookie) => cookie !== null)
189
+ }
190
+
191
+ export function createLocalAppRegistry({ settingsPath, deniedPorts = () => [] }) {
192
+ let cache = { mtime: -1, apps: [] }
193
+
194
+ function list() {
195
+ let mtime = 0
196
+ try { mtime = fs.statSync(settingsPath).mtimeMs } catch { /* 文件不存在 */ }
197
+ if (mtime !== cache.mtime) cache = { mtime, apps: normalizedList(readSettingsFile(settingsPath), deniedPorts()) }
198
+ return cache.apps.map(cloneApp)
199
+ }
200
+
201
+ function writeApps(apps) {
202
+ const settings = readSettingsFile(settingsPath, { strict: true })
203
+ settings.apps = apps
204
+ fs.mkdirSync(path.dirname(settingsPath), { recursive: true })
205
+ const temp = `${settingsPath}.${process.pid}.tmp`
206
+ fs.writeFileSync(temp, JSON.stringify(settings, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
207
+ fs.renameSync(temp, settingsPath)
208
+ cache = { mtime: fs.statSync(settingsPath).mtimeMs, apps: normalizedList(settings, deniedPorts()) }
209
+ }
210
+
211
+ function save(input) {
212
+ const validated = validateApp(input, deniedPorts())
213
+ if (!validated.ok) return validated
214
+ const id = validated.app.id
215
+ const originalId = normalizeAppId(input.originalId ?? '')
216
+ let raw
217
+ try {
218
+ raw = readSettingsFile(settingsPath, { strict: true })
219
+ } catch {
220
+ return { ok: false, error: 'settings.json 已损坏,未做任何修改;请先修复配置文件' }
221
+ }
222
+ const current = Array.isArray(raw.apps) ? raw.apps.filter((item) => item && typeof item === 'object') : []
223
+ if (current.some((item) => normalizeAppId(item.id) === id && normalizeAppId(item.id) !== originalId)) {
224
+ return { ok: false, error: `应用 ID ${id} 已存在` }
225
+ }
226
+ const index = current.findIndex((item) => normalizeAppId(item.id) === originalId)
227
+ const record = { ...validated.app }
228
+ if (index >= 0) current[index] = record
229
+ else current.push(record)
230
+ try {
231
+ writeApps(current)
232
+ } catch (error) {
233
+ return { ok: false, error: '配置写入失败:' + String(error?.message ?? error).slice(0, 160) }
234
+ }
235
+ return { ok: true, app: cloneApp(record) }
236
+ }
237
+
238
+ function update(id, changes) {
239
+ const existing = list().find((item) => item.id === normalizeAppId(id))
240
+ if (!existing) return { ok: false, error: '应用不存在' }
241
+ return save({ ...existing, ...changes, originalId: existing.id })
242
+ }
243
+
244
+ function remove(id) {
245
+ const normalized = normalizeAppId(id)
246
+ const current = list()
247
+ if (!current.some((item) => item.id === normalized)) return { ok: false, error: '应用不存在' }
248
+ try {
249
+ writeApps(current.filter((item) => item.id !== normalized))
250
+ } catch (error) {
251
+ return { ok: false, error: '配置写入失败:' + String(error?.message ?? error).slice(0, 160) }
252
+ }
253
+ return { ok: true }
254
+ }
255
+
256
+ return { list, save, update, remove }
257
+ }
258
+
259
+ /** 管理页的端口探活;不是完整的应用健康检查,文案必须写“端口可达”。 */
260
+ export function probeAppPort(app, timeoutMs = 500) {
261
+ return new Promise((resolve) => {
262
+ const target = new URL(app.target)
263
+ const socket = net.connect({ host: target.hostname.replace(/^\[|\]$/gu, ''), port: Number(target.port || 80) })
264
+ let settled = false
265
+ const done = (ok) => {
266
+ if (settled) return
267
+ settled = true
268
+ try { socket.destroy() } catch { /* 已关闭 */ }
269
+ resolve(ok)
270
+ }
271
+ socket.once('connect', () => done(true))
272
+ socket.once('error', () => done(false))
273
+ socket.setTimeout(timeoutMs, () => done(false))
274
+ })
275
+ }
package/lib/markdown.mjs CHANGED
@@ -27,7 +27,9 @@ export function escapeHtml(value) {
27
27
  const DANGEROUS_PROTOCOL = /^\s*(?:javascript|data|vbscript|file|blob)\s*:/iu
28
28
 
29
29
  function cleanUrl(raw) {
30
- let url = String(raw ?? '').trim()
30
+ // 唯一调用方 resolveTarget 只会收到正则捕获到的字符串(见 inline 的三处 replace),
31
+ // 因此不需要 nullish 兜底;保留兜底会产生永远不可达的分支。
32
+ let url = String(raw).trim()
31
33
  if (url.startsWith('<') && url.endsWith('>')) url = url.slice(1, -1).trim()
32
34
  if (url === '') return null
33
35
  if (DANGEROUS_PROTOCOL.test(url)) return null
@@ -80,15 +82,15 @@ function inline(text, options) {
80
82
  return token
81
83
  }
82
84
 
83
- let out = String(text ?? '')
85
+ let out = String(text)
84
86
 
85
87
  // 1) 行内代码 `code`
86
88
  out = out.replace(/(`+)([^`]+?)\1/gu, (match, ticks, code) => put('<code>' + escapeHtml(code.trim()) + '</code>'))
87
89
 
88
90
  // 2) 自动链接 <https://...>
89
91
  out = out.replace(/<((?:https?|mailto):[^<>\s]+)>/giu, (match, url) => {
90
- const target = resolveTarget(url, options)
91
- if (target === null) return escapeHtml(match)
92
+ // 正则只放行 https?/mailto,cleanUrl 的危险协议表不含这两个协议,
93
+ // 所以 resolveTarget 必然返回 external,不需要 target === null 的不可达兜底。
92
94
  return put('<a href="' + escapeHtml(url) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(url) + '</a>')
93
95
  })
94
96