@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.
- 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 +213 -311
- package/lib/app-proxy.mjs +262 -0
- package/lib/csrf.mjs +38 -0
- package/lib/files-page.mjs +6 -13
- 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 +44 -0
- package/lib/term-page.mjs +4 -6
- 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 +38 -9
- package/lib/vnc-probe.mjs +48 -0
- package/lib/window-follow.mjs +66 -0
- package/lib/window-page.mjs +4 -5
- package/package.json +2 -2
- package/permissions.json +7 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 手机端补丁:index.js 把它注入到 DSH 页面(/dsh_homing/mobile.js、mobile.css)。
|
|
3
|
+
*
|
|
4
|
+
* 只做「手机上明显做不到、或做了也白做」的事:
|
|
5
|
+
* - 页头「文件夹 + 小箭头」分体按钮 = 在 DSH 那台电脑上打开工作区目录。
|
|
6
|
+
* 你人不在那台电脑前,手机上点它只会收到「已在其它设备打开」,什么也看不到;
|
|
7
|
+
* 这里统一接到本插件的文件页 /files。
|
|
8
|
+
* - 应用菜单里只能在电脑上启动的项(资源管理器 / VS Code / Git Bash / 终端)
|
|
9
|
+
* 同样接到对应网页(文件页 / 终端页)。
|
|
10
|
+
* - 窄屏自动收起右侧栏、记住最后点过的工作区、上报活跃信标。
|
|
11
|
+
*
|
|
12
|
+
* 定位按钮不靠易变的 class 名:优先用 DSH 的稳定标记 data-open-target,
|
|
13
|
+
* 老版本没有标记时退回结构判断。细节见下面 splitHost 的注释。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
|
|
17
|
+
@media (max-width: 760px) {
|
|
18
|
+
[class*="_frame"] { min-width: 0; }
|
|
19
|
+
}
|
|
20
|
+
`;
|
|
21
|
+
|
|
22
|
+
export const MOBILE_JS = String.raw`(() => {
|
|
23
|
+
const narrow = () => window.innerWidth <= 760
|
|
24
|
+
// 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
|
|
25
|
+
// 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
|
|
26
|
+
const LAST_WS_KEY = 'dsh-homing:last-workspace'
|
|
27
|
+
document.addEventListener('click', (event) => {
|
|
28
|
+
const node = event.target
|
|
29
|
+
if (node === null || typeof node.closest !== 'function') return
|
|
30
|
+
const item = node.closest('[role="menuitem"]')
|
|
31
|
+
const side = node.closest('[class*="sidebarCol"]')
|
|
32
|
+
const candidate = item ?? (side === null ? null : node.closest('button, [role="treeitem"], [class*="session"], [class*="item"], div'))
|
|
33
|
+
if (candidate === null) return
|
|
34
|
+
const text = (candidate.textContent || '').replace(/\s+/g, ' ').trim()
|
|
35
|
+
if (text === '' || text.length > 40) return
|
|
36
|
+
// 排除操作类菜单项,只记看起来像工作区名字的
|
|
37
|
+
if (/文件资源管理器|VS Code|Git Bash|添加工作区|新会话|搜索|设置|插件|自动化任务|更多|账号|退出/u.test(text)) return
|
|
38
|
+
try { window.localStorage.setItem(LAST_WS_KEY, text) } catch { /* 隐私模式 */ }
|
|
39
|
+
}, true)
|
|
40
|
+
|
|
41
|
+
// 当前会话标题:从标题栏(页面顶部、class 里带 title/tab/header 的元素)取最长的文本。
|
|
42
|
+
// 用它去反查会话记录里的 cwd,就能打开"当前会话所属工作区"的目录。
|
|
43
|
+
const currentSessionTitle = () => {
|
|
44
|
+
let best = ''
|
|
45
|
+
for (const node of document.querySelectorAll('div, span, h1, h2, header')) {
|
|
46
|
+
const rect = node.getBoundingClientRect()
|
|
47
|
+
if (rect.width === 0 || rect.height === 0) continue
|
|
48
|
+
if (rect.top > 120 || rect.height > 44) continue
|
|
49
|
+
const cls = String(node.className || '')
|
|
50
|
+
if (!/title|tab|header|crumb|label/iu.test(cls)) continue
|
|
51
|
+
const text = (node.textContent || '').trim()
|
|
52
|
+
if (text.length < 2 || text.length > 60) continue
|
|
53
|
+
if (text.length > best.length) best = text
|
|
54
|
+
}
|
|
55
|
+
return best
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// 应用把"当前会话"存在 localStorage 里,直接读它 —— 这是确定值,不靠猜。
|
|
59
|
+
const currentSessionId = () => {
|
|
60
|
+
try {
|
|
61
|
+
const raw = window.localStorage.getItem('dsh.sessions.current')
|
|
62
|
+
if (raw === null) return ''
|
|
63
|
+
const parsed = JSON.parse(raw)
|
|
64
|
+
const id = parsed && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
|
|
65
|
+
return /^session-[A-Za-z0-9-]+$/u.test(id) ? id : ''
|
|
66
|
+
} catch {
|
|
67
|
+
return ''
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const goFiles = () => {
|
|
72
|
+
const session = currentSessionId()
|
|
73
|
+
if (session !== '') {
|
|
74
|
+
window.location.href = '/files?session=' + encodeURIComponent(session)
|
|
75
|
+
return
|
|
76
|
+
}
|
|
77
|
+
let hint = ''
|
|
78
|
+
try { hint = currentSessionTitle() || window.localStorage.getItem(LAST_WS_KEY) || '' } catch { hint = '' }
|
|
79
|
+
window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/* ---------- 页头「文件夹 + 小箭头」分体按钮 ----------
|
|
83
|
+
* 它做的事是在 DSH 所在的电脑上启动程序(资源管理器 / VS Code / Git Bash)。
|
|
84
|
+
* 手机上没有那台电脑的屏幕,点了只会收到「已在其它设备打开」——纯噪音。
|
|
85
|
+
* 这里把它(主按钮和小箭头都算)接到文件页 /files。
|
|
86
|
+
*
|
|
87
|
+
* 定位必须稳:页头里还有子智能体面板、更多菜单等 aria-haspopup 控件,而且
|
|
88
|
+
* 它们排在分体按钮前面。「找第一个 aria-haspopup 的父容器」会认成子智能体
|
|
89
|
+
* 那个容器,于是点分体按钮时判定不命中、补丁失效(手机端历史 bug)。
|
|
90
|
+
* 所以:
|
|
91
|
+
* 1. 优先用 DSH 的稳定标记 data-open-target="directory"(分体按钮容器);
|
|
92
|
+
* 2. 老版本没有标记时退回结构判断 —— 同一容器里恰好两个按钮,一个带
|
|
93
|
+
* aria-haspopup="menu"(小箭头),另一个是纯图标主按钮(里面是应用图标)。
|
|
94
|
+
*/
|
|
95
|
+
const splitHost = (node) => {
|
|
96
|
+
if (node === null || node === undefined || typeof node.closest !== 'function') return null
|
|
97
|
+
const marked = node.closest('[data-open-target="directory"]')
|
|
98
|
+
if (marked !== null) return marked
|
|
99
|
+
const button = node.closest('button, [role="button"]')
|
|
100
|
+
if (button === null) return null
|
|
101
|
+
const host = button.parentElement
|
|
102
|
+
if (host === null) return null
|
|
103
|
+
const buttons = host.querySelectorAll('button, [role="button"]')
|
|
104
|
+
if (buttons.length !== 2) return null
|
|
105
|
+
let main = null
|
|
106
|
+
let chevron = null
|
|
107
|
+
for (const item of buttons) {
|
|
108
|
+
if (item.hasAttribute('aria-haspopup')) chevron = item
|
|
109
|
+
else main = item
|
|
110
|
+
}
|
|
111
|
+
if (main === null || chevron === null) return null
|
|
112
|
+
if (chevron.getAttribute('aria-haspopup') !== 'menu') return null
|
|
113
|
+
if ((main.textContent || '').trim() !== '') return null
|
|
114
|
+
if (main.querySelector('img, svg') === null) return null
|
|
115
|
+
const rect = chevron.getBoundingClientRect()
|
|
116
|
+
if (rect.width === 0 || rect.height === 0) return null
|
|
117
|
+
if (rect.top > 200) return null
|
|
118
|
+
return host
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
document.addEventListener('click', (event) => {
|
|
122
|
+
const node = event.target
|
|
123
|
+
if (node === null || typeof node.closest !== 'function') return
|
|
124
|
+
const host = splitHost(node)
|
|
125
|
+
if (host === null) return
|
|
126
|
+
event.preventDefault()
|
|
127
|
+
event.stopPropagation()
|
|
128
|
+
goFiles()
|
|
129
|
+
}, true)
|
|
130
|
+
|
|
131
|
+
/* ---------- 只能在本机启动的菜单项 ----------
|
|
132
|
+
* 应用下拉里的「文件资源管理器 / VS Code / Git Bash / 终端」全是在 DSH 那台
|
|
133
|
+
* 电脑上启动桌面程序。这里接到对应网页:文件类 → /files,终端类 → /term。
|
|
134
|
+
* 只在 role=menuitem / role=option 上生效,避免误伤正文里的同名文字。
|
|
135
|
+
*/
|
|
136
|
+
const openFilesFromMenu = (item) => {
|
|
137
|
+
// 尽量从属性里挖工作区路径,挖不到就让文件页自己决定默认目录
|
|
138
|
+
let target = ''
|
|
139
|
+
for (const holder of [item, ...(item.querySelectorAll('[data-path], [title]') || [])]) {
|
|
140
|
+
if (holder === null) continue
|
|
141
|
+
const dataPath = holder.getAttribute && holder.getAttribute('data-path')
|
|
142
|
+
const title = holder.getAttribute && holder.getAttribute('title')
|
|
143
|
+
if (dataPath) { target = dataPath; break }
|
|
144
|
+
if (title && /^[A-Za-z]:[\\/]|^\//u.test(title)) { target = title; break }
|
|
145
|
+
}
|
|
146
|
+
// 带上最后选中的工作区名,服务端会映射成路径;映射不到就落到默认工作区
|
|
147
|
+
let remembered = ''
|
|
148
|
+
try { remembered = window.localStorage.getItem(LAST_WS_KEY) || '' } catch { /* 隐私模式 */ }
|
|
149
|
+
const selected = remembered !== '' ? remembered : (() => {
|
|
150
|
+
const side = document.querySelector('[class*="sidebarCol"]')
|
|
151
|
+
if (side === null) return ''
|
|
152
|
+
let best = ''
|
|
153
|
+
for (const node of side.querySelectorAll('[class*="selected"], [class*="active"], [aria-current]')) {
|
|
154
|
+
const text = (node.textContent || '').trim()
|
|
155
|
+
if (text === '' || text.length > 40) continue
|
|
156
|
+
if (best === '' || text.length < best.length) best = text
|
|
157
|
+
}
|
|
158
|
+
return best
|
|
159
|
+
})()
|
|
160
|
+
const session = currentSessionId()
|
|
161
|
+
const query = target ? '?path=' + encodeURIComponent(target)
|
|
162
|
+
: session !== '' ? '?session=' + encodeURIComponent(session)
|
|
163
|
+
: '?hint=' + encodeURIComponent(currentSessionTitle() || selected || '')
|
|
164
|
+
window.location.href = '/files' + query
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const openTermFromMenu = () => {
|
|
168
|
+
const session = currentSessionId()
|
|
169
|
+
window.location.href = '/term' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
document.addEventListener('click', (event) => {
|
|
173
|
+
const node = event.target
|
|
174
|
+
if (node === null || typeof node.closest !== 'function') return
|
|
175
|
+
const item = node.closest('[role="menuitem"], [role="option"]')
|
|
176
|
+
if (item === null) return
|
|
177
|
+
const text = (item.textContent || '').replace(/\s+/g, ' ').trim()
|
|
178
|
+
if (text === '' || text.length > 60) return
|
|
179
|
+
if (/文件资源管理器|文件管理器|访达|显示文件位置|在文件夹显示|在访达显示|VS Code|Visual Studio Code/u.test(text)) {
|
|
180
|
+
event.preventDefault()
|
|
181
|
+
event.stopPropagation()
|
|
182
|
+
openFilesFromMenu(item)
|
|
183
|
+
return
|
|
184
|
+
}
|
|
185
|
+
if (/Git Bash|终端|Terminal|PowerShell|命令提示符/u.test(text)) {
|
|
186
|
+
event.preventDefault()
|
|
187
|
+
event.stopPropagation()
|
|
188
|
+
openTermFromMenu()
|
|
189
|
+
}
|
|
190
|
+
}, true)
|
|
191
|
+
|
|
192
|
+
let lastRight = 0
|
|
193
|
+
const closeRightBar = () => {
|
|
194
|
+
if (!narrow()) return
|
|
195
|
+
if (document.querySelector('[data-rightbar-collapsed="false"]') === null) return
|
|
196
|
+
if (Date.now() - lastRight < 2500) return
|
|
197
|
+
const button = document.querySelector('[aria-label="收起右侧边栏"]')
|
|
198
|
+
if (button === null) return
|
|
199
|
+
lastRight = Date.now()
|
|
200
|
+
button.click()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const start = () => {
|
|
204
|
+
closeRightBar()
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/* ---------- SESSION_MENU_ITEMS ----------
|
|
208
|
+
* 在 DSH 会话「…」菜单里追加两项:
|
|
209
|
+
* - 下载工作区文件:跳到文件页(可逐个文件下载)
|
|
210
|
+
* - 重启 DSH / 守护进程:跳到重启页
|
|
211
|
+
* 做法:复制一个原生菜单项(连同图标容器与样式),只替换文字和图标路径;
|
|
212
|
+
* 每轮先清掉旧项,并全局 prune,保证每项最多一个。
|
|
213
|
+
*/
|
|
214
|
+
const MENU_HINT = /下载 Session 日志|复制会话为 Markdown|反馈/u
|
|
215
|
+
const ICON_RESTART = '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>'
|
|
216
|
+
const ICON_DOWNLOAD = '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/>'
|
|
217
|
+
let menuTimer = null
|
|
218
|
+
|
|
219
|
+
const textNodeMatching = (node, pattern) => {
|
|
220
|
+
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)
|
|
221
|
+
for (let current = walker.nextNode(); current !== null; current = walker.nextNode()) {
|
|
222
|
+
if (pattern.test(current.nodeValue || '')) return current
|
|
223
|
+
}
|
|
224
|
+
return null
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const buildMenuItem = (template, label, icon, action) => {
|
|
228
|
+
const link = template.cloneNode(true)
|
|
229
|
+
link.setAttribute('role', 'menuitem')
|
|
230
|
+
link.setAttribute('href', '#')
|
|
231
|
+
link.style.textDecoration = 'none'
|
|
232
|
+
const textNode = textNodeMatching(link, /反馈|下载 Session 日志|复制会话为 Markdown/u)
|
|
233
|
+
if (textNode !== null) textNode.nodeValue = label
|
|
234
|
+
else link.textContent = label
|
|
235
|
+
const svg = link.querySelector('svg')
|
|
236
|
+
if (svg !== null) {
|
|
237
|
+
svg.innerHTML = icon
|
|
238
|
+
svg.setAttribute('viewBox', '0 0 24 24')
|
|
239
|
+
svg.setAttribute('fill', 'none')
|
|
240
|
+
svg.setAttribute('stroke', 'currentColor')
|
|
241
|
+
svg.setAttribute('stroke-width', '2')
|
|
242
|
+
svg.setAttribute('stroke-linecap', 'round')
|
|
243
|
+
svg.setAttribute('stroke-linejoin', 'round')
|
|
244
|
+
}
|
|
245
|
+
link.addEventListener('click', (event) => {
|
|
246
|
+
event.preventDefault()
|
|
247
|
+
event.stopPropagation()
|
|
248
|
+
action()
|
|
249
|
+
}, true)
|
|
250
|
+
return link
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const enhanceMenus = () => {
|
|
254
|
+
const done = new Set()
|
|
255
|
+
for (const item of document.querySelectorAll('[role="menuitem"]')) {
|
|
256
|
+
const menu = item.closest('[role="menu"]') ?? item.parentElement
|
|
257
|
+
if (menu === null || done.has(menu)) continue
|
|
258
|
+
if (!MENU_HINT.test(menu.textContent || '')) continue
|
|
259
|
+
done.add(menu)
|
|
260
|
+
|
|
261
|
+
for (const old of menu.querySelectorAll('[data-dsh-homing-download],[data-dsh-homing-restart]')) old.remove()
|
|
262
|
+
|
|
263
|
+
const items = [...menu.querySelectorAll('[role="menuitem"]')]
|
|
264
|
+
const template = items.find((node) => node.querySelector('svg')) ?? items[0]
|
|
265
|
+
if (!template) continue
|
|
266
|
+
|
|
267
|
+
const download = buildMenuItem(template, '下载工作区文件', ICON_DOWNLOAD, () => goFiles())
|
|
268
|
+
download.setAttribute('data-dsh-homing-download', '1')
|
|
269
|
+
const restart = buildMenuItem(template, '重启 DSH / 守护进程', ICON_RESTART, () => window.location.assign('/dsh_homing/restart'))
|
|
270
|
+
restart.setAttribute('data-dsh-homing-restart', '1')
|
|
271
|
+
|
|
272
|
+
menu.appendChild(download)
|
|
273
|
+
menu.appendChild(restart)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// 兜底:无论菜单容器怎么嵌套,每类最多保留一个
|
|
278
|
+
const pruneMenuItems = () => {
|
|
279
|
+
for (const selector of ['[data-dsh-homing-download]', '[data-dsh-homing-restart]']) {
|
|
280
|
+
const all = [...document.querySelectorAll(selector)]
|
|
281
|
+
for (let i = 0; i < all.length - 1; i += 1) all[i].remove()
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const menuObserver = new MutationObserver(() => {
|
|
286
|
+
if (menuTimer) return
|
|
287
|
+
menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
|
|
288
|
+
})
|
|
289
|
+
menuObserver.observe(document.body, { childList: true, subtree: true })
|
|
290
|
+
|
|
291
|
+
/* ---------- ALIVE_BEACON ----------
|
|
292
|
+
* 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
|
|
293
|
+
* 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
|
|
294
|
+
* 节流 2 秒,页面隐藏时不发(后台标签页不算活跃)。
|
|
295
|
+
*/
|
|
296
|
+
const ALIVE_INTERVAL = 2000
|
|
297
|
+
let aliveAt = 0
|
|
298
|
+
const alive = () => {
|
|
299
|
+
const now = Date.now()
|
|
300
|
+
if (now - aliveAt < ALIVE_INTERVAL) return
|
|
301
|
+
aliveAt = now
|
|
302
|
+
try {
|
|
303
|
+
if (document.visibilityState === 'hidden') return
|
|
304
|
+
const body = JSON.stringify({ at: now, path: location.pathname })
|
|
305
|
+
if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
|
|
306
|
+
else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
|
|
307
|
+
} catch (error) {
|
|
308
|
+
/* 忽略 */
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
document.addEventListener('keydown', alive, true)
|
|
312
|
+
document.addEventListener('pointerdown', alive, true)
|
|
313
|
+
document.addEventListener('input', alive, true)
|
|
314
|
+
document.addEventListener('compositionstart', alive, true)
|
|
315
|
+
window.addEventListener('focus', alive, true)
|
|
316
|
+
|
|
317
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
|
|
318
|
+
else start()
|
|
319
|
+
})();
|
|
320
|
+
|
|
321
|
+
`;
|
package/lib/nav.mjs
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 插件内所有页面共用的顶部导航。
|
|
3
|
+
*
|
|
4
|
+
* 目标:无论从哪个页面(文件 / Git / 终端 / 窗口 / 桌面 / 调试 / 账户 / 登录…)
|
|
5
|
+
* 都能一眼看到并一键回到 DSH 主页。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const NAV_CSS = `
|
|
9
|
+
.dsh-topnav { display:flex; gap:6px; overflow-x:auto; white-space:nowrap; align-items:center;
|
|
10
|
+
padding:8px 10px; margin:0 0 10px; background:#141920; border-bottom:1px solid #262b35;
|
|
11
|
+
position:sticky; top:0; z-index:30; -webkit-overflow-scrolling:touch; }
|
|
12
|
+
.dsh-topnav::-webkit-scrollbar { display:none; }
|
|
13
|
+
.dsh-topnav a { flex:0 0 auto; padding:7px 11px; border-radius:8px; background:#222833;
|
|
14
|
+
border:1px solid #333c48; color:#c7cdd8; text-decoration:none; font-size:13px; line-height:1.2; }
|
|
15
|
+
.dsh-topnav a:hover { background:#2c3442; }
|
|
16
|
+
.dsh-topnav a.home { background:#2f4b8f; border-color:#3f63b8; color:#fff; font-weight:600; }
|
|
17
|
+
.dsh-topnav .spacer { flex:1 1 auto; }
|
|
18
|
+
`
|
|
19
|
+
|
|
20
|
+
const LINKS = [
|
|
21
|
+
['/', '← 返回 DSH', 'home'],
|
|
22
|
+
['/files', '文件', ''],
|
|
23
|
+
['/git', 'Git', ''],
|
|
24
|
+
['/term', '终端', ''],
|
|
25
|
+
['/remote', '窗口', ''],
|
|
26
|
+
['/vnc', '桌面', ''],
|
|
27
|
+
['/dsh_homing/apps', '应用', ''],
|
|
28
|
+
['/debug', '调试', ''],
|
|
29
|
+
['/dsh_homing/account', '账户', ''],
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 顶部导航 HTML。
|
|
34
|
+
* @param {{ current?: string }} [options] current 可选:/files 等,用于高亮
|
|
35
|
+
*/
|
|
36
|
+
export function topNav({ current = '' } = {}) {
|
|
37
|
+
const items = LINKS.map(([href, label, cls]) => {
|
|
38
|
+
const active = current !== '' && href === current
|
|
39
|
+
const classes = [cls, active ? 'active' : ''].filter(Boolean).join(' ')
|
|
40
|
+
const style = active ? ' style="background:#3a4658;color:#fff"' : ''
|
|
41
|
+
return '<a class="' + classes + '" href="' + href + '"' + style + '>' + label + '</a>'
|
|
42
|
+
}).join('')
|
|
43
|
+
return '<nav class="dsh-topnav">' + items + '</nav>'
|
|
44
|
+
}
|
package/lib/term-page.mjs
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
* 为了满足 CSP(不引外网脚本),xterm.js / xterm.css 都从本地 /term/vendor/ 提供,
|
|
9
9
|
* 页面自身的脚本也从 /term/app.js 单独加载(不在 HTML 里内联)。
|
|
10
10
|
*/
|
|
11
|
+
import { NAV_CSS, topNav } from './nav.mjs'
|
|
12
|
+
|
|
11
13
|
const escapeHtml = (value) => String(value ?? '')
|
|
12
14
|
.replaceAll('&', '&')
|
|
13
15
|
.replaceAll('<', '<')
|
|
@@ -83,15 +85,11 @@ export function renderTermPage({ cwd = '', host = '', user = '', connected = tru
|
|
|
83
85
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
84
86
|
<title>终端 · DSH</title>
|
|
85
87
|
<link rel="stylesheet" href="/term/vendor/xterm.css">
|
|
86
|
-
<style>${STYLE}</style>
|
|
88
|
+
<style>${STYLE}${NAV_CSS}</style>
|
|
87
89
|
</head>
|
|
88
90
|
<body>
|
|
91
|
+
${topNav({ current: '/term' })}
|
|
89
92
|
<div class="bar">
|
|
90
|
-
<a href="/">DSH</a>
|
|
91
|
-
<a href="/files?path=${encodeURIComponent(cwd)}">文件</a>
|
|
92
|
-
<a href="/git?path=${encodeURIComponent(cwd)}">Git</a>
|
|
93
|
-
<a href="/remote">窗口</a>
|
|
94
|
-
<a href="/vnc">桌面</a>
|
|
95
93
|
${shells.length > 0 ? `<form method="post" action="/term/shell" class="shellpick" style="display:flex;gap:4px;align-items:center;margin:0">
|
|
96
94
|
<select name="shell" aria-label="终端类型" style="max-width:130px;padding:2px 4px;border-radius:5px;border:1px solid #333;background:#232323;color:#cfcfcf;font:inherit;font-size:11px">
|
|
97
95
|
${shellOptions}
|