@andy.ian/dsh-homing 2.1.14 → 2.2.2

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.
@@ -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
+ }
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
+ }
@@ -3,6 +3,8 @@
3
3
  * 全部服务端渲染 + 原生表单:微信/鸿蒙浏览器里最稳,不依赖任何 JS 框架。
4
4
  */
5
5
 
6
+ import { NAV_CSS, topNav } from './nav.mjs'
7
+
6
8
  const escapeHtml = (value) => String(value ?? '')
7
9
  .replaceAll('&', '&amp;')
8
10
  .replaceAll('<', '&lt;')
@@ -63,12 +65,12 @@ const STYLE = `
63
65
  .md-body a.md-img { border-bottom:0; }
64
66
  `
65
67
 
66
- export function layout({ title, body }) {
68
+ export function layout({ title, body, current = '/files' }) {
67
69
  return `<!doctype html>
68
70
  <html lang="zh-CN"><head><meta charset="utf-8">
69
71
  <meta name="viewport" content="width=device-width, initial-scale=1">
70
72
  <title>${escapeHtml(title)} · DSH 文件</title>
71
- <style>${STYLE}.flist { display: flex; flex-direction: column; }
73
+ <style>${STYLE}${NAV_CSS}.flist { display: flex; flex-direction: column; }
72
74
  .sortbar { display: flex; align-items: center; gap: 6px; padding: 6px 2px 8px; color: #8b93a1; font-size: 12px; }
73
75
  .sortlabel { margin-right: 2px; }
74
76
  .sortbtn { padding: 4px 9px; border-radius: 6px; background: #222833; border: 1px solid #333c48; color: #b9c3d1; font-size: 12px; }
@@ -83,7 +85,7 @@ export function layout({ title, body }) {
83
85
  .fempty { padding: 18px 4px; color: #8b93a1; }
84
86
  .flist .mm { grid-area: menu; }
85
87
  </style></head>
86
- <body><div class="wrap">${body}</div></body></html>`
88
+ <body><div class="wrap">${topNav({ current })}${body}</div></body></html>`
87
89
  }
88
90
 
89
91
  const messageHtml = (message, isError) => (message
@@ -316,11 +318,6 @@ ${entry.dir ? `<a class="mi" role="menuitem" data-act="paste" data-path="${escap
316
318
  <div style="display:flex;align-items:center;gap:8px;flex-wrap:nowrap;min-width:0">
317
319
  <h1 style="margin:0;flex:0 0 auto;font-size:18px">文件</h1>
318
320
  <div style="flex:1 1 auto;display:flex;align-items:center;justify-content:flex-end;gap:4px;flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none">
319
- <a class="btn ghost" href="/" style="${navStyle}">DSH</a>
320
- <a class="btn ghost" href="/term" style="${navStyle}">终端</a>
321
- <a class="btn ghost" href="/remote" style="${navStyle}">窗口</a>
322
- <a class="btn ghost" href="/vnc" style="${navStyle}">桌面</a>
323
- <a class="btn ghost" href="/git?path=${encodeURIComponent(info.path)}" style="${navStyle}">Git</a>
324
321
  <a class="btn ghost" href="/files?path=${encodeURIComponent(home)}" style="${navStyle}">HOME</a>
325
322
  <a class="btn ghost" href="/files?path=${encodeURIComponent(dataDir)}" style="${navStyle}">配置</a>
326
323
  ${parent}
@@ -511,10 +508,6 @@ export function renderGitPage({ repoPath, summary = null, args = '', result = nu
511
508
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">刷新</a>
512
509
  <a class="btn ghost" href="/files?path=${encodeURIComponent(repoPath)}"
513
510
  style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">看文件</a>
514
- <a class="btn ghost" href="/term"
515
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">终端</a>
516
- <a class="btn ghost" href="/"
517
- style="flex:1;text-align:center;padding:10px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;font-size:14px">DSH</a>
518
511
  </div>
519
512
  </div>
520
513
  ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
@@ -561,7 +554,7 @@ export function renderGitPage({ repoPath, summary = null, args = '', result = nu
561
554
  <pre>${escapeHtml(result.output ?? '')}</pre>
562
555
  `}
563
556
  <p class="crumbs">命令只执行 git 本身,不经过 shell;push/pull 用你本机已配置的凭据。</p>`
564
- return layout({ title: 'Git', body })
557
+ return layout({ title: 'Git', body, current: '/git' })
565
558
  }
566
559
 
567
560
  /** 编辑页:textarea + 保存 */
@@ -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
+ }