@andy.ian/dsh-homing 2.1.15 → 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.
- package/README.md +151 -110
- package/SECURITY.md +3 -0
- package/bin/restart-daemon.mjs +0 -0
- package/bin/restart.mjs +0 -0
- package/index.js +200 -301
- package/lib/app-proxy.mjs +262 -0
- package/lib/csrf.mjs +38 -0
- package/lib/local-apps-page.mjs +64 -0
- package/lib/local-apps.mjs +270 -0
- package/lib/mobile-patch.mjs +321 -0
- package/lib/nav.mjs +1 -0
- package/lib/vendor/vnc.bundle.js +189 -73
- package/lib/vnc-app.js +112 -23
- package/lib/vnc-boot.js +1 -1
- package/lib/vnc-page.mjs +34 -4
- package/lib/vnc-probe.mjs +48 -0
- package/lib/window-follow.mjs +66 -0
- package/package.json +2 -2
- package/permissions.json +7 -0
|
@@ -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('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
|
|
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
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** 本地应用管理页:只依赖原生表单,兼容手机浏览器。 */
|
|
2
|
+
import { NAV_CSS, topNav } from './nav.mjs'
|
|
3
|
+
|
|
4
|
+
const escapeHtml = (value) => String(value ?? '')
|
|
5
|
+
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
6
|
+
.replaceAll('"', '"').replaceAll("'", ''')
|
|
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
|
+
}
|
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
return {
|
|
47
|
+
ok: true,
|
|
48
|
+
app: {
|
|
49
|
+
id,
|
|
50
|
+
name,
|
|
51
|
+
target: `${target.protocol}//${target.hostname.includes(':') ? `[${target.hostname}]` : target.hostname}:${port}${basePath}`,
|
|
52
|
+
enabled: input?.enabled !== false,
|
|
53
|
+
// 同源 HTML/JS 默认不受信。只有明确勾选后才允许返回可执行网页内容。
|
|
54
|
+
trusted: input?.trusted === true,
|
|
55
|
+
allowInsecureTls: input?.allowInsecureTls === true && target.protocol === 'https:',
|
|
56
|
+
},
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function cloneApp(app) {
|
|
61
|
+
return app && typeof app === 'object' ? { ...app } : null
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readSettingsFile(file, { strict = false } = {}) {
|
|
65
|
+
try {
|
|
66
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
67
|
+
return value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (strict && fs.existsSync(file)) throw error
|
|
70
|
+
return {}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function normalizedList(raw, deniedPorts = []) {
|
|
75
|
+
const list = Array.isArray(raw?.apps) ? raw.apps : []
|
|
76
|
+
const seen = new Set()
|
|
77
|
+
const result = []
|
|
78
|
+
for (const item of list) {
|
|
79
|
+
if (!item || typeof item !== 'object') continue
|
|
80
|
+
const id = normalizeAppId(item.id)
|
|
81
|
+
if (!APP_ID_RE.test(id) || seen.has(id)) continue
|
|
82
|
+
const app = validateApp({ ...item, id }, deniedPorts)
|
|
83
|
+
if (!app.ok) continue
|
|
84
|
+
seen.add(id)
|
|
85
|
+
result.push(app.app)
|
|
86
|
+
}
|
|
87
|
+
return result
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** URL /apps/<id>/<rest> 的解析;rest 保留原始编码。 */
|
|
91
|
+
export function matchAppPath(pathname, apps) {
|
|
92
|
+
if (pathname === '/apps' || pathname === '/apps/') return { root: true }
|
|
93
|
+
if (!pathname.startsWith('/apps/')) return null
|
|
94
|
+
const tail = pathname.slice('/apps/'.length)
|
|
95
|
+
const slash = tail.indexOf('/')
|
|
96
|
+
const id = normalizeAppId(slash < 0 ? tail : tail.slice(0, slash))
|
|
97
|
+
if (!APP_ID_RE.test(id)) return { invalid: true }
|
|
98
|
+
const rest = slash < 0 ? '' : tail.slice(slash)
|
|
99
|
+
const app = apps.find((item) => item.id === id && item.enabled === true) ?? null
|
|
100
|
+
return { id, app, rest }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function upstreamPath(app, rest, search = '') {
|
|
104
|
+
const base = new URL(app.target).pathname.replace(/\/+$/u, '')
|
|
105
|
+
return (base || '') + (rest || '/') + (search || '')
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function publicPathFromTarget(pathname, app) {
|
|
109
|
+
const base = new URL(app.target).pathname.replace(/\/+$/u, '')
|
|
110
|
+
let rest = String(pathname || '/')
|
|
111
|
+
if (base && rest === base) rest = '/'
|
|
112
|
+
else if (base && rest.startsWith(base + '/')) rest = rest.slice(base.length)
|
|
113
|
+
if (!rest.startsWith('/')) rest = '/' + rest
|
|
114
|
+
return `/apps/${app.id}${rest}`
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 将上游 Location 映射回公开前缀。
|
|
119
|
+
* rest 是本次请求的上游相对路径,用于正确解析 Location: next 这类相对地址。
|
|
120
|
+
*/
|
|
121
|
+
export function rewriteLocation(value, app, rest = '/') {
|
|
122
|
+
if (typeof value !== 'string' || value === '') return value
|
|
123
|
+
const prefix = `/apps/${app.id}`
|
|
124
|
+
if (value === prefix || value.startsWith(prefix + '/') || value.startsWith(prefix + '?') || value.startsWith(prefix + '#')) return value
|
|
125
|
+
try {
|
|
126
|
+
const source = new URL(app.target)
|
|
127
|
+
const current = source.origin + upstreamPath(app, rest)
|
|
128
|
+
const location = new URL(value, current)
|
|
129
|
+
if (location.origin !== source.origin) return value
|
|
130
|
+
if (location.pathname === prefix || location.pathname.startsWith(prefix + '/')) {
|
|
131
|
+
return location.pathname + location.search + location.hash
|
|
132
|
+
}
|
|
133
|
+
return publicPathFromTarget(location.pathname, app) + location.search + location.hash
|
|
134
|
+
} catch {
|
|
135
|
+
return value
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Cookie 必须按应用隔离;同时不允许把插件会话 Cookie 发给本地服务。 */
|
|
140
|
+
export function scrubPluginCookies(header) {
|
|
141
|
+
const parts = String(header ?? '').split(';').map((item) => item.trim()).filter(Boolean)
|
|
142
|
+
return parts.filter((item) => {
|
|
143
|
+
const name = item.split('=', 1)[0].trim().toLowerCase()
|
|
144
|
+
return !name.startsWith('dsh-homing-')
|
|
145
|
+
&& !name.startsWith('dsh-auth-')
|
|
146
|
+
&& name !== 'dsh-entry'
|
|
147
|
+
&& name !== 'dsh-device'
|
|
148
|
+
}).join('; ')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function rewriteSetCookie(value, app) {
|
|
152
|
+
const values = Array.isArray(value) ? value : [value]
|
|
153
|
+
const base = new URL(app.target).pathname.replace(/\/+$/u, '')
|
|
154
|
+
return values.map((cookie) => {
|
|
155
|
+
const attributes = String(cookie ?? '').split(';').map((item) => item.trim()).filter(Boolean)
|
|
156
|
+
const name = String(attributes[0] ?? '').split('=', 1)[0].trim().toLowerCase()
|
|
157
|
+
// 应用绝不能覆盖或伪造插件的登录/设备凭据。
|
|
158
|
+
if (name.startsWith('dsh-homing-') || name.startsWith('dsh-auth-') || name === 'dsh-entry' || name === 'dsh-device') return null
|
|
159
|
+
const kept = []
|
|
160
|
+
let pathWritten = false
|
|
161
|
+
for (const attribute of attributes) {
|
|
162
|
+
const [key, rawValue] = attribute.split('=', 2)
|
|
163
|
+
if (key.toLowerCase() === 'domain') continue
|
|
164
|
+
if (key.toLowerCase() === 'path') {
|
|
165
|
+
let oldPath = rawValue || '/'
|
|
166
|
+
const publicPrefix = `/apps/${app.id}`
|
|
167
|
+
if (oldPath === publicPrefix || oldPath.startsWith(publicPrefix + '/')) {
|
|
168
|
+
// 已经是公开路径:保留,不能再次添加前缀。
|
|
169
|
+
kept.push(`Path=${oldPath}`)
|
|
170
|
+
pathWritten = true
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
if (base && oldPath === base) oldPath = '/'
|
|
174
|
+
else if (base && oldPath.startsWith(base + '/')) oldPath = oldPath.slice(base.length)
|
|
175
|
+
kept.push(`Path=/apps/${app.id}${oldPath === '/' ? '/' : oldPath}`)
|
|
176
|
+
pathWritten = true
|
|
177
|
+
} else {
|
|
178
|
+
kept.push(attribute)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!pathWritten) kept.push(`Path=/apps/${app.id}/`)
|
|
182
|
+
return kept.join('; ')
|
|
183
|
+
}).filter((cookie) => cookie !== null)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export function createLocalAppRegistry({ settingsPath, deniedPorts = () => [] }) {
|
|
187
|
+
let cache = { mtime: -1, apps: [] }
|
|
188
|
+
|
|
189
|
+
function list() {
|
|
190
|
+
let mtime = 0
|
|
191
|
+
try { mtime = fs.statSync(settingsPath).mtimeMs } catch { /* 文件不存在 */ }
|
|
192
|
+
if (mtime !== cache.mtime) cache = { mtime, apps: normalizedList(readSettingsFile(settingsPath), deniedPorts()) }
|
|
193
|
+
return cache.apps.map(cloneApp)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function writeApps(apps) {
|
|
197
|
+
const settings = readSettingsFile(settingsPath, { strict: true })
|
|
198
|
+
settings.apps = apps
|
|
199
|
+
fs.mkdirSync(path.dirname(settingsPath), { recursive: true })
|
|
200
|
+
const temp = `${settingsPath}.${process.pid}.tmp`
|
|
201
|
+
fs.writeFileSync(temp, JSON.stringify(settings, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
202
|
+
fs.renameSync(temp, settingsPath)
|
|
203
|
+
cache = { mtime: fs.statSync(settingsPath).mtimeMs, apps: normalizedList(settings, deniedPorts()) }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function save(input) {
|
|
207
|
+
const validated = validateApp(input, deniedPorts())
|
|
208
|
+
if (!validated.ok) return validated
|
|
209
|
+
const id = validated.app.id
|
|
210
|
+
const originalId = normalizeAppId(input.originalId ?? '')
|
|
211
|
+
let raw
|
|
212
|
+
try {
|
|
213
|
+
raw = readSettingsFile(settingsPath, { strict: true })
|
|
214
|
+
} catch {
|
|
215
|
+
return { ok: false, error: 'settings.json 已损坏,未做任何修改;请先修复配置文件' }
|
|
216
|
+
}
|
|
217
|
+
const current = Array.isArray(raw.apps) ? raw.apps.filter((item) => item && typeof item === 'object') : []
|
|
218
|
+
if (current.some((item) => normalizeAppId(item.id) === id && normalizeAppId(item.id) !== originalId)) {
|
|
219
|
+
return { ok: false, error: `应用 ID ${id} 已存在` }
|
|
220
|
+
}
|
|
221
|
+
const index = current.findIndex((item) => normalizeAppId(item.id) === originalId)
|
|
222
|
+
const record = { ...validated.app }
|
|
223
|
+
if (index >= 0) current[index] = record
|
|
224
|
+
else current.push(record)
|
|
225
|
+
try {
|
|
226
|
+
writeApps(current)
|
|
227
|
+
} catch (error) {
|
|
228
|
+
return { ok: false, error: '配置写入失败:' + String(error?.message ?? error).slice(0, 160) }
|
|
229
|
+
}
|
|
230
|
+
return { ok: true, app: cloneApp(record) }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function update(id, changes) {
|
|
234
|
+
const existing = list().find((item) => item.id === normalizeAppId(id))
|
|
235
|
+
if (!existing) return { ok: false, error: '应用不存在' }
|
|
236
|
+
return save({ ...existing, ...changes, originalId: existing.id })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function remove(id) {
|
|
240
|
+
const normalized = normalizeAppId(id)
|
|
241
|
+
const current = list()
|
|
242
|
+
if (!current.some((item) => item.id === normalized)) return { ok: false, error: '应用不存在' }
|
|
243
|
+
try {
|
|
244
|
+
writeApps(current.filter((item) => item.id !== normalized))
|
|
245
|
+
} catch (error) {
|
|
246
|
+
return { ok: false, error: '配置写入失败:' + String(error?.message ?? error).slice(0, 160) }
|
|
247
|
+
}
|
|
248
|
+
return { ok: true }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return { list, save, update, remove }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 管理页的端口探活;不是完整的应用健康检查,文案必须写“端口可达”。 */
|
|
255
|
+
export function probeAppPort(app, timeoutMs = 500) {
|
|
256
|
+
return new Promise((resolve) => {
|
|
257
|
+
const target = new URL(app.target)
|
|
258
|
+
const socket = net.connect({ host: target.hostname.replace(/^\[|\]$/gu, ''), port: Number(target.port || 80) })
|
|
259
|
+
let settled = false
|
|
260
|
+
const done = (ok) => {
|
|
261
|
+
if (settled) return
|
|
262
|
+
settled = true
|
|
263
|
+
try { socket.destroy() } catch { /* 已关闭 */ }
|
|
264
|
+
resolve(ok)
|
|
265
|
+
}
|
|
266
|
+
socket.once('connect', () => done(true))
|
|
267
|
+
socket.once('error', () => done(false))
|
|
268
|
+
socket.setTimeout(timeoutMs, () => done(false))
|
|
269
|
+
})
|
|
270
|
+
}
|