@andy.ian/dsh-homing 2.2.2 → 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.
- package/index.js +713 -309
- package/lib/app-proxy.mjs +1 -1
- package/lib/auth-guard.js +57 -0
- package/lib/client-report.js +168 -0
- package/lib/compress.mjs +3 -2
- package/lib/debug-page.js +150 -0
- package/lib/exec-path.mjs +9 -1
- package/lib/files-page.mjs +3 -3
- package/lib/files.mjs +14 -15
- package/lib/format-age.mjs +32 -0
- package/lib/git.mjs +37 -19
- package/lib/idb-fallback.js +140 -0
- package/lib/local-apps.mjs +9 -4
- package/lib/markdown.mjs +6 -4
- package/lib/mobile-patch.mjs +109 -1
- package/lib/netdiag.js +211 -0
- package/lib/node-runtime.mjs +30 -13
- package/lib/office.mjs +42 -20
- package/lib/orientation.mjs +88 -53
- package/lib/pty.mjs +2 -9
- package/lib/recover.js +66 -0
- package/lib/secret.mjs +25 -9
- package/lib/shells.mjs +2 -2
- package/lib/vnc-auth-proxy.mjs +5 -2
- package/lib/vnc-keyboard.mjs +3 -3
- package/lib/vnc-probe.mjs +8 -10
- package/lib/window-remote.mjs +266 -192
- package/lib/ws-bridge.mjs +6 -3
- package/package.json +1 -1
- package/restart/client.mjs +20 -1
- package/restart/daemon/README.md +22 -0
- package/restart/daemon/lib/detach.mjs +11 -5
- package/restart/daemon/lib/restart-flow.mjs +26 -12
- package/restart/daemon/lib/update-state.mjs +118 -1
- package/restart/daemon/main.mjs +68 -20
- package/restart/runner.mjs +9 -5
- package/restart/service.mjs +4 -3
- package/restart/watchdog.mjs +8 -2
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IndexedDB 兜底(保险机制,2026-11-15)
|
|
3
|
+
*
|
|
4
|
+
* 背景:华为浏览器(ArkWeb)上观察到存储类 API 会**不回调**——
|
|
5
|
+
* caches.keys()、navigator.serviceWorker.getRegistrations() 实测超时返回 null。
|
|
6
|
+
* 排查首页卡死时曾经怀疑「IndexedDB open 挂死」,但后来证伪:
|
|
7
|
+
* 同一时刻 Aira 的 idb-probe 也超时,而它的应用照常加载;
|
|
8
|
+
* 最终确定首页卡死的真实原因是「缓存的旧页面壳」+「插件说明符无法解析」,
|
|
9
|
+
* 与 IndexedDB 无关(本兜底在修复后一次都没触发过)。
|
|
10
|
+
*
|
|
11
|
+
* 之所以仍然保留:如果用户环境里 IndexedDB 真的挂住(同一类 API 不回调的现象确实存在),
|
|
12
|
+
* 应用就会永远等下去。这里在 8 秒无回调时降级到内存实现,把「死等」变成「能启动」。
|
|
13
|
+
*
|
|
14
|
+
* 触发条件极窄,正常浏览器完全不受影响:先走真实实现,只有它一个回调都不给时才接管。
|
|
15
|
+
*/
|
|
16
|
+
(() => {
|
|
17
|
+
if (typeof indexedDB === 'undefined') return
|
|
18
|
+
const real = indexedDB
|
|
19
|
+
const TIMEOUT_MS = 8000
|
|
20
|
+
const patched = new WeakSet()
|
|
21
|
+
|
|
22
|
+
function memoryStore() {
|
|
23
|
+
const map = new Map()
|
|
24
|
+
return {
|
|
25
|
+
_map: map,
|
|
26
|
+
get(key) { return wrapRequest(() => map.get(key)) },
|
|
27
|
+
getAll() { return wrapRequest(() => [...map.values()]) },
|
|
28
|
+
getAllKeys() { return wrapRequest(() => [...map.keys()]) },
|
|
29
|
+
count() { return wrapRequest(() => map.size) },
|
|
30
|
+
put(value, key) { return wrapRequest(() => { const k = key ?? value?.id ?? Math.random(); map.set(k, value); return k }) },
|
|
31
|
+
add(value, key) { return wrapRequest(() => { const k = key ?? value?.id ?? Math.random(); if (map.has(k)) throw new Error('ConstraintError'); map.set(k, value); return k }) },
|
|
32
|
+
delete(key) { return wrapRequest(() => { map.delete(key) }) },
|
|
33
|
+
clear() { return wrapRequest(() => { map.clear() }) },
|
|
34
|
+
openCursor() { return wrapRequest(() => null) },
|
|
35
|
+
createIndex() { return { name: 'index', get: (key) => wrapRequest(() => undefined), getAll: () => wrapRequest(() => []) } },
|
|
36
|
+
index() { return { name: 'index', get: (key) => wrapRequest(() => undefined), getAll: () => wrapRequest(() => []) } },
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 最小 IDBRequest:异步回调,支持 onsuccess / onerror */
|
|
41
|
+
function wrapRequest(fn) {
|
|
42
|
+
const request = { result: undefined, error: null, onsuccess: null, onerror: null }
|
|
43
|
+
setTimeout(() => {
|
|
44
|
+
try {
|
|
45
|
+
request.result = fn()
|
|
46
|
+
if (typeof request.onsuccess === 'function') request.onsuccess({ target: request })
|
|
47
|
+
} catch (error) {
|
|
48
|
+
request.error = error
|
|
49
|
+
if (typeof request.onerror === 'function') request.onerror({ target: request })
|
|
50
|
+
}
|
|
51
|
+
}, 0)
|
|
52
|
+
return request
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 内存版数据库:store 名称按需创建 */
|
|
56
|
+
function memoryDatabase(stores, version) {
|
|
57
|
+
const byName = new Map()
|
|
58
|
+
const names = {
|
|
59
|
+
length: stores.length,
|
|
60
|
+
contains: (name) => stores.includes(name),
|
|
61
|
+
item: (index) => stores[index] ?? null,
|
|
62
|
+
[Symbol.iterator]: function* iterate() { yield* stores },
|
|
63
|
+
}
|
|
64
|
+
const ensure = (name) => {
|
|
65
|
+
if (!byName.has(name)) byName.set(name, memoryStore())
|
|
66
|
+
return byName.get(name)
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
name: 'memory',
|
|
70
|
+
version: version ?? 1,
|
|
71
|
+
objectStoreNames: names,
|
|
72
|
+
createObjectStore(name) { stores.push(name); return ensure(name) },
|
|
73
|
+
deleteObjectStore(name) { const at = stores.indexOf(name); if (at >= 0) stores.splice(at, 1) },
|
|
74
|
+
transaction(storeNames) {
|
|
75
|
+
const list = Array.isArray(storeNames) ? storeNames : [storeNames]
|
|
76
|
+
const tx = { oncomplete: null, onerror: null, onabort: null, error: null, mode: 'readwrite', objectStore: (name) => ensure(name), abort() {} }
|
|
77
|
+
setTimeout(() => { if (typeof tx.oncomplete === 'function') tx.oncomplete({ target: tx }) }, 0)
|
|
78
|
+
for (const name of list) ensure(name)
|
|
79
|
+
return tx
|
|
80
|
+
},
|
|
81
|
+
close() {},
|
|
82
|
+
onversionchange: null,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
indexedDB.open = function patchedOpen(name, version) {
|
|
87
|
+
const request = { result: undefined, error: null, onsuccess: null, onerror: null, onupgradeneeded: null, onblocked: null }
|
|
88
|
+
let settled = false
|
|
89
|
+
const settle = () => { settled = true }
|
|
90
|
+
|
|
91
|
+
let realRequest = null
|
|
92
|
+
try {
|
|
93
|
+
realRequest = real.open(name, version)
|
|
94
|
+
} catch (error) {
|
|
95
|
+
// 真实实现直接抛错:立刻走内存兜底
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (realRequest) {
|
|
99
|
+
realRequest.onupgradeneeded = (event) => {
|
|
100
|
+
if (typeof request.onupgradeneeded === 'function') request.onupgradeneeded(event)
|
|
101
|
+
}
|
|
102
|
+
realRequest.onsuccess = (event) => {
|
|
103
|
+
settle()
|
|
104
|
+
request.result = realRequest.result
|
|
105
|
+
if (typeof request.onsuccess === 'function') request.onsuccess(event)
|
|
106
|
+
}
|
|
107
|
+
realRequest.onerror = (event) => {
|
|
108
|
+
settle()
|
|
109
|
+
request.error = realRequest.error
|
|
110
|
+
if (typeof request.onerror === 'function') request.onerror(event)
|
|
111
|
+
}
|
|
112
|
+
realRequest.onblocked = (event) => {
|
|
113
|
+
// blocked 不代表失败,但如果一直不前进也会挂住,交给下面的超时兜底
|
|
114
|
+
if (typeof request.onblocked === 'function') request.onblocked(event)
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
setTimeout(() => {
|
|
119
|
+
if (settled) return
|
|
120
|
+
// 8 秒没有任何回调:判定为挂死,用内存库接管
|
|
121
|
+
const stores = []
|
|
122
|
+
const db = memoryDatabase(stores, version)
|
|
123
|
+
console.warn('[dsh-homing] IndexedDB open 挂死超过 ' + TIMEOUT_MS + 'ms,改用内存实现:' + name)
|
|
124
|
+
try {
|
|
125
|
+
if (typeof request.onupgradeneeded === 'function') request.onupgradeneeded({ target: { result: db, oldVersion: 0, newVersion: version ?? 1 } })
|
|
126
|
+
} catch (error) { /* 忽略 */ }
|
|
127
|
+
request.result = db
|
|
128
|
+
try {
|
|
129
|
+
if (typeof request.onsuccess === 'function') request.onsuccess({ target: request })
|
|
130
|
+
} catch (error) { /* 忽略 */ }
|
|
131
|
+
try {
|
|
132
|
+
// 上报给服务端,便于确认兜底是否被触发
|
|
133
|
+
const body = JSON.stringify({ kind: 'idb-fallback', message: 'open 挂死,已启用内存实现', url: location.href.slice(0, 120), at: new Date().toISOString() })
|
|
134
|
+
fetch('/dsh_homing/client-error', { method: 'POST', headers: { 'content-type': 'application/json' }, body, cache: 'no-store', keepalive: true }).catch(() => {})
|
|
135
|
+
} catch (error) { /* 忽略 */ }
|
|
136
|
+
}, TIMEOUT_MS)
|
|
137
|
+
|
|
138
|
+
return request
|
|
139
|
+
}
|
|
140
|
+
})()
|
package/lib/local-apps.mjs
CHANGED
|
@@ -43,12 +43,14 @@ export function validateApp(input, deniedPorts = []) {
|
|
|
43
43
|
const port = Number(target.port || (target.protocol === 'https:' ? 443 : 80))
|
|
44
44
|
if (deniedPorts.map(Number).includes(port)) return { ok: false, error: `端口 ${port} 是插件或 DSH 的管理端口,不能代理` }
|
|
45
45
|
const basePath = target.pathname === '/' ? '' : target.pathname.replace(/\/+$/u, '')
|
|
46
|
+
// 注意:URL.hostname 对 IPv6 已经返回带方括号的形式([::1]),不能再包一层,
|
|
47
|
+
// 否则会得到 http://[[::1]]:9000 这种非法 URL(2026-11-17 实测发现)。
|
|
46
48
|
return {
|
|
47
49
|
ok: true,
|
|
48
50
|
app: {
|
|
49
51
|
id,
|
|
50
52
|
name,
|
|
51
|
-
target: `${target.protocol}//${target.hostname
|
|
53
|
+
target: `${target.protocol}//${target.hostname}:${port}${basePath}`,
|
|
52
54
|
enabled: input?.enabled !== false,
|
|
53
55
|
// 同源 HTML/JS 默认不受信。只有明确勾选后才允许返回可执行网页内容。
|
|
54
56
|
trusted: input?.trusted === true,
|
|
@@ -58,7 +60,9 @@ export function validateApp(input, deniedPorts = []) {
|
|
|
58
60
|
}
|
|
59
61
|
|
|
60
62
|
function cloneApp(app) {
|
|
61
|
-
|
|
63
|
+
// 只会传入归一化后的对象(见 normalizedList / save 的调用点);
|
|
64
|
+
// 对象展开对 null/undefined 也是安全的(得到 {}),因此不需要不可达的判空分支。
|
|
65
|
+
return { ...app }
|
|
62
66
|
}
|
|
63
67
|
|
|
64
68
|
function readSettingsFile(file, { strict = false } = {}) {
|
|
@@ -107,10 +111,11 @@ export function upstreamPath(app, rest, search = '') {
|
|
|
107
111
|
|
|
108
112
|
function publicPathFromTarget(pathname, app) {
|
|
109
113
|
const base = new URL(app.target).pathname.replace(/\/+$/u, '')
|
|
110
|
-
|
|
114
|
+
// 唯一调用方传入的是 new URL(...).pathname,恒为以 / 开头的非空字符串,
|
|
115
|
+
// 因此不需要「空值兜底」和「补前导 /」这两个走不到的防御分支。
|
|
116
|
+
let rest = String(pathname)
|
|
111
117
|
if (base && rest === base) rest = '/'
|
|
112
118
|
else if (base && rest.startsWith(base + '/')) rest = rest.slice(base.length)
|
|
113
|
-
if (!rest.startsWith('/')) rest = '/' + rest
|
|
114
119
|
return `/apps/${app.id}${rest}`
|
|
115
120
|
}
|
|
116
121
|
|
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
|
-
|
|
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
|
-
|
|
91
|
-
|
|
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
|
|
package/lib/mobile-patch.mjs
CHANGED
|
@@ -19,7 +19,46 @@ export const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
|
|
|
19
19
|
}
|
|
20
20
|
`;
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* 计算把浮层拉回视口所需的位移(像素,四舍五入)。
|
|
24
|
+
*
|
|
25
|
+
* 手机上的浮层(额度面板、菜单、对话框)常以「相对按钮定位」的方式出现,
|
|
26
|
+
* 在窄屏上会有一部分跑到屏幕左侧或右侧外面,内容被裁掉。这里只算位移,
|
|
27
|
+
* 由调用方用 CSS `translate`(独立于 transform,不会破坏原有动画)施加。
|
|
28
|
+
*
|
|
29
|
+
* @param {{left:number, top:number, right:number, bottom:number, width:number, height:number}} rect
|
|
30
|
+
* @param {{width:number, height:number}} viewport
|
|
31
|
+
* @param {number} [margin] 距视口边缘留白
|
|
32
|
+
* @returns {{dx:number, dy:number}}
|
|
33
|
+
*/
|
|
34
|
+
export function clampPopoverOffset(rect, viewport, margin = 8) {
|
|
35
|
+
const offset = { dx: 0, dy: 0 };
|
|
36
|
+
if (!rect || !viewport) return offset;
|
|
37
|
+
const width = Number(viewport.width) || 0;
|
|
38
|
+
const height = Number(viewport.height) || 0;
|
|
39
|
+
if (width <= 0 || height <= 0) return offset;
|
|
40
|
+
const left = Number(rect.left) || 0;
|
|
41
|
+
const top = Number(rect.top) || 0;
|
|
42
|
+
const boxWidth = Number(rect.width) || 0;
|
|
43
|
+
const boxHeight = Number(rect.height) || 0;
|
|
44
|
+
if (boxWidth <= 0 || boxHeight <= 0) return offset;
|
|
45
|
+
|
|
46
|
+
// 水平:比视口还宽时贴左边缘(否则怎么移都会裁),否则把越界的一侧推回来
|
|
47
|
+
if (boxWidth > width - margin * 2) offset.dx = margin - left;
|
|
48
|
+
else if (left < margin) offset.dx = margin - left;
|
|
49
|
+
else if (left + boxWidth > width - margin) offset.dx = width - margin - (left + boxWidth);
|
|
50
|
+
|
|
51
|
+
// 垂直:同理
|
|
52
|
+
if (boxHeight > height - margin * 2) offset.dy = margin - top;
|
|
53
|
+
else if (top < margin) offset.dy = margin - top;
|
|
54
|
+
else if (top + boxHeight > height - margin) offset.dy = height - margin - (top + boxHeight);
|
|
55
|
+
|
|
56
|
+
return { dx: Math.round(offset.dx), dy: Math.round(offset.dy) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
22
60
|
export const MOBILE_JS = String.raw`(() => {
|
|
61
|
+
const clampPopoverOffset = ${clampPopoverOffset.toString()}
|
|
23
62
|
const narrow = () => window.innerWidth <= 760
|
|
24
63
|
// 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
|
|
25
64
|
// 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
|
|
@@ -284,10 +323,79 @@ export const MOBILE_JS = String.raw`(() => {
|
|
|
284
323
|
|
|
285
324
|
const menuObserver = new MutationObserver(() => {
|
|
286
325
|
if (menuTimer) return
|
|
287
|
-
menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems() }, 80)
|
|
326
|
+
menuTimer = setTimeout(() => { menuTimer = null; enhanceMenus(); pruneMenuItems(); scheduleClamp() }, 80)
|
|
288
327
|
})
|
|
289
328
|
menuObserver.observe(document.body, { childList: true, subtree: true })
|
|
290
329
|
|
|
330
|
+
/* ---------- 浮层不越出屏幕 ----------
|
|
331
|
+
* 额度面板、菜单、对话框大多按「相对触发按钮」定位,窄屏上会有一部分落到
|
|
332
|
+
* 屏幕左侧/右侧外面,文字被裁掉(手机上实测:额度面板左边整块看不见)。
|
|
333
|
+
* 这里在浮层出现后把它平移回视口内:
|
|
334
|
+
* - 只处理 position: fixed/absolute 且 z-index >= 100 的可见元素;
|
|
335
|
+
* - 用 CSS translate 属性(不是 transform),不与原动画/居中冲突;
|
|
336
|
+
* - 每次重新计算前先复位,避免位移叠加。
|
|
337
|
+
*/
|
|
338
|
+
const floatingStyleOf = (node) => {
|
|
339
|
+
try {
|
|
340
|
+
if (typeof window.getComputedStyle === 'function') return window.getComputedStyle(node)
|
|
341
|
+
if (typeof getComputedStyle === 'function') return getComputedStyle(node)
|
|
342
|
+
} catch (error) {
|
|
343
|
+
/* 忽略 */
|
|
344
|
+
}
|
|
345
|
+
return null
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const clampPopovers = () => {
|
|
349
|
+
try {
|
|
350
|
+
const viewport = {
|
|
351
|
+
width: Number(window.innerWidth) || Number(document.documentElement && document.documentElement.clientWidth) || 0,
|
|
352
|
+
height: Number(window.innerHeight) || Number(document.documentElement && document.documentElement.clientHeight) || 0,
|
|
353
|
+
}
|
|
354
|
+
if (viewport.width <= 0 || viewport.height <= 0) return 0
|
|
355
|
+
const selector = 'body > div, body > div > div, [role="dialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]'
|
|
356
|
+
const nodes = document.querySelectorAll ? document.querySelectorAll(selector) : []
|
|
357
|
+
let moved = 0
|
|
358
|
+
for (const node of nodes) {
|
|
359
|
+
if (node === null || typeof node.getBoundingClientRect !== 'function') continue
|
|
360
|
+
const computed = floatingStyleOf(node)
|
|
361
|
+
const position = String((computed && computed.position) || '')
|
|
362
|
+
if (position !== 'fixed' && position !== 'absolute') continue
|
|
363
|
+
const zIndex = Number.parseInt(String((computed && computed.zIndex) || '0'), 10)
|
|
364
|
+
if (!Number.isFinite(zIndex) || zIndex < 100) continue
|
|
365
|
+
if (computed && (computed.visibility === 'hidden' || computed.display === 'none')) continue
|
|
366
|
+
if (computed && Number(computed.opacity) === 0) continue
|
|
367
|
+
const style = node.style
|
|
368
|
+
if (style === null || style === undefined) continue
|
|
369
|
+
// 复位上一次的位移,再按当前(未平移)位置计算
|
|
370
|
+
if ('translate' in style) style.translate = ''
|
|
371
|
+
const rect = node.getBoundingClientRect()
|
|
372
|
+
if (rect === null || Number(rect.width) <= 0 || Number(rect.height) <= 0) continue
|
|
373
|
+
const offset = clampPopoverOffset(rect, viewport)
|
|
374
|
+
if (offset.dx === 0 && offset.dy === 0) continue
|
|
375
|
+
if ('translate' in style) {
|
|
376
|
+
style.translate = offset.dx + 'px ' + offset.dy + 'px'
|
|
377
|
+
moved += 1
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return moved
|
|
381
|
+
} catch (error) {
|
|
382
|
+
return 0
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
let clampTimer = null
|
|
387
|
+
const scheduleClamp = () => {
|
|
388
|
+
if (clampTimer !== null) return
|
|
389
|
+
const run = () => { clampTimer = null; clampPopovers() }
|
|
390
|
+
if (typeof setTimeout === 'function') clampTimer = setTimeout(run, 120)
|
|
391
|
+
else run()
|
|
392
|
+
}
|
|
393
|
+
document.addEventListener('pointerup', scheduleClamp, true)
|
|
394
|
+
document.addEventListener('click', scheduleClamp, true)
|
|
395
|
+
window.addEventListener('resize', scheduleClamp)
|
|
396
|
+
// 调试/测试入口:也可手动触发一次
|
|
397
|
+
if (window.__dshHomingClampPopovers === undefined) window.__dshHomingClampPopovers = clampPopovers
|
|
398
|
+
|
|
291
399
|
/* ---------- ALIVE_BEACON ----------
|
|
292
400
|
* 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
|
|
293
401
|
* 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
|
package/lib/netdiag.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 网络自检脚本(v5,2026-11-15)
|
|
3
|
+
*
|
|
4
|
+
* 可以在两个地方用:
|
|
5
|
+
* 1. /debug 调试页:有 #netdiag-run 按钮,点一下才跑,输出到 #netdiag-out
|
|
6
|
+
* 2. /dsh_homing/netdiag 独立页:没有按钮,加载即自动跑,输出到 #out
|
|
7
|
+
*
|
|
8
|
+
* 设计要点:
|
|
9
|
+
* - 每步都有硬超时(华为浏览器里 caches.keys()/getRegistrations() 可能永不返回)
|
|
10
|
+
* - 每完成一步就追加一行,页面实时可见
|
|
11
|
+
* - **先把结果回传服务端**再显示结论:页面截不全也能从审计里拿到完整证据
|
|
12
|
+
* - 测真正的 RPC 通道 /api/remote.mux(不是根路径),并附带根路径作参考
|
|
13
|
+
* - 用于匹配资源引用的 HTML 片段要足够长(v4 只取 400 字符,导致误报"找不到入口脚本")
|
|
14
|
+
*/
|
|
15
|
+
(() => {
|
|
16
|
+
const debugButton = document.getElementById('netdiag-run')
|
|
17
|
+
const out = document.getElementById('netdiag-out') ?? document.getElementById('out')
|
|
18
|
+
const copyButton = document.getElementById('netdiag-copy') ?? document.getElementById('copy')
|
|
19
|
+
const autoRun = !debugButton
|
|
20
|
+
|
|
21
|
+
const lines = []
|
|
22
|
+
const started = Date.now()
|
|
23
|
+
|
|
24
|
+
function render() {
|
|
25
|
+
if (out) out.textContent = lines.join('\n')
|
|
26
|
+
}
|
|
27
|
+
function line(text) {
|
|
28
|
+
lines.push(text)
|
|
29
|
+
render()
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function withTimeout(promise, ms, label) {
|
|
33
|
+
return Promise.race([
|
|
34
|
+
promise.catch((error) => ({ error: String(error && error.message ? error.message : error) })),
|
|
35
|
+
new Promise((resolve) => setTimeout(() => resolve({ error: label + ' 超时(' + ms + 'ms)' }), ms)),
|
|
36
|
+
])
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function httpProbe(url, { timeoutMs = 8000, method = 'GET', body = null, headers = {} } = {}) {
|
|
40
|
+
const begin = Date.now()
|
|
41
|
+
const controller = new AbortController()
|
|
42
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
43
|
+
try {
|
|
44
|
+
const response = await fetch(url, {
|
|
45
|
+
method, body, cache: 'no-store', credentials: 'same-origin',
|
|
46
|
+
signal: controller.signal, headers: { accept: '*/*', ...headers },
|
|
47
|
+
})
|
|
48
|
+
const text = await response.text()
|
|
49
|
+
return {
|
|
50
|
+
status: response.status, bytes: text.length, ms: Date.now() - begin,
|
|
51
|
+
cacheControl: response.headers.get('cache-control') ?? '',
|
|
52
|
+
head: text.slice(0, 400),
|
|
53
|
+
// 用于在完整 HTML 里匹配资源引用(head 只有 400 字符,不能拿来匹配)
|
|
54
|
+
rawLength: text.length,
|
|
55
|
+
assetScript: /\/assets\/index-[A-Za-z0-9_-]+\.js/u.exec(text)?.[0] ?? '',
|
|
56
|
+
}
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const aborted = error && (error.name === 'AbortError' || error.name === 'TimeoutError')
|
|
59
|
+
return { status: aborted ? 'TIMEOUT' : 'ERR', ms: Date.now() - begin, error: String(error && error.message ? error.message : error) }
|
|
60
|
+
} finally {
|
|
61
|
+
clearTimeout(timer)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function wsProbe(pathName, timeoutMs = 6000) {
|
|
66
|
+
return new Promise((resolve) => {
|
|
67
|
+
let socket = null
|
|
68
|
+
let settled = false
|
|
69
|
+
const done = (value) => {
|
|
70
|
+
if (settled) return
|
|
71
|
+
settled = true
|
|
72
|
+
try { socket && socket.close() } catch (error) { /* 忽略 */ }
|
|
73
|
+
resolve(value)
|
|
74
|
+
}
|
|
75
|
+
const timer = setTimeout(() => done({ ok: false, detail: '超时(' + timeoutMs + 'ms)' }), timeoutMs)
|
|
76
|
+
try {
|
|
77
|
+
const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:'
|
|
78
|
+
socket = new WebSocket(`${scheme}//${location.host}${pathName}`)
|
|
79
|
+
socket.onopen = () => { clearTimeout(timer); done({ ok: true, detail: '101 已建立' }) }
|
|
80
|
+
socket.onerror = () => { clearTimeout(timer); done({ ok: false, detail: 'error 事件(握手被拒或连接被断)' }) }
|
|
81
|
+
socket.onclose = (event) => { clearTimeout(timer); done({ ok: false, detail: '被关闭 code=' + event.code + (event.reason ? ' ' + event.reason : '') }) }
|
|
82
|
+
} catch (error) {
|
|
83
|
+
clearTimeout(timer)
|
|
84
|
+
done({ ok: false, detail: '抛出:' + String(error && error.message ? error.message : error) })
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async function cacheProbe() {
|
|
90
|
+
const result = { caches: null, serviceWorkers: null }
|
|
91
|
+
try {
|
|
92
|
+
if (typeof caches !== 'undefined' && caches.keys) {
|
|
93
|
+
const names = await withTimeout(caches.keys(), 3000, 'caches.keys')
|
|
94
|
+
result.caches = Array.isArray(names) ? names : null
|
|
95
|
+
} else {
|
|
96
|
+
result.caches = 'unsupported'
|
|
97
|
+
}
|
|
98
|
+
} catch (error) { result.caches = 'error' }
|
|
99
|
+
try {
|
|
100
|
+
if (navigator.serviceWorker && navigator.serviceWorker.getRegistrations) {
|
|
101
|
+
const list = await withTimeout(navigator.serviceWorker.getRegistrations(), 3000, 'getRegistrations')
|
|
102
|
+
result.serviceWorkers = Array.isArray(list) ? list.length : null
|
|
103
|
+
} else {
|
|
104
|
+
result.serviceWorkers = 'unsupported'
|
|
105
|
+
}
|
|
106
|
+
} catch (error) { result.serviceWorkers = 'error' }
|
|
107
|
+
return result
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function run() {
|
|
111
|
+
lines.length = 0
|
|
112
|
+
line('开始检测 ' + new Date().toLocaleTimeString())
|
|
113
|
+
line('地址: ' + location.href)
|
|
114
|
+
line('UA: ' + navigator.userAgent)
|
|
115
|
+
line('')
|
|
116
|
+
|
|
117
|
+
line('① 首页 HTML')
|
|
118
|
+
const home = await httpProbe('/')
|
|
119
|
+
line(home.error
|
|
120
|
+
? ' ✗ ' + home.error
|
|
121
|
+
: ' HTTP ' + home.status + ' · ' + home.bytes + 'B · ' + home.ms + 'ms · ' + (home.cacheControl || '无 cache-control'))
|
|
122
|
+
|
|
123
|
+
line('② 鉴权状态')
|
|
124
|
+
const authState = await httpProbe('/dsh_homing/auth-state', { headers: { accept: 'application/json' } })
|
|
125
|
+
line(authState.error ? ' ✗ ' + authState.error : ' HTTP ' + authState.status + ' · ' + authState.head.slice(0, 160))
|
|
126
|
+
|
|
127
|
+
line('③ 入口脚本')
|
|
128
|
+
let assetPath = home.assetScript ?? ''
|
|
129
|
+
let asset = { status: '(跳过)' }
|
|
130
|
+
if (home.error) {
|
|
131
|
+
line(' ✗ 取首页失败:' + home.error)
|
|
132
|
+
} else if (assetPath === '') {
|
|
133
|
+
line(' ✗ 首页里找不到 /assets/index-*.js(HTML ' + home.bytes + 'B)')
|
|
134
|
+
} else {
|
|
135
|
+
asset = await httpProbe(assetPath)
|
|
136
|
+
line(' ' + assetPath)
|
|
137
|
+
line(asset.error ? ' ✗ ' + asset.error : ' HTTP ' + asset.status + ' · ' + asset.bytes + 'B · ' + asset.ms + 'ms')
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
line('④ RPC 通道 /api/remote.mux(应用真正用的)')
|
|
141
|
+
const mux = await wsProbe('/api/remote.mux')
|
|
142
|
+
line(' ' + (mux.ok ? '✓ ' + mux.detail : '✗ ' + mux.detail))
|
|
143
|
+
|
|
144
|
+
line('⑤ 根路径 WebSocket(仅参考,应用不用它)')
|
|
145
|
+
const rootWs = await wsProbe('/')
|
|
146
|
+
line(' ' + (rootWs.ok ? '✓ ' + rootWs.detail : '✗ ' + rootWs.detail))
|
|
147
|
+
|
|
148
|
+
line('⑥ 缓存 / Service Worker')
|
|
149
|
+
const cache = await cacheProbe()
|
|
150
|
+
line(' Cache Storage: ' + (Array.isArray(cache.caches) ? (cache.caches.length ? cache.caches.join(', ') : '空') : String(cache.caches)))
|
|
151
|
+
line(' Service Worker: ' + (typeof cache.serviceWorkers === 'number' ? cache.serviceWorkers + ' 个' : String(cache.serviceWorkers)))
|
|
152
|
+
|
|
153
|
+
const payload = {
|
|
154
|
+
at: new Date().toISOString(),
|
|
155
|
+
href: location.href,
|
|
156
|
+
ua: navigator.userAgent,
|
|
157
|
+
elapsedMs: Date.now() - started,
|
|
158
|
+
home, authState, asset, mux, rootWs, cache,
|
|
159
|
+
viewport: { width: innerWidth, height: innerHeight, dpr: devicePixelRatio },
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const sent = await httpProbe('/dsh_homing/netdiag/report', {
|
|
163
|
+
method: 'POST',
|
|
164
|
+
body: JSON.stringify(payload),
|
|
165
|
+
headers: { 'content-type': 'application/json' },
|
|
166
|
+
timeoutMs: 10000,
|
|
167
|
+
})
|
|
168
|
+
line('')
|
|
169
|
+
line(sent.error ? '✗ 回传失败:' + sent.error : '✓ 结果已回传(HTTP ' + sent.status + ',电脑端查审计)')
|
|
170
|
+
line('耗时 ' + (Date.now() - started) + 'ms')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (copyButton) {
|
|
174
|
+
copyButton.addEventListener('click', () => {
|
|
175
|
+
const text = lines.join('\n')
|
|
176
|
+
if (navigator.clipboard && navigator.clipboard.writeText) {
|
|
177
|
+
navigator.clipboard.writeText(text).then(
|
|
178
|
+
() => { copyButton.textContent = '已复制' },
|
|
179
|
+
() => { copyButton.textContent = '复制失败' },
|
|
180
|
+
)
|
|
181
|
+
} else {
|
|
182
|
+
// 没有 clipboard API 时退化为选中文本,用户长按复制
|
|
183
|
+
copyButton.textContent = '请长按选中文本复制'
|
|
184
|
+
if (out && window.getSelection) {
|
|
185
|
+
const range = document.createRange()
|
|
186
|
+
range.selectNodeContents(out)
|
|
187
|
+
const selection = window.getSelection()
|
|
188
|
+
selection.removeAllRanges()
|
|
189
|
+
selection.addRange(range)
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
})
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
if (debugButton) {
|
|
196
|
+
debugButton.addEventListener('click', () => {
|
|
197
|
+
debugButton.disabled = true
|
|
198
|
+
debugButton.textContent = '检测中…'
|
|
199
|
+
if (out) out.textContent = '开始检测…'
|
|
200
|
+
run()
|
|
201
|
+
.catch((error) => line('✗ 自检脚本出错:' + String(error && error.message ? error.message : error)))
|
|
202
|
+
.finally(() => {
|
|
203
|
+
debugButton.disabled = false
|
|
204
|
+
debugButton.textContent = '重新检测'
|
|
205
|
+
})
|
|
206
|
+
})
|
|
207
|
+
if (out) out.textContent = '(点「开始检测」运行)'
|
|
208
|
+
} else if (autoRun) {
|
|
209
|
+
run().catch((error) => line('✗ 自检脚本出错:' + String(error && error.message ? error.message : error)))
|
|
210
|
+
}
|
|
211
|
+
})()
|
package/lib/node-runtime.mjs
CHANGED
|
@@ -4,41 +4,58 @@
|
|
|
4
4
|
* 背景:插件代码跑在 DSH 的 Electron 进程里,`process.execPath` 是
|
|
5
5
|
* "DeepSeek Harness.exe",不是 node。用它去 spawn CLI/守护进程,
|
|
6
6
|
* 实际上会再启动一个 DSH 实例(曾导致点"重启守护进程"却把 DSH 重启)。
|
|
7
|
+
*
|
|
8
|
+
* 所有环境依赖都可注入(env / execPath / platform / homeDir / readdirFn / statFn),
|
|
9
|
+
* 便于测试覆盖"环境变量指定、运行时装在 dsh-runtimes 下、当前进程就是 node、
|
|
10
|
+
* 以及全都找不到时的 PATH 兜底"这几条路径。
|
|
7
11
|
*/
|
|
8
12
|
import fs from 'node:fs'
|
|
9
13
|
import os from 'node:os'
|
|
10
14
|
import path from 'node:path'
|
|
11
15
|
|
|
12
|
-
function dshHome() {
|
|
13
|
-
return
|
|
16
|
+
function dshHome(env = process.env) {
|
|
17
|
+
return env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh')
|
|
14
18
|
}
|
|
15
19
|
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
-
|
|
20
|
+
/**
|
|
21
|
+
* 候选 Node 可执行文件,按优先级排列
|
|
22
|
+
* @param {{ env?: object, execPath?: string, platform?: string, homeDir?: string, readdirFn?: Function }} [options]
|
|
23
|
+
*/
|
|
24
|
+
export function nodeRuntimeCandidates({
|
|
25
|
+
env = process.env,
|
|
26
|
+
execPath = process.execPath,
|
|
27
|
+
platform = process.platform,
|
|
28
|
+
homeDir = dshHome(env),
|
|
29
|
+
readdirFn = (dirPath) => fs.readdirSync(dirPath),
|
|
30
|
+
} = {}) {
|
|
31
|
+
const exe = platform === 'win32' ? 'node.exe' : 'node'
|
|
19
32
|
const candidates = []
|
|
20
|
-
const fromEnv =
|
|
33
|
+
const fromEnv = env.DSH_HOMING_NODE?.trim() || env.DSH_NODE_BIN?.trim()
|
|
21
34
|
if (fromEnv) candidates.push(fromEnv)
|
|
22
35
|
|
|
23
|
-
const runtimesRoot = path.join(
|
|
36
|
+
const runtimesRoot = path.join(homeDir, 'dsh-runtimes')
|
|
24
37
|
try {
|
|
25
|
-
for (const dir of
|
|
38
|
+
for (const dir of readdirFn(runtimesRoot)) {
|
|
26
39
|
candidates.push(path.join(runtimesRoot, dir, 'dependencies', 'node', 'bin', exe))
|
|
27
40
|
}
|
|
28
41
|
} catch { /* 没有 dsh-runtimes 目录 */ }
|
|
29
42
|
|
|
30
43
|
// 当前进程本身就运行在 node 上时直接可用
|
|
31
|
-
if (/node(\.exe)?$/iu.test(
|
|
44
|
+
if (/node(\.exe)?$/iu.test(String(execPath))) candidates.push(execPath)
|
|
32
45
|
|
|
33
46
|
return candidates
|
|
34
47
|
}
|
|
35
48
|
|
|
36
|
-
|
|
37
|
-
|
|
49
|
+
/**
|
|
50
|
+
* 找出第一个真实存在的候选;都找不到时退回 PATH 里的 node
|
|
51
|
+
* @param {{ statFn?: Function, platform?: string }} [options]
|
|
52
|
+
*/
|
|
53
|
+
export function findNodeRuntime({ statFn = (file) => fs.statSync(file), platform = process.platform, ...rest } = {}) {
|
|
54
|
+
for (const candidate of nodeRuntimeCandidates(rest)) {
|
|
38
55
|
try {
|
|
39
|
-
if (candidate &&
|
|
56
|
+
if (candidate && statFn(candidate).isFile()) return candidate
|
|
40
57
|
} catch { /* 继续找 */ }
|
|
41
58
|
}
|
|
42
59
|
// 最后回退:让系统 PATH 找 node(仍比误用 DSH exe 安全)
|
|
43
|
-
return
|
|
60
|
+
return platform === 'win32' ? 'node.exe' : 'node'
|
|
44
61
|
}
|