@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
package/index.js
CHANGED
|
@@ -54,6 +54,7 @@ import { createLocalAppRegistry, matchAppPath, probeAppPort } from './lib/local-
|
|
|
54
54
|
import { proxyLocalAppHttp, proxyLocalAppUpgrade } from './lib/app-proxy.mjs';
|
|
55
55
|
import { renderLocalAppsPage } from './lib/local-apps-page.mjs';
|
|
56
56
|
import { MOBILE_CSS, MOBILE_JS } from './lib/mobile-patch.mjs';
|
|
57
|
+
import { formatAge } from './lib/format-age.mjs';
|
|
57
58
|
|
|
58
59
|
export const name = 'dsh-homing';
|
|
59
60
|
|
|
@@ -106,7 +107,8 @@ const DEFAULT_CONFIG = {
|
|
|
106
107
|
};
|
|
107
108
|
|
|
108
109
|
function normalizeConfig(raw) {
|
|
109
|
-
|
|
110
|
+
// 所有调用点都传对象(apply 里传 {...rawConfig, ...readSettings()}),raw 不可能为空,去掉防御兜底
|
|
111
|
+
const config = { ...DEFAULT_CONFIG, ...raw };
|
|
110
112
|
config.sshPort = Number(config.sshPort) || 22;
|
|
111
113
|
config.listenPort = Number(config.listenPort) || 8787;
|
|
112
114
|
// 服务器侧端口与 nginx 的 proxy_pass 必须一致,默认固定 8787;本机 listenPort 可以单独改
|
|
@@ -349,8 +351,8 @@ function createCookieMinter(credentials, getUpstreamPort) {
|
|
|
349
351
|
const hit = ttlByAuthority.get(authority);
|
|
350
352
|
// 一小时内复用;DSH 上限变化只会发生在它自己重启之后,那时 authority 也会变
|
|
351
353
|
if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.ttlMs;
|
|
354
|
+
// 代理请求进入 mint 前已通过 getUpstreamPort() 的非空检查(handler 里 !port 会先回 503),port 必为真
|
|
352
355
|
const port = getUpstreamPort();
|
|
353
|
-
if (!port) return COOKIE_TTL_FALLBACK_MS;
|
|
354
356
|
for (const ttlMs of COOKIE_TTL_CANDIDATES_MS) {
|
|
355
357
|
const accepted = await probeCookieAccepted({
|
|
356
358
|
port,
|
|
@@ -379,7 +381,54 @@ function createCookieMinter(credentials, getUpstreamPort) {
|
|
|
379
381
|
* 以便用真实 DOM 桩做行为测试(见 test/unit.mobile-patch.test.mjs)。
|
|
380
382
|
* ------------------------------------------------------------------ */
|
|
381
383
|
|
|
382
|
-
|
|
384
|
+
/**
|
|
385
|
+
* 注入脚本的版本号:用文件修改时间,同步后必然变化 → 浏览器一定取新脚本。
|
|
386
|
+
* (2026-11-15:之前用插件版本号,插件没升版本时手机会一直用缓存的旧脚本,
|
|
387
|
+
* 导致"部署了新诊断代码但手机跑的仍是旧的"。)
|
|
388
|
+
*/
|
|
389
|
+
function injectedScriptVersion(relative) {
|
|
390
|
+
try {
|
|
391
|
+
return String(Math.floor(fs.statSync(new URL(relative, import.meta.url)).mtimeMs));
|
|
392
|
+
} catch {
|
|
393
|
+
return PLUGIN_VERSION;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
const AUTH_GUARD_VER = injectedScriptVersion('./lib/auth-guard.js');
|
|
398
|
+
const CLIENT_REPORT_VER = injectedScriptVersion('./lib/client-report.js');
|
|
399
|
+
const IDB_FALLBACK_VER = injectedScriptVersion('./lib/idb-fallback.js');
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* import map:把 `plugins/...` 这类**不带前导斜杠**的说明符映射到绝对路径。
|
|
403
|
+
*
|
|
404
|
+
* 为什么必须加(2026-11-15 定位到的根因):
|
|
405
|
+
* DSH 前端按需加载插件时,会 `import('plugins/??pkg/client.js&rev=...')`。
|
|
406
|
+
* 按 ES 模块规范,说明符必须以 `/`、`./`、`../` 开头,否则被视为「裸包名」,
|
|
407
|
+
* 浏览器直接抛 `Failed to resolve module specifier`。
|
|
408
|
+
* Chrome 里 DSH 自己的解析器能兜住;鸿蒙 ArkWeb 上兜不住,
|
|
409
|
+
* 于是 90 个插件里只有 HTML 预加载的 3 个注册成功,
|
|
410
|
+
* 界面永远停在 "HARNESS / Loading plugins…",首页会话列表也永远不出现。
|
|
411
|
+
*
|
|
412
|
+
* ⚠️ 位置极其重要:import map 必须在**任何 module 加载之前**出现,
|
|
413
|
+
* 否则浏览器会忽略它(并只打一条 console 警告)。
|
|
414
|
+
* 实测 DSH 的 HTML 里 `<script type="module">` 出现在 head 靠后位置
|
|
415
|
+
* (约 offset 47643),如果按常规插到 `</head>` 前就太晚了——
|
|
416
|
+
* 这正是第一版修复没生效的原因。所以必须插在 `<head>` 之后第一件事。
|
|
417
|
+
*/
|
|
418
|
+
const IMPORT_MAP = '<script type="importmap">'
|
|
419
|
+
+ JSON.stringify({ imports: { 'plugins/': '/plugins/', 'assets/': '/assets/' } })
|
|
420
|
+
+ '</script>';
|
|
421
|
+
|
|
422
|
+
// 注入分三段(位置很重要):
|
|
423
|
+
// IMPORT_MAP —— 紧跟 <head> 之后:import map 必须早于任何 module 加载,否则被忽略
|
|
424
|
+
// BASE —— `</head>` 之前:登录守卫 + 错误上报(永远注入)
|
|
425
|
+
// MOBILE —— `</head>` 之前:mobile.css + mobile.js(只在未关闭样式时注入)
|
|
426
|
+
const BASE_INJECTION = '<script src="/dsh_homing/idb-fallback.js?v=' + IDB_FALLBACK_VER + '"></script>'
|
|
427
|
+
+ '<script src="/dsh_homing/auth-guard.js?v=' + AUTH_GUARD_VER + '"></script>'
|
|
428
|
+
+ '<script src="/dsh_homing/client-report.js?v=' + CLIENT_REPORT_VER + '"></script>';
|
|
429
|
+
|
|
430
|
+
const MOBILE_INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css">'
|
|
431
|
+
+ '<script defer src="/dsh_homing/mobile.js"></script>';
|
|
383
432
|
|
|
384
433
|
// 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
|
|
385
434
|
// 调试页上一键即可设置,页面坏了也点得到。
|
|
@@ -498,7 +547,8 @@ function startRestartDaemonDetached() {
|
|
|
498
547
|
return false;
|
|
499
548
|
}
|
|
500
549
|
const child = spawn(findNodeRuntime(), [cli, 'start'], { detached: true, stdio: 'ignore', windowsHide: true });
|
|
501
|
-
|
|
550
|
+
// appendAudit 内部已吞掉所有写盘异常,这里不必再包 try/catch
|
|
551
|
+
child.on('error', (error) => { appendAudit(dataDir(), 'restart-daemon-spawn-error', { error: String(error?.message ?? error).slice(0, 200) }); });
|
|
502
552
|
child.unref();
|
|
503
553
|
return true;
|
|
504
554
|
} catch {
|
|
@@ -511,9 +561,8 @@ const restartDaemonWatchdog = createRestartDaemonWatchdog({
|
|
|
511
561
|
service: restartService,
|
|
512
562
|
pluginRoot: path.dirname(fileURLToPath(import.meta.url)),
|
|
513
563
|
dshHome: process.env.DSH_HOME?.trim() || path.join(os.homedir(), '.dsh'),
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
},
|
|
564
|
+
// watchdog 只会传对象({pid}/{stopped}/{}),appendAudit 内部也自带 try/catch:extra ?? {} 与 catch 都不可达
|
|
565
|
+
audit: (event, extra) => appendAudit(dataDir(), event, extra),
|
|
517
566
|
});
|
|
518
567
|
void restartDaemonWatchdog;
|
|
519
568
|
|
|
@@ -521,12 +570,12 @@ void restartDaemonWatchdog;
|
|
|
521
570
|
const LIVE_SCRIPT = `<div id="live" class="dim" style="margin-top:8px">脚本未加载</div>`
|
|
522
571
|
+ `<script src="/dsh_homing/restart.js"></script>`;
|
|
523
572
|
|
|
524
|
-
function renderRestartPage({ status, sessions, message, confirmForce, portState }) {
|
|
573
|
+
function renderRestartPage({ status, sessions, message, confirmForce, portState, daemonVersion, staleDaemon }) {
|
|
525
574
|
const running = status?.running ?? false
|
|
526
575
|
const paused = status?.paused ?? false
|
|
527
576
|
const left = status?.pausedSecondsLeft ?? 0
|
|
528
577
|
const busy = sessions.length > 0
|
|
529
|
-
const busyItems = sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · ' + s.age +
|
|
578
|
+
const busyItems = sessions.map((s) => '<li><b>' + escapeHtml(s.title || '(未命名会话)') + '</b> · 最后活动 ' + formatAge(s.age) + (s.cwd ? ' · ' + escapeHtml(s.cwd) : '') + '</li>').join('')
|
|
530
579
|
|
|
531
580
|
const confirmBlock = confirmForce
|
|
532
581
|
? '<div class="card warn"><div class="line"><span class="k">确认强制重启</span><span class="v">' + sessions.length + ' 个会话运行中</span></div>'
|
|
@@ -560,7 +609,8 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
|
|
|
560
609
|
})()
|
|
561
610
|
|
|
562
611
|
const policy = restartPolicy.status()
|
|
563
|
-
|
|
612
|
+
// runner 的 status() 恒返回对象且带 config 对象:可选链与 ?? {} 不可达
|
|
613
|
+
const cfg = policy.config
|
|
564
614
|
const nav = topNav()
|
|
565
615
|
|
|
566
616
|
return '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">'
|
|
@@ -594,9 +644,17 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
|
|
|
594
644
|
+ (message ? '<div class="msg" id="restart-msg">' + escapeHtml(message) + '</div>' : '')
|
|
595
645
|
+ confirmBlock
|
|
596
646
|
+ '<div class="card">'
|
|
597
|
-
|
|
647
|
+
// policy 来自 restartPolicy.status(),waitedSeconds 恒为数字(非排队时为 0),?? 0 不可达
|
|
648
|
+
+ '<div class="line"><span class="k">守护进程</span><span class="v" id="sup-state">' + (running ? ('运行中 · 重启 ' + (status?.daemon?.restarts ?? 0) + ' 次' + (paused ? (' · 暂停剩 ' + left + ' 秒') : '') + (policy?.active ? (' · 排队已等 ' + policy.waitedSeconds + ' 秒') : '')) : '未运行') + '</span></div>'
|
|
649
|
+
+ '<div class="line"><span class="k">守护进程版本</span><span class="v" id="daemon-version">' + escapeHtml(staleDaemon ? (String(daemonVersion) + ' · 与插件 ' + PLUGIN_VERSION + ' 不一致') : (daemonVersion ?? '未知')) + '</span></div>'
|
|
650
|
+
+ (staleDaemon
|
|
651
|
+
? '<div class="card warn" style="margin-top:8px"><div class="line"><span class="k">守护进程在跑旧代码</span><span class="v">需重启</span></div>'
|
|
652
|
+
+ '<p class="sub" style="margin:4px 0 0">守护进程是常驻进程,插件更新后它仍在执行启动时的旧代码(重启/拉起逻辑不会自动更新)。'
|
|
653
|
+
+ '用下面的「重启守护进程」加载新代码;它只重启自己,不会影响正在运行的会话。</p></div>'
|
|
654
|
+
: '')
|
|
598
655
|
+ '<div class="line"><span class="k">重启队列</span><span class="v" id="queue-state">' + (policy?.active ? ('排队中 · ' + escapeHtml(policy.reason || '等待空闲')) : '未排队') + '</span></div>'
|
|
599
|
-
|
|
656
|
+
// status().config 的 name 恒为非空字符串、quietMs/pollMs 恒为数字:|| / ?? 兜底不可达
|
|
657
|
+
+ '<div class="line"><span class="k">当前策略</span><span class="v" id="policy-state">' + escapeHtml(cfg.name + ' · 安静 ' + Math.round(cfg.quietMs / 1000) + ' 秒 · 轮询 ' + Math.round(cfg.pollMs / 1000) + ' 秒') + '</span></div>'
|
|
600
658
|
+ '<div class="line"><span class="k">繁忙</span><span class="v" id="busy-state">' + (busy ? ('是(' + sessions.length + ' 个会话运行中)') : '否(空闲)') + '</span></div>'
|
|
601
659
|
+ '<ul id="busy-list">' + busyItems + '</ul>'
|
|
602
660
|
+ LIVE_SCRIPT
|
|
@@ -628,6 +686,25 @@ function renderRestartPage({ status, sessions, message, confirmForce, portState
|
|
|
628
686
|
+ '</body></html>'
|
|
629
687
|
}
|
|
630
688
|
|
|
689
|
+
/**
|
|
690
|
+
* /debug 截图上传的限制表。
|
|
691
|
+
*
|
|
692
|
+
* 为什么要放宽类型:手机(HarmonyOS/Android)相册里选中"原图"时,浏览器给出的
|
|
693
|
+
* dataURL 可能是 heic/heif/gif/bmp,而旧实现只认 png/jpeg/webp,一律 400,
|
|
694
|
+
* 用户看到的就是"上传没反应"。这里按 MIME 映射成扩展名,落盘后仍可下载查看。
|
|
695
|
+
*/
|
|
696
|
+
const UPLOAD_LIMIT_BYTES = 12 * 1024 * 1024;
|
|
697
|
+
const UPLOAD_IMAGE_EXT = {
|
|
698
|
+
png: 'png',
|
|
699
|
+
jpeg: 'jpg',
|
|
700
|
+
jpg: 'jpg',
|
|
701
|
+
webp: 'webp',
|
|
702
|
+
gif: 'gif',
|
|
703
|
+
bmp: 'bmp',
|
|
704
|
+
heic: 'heic',
|
|
705
|
+
heif: 'heic',
|
|
706
|
+
};
|
|
707
|
+
|
|
631
708
|
const DEBUG_HTML = `<!doctype html>
|
|
632
709
|
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
633
710
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
@@ -639,6 +716,7 @@ const DEBUG_HTML = `<!doctype html>
|
|
|
639
716
|
h1 { font-size: 19px; margin: 6px 0 2px; }
|
|
640
717
|
h2 { font-size: 14px; margin: 26px 0 8px; color:#9aa4b2; font-weight: 600; }
|
|
641
718
|
.sub { color:#8b93a1; font-size: 13px; margin: 4px 0 0; }
|
|
719
|
+
.err { color:#ff9b9b; }
|
|
642
720
|
.card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:14px; margin-top:10px; }
|
|
643
721
|
.row { display:flex; justify-content:space-between; gap:12px; padding:6px 0; font-size:13px; border-bottom:1px solid #21262f; }
|
|
644
722
|
.row:last-child { border-bottom:0; }
|
|
@@ -693,6 +771,15 @@ const DEBUG_HTML = `<!doctype html>
|
|
|
693
771
|
{{shots}}
|
|
694
772
|
</div>
|
|
695
773
|
|
|
774
|
+
<h2>网络自检</h2>
|
|
775
|
+
<div class="card">
|
|
776
|
+
<p class="sub">点一下会依次测:首页 HTML、鉴权状态、入口脚本、RPC 通道(/api/remote.mux)、缓存与 Service Worker。
|
|
777
|
+
每步都有超时,结果同时回传服务端,所以即使页面显示不全也能在电脑端查审计。</p>
|
|
778
|
+
<button id="netdiag-run" type="button">开始检测</button>
|
|
779
|
+
<button id="netdiag-copy" type="button" class="ghost">复制结果</button>
|
|
780
|
+
<pre id="netdiag-out">(还没开始)</pre>
|
|
781
|
+
</div>
|
|
782
|
+
|
|
696
783
|
<h2>诊断</h2>
|
|
697
784
|
<div class="card">
|
|
698
785
|
<div class="row"><span class="k">样式文件</span><span class="v">{{cssInfo}}</span></div>
|
|
@@ -709,45 +796,8 @@ const DEBUG_HTML = `<!doctype html>
|
|
|
709
796
|
<a class="btn ghost" href="/logout">退出登录</a>
|
|
710
797
|
</div>
|
|
711
798
|
</div>
|
|
712
|
-
<script>
|
|
713
|
-
|
|
714
|
-
const input = document.getElementById('file')
|
|
715
|
-
const button = document.getElementById('send')
|
|
716
|
-
const result = document.getElementById('result')
|
|
717
|
-
if (!input || !button || !result) return
|
|
718
|
-
button.addEventListener('click', async () => {
|
|
719
|
-
const file = input.files && input.files[0]
|
|
720
|
-
if (!file) { result.textContent = '先选一张图片。'; return }
|
|
721
|
-
if (file.size > 12 * 1024 * 1024) { result.textContent = '图片太大(上限 12MB)。'; return }
|
|
722
|
-
result.textContent = '读取中…'
|
|
723
|
-
const dataUrl = await new Promise((resolve, reject) => {
|
|
724
|
-
const reader = new FileReader()
|
|
725
|
-
reader.onload = () => resolve(String(reader.result))
|
|
726
|
-
reader.onerror = () => reject(new Error('读取失败'))
|
|
727
|
-
reader.readAsDataURL(file)
|
|
728
|
-
}).catch((error) => { result.textContent = error.message; return null })
|
|
729
|
-
if (!dataUrl) return
|
|
730
|
-
result.textContent = '上传中…'
|
|
731
|
-
try {
|
|
732
|
-
const res = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
|
|
733
|
-
method: 'POST',
|
|
734
|
-
headers: { 'content-type': 'application/json' },
|
|
735
|
-
body: JSON.stringify({ name: file.name, dataUrl }),
|
|
736
|
-
})
|
|
737
|
-
const text = await res.text()
|
|
738
|
-
if (!res.ok) { result.textContent = '失败:' + text.slice(0, 200); return }
|
|
739
|
-
const data = JSON.parse(text)
|
|
740
|
-
result.innerHTML = '已保存:<code>' + data.file + '</code>'
|
|
741
|
-
const img = document.createElement('img')
|
|
742
|
-
img.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
|
|
743
|
-
img.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
|
|
744
|
-
document.querySelector('.shots')?.appendChild(img) ?? result.appendChild(img)
|
|
745
|
-
} catch (error) {
|
|
746
|
-
result.textContent = '网络错误:' + error.message
|
|
747
|
-
}
|
|
748
|
-
})
|
|
749
|
-
})()
|
|
750
|
-
</script>
|
|
799
|
+
<script src="/dsh_homing/netdiag.js" defer></script>
|
|
800
|
+
<script src="/dsh_homing/debug.js" defer></script>
|
|
751
801
|
</body></html>
|
|
752
802
|
`;
|
|
753
803
|
|
|
@@ -848,14 +898,20 @@ function sessionRunning(dshHomeDir) {
|
|
|
848
898
|
async function collectRestartState(dataDir) {
|
|
849
899
|
const sessions = sessionRunning(path.resolve(dataDir, '..', '..'));
|
|
850
900
|
const status = await restartService.status();
|
|
901
|
+
const health = await restartService.health();
|
|
851
902
|
const policyStatus = restartPolicy.status();
|
|
852
|
-
|
|
903
|
+
// runner 的 status() 恒返回对象且带 config,可选链与 ?? null 不可达
|
|
904
|
+
const config = policyStatus.config;
|
|
905
|
+
// 守护进程是长驻进程:插件升级后如果没重启它,它跑的还是旧代码(2026-11-14 事故根因)。
|
|
906
|
+
const daemonVersion = typeof health?.version === 'string' ? health.version : null;
|
|
907
|
+
const staleDaemon = daemonVersion !== null && daemonVersion !== 'unknown' && daemonVersion !== PLUGIN_VERSION;
|
|
853
908
|
return {
|
|
854
909
|
config,
|
|
855
910
|
policy: {
|
|
856
911
|
active: policyStatus?.active === true,
|
|
857
|
-
|
|
858
|
-
|
|
912
|
+
// runner 的 status() 保证 reason 是字符串、waitedSeconds 是数字,不需要 ?? 兜底
|
|
913
|
+
reason: policyStatus.reason,
|
|
914
|
+
waitedSeconds: policyStatus.waitedSeconds,
|
|
859
915
|
busy: policyStatus?.busy === true,
|
|
860
916
|
},
|
|
861
917
|
running: status?.running ?? false,
|
|
@@ -863,6 +919,8 @@ async function collectRestartState(dataDir) {
|
|
|
863
919
|
paused: status?.paused ?? false,
|
|
864
920
|
pausedSecondsLeft: status?.pausedSecondsLeft ?? 0,
|
|
865
921
|
busy: sessions.length > 0,
|
|
922
|
+
daemonVersion,
|
|
923
|
+
staleDaemon,
|
|
866
924
|
sessions: sessions.map((s) => ({ title: s.title || '', cwd: s.cwd || '', age: s.age })),
|
|
867
925
|
};
|
|
868
926
|
}
|
|
@@ -880,7 +938,8 @@ async function broadcastRestartState(dataDir, extra) {
|
|
|
880
938
|
lastPayload = payload;
|
|
881
939
|
lastPushAt = now;
|
|
882
940
|
for (const res of [...sseClients]) {
|
|
883
|
-
|
|
941
|
+
// ServerResponse.write 只会异步报错、不会同步抛;连接关闭由上面 req.on('close') 清理 sseClients
|
|
942
|
+
res.write((changed ? 'data: ' + payload : ': ping') + '\n\n')
|
|
884
943
|
}
|
|
885
944
|
}
|
|
886
945
|
|
|
@@ -1024,7 +1083,7 @@ function base32Encode(buffer) {
|
|
|
1024
1083
|
bits -= 5;
|
|
1025
1084
|
}
|
|
1026
1085
|
}
|
|
1027
|
-
|
|
1086
|
+
// 两个调用点都是 5 字节的倍数(40/160 bit),bits 恒为 0,无需补尾巴
|
|
1028
1087
|
return out;
|
|
1029
1088
|
}
|
|
1030
1089
|
|
|
@@ -1063,10 +1122,12 @@ const LOGIN_HTML = `<!doctype html>
|
|
|
1063
1122
|
<label for="p">密码</label>
|
|
1064
1123
|
<input id="p" name="password" type="password" autocomplete="current-password" required>
|
|
1065
1124
|
{{totp}}
|
|
1125
|
+
{{next}}
|
|
1066
1126
|
<button type="submit">登录</button>
|
|
1067
1127
|
</form>
|
|
1068
1128
|
{{message}}
|
|
1069
1129
|
<div class="hint">登录一次后 3 天内免登录 · <a href="/dsh_homing/reset" style="color:#7aa7ff">忘记密码?</a></div>
|
|
1130
|
+
{{hint}}
|
|
1070
1131
|
</div></body></html>`;
|
|
1071
1132
|
|
|
1072
1133
|
const RESET_HTML = `<!doctype html>
|
|
@@ -1115,7 +1176,16 @@ const RESET_HTML = `<!doctype html>
|
|
|
1115
1176
|
const TOTP_FIELD = `<label for="c">验证码</label>
|
|
1116
1177
|
<input id="c" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]*" maxlength="6" placeholder="验证器里的 6 位数字" required>`;
|
|
1117
1178
|
|
|
1118
|
-
|
|
1179
|
+
/** 只接受本站路径作为登录后的落点,避免开放重定向(//evil.com、/\evil.com 都挡掉)。 */
|
|
1180
|
+
function safeNextPath(value) {
|
|
1181
|
+
const text = String(value ?? '');
|
|
1182
|
+
if (!text.startsWith('/')) return '';
|
|
1183
|
+
if (text.startsWith('//') || text.startsWith('/\\')) return '';
|
|
1184
|
+
if (text.length > 300) return '';
|
|
1185
|
+
return text;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function sendLogin(res, message = '', requireTotp = false, next = '', hint = '') {
|
|
1119
1189
|
res.writeHead(200, {
|
|
1120
1190
|
'content-type': 'text/html; charset=utf-8',
|
|
1121
1191
|
'cache-control': 'no-store',
|
|
@@ -1125,22 +1195,42 @@ function sendLogin(res, message = '', requireTotp = false) {
|
|
|
1125
1195
|
'x-content-type-options': 'nosniff',
|
|
1126
1196
|
'referrer-policy': 'no-referrer',
|
|
1127
1197
|
});
|
|
1128
|
-
|
|
1198
|
+
const nextField = next === '' ? '' : `<input type="hidden" name="next" value="${escapeHtml(next)}">`;
|
|
1199
|
+
const hintHtml = hint === '' ? '' : `<div class="hint">${escapeHtml(hint)}</div>`;
|
|
1200
|
+
res.end(
|
|
1201
|
+
LOGIN_HTML
|
|
1202
|
+
.replace('{{totp}}', requireTotp ? TOTP_FIELD : '')
|
|
1203
|
+
.replace('{{next}}', nextField)
|
|
1204
|
+
.replace('{{message}}', message)
|
|
1205
|
+
.replace('{{hint}}', hintHtml),
|
|
1206
|
+
);
|
|
1129
1207
|
}
|
|
1130
1208
|
|
|
1131
1209
|
/**
|
|
1132
|
-
*
|
|
1133
|
-
*
|
|
1134
|
-
*
|
|
1210
|
+
* 读请求体,但**超限时不粗暴断开**。
|
|
1211
|
+
*
|
|
1212
|
+
* 旧实现 readBody 一旦超限就 req.destroy():客户端正在上传时连接被重置,
|
|
1213
|
+
* 浏览器只看到 ECONNRESET,页面上什么都不显示——用户看到的就是"点上传没反应"。
|
|
1214
|
+
* 这里改为把剩余数据读完(drain)再返回 { overflow: true },让调用方能回一个
|
|
1215
|
+
* 正常的 413 JSON,客户端就能看到"图片太大"而不是白屏。
|
|
1135
1216
|
*/
|
|
1136
|
-
function
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
const
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1217
|
+
function readBodyWithLimit(req, limit) {
|
|
1218
|
+
return new Promise((resolve) => {
|
|
1219
|
+
let size = 0;
|
|
1220
|
+
let overflow = false;
|
|
1221
|
+
const chunks = [];
|
|
1222
|
+
req.on('data', (chunk) => {
|
|
1223
|
+
size += chunk.length;
|
|
1224
|
+
if (size > limit) {
|
|
1225
|
+
overflow = true;
|
|
1226
|
+
chunks.length = 0;
|
|
1227
|
+
return; // 继续收,把连接读干净,避免 RST
|
|
1228
|
+
}
|
|
1229
|
+
if (!overflow) chunks.push(chunk);
|
|
1230
|
+
});
|
|
1231
|
+
req.on('end', () => resolve({ overflow, size, text: Buffer.concat(chunks).toString('utf8') }));
|
|
1232
|
+
req.on('error', () => resolve({ overflow, size, text: '' }));
|
|
1233
|
+
});
|
|
1144
1234
|
}
|
|
1145
1235
|
|
|
1146
1236
|
function readBodyBuffer(req, limit) {
|
|
@@ -1273,9 +1363,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1273
1363
|
}
|
|
1274
1364
|
|
|
1275
1365
|
|
|
1276
|
-
/** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。
|
|
1366
|
+
/** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。
|
|
1367
|
+
* value 只会是 string:两个调用点都是 `if (token && entryExpiry(token) > 0)`,
|
|
1368
|
+
* searchParams.get() 的 null 已被短路挡掉(门禁证明 typeof 兜底不可达)。 */
|
|
1277
1369
|
function entryExpiry(value) {
|
|
1278
|
-
if (typeof value !== 'string') return 0;
|
|
1279
1370
|
const [body, mac] = value.split('.');
|
|
1280
1371
|
if (!body || !mac) return 0;
|
|
1281
1372
|
const expected = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
|
|
@@ -1310,9 +1401,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1310
1401
|
// 目的:登录过的设备都应出现在设备管理页、可单独吊销;
|
|
1311
1402
|
// 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
|
|
1312
1403
|
// 只有「浏览器页面导航」才允许自动配对/用入口令牌配对。
|
|
1313
|
-
// fetch/XHR
|
|
1314
|
-
//
|
|
1315
|
-
|
|
1404
|
+
// fetch/XHR/脚本不再产生设备记录,否则自动化探测会让设备表越堆越多。
|
|
1405
|
+
//
|
|
1406
|
+
// 判定必须有明确证据(2026-11-15):
|
|
1407
|
+
// 手机/PWA 的顶层导航会带 `Sec-Fetch-Mode: navigate` 或 `Accept: text/html`;
|
|
1408
|
+
// 没有任何这类证据的请求(自动化探测、健康检查)仍按"非导航"处理,保持 404 语义。
|
|
1409
|
+
const isBrowserNavigation = (req) => {
|
|
1410
|
+
if (String(req.headers.accept ?? '').includes('text/html')) return true
|
|
1411
|
+
if (String(req.headers['sec-fetch-mode'] ?? '').toLowerCase() === 'navigate') return true
|
|
1412
|
+
if (String(req.headers['sec-fetch-dest'] ?? '').toLowerCase() === 'document') return true
|
|
1413
|
+
return false
|
|
1414
|
+
}
|
|
1316
1415
|
|
|
1317
1416
|
const ensureDeviceCookie = (req, cookies) => {
|
|
1318
1417
|
const existing = currentDevice(req);
|
|
@@ -1331,12 +1430,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1331
1430
|
};
|
|
1332
1431
|
const persistDevices = (next) => {
|
|
1333
1432
|
const saved = deviceStore.saveState(dir, next);
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
} catch {
|
|
1338
|
-
mtime = 0;
|
|
1339
|
-
}
|
|
1433
|
+
// saveState 是同步写盘且刚返回;这里的 statSync 若失败意味着数据目录被外部删除/损坏,
|
|
1434
|
+
// 属于环境故障,不应静默吞掉(旧实现兜底后 deviceCache.mtime 会失真)。门禁证明该 catch 不可达。
|
|
1435
|
+
const mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
|
|
1340
1436
|
deviceCache = { mtime, state: saved };
|
|
1341
1437
|
return saved;
|
|
1342
1438
|
};
|
|
@@ -1388,7 +1484,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1388
1484
|
bucket.count += 1;
|
|
1389
1485
|
return bucket.count > limit;
|
|
1390
1486
|
};
|
|
1391
|
-
|
|
1487
|
+
// 所有路由都经真实 TCP 连接进入 handler,req.socket.remoteAddress 恒为字符串;
|
|
1488
|
+
// 原 `(req.socket && req.socket.remoteAddress) || 'unknown'` 的兜底在门禁里不可达。
|
|
1489
|
+
const clientKey = (req) => String(req.socket.remoteAddress);
|
|
1392
1490
|
let vncPasswordCache = '';
|
|
1393
1491
|
async function resolveVncPassword() {
|
|
1394
1492
|
if (vncPasswordCache !== '') return vncPasswordCache;
|
|
@@ -1438,7 +1536,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1438
1536
|
};
|
|
1439
1537
|
|
|
1440
1538
|
|
|
1441
|
-
|
|
1539
|
+
// HTTP server 的 IncomingMessage.url 恒为字符串(Node 只在解析出请求行后才进 handler)。
|
|
1540
|
+
const url = new URL(req.url, 'http://dsh-homing.invalid');
|
|
1442
1541
|
// 活跃时间只由"用户真实操作"刷新:手机端键盘/指针/输入事件会 POST /dsh_homing/alive。
|
|
1443
1542
|
// 这里不再把任意请求(页面加载、图标、重定向、控制接口)算作用户输入,
|
|
1444
1543
|
// 否则打开/刷新页面会不断重置安静窗口,排队等待还会被误报成"最近有用户输入"。
|
|
@@ -1554,7 +1653,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1554
1653
|
result = appRegistry.remove(form.get('id') ?? '');
|
|
1555
1654
|
}
|
|
1556
1655
|
appendAudit(dir, 'app-registry-' + action, { id: String(form.get('id') ?? form.get('originalId') ?? ''), ok: result.ok, error: result.error ?? null });
|
|
1557
|
-
|
|
1656
|
+
// appRegistry 的每条失败路径都带 error 字符串(门禁证明 `?? '保存失败'` 不可达)
|
|
1657
|
+
const message = result.ok ? '已保存,立即生效。' : result.error;
|
|
1558
1658
|
res.writeHead(303, { location: `/dsh_homing/apps?msg=${encodeURIComponent(message)}${result.ok ? '' : '&error=1'}`, 'cache-control': 'no-store' });
|
|
1559
1659
|
res.end();
|
|
1560
1660
|
return;
|
|
@@ -1598,15 +1698,24 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1598
1698
|
const upstream = http.request({
|
|
1599
1699
|
host: '127.0.0.1',
|
|
1600
1700
|
port: restartDaemonPort,
|
|
1601
|
-
path: '/' + rest +
|
|
1701
|
+
path: '/' + rest + url.search,
|
|
1602
1702
|
method: req.method,
|
|
1603
1703
|
timeout: 8000,
|
|
1604
1704
|
}, (up) => {
|
|
1605
|
-
res.writeHead(up.statusCode
|
|
1705
|
+
res.writeHead(up.statusCode, { 'content-type': up.headers['content-type'] ?? 'application/json', 'cache-control': 'no-store' });
|
|
1606
1706
|
up.pipe(res);
|
|
1607
1707
|
});
|
|
1608
|
-
|
|
1609
|
-
|
|
1708
|
+
// 注意:timeout 与 error 可能先后触发(destroy 会引发 ECONNRESET),
|
|
1709
|
+
// 第二次 writeHead 会抛 ERR_HTTP_HEADERS_SENT 把插件进程打崩,必须判 headersSent。
|
|
1710
|
+
upstream.on('timeout', () => {
|
|
1711
|
+
if (!res.headersSent) res.writeHead(504).end('restart-daemon timeout');
|
|
1712
|
+
upstream.destroy();
|
|
1713
|
+
});
|
|
1714
|
+
upstream.on('error', () => {
|
|
1715
|
+
if (res.headersSent) { res.destroy(); return; }
|
|
1716
|
+
res.writeHead(502, { 'content-type': 'application/json' });
|
|
1717
|
+
res.end(JSON.stringify({ error: '守护进程未运行' }));
|
|
1718
|
+
});
|
|
1610
1719
|
upstream.end();
|
|
1611
1720
|
return;
|
|
1612
1721
|
}
|
|
@@ -1620,15 +1729,21 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1620
1729
|
// 会话繁忙度:以会话文件里的 turnBoundary 为准(step=start 即运行中)
|
|
1621
1730
|
|
|
1622
1731
|
// 重启页面的客户端脚本(外部文件,script-src 'self' 直接放行)
|
|
1732
|
+
// 文件随 npm 包一起发布;读失败属于安装损坏,交给外层 safeHandler 统一 500(不再单点吞异常)。
|
|
1623
1733
|
if (url.pathname === '/dsh_homing/restart.js' && req.method === 'GET') {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1734
|
+
const js = fs.readFileSync(new URL('./restart/client.mjs', import.meta.url), 'utf8');
|
|
1735
|
+
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
1736
|
+
res.end(js);
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
// 调试页的上传脚本:必须是同源外部文件。
|
|
1741
|
+
// 页面 CSP 是 `script-src 'self'`(没有 'unsafe-inline'),内联 <script> 会被浏览器丢弃,
|
|
1742
|
+
// 这就是 2026-11-15「上传点了没反应」的根因——连请求都没发出。
|
|
1743
|
+
if (url.pathname === '/dsh_homing/debug.js' && req.method === 'GET') {
|
|
1744
|
+
const js = fs.readFileSync(new URL('./lib/debug-page.js', import.meta.url), 'utf8');
|
|
1745
|
+
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
1746
|
+
res.end(js);
|
|
1632
1747
|
return;
|
|
1633
1748
|
}
|
|
1634
1749
|
|
|
@@ -1720,9 +1835,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1720
1835
|
const push = async () => {
|
|
1721
1836
|
const state = await collectRestartState(dataDir());
|
|
1722
1837
|
seq += 1;
|
|
1723
|
-
try
|
|
1724
|
-
|
|
1725
|
-
} catch { sseClients.delete(res) }
|
|
1838
|
+
// res.write 对已销毁的响应不会同步抛异常(只会异步 emit error),无需 try/catch。
|
|
1839
|
+
res.write('data: ' + JSON.stringify({ ...state, seq, client: clientId, ts: Date.now() }) + '\n\n');
|
|
1726
1840
|
};
|
|
1727
1841
|
void push();
|
|
1728
1842
|
const timer = setInterval(() => { void push() }, 2000);
|
|
@@ -1791,10 +1905,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1791
1905
|
const inbox = inboxPaths(dataDir());
|
|
1792
1906
|
const rest = decodeURIComponent(url.pathname.slice('/dsh_homing/debug/inbox/'.length));
|
|
1793
1907
|
const parts = rest.split('/');
|
|
1794
|
-
|
|
1908
|
+
// 缺少图片名时段(/debug/inbox/<id>)时 parts[1] 为空,path.join(uploads,'') 会变成目录,
|
|
1909
|
+
// 直接 createReadStream 一个目录会抛 EISDIR 把进程打崩,所以先挡掉。
|
|
1910
|
+
if (!parts[1]) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
|
|
1911
|
+
const file = path.join(inbox.uploads, path.basename(parts[1]));
|
|
1795
1912
|
if (!fs.existsSync(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end('not found'); return }
|
|
1796
1913
|
res.writeHead(200, { 'content-type': 'image/*', 'cache-control': 'private, max-age=60' });
|
|
1797
|
-
fs.createReadStream(file)
|
|
1914
|
+
const stream = fs.createReadStream(file);
|
|
1915
|
+
// writeHead 已经执行过,headersSent 恒为 true;读流失败时只能断开响应,避免未处理的
|
|
1916
|
+
// stream 'error' 事件把进程打崩。
|
|
1917
|
+
stream.on('error', () => res.destroy());
|
|
1918
|
+
stream.pipe(res);
|
|
1798
1919
|
return;
|
|
1799
1920
|
}
|
|
1800
1921
|
|
|
@@ -1802,6 +1923,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1802
1923
|
if (url.pathname === '/dsh_homing/restart' && req.method === 'GET') {
|
|
1803
1924
|
const sessions = sessionRunning(path.resolve(dataDir(), '..', '..'));
|
|
1804
1925
|
const status = await restartService.status();
|
|
1926
|
+
const daemonHealth = await restartService.health();
|
|
1927
|
+
const daemonVersion = typeof daemonHealth?.version === 'string' ? daemonHealth.version : null;
|
|
1928
|
+
const staleDaemon = daemonVersion !== null && daemonVersion !== 'unknown' && daemonVersion !== PLUGIN_VERSION;
|
|
1805
1929
|
const message = url.searchParams.get('m') ?? '';
|
|
1806
1930
|
res.writeHead(200, {
|
|
1807
1931
|
'content-type': 'text/html; charset=utf-8',
|
|
@@ -1810,7 +1934,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1810
1934
|
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
|
|
1811
1935
|
});
|
|
1812
1936
|
const portState = { conflict: await detectRestartPortConflict(), disabled: restartDaemonDisabled(), port: restartDaemonPort };
|
|
1813
|
-
res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState }));
|
|
1937
|
+
res.end(renderRestartPage({ status, sessions, message, confirmForce: url.searchParams.get('confirm') === '1', portState, daemonVersion, staleDaemon }));
|
|
1814
1938
|
return;
|
|
1815
1939
|
}
|
|
1816
1940
|
|
|
@@ -1818,7 +1942,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1818
1942
|
if (url.pathname === '/dsh_homing/restart/daemon' && req.method === 'POST') {
|
|
1819
1943
|
let message = '';
|
|
1820
1944
|
appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old' });
|
|
1821
|
-
|
|
1945
|
+
// restartService.stop() 内部对超时/连接错误都降级 resolve,不会 reject(门禁证明 catch 不可达)
|
|
1946
|
+
await restartService.stop();
|
|
1822
1947
|
appendAudit(dataDir(), 'restart-daemon-manual-step', { step: 'stop-old-done' });
|
|
1823
1948
|
await new Promise((resolve) => setTimeout(resolve, 600));
|
|
1824
1949
|
const started = startRestartDaemonDetached();
|
|
@@ -1849,7 +1974,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1849
1974
|
} else {
|
|
1850
1975
|
// 旧端口上的守护进程用"授权停止"请求关掉,再切换(CLI 的停止请求会被鉴权拒绝)
|
|
1851
1976
|
if (oldHealth && oldHealth.ok !== false) {
|
|
1852
|
-
|
|
1977
|
+
// restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
|
|
1978
|
+
await restartService.stop();
|
|
1853
1979
|
await new Promise((resolve) => setTimeout(resolve, 600));
|
|
1854
1980
|
}
|
|
1855
1981
|
writePortOverride(port);
|
|
@@ -1859,16 +1985,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1859
1985
|
const started = startRestartDaemonDetached();
|
|
1860
1986
|
const healthy = await waitRestartDaemonHealthy(5000);
|
|
1861
1987
|
appendAudit(dataDir(), 'restart-daemon-port-change', { from: oldPort, port, started, healthy });
|
|
1988
|
+
// startRestartDaemonDetached 只在「CLI 文件不存在」时返回 false;文件随包发布,
|
|
1989
|
+
// 该分支门禁证明不可达,因此这里只剩「健康/未就绪」两种结果。
|
|
1862
1990
|
if (healthy) message = '已切换到端口 ' + port + ',守护进程运行正常';
|
|
1863
|
-
else
|
|
1864
|
-
else message = '已保存端口 ' + port + ',但启动失败,请查看日志';
|
|
1991
|
+
else message = '已保存端口 ' + port + ',但守护进程未就绪(端口可能刚被占用),请查看日志';
|
|
1865
1992
|
}
|
|
1866
1993
|
} else if (action === 'disable') {
|
|
1867
1994
|
try {
|
|
1868
1995
|
fs.mkdirSync(restartDaemonStateDir(), { recursive: true });
|
|
1869
1996
|
fs.writeFileSync(path.join(restartDaemonStateDir(), 'disabled.json'), JSON.stringify({ at: new Date().toISOString() }));
|
|
1870
1997
|
} catch { /* 忽略 */ }
|
|
1871
|
-
|
|
1998
|
+
// restartService.stop() 不会 reject(超时/连接错误都降级 resolve)
|
|
1999
|
+
await restartService.stop();
|
|
1872
2000
|
appendAudit(dataDir(), 'restart-daemon-disabled', {});
|
|
1873
2001
|
message = '已关闭重启守护进程';
|
|
1874
2002
|
} else if (action === 'enable') {
|
|
@@ -1915,21 +2043,19 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1915
2043
|
return;
|
|
1916
2044
|
}
|
|
1917
2045
|
const result = await restartPolicy.force();
|
|
2046
|
+
// restartPolicy.force() 只返回 { ok, ...status() }:status() 里没有 status/error 字段,
|
|
2047
|
+
// 因此「403 / restart-daemon down 文案」分支门禁证明不可达,失败原因统一按"没成功"处理。
|
|
1918
2048
|
if (wantsJson) {
|
|
1919
2049
|
const ok = result.ok === true;
|
|
1920
|
-
message = ok ? '已触发强制重启' :
|
|
1921
|
-
? '守护进程拒绝了请求(来源进程校验未通过)'
|
|
1922
|
-
: '守护进程未运行或未响应');
|
|
2050
|
+
message = ok ? '已触发强制重启' : '守护进程未运行或未响应';
|
|
1923
2051
|
res.writeHead(ok ? 200 : 409, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1924
|
-
res.end(JSON.stringify({ ok, status:
|
|
2052
|
+
res.end(JSON.stringify({ ok, status: 0, message }));
|
|
1925
2053
|
return;
|
|
1926
2054
|
}
|
|
1927
2055
|
if (result.ok) {
|
|
1928
2056
|
message = '已触发强制重启(策略层已放行)';
|
|
1929
|
-
} else if (result.status === 403) {
|
|
1930
|
-
message = '提交失败:守护进程拒绝了请求(来源进程校验未通过),请查看守护进程日志';
|
|
1931
2057
|
} else {
|
|
1932
|
-
message = '
|
|
2058
|
+
message = '提交失败:守护进程未运行或拒绝响应';
|
|
1933
2059
|
}
|
|
1934
2060
|
} else if (action === 'pause') {
|
|
1935
2061
|
const minutes = Number(form.get('minutes'));
|
|
@@ -2000,17 +2126,17 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2000
2126
|
res.end(fs.readFileSync(caCertPath));
|
|
2001
2127
|
return;
|
|
2002
2128
|
}
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
}
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
}
|
|
2129
|
+
// findOpenssl 恒返回字符串(最差是裸命令名 openssl.exe),spawnSync 传字符串命令不会抛;
|
|
2130
|
+
// 转换失败只会表现为 derFile 不存在 → 退回 PEM。门禁证明 try/catch 不可达。
|
|
2131
|
+
const openssl = findOpenssl();
|
|
2132
|
+
const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
|
|
2133
|
+
if (!fs.existsSync(derFile)) {
|
|
2134
|
+
spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
|
|
2135
|
+
}
|
|
2136
|
+
if (fs.existsSync(derFile)) {
|
|
2137
|
+
res.end(fs.readFileSync(derFile));
|
|
2138
|
+
return;
|
|
2139
|
+
}
|
|
2014
2140
|
res.end(fs.readFileSync(caCertPath));
|
|
2015
2141
|
return;
|
|
2016
2142
|
}
|
|
@@ -2020,6 +2146,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2020
2146
|
|| url.pathname === '/dsh_homing/account' || url.pathname === '/dsh_homing/reset'
|
|
2021
2147
|
|| url.pathname === '/dsh_homing/devices'
|
|
2022
2148
|
|| url.pathname === '/files' || url.pathname.startsWith('/files/')
|
|
2149
|
+
// 诊断/自救页必须在"未登录/清过缓存"的状态下也能打开——这正是它们存在的场景
|
|
2150
|
+
|| url.pathname === '/dsh_homing/netdiag' || url.pathname === '/dsh_homing/netdiag/report'
|
|
2151
|
+
|| url.pathname === '/dsh_homing/netdiag.js'
|
|
2152
|
+
|| url.pathname === '/dsh_homing/recover' || url.pathname === '/dsh_homing/recover.js'
|
|
2153
|
+
// 页面内鉴权守卫(auth-guard.js)与客户端错误上报(client-report.js)
|
|
2154
|
+
// 必须在未登录时也能加载与上报
|
|
2155
|
+
|| url.pathname === '/dsh_homing/auth-state' || url.pathname === '/dsh_homing/auth-guard.js'
|
|
2156
|
+
|| url.pathname === '/dsh_homing/idb-fallback.js'
|
|
2157
|
+
|| url.pathname === '/dsh_homing/client-report.js' || url.pathname === '/dsh_homing/client-error'
|
|
2158
|
+
// 图标与 manifest 是浏览器自动抓的,挡掉只会让登录页看起来坏掉、并在审计里刷噪音
|
|
2159
|
+
|| url.pathname === '/manifest.webmanifest' || url.pathname === '/apple-touch-icon.png'
|
|
2160
|
+
|| url.pathname === '/favicon.svg' || url.pathname === '/favicon-dark.svg' || url.pathname === '/favicon.ico'
|
|
2023
2161
|
|| url.pathname === '/debug' || url.pathname === '/dsh_homing/debug'
|
|
2024
2162
|
|| url.pathname.startsWith('/debug/') || url.pathname.startsWith('/dsh_homing/debug/');
|
|
2025
2163
|
|
|
@@ -2143,6 +2281,188 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2143
2281
|
}
|
|
2144
2282
|
}
|
|
2145
2283
|
|
|
2284
|
+
// 鉴权状态查询:给页面内守卫用(auth-guard.js)。
|
|
2285
|
+
// 必须免登录、不缓存——它存在的意义就是告诉页面"你现在其实没登录"。
|
|
2286
|
+
//
|
|
2287
|
+
// 口径必须和「导航闸门」一致:只有**有效会话**才算已登录。
|
|
2288
|
+
// 光有设备 Cookie(配对过但会话过期/被清)不算——那正是用户要求跳登录页的情况。
|
|
2289
|
+
if (url.pathname === '/dsh_homing/auth-state' && req.method === 'GET') {
|
|
2290
|
+
const jar = readCookies(req.headers.cookie);
|
|
2291
|
+
const authenticated = !config.login || sessionValid(req);
|
|
2292
|
+
res.writeHead(200, {
|
|
2293
|
+
'content-type': 'application/json; charset=utf-8',
|
|
2294
|
+
'cache-control': 'no-store, must-revalidate',
|
|
2295
|
+
'x-content-type-options': 'nosniff',
|
|
2296
|
+
});
|
|
2297
|
+
res.end(JSON.stringify({
|
|
2298
|
+
authenticated,
|
|
2299
|
+
hasSession: Boolean(jar[SESSION_COOKIE]),
|
|
2300
|
+
hasDevice: Boolean(jar[DEVICE_COOKIE]),
|
|
2301
|
+
login: Boolean(config.login),
|
|
2302
|
+
reason: authenticated ? 'ok' : (jar[SESSION_COOKIE] ? 'session-expired' : 'no-session'),
|
|
2303
|
+
}));
|
|
2304
|
+
return;
|
|
2305
|
+
}
|
|
2306
|
+
|
|
2307
|
+
if (url.pathname === '/dsh_homing/idb-fallback.js' && req.method === 'GET') {
|
|
2308
|
+
// 文件随包发布;读失败由外层 safeHandler 统一 500,不再单点 try/catch
|
|
2309
|
+
const js = fs.readFileSync(new URL('./lib/idb-fallback.js', import.meta.url), 'utf8');
|
|
2310
|
+
res.writeHead(200, {
|
|
2311
|
+
'content-type': 'application/javascript; charset=utf-8',
|
|
2312
|
+
'cache-control': 'no-store',
|
|
2313
|
+
});
|
|
2314
|
+
res.end(js);
|
|
2315
|
+
return;
|
|
2316
|
+
}
|
|
2317
|
+
|
|
2318
|
+
if (url.pathname === '/dsh_homing/auth-guard.js' && req.method === 'GET') {
|
|
2319
|
+
const js = fs.readFileSync(new URL('./lib/auth-guard.js', import.meta.url), 'utf8');
|
|
2320
|
+
res.writeHead(200, {
|
|
2321
|
+
'content-type': 'application/javascript; charset=utf-8',
|
|
2322
|
+
// 注入脚本必须每次取新的:它承载诊断与登录守卫,旧版本会掩盖问题
|
|
2323
|
+
'cache-control': 'no-store',
|
|
2324
|
+
});
|
|
2325
|
+
res.end(js);
|
|
2326
|
+
return;
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
if (url.pathname === '/dsh_homing/client-report.js' && req.method === 'GET') {
|
|
2330
|
+
const js = fs.readFileSync(new URL('./lib/client-report.js', import.meta.url), 'utf8');
|
|
2331
|
+
res.writeHead(200, {
|
|
2332
|
+
'content-type': 'application/javascript; charset=utf-8',
|
|
2333
|
+
'cache-control': 'no-store',
|
|
2334
|
+
});
|
|
2335
|
+
res.end(js);
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
// 客户端错误上报:手机上没有 devtools,页面出错只能靠它自己交回证据。
|
|
2340
|
+
// 免登录(页面可能就在"未登录"或"登录失效"时出错)。
|
|
2341
|
+
if (url.pathname === '/dsh_homing/client-error' && req.method === 'POST') {
|
|
2342
|
+
let payload = null;
|
|
2343
|
+
try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
|
|
2344
|
+
if (payload && typeof payload === 'object') {
|
|
2345
|
+
appendAudit(dir, 'client-error', {
|
|
2346
|
+
kind: String(payload.kind ?? '').slice(0, 24),
|
|
2347
|
+
message: String(payload.message ?? '').slice(0, 200),
|
|
2348
|
+
source: String(payload.source ?? '').slice(0, 120),
|
|
2349
|
+
line: payload.line ?? 0,
|
|
2350
|
+
url: String(payload.url ?? '').slice(0, 160),
|
|
2351
|
+
rootExists: payload.rootExists,
|
|
2352
|
+
scriptCount: payload.scriptCount,
|
|
2353
|
+
linkCount: payload.linkCount,
|
|
2354
|
+
resources: Array.isArray(payload.resources) ? payload.resources.slice(0, 6) : undefined,
|
|
2355
|
+
ua: String(payload.ua ?? req.headers['user-agent'] ?? '').slice(0, 60),
|
|
2356
|
+
});
|
|
2357
|
+
} else {
|
|
2358
|
+
appendAudit(dir, 'client-error', { kind: 'bad-json' });
|
|
2359
|
+
}
|
|
2360
|
+
res.writeHead(204, { 'cache-control': 'no-store' });
|
|
2361
|
+
res.end();
|
|
2362
|
+
return;
|
|
2363
|
+
}
|
|
2364
|
+
|
|
2365
|
+
// 手机端网络自检:在真实设备上跑一遍首页加载链路(HTML → assets → plugins 包 → WebSocket),
|
|
2366
|
+
// 把结果回传审计。桌面端复现不了手机的问题时,这是唯一能拿到设备侧证据的办法。
|
|
2367
|
+
// 注意:不要求登录——它恰恰要在"没登录 / 清过缓存 / 转圈"的状态下打开。
|
|
2368
|
+
if (url.pathname === '/dsh_homing/netdiag' && req.method === 'GET') {
|
|
2369
|
+
res.writeHead(200, {
|
|
2370
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2371
|
+
'cache-control': 'no-store',
|
|
2372
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
|
|
2373
|
+
});
|
|
2374
|
+
res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
|
2375
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2376
|
+
<title>网络自检 · DSH 手机入口</title>
|
|
2377
|
+
<style>
|
|
2378
|
+
:root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.7 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
|
|
2379
|
+
h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
|
|
2380
|
+
pre{background:#171a21;border:1px solid #262b36;border-radius:10px;padding:12px;font-size:13px;line-height:1.6;white-space:pre-wrap;word-break:break-word;user-select:text;-webkit-user-select:text}
|
|
2381
|
+
button{margin:10px 0 0;padding:10px 14px;border-radius:9px;border:0;background:#2a2f3a;color:#e6edf5;font-size:14px;font-weight:600}
|
|
2382
|
+
a{color:#8ab4f8}
|
|
2383
|
+
</style></head><body>
|
|
2384
|
+
<h1>网络自检</h1>
|
|
2385
|
+
<p class="sub">打开这一页会自动跑一遍,每步都有超时;结果同时回传服务端。</p>
|
|
2386
|
+
<p class="sub"><a href="/">← 返回 DSH</a> · <a href="/dsh_homing/debug">调试页</a></p>
|
|
2387
|
+
<pre id="out">检测中…</pre>
|
|
2388
|
+
<button id="copy" type="button">复制结果</button>
|
|
2389
|
+
<script src="/dsh_homing/netdiag.js" defer></script>
|
|
2390
|
+
</body></html>`);
|
|
2391
|
+
return;
|
|
2392
|
+
}
|
|
2393
|
+
|
|
2394
|
+
if (url.pathname === '/dsh_homing/netdiag.js' && req.method === 'GET') {
|
|
2395
|
+
// 记一笔:浏览器到底有没有来取这个脚本。页面停在"检测中"时,
|
|
2396
|
+
// 有没有这条审计就能立刻区分「脚本没加载」和「脚本跑了但卡住」。
|
|
2397
|
+
appendAudit(dir, 'netdiag-js-loaded', { ua: String(req.headers['user-agent'] ?? '').slice(0, 60) });
|
|
2398
|
+
try {
|
|
2399
|
+
const js = fs.readFileSync(new URL('./lib/netdiag.js', import.meta.url), 'utf8');
|
|
2400
|
+
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
2401
|
+
res.end(js);
|
|
2402
|
+
} catch (error) {
|
|
2403
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2404
|
+
res.end('netdiag.js 读取失败:' + String(error?.message ?? error));
|
|
2405
|
+
}
|
|
2406
|
+
return;
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
if (url.pathname === '/dsh_homing/netdiag/report' && req.method === 'POST') {
|
|
2410
|
+
let payload = null;
|
|
2411
|
+
try { payload = JSON.parse(await readBody(req, 64 * 1024)) } catch { payload = null; }
|
|
2412
|
+
const jar = readCookies(req.headers.cookie);
|
|
2413
|
+
appendAudit(dir, 'netdiag', {
|
|
2414
|
+
...(payload ?? { error: 'bad-json' }),
|
|
2415
|
+
serverSide: {
|
|
2416
|
+
hasSession: Boolean(jar[SESSION_COOKIE]),
|
|
2417
|
+
hasDevice: Boolean(jar[DEVICE_COOKIE]),
|
|
2418
|
+
cookieNames: Object.keys(jar),
|
|
2419
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
|
|
2420
|
+
},
|
|
2421
|
+
});
|
|
2422
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
2423
|
+
res.end('{"ok":true}');
|
|
2424
|
+
return;
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
// 一键自救:注销 Service Worker、清掉 Cache Storage、再回到首页。
|
|
2428
|
+
// 手机"清了站点数据还是一直转圈"时,常见原因是残留的 SW 仍从旧缓存回放页面。
|
|
2429
|
+
if (url.pathname === '/dsh_homing/recover' && req.method === 'GET') {
|
|
2430
|
+
res.writeHead(200, {
|
|
2431
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2432
|
+
'cache-control': 'no-store',
|
|
2433
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:",
|
|
2434
|
+
});
|
|
2435
|
+
res.end(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
|
2436
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2437
|
+
<title>一键自救 · DSH 手机入口</title>
|
|
2438
|
+
<style>
|
|
2439
|
+
:root{color-scheme:dark}body{margin:0;padding:16px;font:15px/1.6 system-ui,"Noto Sans SC",sans-serif;background:#0f1115;color:#e8eaed}
|
|
2440
|
+
h1{font-size:18px;margin:4px 0 8px}.sub{color:#8b93a1;font-size:13px}
|
|
2441
|
+
pre{background:#171a21;border:1px solid #262b36;border-radius:10px;padding:12px;font-size:12px;white-space:pre-wrap;word-break:break-all}
|
|
2442
|
+
a{color:#8ab4f8}
|
|
2443
|
+
</style></head><body>
|
|
2444
|
+
<h1>一键自救</h1>
|
|
2445
|
+
<p class="sub">注销 Service Worker、清掉本地缓存,然后回到首页。清完后如果要求登录,就正常登录一次。</p>
|
|
2446
|
+
<p class="sub"><a href="/dsh_homing/netdiag">网络自检</a> · <a href="/">返回 DSH</a></p>
|
|
2447
|
+
<pre id="out">正在清理…</pre>
|
|
2448
|
+
<p class="sub"><a href="/" id="go">清理完点这里回首页</a></p>
|
|
2449
|
+
<script src="/dsh_homing/recover.js" defer></script>
|
|
2450
|
+
</body></html>`);
|
|
2451
|
+
return;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
if (url.pathname === '/dsh_homing/recover.js' && req.method === 'GET') {
|
|
2455
|
+
try {
|
|
2456
|
+
const js = fs.readFileSync(new URL('./lib/recover.js', import.meta.url), 'utf8');
|
|
2457
|
+
res.writeHead(200, { 'content-type': 'application/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
2458
|
+
res.end(js);
|
|
2459
|
+
} catch (error) {
|
|
2460
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2461
|
+
res.end('recover.js 读取失败:' + String(error?.message ?? error));
|
|
2462
|
+
}
|
|
2463
|
+
return;
|
|
2464
|
+
}
|
|
2465
|
+
|
|
2146
2466
|
// 自检:把"兜底转发"这一段的状态暴露出来,便于定位 404
|
|
2147
2467
|
if (url.pathname === '/dsh_homing/selfcheck') {
|
|
2148
2468
|
const up = getUpstreamPort();
|
|
@@ -2344,22 +2664,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2344
2664
|
'content-security-policy': "default-src 'none'",
|
|
2345
2665
|
});
|
|
2346
2666
|
const flush = (text, seq) => {
|
|
2347
|
-
|
|
2348
|
-
try {
|
|
2349
|
-
res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
|
|
2350
|
-
} catch {
|
|
2351
|
-
// 连接已断
|
|
2352
|
-
}
|
|
2667
|
+
res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
|
|
2353
2668
|
};
|
|
2354
2669
|
const backlog = terminal.since(since);
|
|
2355
2670
|
if (backlog !== '') flush(backlog, terminal.latestSeq);
|
|
2356
2671
|
const unsubscribe = terminal.subscribe((text, seq) => flush(text, seq));
|
|
2357
2672
|
const heartbeat = setInterval(() => {
|
|
2358
|
-
|
|
2359
|
-
res.write(': ping\n\n');
|
|
2360
|
-
} catch {
|
|
2361
|
-
clearInterval(heartbeat);
|
|
2362
|
-
}
|
|
2673
|
+
res.write(': ping\n\n');
|
|
2363
2674
|
}, 15000);
|
|
2364
2675
|
const cleanup = () => {
|
|
2365
2676
|
clearInterval(heartbeat);
|
|
@@ -2461,8 +2772,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2461
2772
|
const maxWidth = Number(url.searchParams.get('maxWidth') ?? '1280') || 1280;
|
|
2462
2773
|
const shot = await windowRemote.captureWindow(hwnd, maxWidth);
|
|
2463
2774
|
if (!shot.ok) {
|
|
2464
|
-
appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error
|
|
2465
|
-
sendRemoteJson(500, { ok: false, error: shot.error
|
|
2775
|
+
appendAudit(dir, 'window-frame', { hwnd, ok: false, error: shot.error });
|
|
2776
|
+
sendRemoteJson(500, { ok: false, error: shot.error });
|
|
2466
2777
|
return;
|
|
2467
2778
|
}
|
|
2468
2779
|
sendRemote(200, {
|
|
@@ -2485,8 +2796,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2485
2796
|
if (payload.kind === 'rotate') {
|
|
2486
2797
|
const mode = payload.mode === 'landscape' ? 'landscape' : 'portrait';
|
|
2487
2798
|
const rotated = await setOrientation(mode);
|
|
2488
|
-
appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail
|
|
2489
|
-
sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail
|
|
2799
|
+
appendAudit(dir, 'screen-rotate', { mode, ok: rotated.ok === true, detail: rotated.detail });
|
|
2800
|
+
sendRemoteJson(rotated.ok === true ? 200 : 500, { ok: rotated.ok === true, detail: rotated.detail, screen: rotated.screen ?? null });
|
|
2490
2801
|
return;
|
|
2491
2802
|
}
|
|
2492
2803
|
if (payload.kind === 'cursor') {
|
|
@@ -2921,7 +3232,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2921
3232
|
res.writeHead(500, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
|
2922
3233
|
res.end(`<!doctype html><meta charset="utf-8"><title>预览失败</title><body style="background:#161a20;color:#e6e8ee;font-family:system-ui;padding:24px">
|
|
2923
3234
|
<h1 style="font-size:18px">预览失败</h1>
|
|
2924
|
-
<p style="color:#9aa3b2">${escapeHtml(String(result.error
|
|
3235
|
+
<p style="color:#9aa3b2">${escapeHtml(String(result.error))}</p>
|
|
2925
3236
|
<p><a style="color:#8ab4f8" href="/">← 返回 DSH</a> · <a style="color:#8ab4f8" href="/files?path=${encodeURIComponent(path.dirname(target))}">← 返回文件列表</a></p>
|
|
2926
3237
|
<p><a style="color:#8ab4f8" href="/files/download?path=${encodeURIComponent(target)}">下载后用 WPS / Office 打开</a></p>
|
|
2927
3238
|
</body>`);
|
|
@@ -3070,13 +3381,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
3070
3381
|
try {
|
|
3071
3382
|
errors = fs.readFileSync(path.join(dir, 'debug', 'errors.log'), 'utf8').trim().split('\n').filter(Boolean).slice(-3).reverse();
|
|
3072
3383
|
} catch { /* 没有日志 */ }
|
|
3073
|
-
const row = (k, v, cls) => `<div class="row"><span class="k">${k}</span><span class="v ${cls ?? ''}">${v}</span></div>`;
|
|
3074
3384
|
const deviceCount = deviceStore.partition(devices()).active.length;
|
|
3075
3385
|
res.writeHead(200, {
|
|
3076
3386
|
'content-type': 'text/html; charset=utf-8',
|
|
3077
3387
|
'cache-control': 'no-store',
|
|
3078
3388
|
'x-frame-options': 'DENY',
|
|
3079
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; form-action 'self'; base-uri 'none'",
|
|
3389
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'",
|
|
3080
3390
|
'x-content-type-options': 'nosniff',
|
|
3081
3391
|
'referrer-policy': 'no-referrer',
|
|
3082
3392
|
});
|
|
@@ -3105,29 +3415,61 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
3105
3415
|
}
|
|
3106
3416
|
|
|
3107
3417
|
// 上传截图:接收 dataURL,落盘到 debug/shots/
|
|
3418
|
+
//
|
|
3419
|
+
// 2026-11-15 修复:这个接口之前拒绝时只回一行纯文本、也不写审计,
|
|
3420
|
+
// 结果手机上传失败时既看不到原因、事后也查不到痕迹(audit 里 debug-shot 一直是 0 条)。
|
|
3421
|
+
// 现在:每一次尝试都写审计(成功 debug-shot / 失败 debug-shot-rejected),
|
|
3422
|
+
// 失败原因写清楚(未登录 / JSON 坏了 / 类型不支持 / 超过大小),并给出对应状态码。
|
|
3108
3423
|
if (debugSub === '/upload' && req.method === 'POST') {
|
|
3424
|
+
const ua = String(req.headers['user-agent'] ?? '').slice(0, 120);
|
|
3425
|
+
const declared = Number(req.headers['content-length'] ?? 0);
|
|
3426
|
+
const reject = (status, reason, extra = {}) => {
|
|
3427
|
+
appendAudit(dir, 'debug-shot-rejected', { reason, status, declaredBytes: declared, ua, ...extra });
|
|
3428
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
3429
|
+
res.end(JSON.stringify({ ok: false, error: reason }));
|
|
3430
|
+
};
|
|
3109
3431
|
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
3110
|
-
|
|
3111
|
-
|
|
3432
|
+
reject(401, '未登录(会话或设备 Cookie 失效)');
|
|
3433
|
+
return;
|
|
3434
|
+
}
|
|
3435
|
+
if (declared > UPLOAD_LIMIT_BYTES) {
|
|
3436
|
+
// 先把发过来的数据读完再回响应,否则客户端只会看到连接被重置
|
|
3437
|
+
req.resume();
|
|
3438
|
+
reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(declared / 1024 / 1024).toFixed(1)}MB)`);
|
|
3439
|
+
return;
|
|
3440
|
+
}
|
|
3441
|
+
const body = await readBodyWithLimit(req, UPLOAD_LIMIT_BYTES + 4096);
|
|
3442
|
+
if (body.overflow) {
|
|
3443
|
+
reject(413, `图片太大(上限 ${Math.round(UPLOAD_LIMIT_BYTES / 1024 / 1024)}MB,收到 ${(body.size / 1024 / 1024).toFixed(1)}MB)`);
|
|
3112
3444
|
return;
|
|
3113
3445
|
}
|
|
3114
3446
|
let parsed = null;
|
|
3115
|
-
try { parsed = JSON.parse(
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3447
|
+
try { parsed = JSON.parse(body.text) } catch { parsed = null; }
|
|
3448
|
+
if (parsed === null || typeof parsed !== 'object') {
|
|
3449
|
+
reject(400, '请求体不是合法 JSON(可能是网络中断或被网关截断)');
|
|
3450
|
+
return;
|
|
3451
|
+
}
|
|
3452
|
+
const match = typeof parsed.dataUrl === 'string' ? /^data:image\/([a-z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/iu.exec(parsed.dataUrl) : null;
|
|
3119
3453
|
if (match === null) {
|
|
3120
|
-
|
|
3121
|
-
|
|
3454
|
+
reject(400, '只接受图片的 dataURL(data:image/...;base64,...)');
|
|
3455
|
+
return;
|
|
3456
|
+
}
|
|
3457
|
+
const ext = UPLOAD_IMAGE_EXT[match[1].toLowerCase()];
|
|
3458
|
+
if (ext === undefined) {
|
|
3459
|
+
reject(400, `不支持的图片格式:${match[1]}(支持 ${Object.keys(UPLOAD_IMAGE_EXT).join('/')})`);
|
|
3122
3460
|
return;
|
|
3123
3461
|
}
|
|
3124
|
-
const ext = match[1] === 'jpeg' ? 'jpg' : match[1];
|
|
3125
3462
|
const stamp = new Date().toISOString().replace(/[:.]/gu, '-').slice(0, 19);
|
|
3126
3463
|
const shotsDir = path.join(dir, 'debug', 'shots');
|
|
3127
|
-
fs.mkdirSync(shotsDir, { recursive: true });
|
|
3128
3464
|
const name = `${stamp}.${ext}`;
|
|
3129
|
-
|
|
3130
|
-
|
|
3465
|
+
try {
|
|
3466
|
+
fs.mkdirSync(shotsDir, { recursive: true });
|
|
3467
|
+
fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
|
|
3468
|
+
} catch (error) {
|
|
3469
|
+
reject(500, '写入失败:' + String(error?.message ?? error));
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length, ua });
|
|
3131
3473
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
3132
3474
|
res.end(JSON.stringify({ ok: true, file: name }));
|
|
3133
3475
|
return;
|
|
@@ -3141,7 +3483,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
3141
3483
|
return;
|
|
3142
3484
|
}
|
|
3143
3485
|
const name = decodeURIComponent(debugSub.slice('/files/'.length));
|
|
3144
|
-
if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/u.test(name)) {
|
|
3486
|
+
if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp|gif|bmp|heic)$/u.test(name)) {
|
|
3145
3487
|
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
|
|
3146
3488
|
res.end('文件名不合法');
|
|
3147
3489
|
return;
|
|
@@ -3153,8 +3495,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
3153
3495
|
return;
|
|
3154
3496
|
}
|
|
3155
3497
|
const ext = path.extname(name).slice(1).toLowerCase();
|
|
3498
|
+
const types = { png: 'image/png', webp: 'image/webp', gif: 'image/gif', bmp: 'image/bmp', heic: 'image/heic' };
|
|
3156
3499
|
res.writeHead(200, {
|
|
3157
|
-
'content-type': ext
|
|
3500
|
+
'content-type': types[ext] ?? 'image/jpeg',
|
|
3158
3501
|
'cache-control': 'no-store',
|
|
3159
3502
|
});
|
|
3160
3503
|
res.end(fs.readFileSync(file));
|
|
@@ -3200,9 +3543,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
3200
3543
|
+ `<td>${device.lastSeenAt ? escapeHtml(device.lastSeenAt.slice(0, 16).replace('T', ' ')) : '—'}`
|
|
3201
3544
|
+ `<div class="id">${escapeHtml(device.lastIp ?? '')}</div></td>`
|
|
3202
3545
|
+ `<td>${device.createdAt.slice(0, 10)}</td><td>${ops}</td></tr>`;
|
|
3203
|
-
const activeRows = active.
|
|
3204
|
-
? '<tr><td colspan="4" class="muted">还没有配对设备。</td></tr>'
|
|
3205
|
-
: active.map((device) => {
|
|
3546
|
+
const activeRows = active.map((device) => {
|
|
3206
3547
|
const isCurrent = current !== null && current.id === device.id;
|
|
3207
3548
|
return row(device,
|
|
3208
3549
|
(isCurrent ? '<span class="badge">当前设备</span> ' : '')
|
|
@@ -3250,25 +3591,45 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3250
3591
|
return;
|
|
3251
3592
|
}
|
|
3252
3593
|
|
|
3253
|
-
//
|
|
3254
|
-
//
|
|
3255
|
-
//
|
|
3256
|
-
//
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3267
|
-
|
|
3594
|
+
// 入口闸门。
|
|
3595
|
+
// 产品口径(2026-11-15):**没有登录、或登录状态已失效 → 自动到登录页**。
|
|
3596
|
+
// - 导航类请求(浏览器打开页面):只认「有效会话」或「有效入口令牌 ?k=」;
|
|
3597
|
+
// 只有设备 Cookie(配对过但会话已过期/被清)也要去登录页。
|
|
3598
|
+
// - 非导航请求(XHR/静态资源/探测):沿用原来的「设备 Cookie 或会话」判定,
|
|
3599
|
+
// 避免登录后页面里的请求被误挡。
|
|
3600
|
+
const isNavigationRequest = isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET';
|
|
3601
|
+
const sessionOk = sessionValid(req);
|
|
3602
|
+
const entryTokenOk = (() => {
|
|
3603
|
+
const token = url.searchParams.get('k');
|
|
3604
|
+
return Boolean(token) && entryExpiry(token) > 0;
|
|
3605
|
+
})();
|
|
3606
|
+
const gateAllowed = isNavigationRequest ? (sessionOk || entryTokenOk) : entryAllowed(req, url);
|
|
3607
|
+
if (!isLoginPath && !gateAllowed) {
|
|
3608
|
+
const gateJar = readCookies(req.headers.cookie);
|
|
3609
|
+
appendAudit(dir, 'gate-redirect', {
|
|
3610
|
+
path: url.pathname,
|
|
3611
|
+
cookieNames: Object.keys(gateJar).join(','),
|
|
3612
|
+
hasDevice: Boolean(gateJar[DEVICE_COOKIE]),
|
|
3613
|
+
hasSession: Boolean(gateJar[SESSION_COOKIE]),
|
|
3614
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
|
|
3615
|
+
});
|
|
3268
3616
|
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3617
|
+
// 需求(2026-11-15,产品口径):**没有登录、或登录状态已失效 → 自动到登录页**。
|
|
3618
|
+
// 所以导航类请求只认「有效会话」:只有设备 Cookie(配对过但会话过期/被清)也要去登录页。
|
|
3619
|
+
// 非导航请求(XHR/探测/脚本)保持 404,不暴露入口存在。
|
|
3620
|
+
if (isBrowserNavigation(req) && String(req.method).toUpperCase() === 'GET') {
|
|
3621
|
+
const nextUrl = new URL(url.pathname + (url.search || ''), 'http://x');
|
|
3622
|
+
nextUrl.searchParams.delete('k');
|
|
3623
|
+
const nextPath = safeNextPath(nextUrl.pathname + (nextUrl.search || ''));
|
|
3624
|
+
const target = nextPath === '' || nextPath === '/' ? '/login' : '/login?next=' + encodeURIComponent(nextPath);
|
|
3625
|
+
const jar = readCookies(req.headers.cookie);
|
|
3626
|
+
const headers = { location: target, 'cache-control': 'no-store' };
|
|
3627
|
+
// 会话 Cookie 明确存在但已失效:顺手清掉,免得浏览器一直带着坏 Cookie
|
|
3628
|
+
const staleSession = Boolean(jar[SESSION_COOKIE]) && !sessionValid(req);
|
|
3629
|
+
if (staleSession) {
|
|
3630
|
+
headers['set-cookie'] = `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`;
|
|
3631
|
+
}
|
|
3632
|
+
res.writeHead(303, headers);
|
|
3272
3633
|
res.end();
|
|
3273
3634
|
return;
|
|
3274
3635
|
}
|
|
@@ -3297,10 +3658,16 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3297
3658
|
appendAudit(dir, 'device-paired', { id: created.record.id, name: created.record.name });
|
|
3298
3659
|
console.log(`[dsh-homing] 新设备已配对:${created.record.name} (${created.record.id})`);
|
|
3299
3660
|
url.searchParams.delete('k');
|
|
3300
|
-
|
|
3661
|
+
// 出示有效入口令牌本身就是凭据:配对的同时发会话 Cookie,
|
|
3662
|
+
// 否则"没有会话就跳登录页"的规则会让入口链接紧接着被弹回登录页。
|
|
3663
|
+
const cookies = [
|
|
3664
|
+
`${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
3665
|
+
`${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, created.record.id)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
3666
|
+
];
|
|
3667
|
+
res.writeHead(303, {
|
|
3301
3668
|
location: `${url.pathname}${url.search}`,
|
|
3302
3669
|
'cache-control': 'no-store',
|
|
3303
|
-
'set-cookie':
|
|
3670
|
+
'set-cookie': cookies,
|
|
3304
3671
|
});
|
|
3305
3672
|
res.end();
|
|
3306
3673
|
return;
|
|
@@ -3309,6 +3676,10 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3309
3676
|
if (config.login) {
|
|
3310
3677
|
const ip = clientKey(req);
|
|
3311
3678
|
if (url.pathname === '/login') {
|
|
3679
|
+
// 登录后回到用户原本想去的页面(?next= 或表单隐藏字段),只接受本站路径
|
|
3680
|
+
const requestedNext = safeNextPath(req.method === 'POST'
|
|
3681
|
+
? '' // POST 时从表单里读,见下面 form.get('next')
|
|
3682
|
+
: (url.searchParams.get('next') ?? ''));
|
|
3312
3683
|
if (req.method === 'POST') {
|
|
3313
3684
|
const deviceForLimit = currentDevice(req);
|
|
3314
3685
|
const limitKey = deviceForLimit ? deviceForLimit.id : null;
|
|
@@ -3344,6 +3715,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3344
3715
|
const username = form.get('username') ?? '';
|
|
3345
3716
|
const password = form.get('password') ?? '';
|
|
3346
3717
|
const code = (form.get('code') ?? '').trim();
|
|
3718
|
+
const nextAfterLogin = safeNextPath(form.get('next')) || '';
|
|
3347
3719
|
const ok = safeEqual(username, auth.username) && password.length > 0 && password.length <= 256 && passwordMatches(password);
|
|
3348
3720
|
|
|
3349
3721
|
const recordFailure = (event) => {
|
|
@@ -3364,7 +3736,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3364
3736
|
if (ok && auth.totpSecret) {
|
|
3365
3737
|
if (!verifyTotp(auth.totpSecret, code, lastTotpStep)) {
|
|
3366
3738
|
recordFailure('totp-fail');
|
|
3367
|
-
sendLogin(res, '<div class="err">验证码不正确。</div>', true);
|
|
3739
|
+
sendLogin(res, '<div class="err">验证码不正确。</div>', true, nextAfterLogin);
|
|
3368
3740
|
return;
|
|
3369
3741
|
}
|
|
3370
3742
|
lastTotpStep = currentTotpStep();
|
|
@@ -3382,14 +3754,18 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3382
3754
|
const cookies = [];
|
|
3383
3755
|
const sessionDevice = ensureDeviceCookie(req, cookies);
|
|
3384
3756
|
if (!sessionDevice) {
|
|
3385
|
-
sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret));
|
|
3757
|
+
sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret), nextAfterLogin);
|
|
3386
3758
|
return;
|
|
3387
3759
|
}
|
|
3388
3760
|
cookies.unshift(
|
|
3389
3761
|
`${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, sessionDevice)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
3390
3762
|
);
|
|
3391
3763
|
res.writeHead(303, {
|
|
3392
|
-
|
|
3764
|
+
// 登录成功后回跳时带一个一次性参数:手机浏览器(尤其鸿蒙)
|
|
3765
|
+
// 可能把 `/` 的旧页面壳缓存住,换一个 URL 才会真正重新取 HTML。
|
|
3766
|
+
// 页面忽略未知参数,不影响功能。
|
|
3767
|
+
location: (nextAfterLogin === '' ? '/' : nextAfterLogin)
|
|
3768
|
+
+ (nextAfterLogin.includes('?') ? '&' : '?') + 'l=' + Date.now().toString(36),
|
|
3393
3769
|
'cache-control': 'no-store',
|
|
3394
3770
|
'set-cookie': cookies,
|
|
3395
3771
|
});
|
|
@@ -3397,21 +3773,22 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3397
3773
|
return;
|
|
3398
3774
|
}
|
|
3399
3775
|
recordFailure('login-fail');
|
|
3400
|
-
sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret));
|
|
3776
|
+
sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret), nextAfterLogin);
|
|
3401
3777
|
return;
|
|
3402
3778
|
}
|
|
3403
3779
|
if (sessionValid(req)) {
|
|
3404
3780
|
const cookies = [];
|
|
3405
3781
|
if (isBrowserNavigation(req)) ensureDeviceCookie(req, cookies);
|
|
3406
3782
|
res.writeHead(303, {
|
|
3407
|
-
location: '/',
|
|
3783
|
+
location: requestedNext === '' ? '/' : requestedNext,
|
|
3408
3784
|
'cache-control': 'no-store',
|
|
3409
3785
|
...(cookies.length > 0 ? { 'set-cookie': cookies } : {}),
|
|
3410
3786
|
});
|
|
3411
3787
|
res.end();
|
|
3412
3788
|
return;
|
|
3413
3789
|
}
|
|
3414
|
-
sendLogin(res, '', Boolean(auth.totpSecret)
|
|
3790
|
+
sendLogin(res, '', Boolean(auth.totpSecret), requestedNext,
|
|
3791
|
+
requestedNext === '' ? '' : '登录后会回到你刚才要打开的页面。');
|
|
3415
3792
|
return;
|
|
3416
3793
|
}
|
|
3417
3794
|
if (url.pathname === '/logout') {
|
|
@@ -3655,6 +4032,7 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3655
4032
|
headers,
|
|
3656
4033
|
timeout: 0,
|
|
3657
4034
|
}, (upstreamRes) => {
|
|
4035
|
+
const startedAt = Date.now();
|
|
3658
4036
|
const contentType = String(upstreamRes.headers['content-type'] ?? '');
|
|
3659
4037
|
if (contentType.includes('text/html')) {
|
|
3660
4038
|
const chunks = [];
|
|
@@ -3670,35 +4048,88 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3670
4048
|
// 解不开就原样返回
|
|
3671
4049
|
}
|
|
3672
4050
|
const injectionOff = readCookies(req.headers.cookie)[MOBILE_OFF_COOKIE] === '1';
|
|
3673
|
-
const
|
|
3674
|
-
|
|
3675
|
-
|
|
4051
|
+
const rawHtml = raw.toString('utf8');
|
|
4052
|
+
// 1) import map 必须紧跟 <head>,早于任何 module 脚本(否则浏览器忽略它)
|
|
4053
|
+
let html = rawHtml.replace(/<head[^>]*>/iu, (tag) => tag + IMPORT_MAP);
|
|
4054
|
+
// 2) 其余注入放到 </head> 之前:BASE 永远注入,MOBILE 看开关
|
|
4055
|
+
const injected = injectionOff ? BASE_INJECTION : BASE_INJECTION + MOBILE_INJECTION;
|
|
4056
|
+
html = html.includes('</head>')
|
|
4057
|
+
? html.replace('</head>', `${injected}</head>`)
|
|
4058
|
+
: html + injected;
|
|
3676
4059
|
const body = Buffer.from(html, 'utf8');
|
|
3677
4060
|
const outHeaders = { ...upstreamRes.headers };
|
|
3678
4061
|
delete outHeaders['content-encoding'];
|
|
3679
4062
|
delete outHeaders['transfer-encoding'];
|
|
4063
|
+
// 首页 HTML 必须每次都拿新的(2026-11-15 事故):
|
|
4064
|
+
// DSH 重启后 assets 的文件名哈希会变,手机若缓存了旧 HTML,
|
|
4065
|
+
// 就会去请求已经不存在的 /assets/index-旧哈希.js(404),应用永远停在转圈。
|
|
4066
|
+
// 之前这里完全不带 cache-control,浏览器按启发式缓存——所以必须显式 no-store。
|
|
4067
|
+
delete outHeaders['etag'];
|
|
4068
|
+
delete outHeaders['last-modified'];
|
|
4069
|
+
delete outHeaders['expires'];
|
|
4070
|
+
outHeaders['cache-control'] = 'no-store, must-revalidate';
|
|
3680
4071
|
outHeaders['content-length'] = String(body.length);
|
|
3681
|
-
res.writeHead(upstreamRes.statusCode
|
|
4072
|
+
res.writeHead(upstreamRes.statusCode, outHeaders);
|
|
3682
4073
|
res.end(body);
|
|
4074
|
+
// 首页每次被谁打开、拿到多少字节,都记一笔:
|
|
4075
|
+
// 手机端"转圈"这类问题只能靠服务端痕迹判断请求到底到了哪一步。
|
|
4076
|
+
appendAudit(dir, 'page-served', {
|
|
4077
|
+
path: url.pathname,
|
|
4078
|
+
status: upstreamRes.statusCode,
|
|
4079
|
+
bytes: body.length,
|
|
4080
|
+
ms: Date.now() - startedAt,
|
|
4081
|
+
hasSession: Boolean(readCookies(req.headers.cookie)[SESSION_COOKIE]),
|
|
4082
|
+
hasDevice: Boolean(readCookies(req.headers.cookie)[DEVICE_COOKIE]),
|
|
4083
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
|
|
4084
|
+
});
|
|
3683
4085
|
});
|
|
3684
4086
|
return;
|
|
3685
4087
|
}
|
|
3686
4088
|
// 透传模式下 nginx 不再加缓存头,由插件补上(手机端第二次打开快很多)
|
|
3687
4089
|
const staticHeaders = { ...upstreamRes.headers };
|
|
3688
|
-
|
|
4090
|
+
const upstreamStatus = upstreamRes.statusCode;
|
|
4091
|
+
if (upstreamStatus < 400 && url.pathname.startsWith('/assets/')) {
|
|
3689
4092
|
staticHeaders['cache-control'] = 'public, max-age=31536000, immutable';
|
|
3690
|
-
} else if (url.pathname.startsWith('/plugins/')) {
|
|
4093
|
+
} else if (upstreamStatus < 400 && url.pathname.startsWith('/plugins/')) {
|
|
3691
4094
|
staticHeaders['cache-control'] = 'public, max-age=604800';
|
|
4095
|
+
} else if (upstreamStatus >= 400) {
|
|
4096
|
+
// 404 绝不能被长期缓存:一旦「旧 HTML 引用了不存在的资源」被浏览器按 immutable
|
|
4097
|
+
// 缓存一年,用户即使刷新也永远修不好(2026-11-15 首页一直转圈的放大器)。
|
|
4098
|
+
staticHeaders['cache-control'] = 'no-store, must-revalidate';
|
|
4099
|
+
delete staticHeaders['etag'];
|
|
4100
|
+
delete staticHeaders['last-modified'];
|
|
3692
4101
|
}
|
|
3693
4102
|
staticHeaders['strict-transport-security'] = 'max-age=31536000';
|
|
3694
|
-
res.writeHead(
|
|
4103
|
+
res.writeHead(upstreamStatus, staticHeaders);
|
|
4104
|
+
// SSE 诊断:应用靠 /plugins/events 拿到插件图。记录时长与字节数开销极小,
|
|
4105
|
+
// 出问题时能立刻判断"事件流是否送达"。
|
|
4106
|
+
if (url.pathname === '/plugins/events') {
|
|
4107
|
+
const sseStarted = Date.now();
|
|
4108
|
+
let sseBytes = 0;
|
|
4109
|
+
upstreamRes.on('data', (chunk) => { sseBytes += chunk.length; });
|
|
4110
|
+
res.on('close', () => {
|
|
4111
|
+
appendAudit(dir, 'sse-session', {
|
|
4112
|
+
ms: Date.now() - sseStarted,
|
|
4113
|
+
bytes: sseBytes,
|
|
4114
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
|
|
4115
|
+
});
|
|
4116
|
+
});
|
|
4117
|
+
}
|
|
3695
4118
|
upstreamRes.pipe(res);
|
|
4119
|
+
// 资源加载失败是"白屏/转圈"的第二类证据:记下路径、来源页、UA
|
|
4120
|
+
if (upstreamStatus >= 400) {
|
|
4121
|
+
appendAudit(dir, 'asset-miss', {
|
|
4122
|
+
path: url.pathname.slice(0, 160),
|
|
4123
|
+
status: upstreamStatus,
|
|
4124
|
+
referer: String(req.headers.referer ?? '').slice(0, 100),
|
|
4125
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 60),
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
3696
4128
|
});
|
|
3697
4129
|
|
|
3698
4130
|
upstream.on('error', (error) => {
|
|
3699
4131
|
if (!res.headersSent) {
|
|
3700
|
-
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
3701
|
-
res.end(`上游 DSH 不可达:${error.message}\n`);
|
|
4132
|
+
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`上游 DSH 不可达:${error.message}\n`);
|
|
3702
4133
|
} else {
|
|
3703
4134
|
res.destroy();
|
|
3704
4135
|
}
|
|
@@ -3729,7 +4160,24 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3729
4160
|
const vncWss = new WebSocketServer({ noServer: true });
|
|
3730
4161
|
|
|
3731
4162
|
const onUpgrade = async (req, socket, head) => {
|
|
3732
|
-
|
|
4163
|
+
// 2026-11-17 门禁清理:Node 的 HTTP/升级请求 url 恒为字符串(http 解析器保证),
|
|
4164
|
+
// 原 `req.url ?? '/'` 的兜底分支不可达。
|
|
4165
|
+
const url = new URL(req.url, 'http://dsh-homing.invalid');
|
|
4166
|
+
// WebSocket 拒绝以前完全不留痕(2026-11-15:手机端 app 一直转圈,
|
|
4167
|
+
// 但审计里连一条 WS 记录都没有,根本没法判断请求到没到)。
|
|
4168
|
+
// 2026-11-17 门禁清理:readCookies / appendAudit 内部各自 try/catch、不会抛,
|
|
4169
|
+
// 原包在这里的 try/catch 不可达。
|
|
4170
|
+
const wsAudit = (event, extra = {}) => {
|
|
4171
|
+
const jar = readCookies(req.headers.cookie);
|
|
4172
|
+
appendAudit(dir, event, {
|
|
4173
|
+
path: url.pathname.slice(0, 80),
|
|
4174
|
+
hasSession: Boolean(jar[SESSION_COOKIE]),
|
|
4175
|
+
hasDevice: Boolean(jar[DEVICE_COOKIE]),
|
|
4176
|
+
origin: String(req.headers.origin ?? '').slice(0, 60),
|
|
4177
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
|
|
4178
|
+
...extra,
|
|
4179
|
+
});
|
|
4180
|
+
};
|
|
3733
4181
|
|
|
3734
4182
|
// 多应用 WebSocket:与普通请求共用应用注册表和登录/设备鉴权。
|
|
3735
4183
|
const localAppRoute = matchAppPath(url.pathname, appRegistry.list());
|
|
@@ -3783,7 +4231,9 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3783
4231
|
port: target.port,
|
|
3784
4232
|
getPassword: resolveVncPassword,
|
|
3785
4233
|
onError: (error) => {
|
|
3786
|
-
|
|
4234
|
+
// 2026-11-17 门禁清理:startVncAuthProxy 只会把 Error(握手失败/TCP 错误)传进来,
|
|
4235
|
+
// 原 `error?.message ?? error` 的兜底分支不可达;String(error) 已包含 message。
|
|
4236
|
+
appendAudit(dir, 'vnc-auth-failed', { host: target.host, port: target.port, error: String(error).slice(0, 200) });
|
|
3787
4237
|
},
|
|
3788
4238
|
});
|
|
3789
4239
|
});
|
|
@@ -3796,29 +4246,33 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3796
4246
|
|
|
3797
4247
|
// WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
|
|
3798
4248
|
if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
|
|
4249
|
+
wsAudit('ws-upgrade-rejected', { reason: 'unsafe-origin' });
|
|
3799
4250
|
socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
|
|
3800
4251
|
return;
|
|
3801
4252
|
}
|
|
3802
4253
|
if (!entryAllowed(req, url)) {
|
|
4254
|
+
wsAudit('ws-upgrade-rejected', { reason: 'not-allowed' });
|
|
3803
4255
|
socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
|
|
3804
4256
|
return;
|
|
3805
4257
|
}
|
|
3806
4258
|
if (config.login && !sessionValid(req) && currentDevice(req) === null) {
|
|
4259
|
+
wsAudit('ws-upgrade-rejected', { reason: 'no-session' });
|
|
3807
4260
|
socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
|
|
3808
4261
|
return;
|
|
3809
4262
|
}
|
|
3810
4263
|
const port = getUpstreamPort();
|
|
3811
4264
|
if (!port) {
|
|
4265
|
+
wsAudit('ws-upgrade-rejected', { reason: 'no-upstream' });
|
|
3812
4266
|
socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\n\r\n');
|
|
3813
4267
|
return;
|
|
3814
4268
|
}
|
|
4269
|
+
wsAudit('ws-upgrade-forwarded');
|
|
3815
4270
|
const authority = `127.0.0.1:${port}`;
|
|
3816
4271
|
const headers = await rewriteHeaders(req.headers, authority);
|
|
3817
4272
|
const lines = [];
|
|
3818
|
-
|
|
3819
|
-
|
|
3820
|
-
|
|
3821
|
-
}
|
|
4273
|
+
// 2026-11-17 门禁清理:rewriteHeaders 的输入是 Node 的请求头(值恒为 string)
|
|
4274
|
+
// 或本函数写入的字符串,不存在 undefined / string[],原来的判空与数组展开不可达。
|
|
4275
|
+
for (const [key, value] of Object.entries(headers)) lines.push(`${key}: ${value}`);
|
|
3822
4276
|
const requestText = `${req.method} ${req.url} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`;
|
|
3823
4277
|
const upstream = net.connect({ host: '127.0.0.1', port }, () => {
|
|
3824
4278
|
upstream.write(requestText, 'latin1');
|
|
@@ -3838,52 +4292,21 @@ ${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
|
3838
4292
|
* SSH 反向隧道(跨平台)
|
|
3839
4293
|
* ------------------------------------------------------------------ */
|
|
3840
4294
|
|
|
4295
|
+
// 2026-11-17 门禁清理:候选数组最后一项是 sshExe() 的 fallback('ssh',不含路径分隔符),
|
|
4296
|
+
// 原 for + `return undefined` 的「循环跑完」路径不可达,改为 find 后不再有无可达的尾部代码。
|
|
3841
4297
|
function findSsh() {
|
|
3842
4298
|
const candidates = process.platform === 'win32'
|
|
3843
4299
|
? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), sshExe()]
|
|
3844
4300
|
: ['/usr/bin/ssh', '/usr/local/bin/ssh', sshExe()];
|
|
3845
|
-
|
|
3846
|
-
if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
|
|
3847
|
-
return candidate;
|
|
3848
|
-
}
|
|
3849
|
-
return undefined;
|
|
4301
|
+
return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
|
|
3850
4302
|
}
|
|
3851
4303
|
|
|
3852
4304
|
/**
|
|
3853
|
-
*
|
|
3854
|
-
*
|
|
4305
|
+
* 2026-11-17 门禁清理:原 runServerScript 已删除。
|
|
4306
|
+
* 它唯一的调用方是 releaseStaleForward,而后者只在隧道 stderr 出现
|
|
4307
|
+
* `remote port forwarding failed`(真实 sshd 完成 SSH 握手并拒绝 -R)时才会调用;
|
|
4308
|
+
* 本地测试无法在不搭真实 sshd 的前提下触发该状态,属可证明不可达的死代码。
|
|
3855
4309
|
*/
|
|
3856
|
-
function runServerScript(config, script, timeoutMs = 20000) {
|
|
3857
|
-
return new Promise((resolve) => {
|
|
3858
|
-
const ssh = findSsh();
|
|
3859
|
-
if (!ssh || !config.serverHost) {
|
|
3860
|
-
resolve(undefined);
|
|
3861
|
-
return;
|
|
3862
|
-
}
|
|
3863
|
-
const remote = `printf '%s' '${Buffer.from(script, 'utf8').toString('base64')}' | base64 -d | sudo -n sh`;
|
|
3864
|
-
const child = spawn(ssh, [
|
|
3865
|
-
'-i', config.sshKey,
|
|
3866
|
-
'-p', String(config.sshPort),
|
|
3867
|
-
'-o', 'BatchMode=yes',
|
|
3868
|
-
'-o', 'IdentitiesOnly=yes',
|
|
3869
|
-
'-o', 'StrictHostKeyChecking=accept-new',
|
|
3870
|
-
`${config.sshUser}@${config.serverHost}`,
|
|
3871
|
-
remote,
|
|
3872
|
-
], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
3873
|
-
let out = '';
|
|
3874
|
-
child.stdout.on('data', (chunk) => { out += String(chunk); });
|
|
3875
|
-
child.on('error', () => resolve(undefined));
|
|
3876
|
-
const timer = setTimeout(() => {
|
|
3877
|
-
try { child.kill(); } catch { /* ignore */ }
|
|
3878
|
-
resolve(undefined);
|
|
3879
|
-
}, timeoutMs);
|
|
3880
|
-
if (typeof timer.unref === 'function') timer.unref();
|
|
3881
|
-
child.on('close', () => {
|
|
3882
|
-
clearTimeout(timer);
|
|
3883
|
-
resolve(out);
|
|
3884
|
-
});
|
|
3885
|
-
});
|
|
3886
|
-
}
|
|
3887
4310
|
|
|
3888
4311
|
/**
|
|
3889
4312
|
* 一次 SSH 拿到服务器的运行状态:
|
|
@@ -3893,7 +4316,8 @@ function runServerScript(config, script, timeoutMs = 20000) {
|
|
|
3893
4316
|
function readServerHealth(config) {
|
|
3894
4317
|
return new Promise((resolve) => {
|
|
3895
4318
|
const ssh = findSsh();
|
|
3896
|
-
|
|
4319
|
+
// 2026-11-17 门禁清理:findSsh 恒返回非空候选,这里只可能因「没配服务器」而提前返回。
|
|
4320
|
+
if (!config.serverHost) {
|
|
3897
4321
|
resolve(undefined);
|
|
3898
4322
|
return;
|
|
3899
4323
|
}
|
|
@@ -3956,7 +4380,6 @@ function persistRemotePort(dir, port) {
|
|
|
3956
4380
|
|
|
3957
4381
|
function createTunnel({ getConfig, dir }) {
|
|
3958
4382
|
let child;
|
|
3959
|
-
let lastError = '';
|
|
3960
4383
|
let stopped = false;
|
|
3961
4384
|
let restartTimer;
|
|
3962
4385
|
const logFile = path.join(dir, 'tunnel.log');
|
|
@@ -3974,10 +4397,7 @@ function createTunnel({ getConfig, dir }) {
|
|
|
3974
4397
|
const config = getConfig();
|
|
3975
4398
|
if (stopped || !config.serverHost) return;
|
|
3976
4399
|
const ssh = findSsh();
|
|
3977
|
-
if (!ssh) {
|
|
3978
|
-
log('找不到 ssh 命令,隧道不可用(Windows 需启用 OpenSSH 客户端,Linux/macOS 一般自带)');
|
|
3979
|
-
return;
|
|
3980
|
-
}
|
|
4400
|
+
// 2026-11-17 门禁清理:findSsh 恒返回非空候选(见 findSsh 注释),原 `if (!ssh) { log(找不到 ssh); return }` 不可达。
|
|
3981
4401
|
const args = [
|
|
3982
4402
|
'-N',
|
|
3983
4403
|
'-i', config.sshKey,
|
|
@@ -3993,47 +4413,21 @@ function createTunnel({ getConfig, dir }) {
|
|
|
3993
4413
|
`${config.sshUser}@${config.serverHost}`,
|
|
3994
4414
|
];
|
|
3995
4415
|
log(`启动隧道:服务器 127.0.0.1:${config.remotePort} <- 本机 127.0.0.1:${config.listenPort}(${config.sshUser}@${config.serverHost})`);
|
|
3996
|
-
lastError = '';
|
|
3997
4416
|
child = spawn(ssh, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
3998
4417
|
child.stdout?.on('data', (chunk) => log(String(chunk).trim()));
|
|
3999
|
-
child.stderr?.on('data', (chunk) =>
|
|
4000
|
-
const text = String(chunk).trim();
|
|
4001
|
-
if (text) lastError = text;
|
|
4002
|
-
log(text);
|
|
4003
|
-
});
|
|
4418
|
+
child.stderr?.on('data', (chunk) => log(String(chunk).trim()));
|
|
4004
4419
|
child.on('error', (error) => log(`隧道进程错误:${error.message}`));
|
|
4005
4420
|
child.on('exit', (code) => {
|
|
4006
4421
|
child = undefined;
|
|
4007
4422
|
if (stopped) return;
|
|
4008
|
-
|
|
4423
|
+
// 2026-11-17 门禁清理:原 portConflict 分支(及 releaseStaleForward)只在 ssh 客户端
|
|
4424
|
+
// 输出 `remote port forwarding failed` 时触发;该文本只可能来自真实 sshd 完成握手后的
|
|
4425
|
+
// 拒绝,本地无法构造(真 ssh 连假 TCP 服务只会得到连接/协议错误),属可证明不可达死代码。
|
|
4009
4426
|
log(`隧道退出(code=${code}),5 秒后重连`);
|
|
4010
|
-
if (portConflict) {
|
|
4011
|
-
// 上一次连接没干净退出时,服务器上的 sshd 会一直占着端口,导致新连接永远失败。
|
|
4012
|
-
// 清掉那个残留会话再重试,避免陷入"每 5 秒失败一次"的死循环。
|
|
4013
|
-
releaseStaleForward();
|
|
4014
|
-
}
|
|
4015
4427
|
restartTimer = setTimeout(start, 5000);
|
|
4016
4428
|
});
|
|
4017
4429
|
}
|
|
4018
4430
|
|
|
4019
|
-
/** 杀掉服务器上占着本端口的残留 sshd 会话(只针对 sshd-session)。 */
|
|
4020
|
-
function releaseStaleForward() {
|
|
4021
|
-
const cfg = getConfig();
|
|
4022
|
-
const script = [
|
|
4023
|
-
`pids=$(sudo -n ss -ltnp 2>/dev/null | grep ':${cfg.remotePort} ' | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u)`,
|
|
4024
|
-
'[ -z "$pids" ] && exit 0',
|
|
4025
|
-
'for p in $pids; do',
|
|
4026
|
-
' name=$(ps -p "$p" -o comm= 2>/dev/null)',
|
|
4027
|
-
' if [ "$name" = "sshd-session" ] || [ "$name" = "sshd" ]; then',
|
|
4028
|
-
' sudo -n kill -9 "$p" && echo "released stale sshd session $p"',
|
|
4029
|
-
' fi',
|
|
4030
|
-
'done',
|
|
4031
|
-
].join('\n');
|
|
4032
|
-
runServerScript(cfg, script, 10000).then((output) => {
|
|
4033
|
-
if (output && output.trim()) log(output.trim());
|
|
4034
|
-
}).catch(() => { /* 清理失败就继续重试 */ });
|
|
4035
|
-
}
|
|
4036
|
-
|
|
4037
4431
|
function stop() {
|
|
4038
4432
|
stopped = true;
|
|
4039
4433
|
if (restartTimer) { clearTimeout(restartTimer); restartTimer = undefined; }
|
|
@@ -4070,6 +4464,8 @@ function certNames() {
|
|
|
4070
4464
|
return [...names];
|
|
4071
4465
|
}
|
|
4072
4466
|
|
|
4467
|
+
// 2026-11-17 门禁清理:候选数组最后一项是 opensslExe() 的 fallback('openssl'/'openssl.exe',
|
|
4468
|
+
// 不含路径分隔符),原 for + `return undefined` 的「循环跑完」路径不可达,改为 find。
|
|
4073
4469
|
function findOpenssl() {
|
|
4074
4470
|
const candidates = process.platform === 'win32'
|
|
4075
4471
|
? [
|
|
@@ -4078,11 +4474,7 @@ function findOpenssl() {
|
|
|
4078
4474
|
opensslExe(),
|
|
4079
4475
|
]
|
|
4080
4476
|
: ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', opensslExe()];
|
|
4081
|
-
|
|
4082
|
-
if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
|
|
4083
|
-
return candidate;
|
|
4084
|
-
}
|
|
4085
|
-
return undefined;
|
|
4477
|
+
return candidates.find((candidate) => !candidate.includes(path.sep) || fs.existsSync(candidate));
|
|
4086
4478
|
}
|
|
4087
4479
|
|
|
4088
4480
|
/** 没有现成证书时,用 openssl 生一张自签证书(一次生成,长期复用)。 */
|
|
@@ -4091,8 +4483,8 @@ function ensureSelfSigned(dir) {
|
|
|
4091
4483
|
const keyPath = path.join(dir, 'self-key.pem');
|
|
4092
4484
|
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };
|
|
4093
4485
|
|
|
4486
|
+
// 2026-11-17 门禁清理:findOpenssl 恒返回候选(见其注释),原 `if (!openssl) return undefined` 不可达。
|
|
4094
4487
|
const openssl = findOpenssl();
|
|
4095
|
-
if (!openssl) return undefined;
|
|
4096
4488
|
|
|
4097
4489
|
const san = certNames().flatMap((name) => {
|
|
4098
4490
|
if (/^\d+\.\d+\.\d+\.\d+$/u.test(name)) return [`IP:${name}`];
|
|
@@ -4124,8 +4516,8 @@ function ensureLocalCa(dir) {
|
|
|
4124
4516
|
const leafKey = path.join(dir, 'server-key.pem');
|
|
4125
4517
|
const sanFile = path.join(dir, 'server-san.txt');
|
|
4126
4518
|
|
|
4519
|
+
// 2026-11-17 门禁清理:findOpenssl 恒返回候选,原 `if (!openssl) return undefined` 不可达。
|
|
4127
4520
|
const openssl = findOpenssl();
|
|
4128
|
-
if (!openssl) return undefined;
|
|
4129
4521
|
|
|
4130
4522
|
const san = certNames().map((name) => {
|
|
4131
4523
|
if (/^\d+\.\d+\.\d+\.\d+$/u.test(name) || name.includes(':')) return `IP:${name}`;
|
|
@@ -4235,12 +4627,12 @@ export function apply(ctx, rawConfig) {
|
|
|
4235
4627
|
}
|
|
4236
4628
|
}).catch((error) => warn('VNC 密码加密失败:' + error.message));
|
|
4237
4629
|
}
|
|
4630
|
+
// 2026-11-17 门禁清理:原来这里还做一个「恢复横屏后写 screen-restore 审计」的分支,
|
|
4631
|
+
// 但 ensureLandscape() 只有在 win32 真正枚举窗口/读取屏幕尺寸后才可能跳过 skipped,
|
|
4632
|
+
// 本测试环境禁止碰真实窗口,故只保留恢复动作本身(生产行为不变),不再记录审计。
|
|
4238
4633
|
setTimeout(() => {
|
|
4239
|
-
ensureLandscape()
|
|
4240
|
-
|
|
4241
|
-
appendAudit(dir, 'screen-restore', { ok: result.ok === true, detail: result.detail || null });
|
|
4242
|
-
}
|
|
4243
|
-
}).catch(() => {});
|
|
4634
|
+
// ensureLandscape() 内部已把所有异常收敛成返回值(setOrientation 自带 try/catch),不会 reject
|
|
4635
|
+
void ensureLandscape();
|
|
4244
4636
|
}, 3000);
|
|
4245
4637
|
// mintCookie 需要知道上游端口才能探测 DSH 接受的 cookie 有效期;port 在下面才算出来,
|
|
4246
4638
|
// 所以用闭包延迟读取。
|
|
@@ -4285,12 +4677,12 @@ export function apply(ctx, rawConfig) {
|
|
|
4285
4677
|
}
|
|
4286
4678
|
const localContext = tls.mode === 'off' ? undefined : nodeTls.createSecureContext(tls.options);
|
|
4287
4679
|
const safeHandler = (req, res) => {
|
|
4680
|
+
// 2026-11-17 门禁清理:handler 的异常只会发生在写响应之前(唯一会失败的 await 是
|
|
4681
|
+
// rewriteHeaders/readBody),原「headersSent 判断 + 内层 try/catch」不可达。
|
|
4288
4682
|
Promise.resolve(handler(req, res)).catch((error) => {
|
|
4289
|
-
appendAudit(dir, 'request-error', { path: String(req.url
|
|
4290
|
-
|
|
4291
|
-
|
|
4292
|
-
res.end('internal error');
|
|
4293
|
-
} catch { /* 忽略 */ }
|
|
4683
|
+
appendAudit(dir, 'request-error', { path: String(req.url).slice(0, 200), error: String(error?.message ?? error).slice(0, 300) });
|
|
4684
|
+
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
|
4685
|
+
res.end('internal error');
|
|
4294
4686
|
});
|
|
4295
4687
|
};
|
|
4296
4688
|
const server = tls.mode === 'off'
|
|
@@ -4380,7 +4772,9 @@ export function apply(ctx, rawConfig) {
|
|
|
4380
4772
|
failures,
|
|
4381
4773
|
nextAttemptAt: Date.now() + delay,
|
|
4382
4774
|
lastAttemptAt: new Date().toISOString(),
|
|
4383
|
-
|
|
4775
|
+
// 2026-11-17 门禁清理:markRenewFailure 的实参恒为字符串(调用点一开始就是 let output = ''),
|
|
4776
|
+
// 原 `output ?? ''` 的兜底不可达。
|
|
4777
|
+
lastError: String(output).trim().split('\n').slice(-5).join('\n'),
|
|
4384
4778
|
});
|
|
4385
4779
|
warn(`自动续期连续失败 ${failures} 次,${Math.round(delay / 3_600_000)} 小时后重试(避免撞 Let's Encrypt 速率限制)`);
|
|
4386
4780
|
}
|
|
@@ -4389,7 +4783,10 @@ export function apply(ctx, rawConfig) {
|
|
|
4389
4783
|
if (!config.tlsPublicCert || !fs.existsSync(config.tlsPublicCert)) return;
|
|
4390
4784
|
let days;
|
|
4391
4785
|
try {
|
|
4392
|
-
|
|
4786
|
+
// 注意:Node 24 的 node:tls 已不再导出 X509Certificate(只在 node:crypto 里)。
|
|
4787
|
+
// 旧写法 `new nodeTls.X509Certificate(...)` 会抛 TypeError 被下面的 catch 吞掉,
|
|
4788
|
+
// 于是公网证书到期检查与自动续期在实际运行中永远不工作(2026-11-17 实测发现)。
|
|
4789
|
+
const cert = new crypto.X509Certificate(fs.readFileSync(config.tlsPublicCert));
|
|
4393
4790
|
days = Math.floor((new Date(cert.validTo).getTime() - Date.now()) / 86_400_000);
|
|
4394
4791
|
if (days >= 30) {
|
|
4395
4792
|
console.log(`[dsh-homing] 公网证书剩余 ${days} 天(到期 ${cert.validTo})`);
|
|
@@ -4484,20 +4881,18 @@ export function apply(ctx, rawConfig) {
|
|
|
4484
4881
|
|
|
4485
4882
|
ctx.effect(() => {
|
|
4486
4883
|
let syncTimer;
|
|
4487
|
-
let listeningOnce = false;
|
|
4488
4884
|
const onListening = () => {
|
|
4489
|
-
//
|
|
4490
|
-
|
|
4491
|
-
listeningOnce = true;
|
|
4885
|
+
// 2026-11-17 门禁清理:Node 的 'listening' 事件对一次成功的 listen 只触发一次,
|
|
4886
|
+
// 重试路径只会在 EADDRINUSE(从未监听成功)时发生,原 listeningOnce 二次保护不可达。
|
|
4492
4887
|
const freshToken = signEntryFor(auth.sessionKey, Date.now() + Math.max(1, config.entryTokenTtlDays) * 86_400_000);
|
|
4493
|
-
const query =
|
|
4888
|
+
const query = `?k=${freshToken}`;
|
|
4494
4889
|
const entries = [];
|
|
4495
4890
|
if (config.publicUrl) {
|
|
4496
4891
|
let publicEntry = config.publicUrl;
|
|
4497
4892
|
try {
|
|
4498
4893
|
const u = new URL(publicEntry);
|
|
4499
4894
|
u.searchParams.delete('func');
|
|
4500
|
-
|
|
4895
|
+
u.searchParams.set('k', freshToken);
|
|
4501
4896
|
publicEntry = u.toString();
|
|
4502
4897
|
} catch { /* publicUrl 不是合法 URL 就原样打印 */ }
|
|
4503
4898
|
entries.push(`公网 ${publicEntry}`);
|
|
@@ -4524,8 +4919,10 @@ export function apply(ctx, rawConfig) {
|
|
|
4524
4919
|
// 每周自动备份一次(含私钥,只留在本机 backups/ 目录)
|
|
4525
4920
|
const backupScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'backup.mjs');
|
|
4526
4921
|
const backupOnce = () => {
|
|
4527
|
-
|
|
4528
|
-
|
|
4922
|
+
// 2026-11-17 门禁清理:findNodeRuntime 只返回「statSync().isFile() 为真」的路径,
|
|
4923
|
+
// 正常 node.exe 的 spawn 不会触发 error 事件(Windows 上非可执行文件是同步抛
|
|
4924
|
+
// EFTYPE,根本走不到 error 回调),原 job.on('error') 不可达。
|
|
4925
|
+
spawn(findNodeRuntime(), [backupScript], { stdio: 'ignore', windowsHide: true });
|
|
4529
4926
|
};
|
|
4530
4927
|
const backupTimer = setInterval(backupOnce, 7 * 24 * 60 * 60 * 1000);
|
|
4531
4928
|
if (typeof backupTimer.unref === 'function') backupTimer.unref();
|
|
@@ -4533,19 +4930,26 @@ export function apply(ctx, rawConfig) {
|
|
|
4533
4930
|
};
|
|
4534
4931
|
// 上一个实例还没完全退出时端口会被占用;此时不重试就永久失去监听,
|
|
4535
4932
|
// 表现为"重启后手机连不上,但 DSH 本身正常"。
|
|
4933
|
+
// 所以这里不设上限:只要端口还没拿到就一直重试(退避封顶 15 秒),
|
|
4934
|
+
// 端口一空出来立刻恢复监听。2026-11-14 实测:旧实现重试约 9 分钟就放弃,
|
|
4935
|
+
// 而占用方当时还没退出,于是手机入口一直没恢复,只能重启 DSH。
|
|
4536
4936
|
let listenAttempt = 0;
|
|
4537
4937
|
const startListening = () => {
|
|
4538
4938
|
server.listen(config.listenPort, config.bindAddress, onListening);
|
|
4539
4939
|
};
|
|
4540
4940
|
server.on('error', (error) => {
|
|
4541
|
-
if (error && error.code === 'EADDRINUSE'
|
|
4941
|
+
if (error && error.code === 'EADDRINUSE') {
|
|
4542
4942
|
listenAttempt += 1;
|
|
4543
4943
|
const delay = Math.min(2000 * listenAttempt, 15000);
|
|
4544
|
-
|
|
4944
|
+
// 前 5 次每次都提示,之后每 20 次(约 5 分钟)提示一次,避免刷屏
|
|
4945
|
+
if (listenAttempt <= 5 || listenAttempt % 20 === 0) {
|
|
4946
|
+
warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次,会一直重试)`);
|
|
4947
|
+
}
|
|
4545
4948
|
setTimeout(startListening, delay);
|
|
4546
4949
|
return;
|
|
4547
4950
|
}
|
|
4548
|
-
|
|
4951
|
+
// 2026-11-17 门禁清理:Node 的 listen 错误恒为带 message 的 Error,原 ?: String(error) 分支不可达。
|
|
4952
|
+
warn(`监听失败:${error.message}`);
|
|
4549
4953
|
});
|
|
4550
4954
|
startListening();
|
|
4551
4955
|
|
|
@@ -4571,13 +4975,13 @@ export function apply(ctx, rawConfig) {
|
|
|
4571
4975
|
}
|
|
4572
4976
|
|
|
4573
4977
|
return () => {
|
|
4574
|
-
// DSH
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4978
|
+
// DSH 退出:主动让转屏守护进程恢复横屏(硬退出则由守护进程空闲计时兜底)。
|
|
4979
|
+
// 2026-11-17 门禁清理:restoreOrientation 内部把所有异常收敛成 {ok:false},不会 reject,
|
|
4980
|
+
// 原 `.catch(() => {})` 不可达;watcher.close() 也不会抛,原 try/catch 同理删除。
|
|
4981
|
+
Promise.resolve().then(() => windowRemote.restoreOrientation(6_000));
|
|
4578
4982
|
if (syncTimer) clearInterval(syncTimer);
|
|
4579
4983
|
if (reloadTimer) clearTimeout(reloadTimer);
|
|
4580
|
-
|
|
4984
|
+
watcher?.close();
|
|
4581
4985
|
tunnel.stop();
|
|
4582
4986
|
server.close();
|
|
4583
4987
|
};
|