@andy.ian/dsh-homing 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/bin/auth.mjs +2 -2
- package/bin/backup.mjs +4 -4
- package/bin/bootstrap-server.mjs +4 -4
- package/bin/entry-link.mjs +2 -2
- package/bin/renew-cert.mjs +1 -1
- package/bin/supervisor.mjs +488 -0
- package/bin/watchdog.mjs +99 -113
- package/cordis.patch.yml +4 -4
- package/index.js +197 -229
- package/lib/files-page.mjs +228 -138
- package/lib/files.mjs +89 -2
- package/lib/limits.mjs +1 -1
- package/lib/pty.mjs +10 -3
- package/package.json +4 -4
- package/lib/session.mjs +0 -216
- package/lib/shell-page.mjs +0 -430
- package/lib/shell.mjs +0 -274
- package/ops/watchdog/dsh-watchdog.ps1 +0 -105
- package/ops/watchdog/restart-now.ps1 +0 -247
package/index.js
CHANGED
|
@@ -23,16 +23,13 @@ import zlib from 'node:zlib';
|
|
|
23
23
|
import * as deviceStore from './lib/devices.mjs';
|
|
24
24
|
import * as filebrowse from './lib/files.mjs';
|
|
25
25
|
import * as gitrun from './lib/git.mjs';
|
|
26
|
-
import * as shellrun from './lib/shell.mjs';
|
|
27
|
-
import { sharedSession, resetSharedSession } from './lib/session.mjs';
|
|
28
26
|
import * as ptyrun from './lib/pty.mjs';
|
|
29
27
|
import { renderTermPage } from './lib/term-page.mjs';
|
|
30
|
-
import {
|
|
31
|
-
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderShellPage } from './lib/files-page.mjs';
|
|
28
|
+
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage } from './lib/files-page.mjs';
|
|
32
29
|
import { checkUnsafeOrigin } from './lib/csrf.mjs';
|
|
33
30
|
import * as limits from './lib/limits.mjs';
|
|
34
31
|
|
|
35
|
-
export const name = 'dsh-
|
|
32
|
+
export const name = 'dsh-homing';
|
|
36
33
|
|
|
37
34
|
// 插件版本(调试页显示用),读不到也不影响运行
|
|
38
35
|
const PLUGIN_VERSION = (() => {
|
|
@@ -94,7 +91,7 @@ function normalizeConfig(raw) {
|
|
|
94
91
|
}
|
|
95
92
|
|
|
96
93
|
/* ------------------------------------------------------------------ *
|
|
97
|
-
* 数据目录(跨平台:$DSH_HOME/integrations/dsh-
|
|
94
|
+
* 数据目录(跨平台:$DSH_HOME/integrations/dsh-homing)
|
|
98
95
|
* ------------------------------------------------------------------ */
|
|
99
96
|
|
|
100
97
|
/** 本机所有局域网 IPv4,用来在日志里给出「同一个 Wi-Fi 用哪条地址」。 */
|
|
@@ -139,7 +136,21 @@ function sendAlert(dir, config, title, text) {
|
|
|
139
136
|
|
|
140
137
|
function dataDir() {
|
|
141
138
|
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
142
|
-
const
|
|
139
|
+
const legacyDir = path.join(home, 'integrations', 'dsh-homing');
|
|
140
|
+
const dir = path.join(home, 'integrations', 'dsh-homing');
|
|
141
|
+
// 数据目录随插件改名:旧目录存在而新目录不存在时,自动迁过去。
|
|
142
|
+
// 只 rename 一次;旧目录里的设备表/密码/证书全部保留,已配对设备不会掉线。
|
|
143
|
+
try {
|
|
144
|
+
if (fs.existsSync(legacyDir) && !fs.existsSync(dir)) {
|
|
145
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
146
|
+
fs.renameSync(legacyDir, dir);
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
// 迁移失败就退回旧目录,不能因为改名把服务弄挂
|
|
150
|
+
if (fs.existsSync(legacyDir)) {
|
|
151
|
+
return legacyDir;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
143
154
|
fs.mkdirSync(dir, { recursive: true });
|
|
144
155
|
return dir;
|
|
145
156
|
}
|
|
@@ -188,7 +199,7 @@ function readCookies(headerValue) {
|
|
|
188
199
|
* 账号(存本机,scrypt 哈希)
|
|
189
200
|
* ------------------------------------------------------------------ */
|
|
190
201
|
|
|
191
|
-
const SESSION_COOKIE = 'dsh-session';
|
|
202
|
+
const SESSION_COOKIE = 'dsh-homing-session';
|
|
192
203
|
const SESSION_SECONDS = 3 * 24 * 60 * 60;
|
|
193
204
|
|
|
194
205
|
function loadAuth(dir) {
|
|
@@ -356,17 +367,17 @@ const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
|
|
|
356
367
|
[class*="_frame"] { min-width: 0; }
|
|
357
368
|
|
|
358
369
|
/* 隐藏时只把侧边栏那一列压成 0,主内容自然占满;其余布局仍归应用自己算 */
|
|
359
|
-
html[data-dsh-
|
|
370
|
+
html[data-dsh-homing-nav="hidden"] [class*="_frame"] {
|
|
360
371
|
grid-template-columns: 0 1fr 0 !important;
|
|
361
372
|
transition: none !important;
|
|
362
373
|
}
|
|
363
|
-
html[data-dsh-
|
|
374
|
+
html[data-dsh-homing-nav="hidden"] [class*="sidebarCol"] {
|
|
364
375
|
min-width: 0 !important;
|
|
365
376
|
overflow: hidden !important;
|
|
366
377
|
}
|
|
367
378
|
|
|
368
379
|
/* 侧边栏完全隐藏时,左上角探出的小耳朵(磁吸感):点它恢复完整侧边栏 */
|
|
369
|
-
.dsh-
|
|
380
|
+
.dsh-homing-ear {
|
|
370
381
|
position: fixed;
|
|
371
382
|
left: 0;
|
|
372
383
|
top: 16px;
|
|
@@ -389,7 +400,7 @@ const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
|
|
|
389
400
|
user-select: none;
|
|
390
401
|
touch-action: manipulation;
|
|
391
402
|
}
|
|
392
|
-
.dsh-
|
|
403
|
+
.dsh-homing-ear:active { background: rgba(60, 66, 78, 0.95); color: #e8eaed; }
|
|
393
404
|
}
|
|
394
405
|
`;
|
|
395
406
|
|
|
@@ -401,7 +412,7 @@ const MOBILE_JS = `(() => {
|
|
|
401
412
|
const sidebar = () => document.querySelector('[class*="sidebarCol"]')
|
|
402
413
|
const openBtn = () => document.querySelector('[aria-label="打开侧边栏"]')
|
|
403
414
|
const collapseBtn = () => document.querySelector('[aria-label="收起侧边栏"]')
|
|
404
|
-
const isHidden = () => root.getAttribute('data-dsh-
|
|
415
|
+
const isHidden = () => root.getAttribute('data-dsh-homing-nav') === 'hidden'
|
|
405
416
|
// 我们自己去点应用按钮时,要绕过下面那个捕获拦截,否则会自己拦自己、无限递归
|
|
406
417
|
let quietClick = false
|
|
407
418
|
const clickQuietly = (btn) => {
|
|
@@ -420,10 +431,10 @@ const MOBILE_JS = `(() => {
|
|
|
420
431
|
const hide = () => {
|
|
421
432
|
if (!narrow()) return false
|
|
422
433
|
const before = widthOf(mainCol())
|
|
423
|
-
root.setAttribute('data-dsh-
|
|
434
|
+
root.setAttribute('data-dsh-homing-nav', 'hidden')
|
|
424
435
|
const after = widthOf(mainCol())
|
|
425
436
|
if (!(after > before + 10)) {
|
|
426
|
-
root.removeAttribute('data-dsh-
|
|
437
|
+
root.removeAttribute('data-dsh-homing-nav')
|
|
427
438
|
console.warn('[dsh-homing] 侧边栏隐藏未生效,已自动撤销')
|
|
428
439
|
updateEar()
|
|
429
440
|
return false
|
|
@@ -433,7 +444,7 @@ const MOBILE_JS = `(() => {
|
|
|
433
444
|
}
|
|
434
445
|
|
|
435
446
|
const showAttribute = () => {
|
|
436
|
-
root.removeAttribute('data-dsh-
|
|
447
|
+
root.removeAttribute('data-dsh-homing-nav')
|
|
437
448
|
updateEar()
|
|
438
449
|
}
|
|
439
450
|
|
|
@@ -481,7 +492,7 @@ const MOBILE_JS = `(() => {
|
|
|
481
492
|
const installEar = () => {
|
|
482
493
|
ear = document.createElement('button')
|
|
483
494
|
ear.type = 'button'
|
|
484
|
-
ear.className = 'dsh-
|
|
495
|
+
ear.className = 'dsh-homing-ear'
|
|
485
496
|
ear.setAttribute('aria-label', '展开侧边栏')
|
|
486
497
|
ear.textContent = '›'
|
|
487
498
|
ear.addEventListener('click', (event) => {
|
|
@@ -509,7 +520,7 @@ const MOBILE_JS = `(() => {
|
|
|
509
520
|
|
|
510
521
|
// 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
|
|
511
522
|
// 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
|
|
512
|
-
const LAST_WS_KEY = 'dsh-
|
|
523
|
+
const LAST_WS_KEY = 'dsh-homing:last-workspace'
|
|
513
524
|
document.addEventListener('click', (event) => {
|
|
514
525
|
const node = event.target
|
|
515
526
|
if (node === null || typeof node.closest !== 'function') return
|
|
@@ -578,7 +589,7 @@ const MOBILE_JS = `(() => {
|
|
|
578
589
|
return
|
|
579
590
|
}
|
|
580
591
|
let hint = ''
|
|
581
|
-
try { hint = currentSessionTitle() || window.localStorage.getItem('dsh-
|
|
592
|
+
try { hint = currentSessionTitle() || window.localStorage.getItem('dsh-homing:last-workspace') || '' } catch { hint = '' }
|
|
582
593
|
window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
|
|
583
594
|
}
|
|
584
595
|
|
|
@@ -707,8 +718,8 @@ const MOBILE_JS = `(() => {
|
|
|
707
718
|
try {
|
|
708
719
|
if (document.visibilityState === 'hidden') return
|
|
709
720
|
const body = JSON.stringify({ at: now, path: location.pathname })
|
|
710
|
-
if (navigator.sendBeacon) navigator.sendBeacon('/
|
|
711
|
-
else fetch('/
|
|
721
|
+
if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
|
|
722
|
+
else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
|
|
712
723
|
} catch (error) {
|
|
713
724
|
/* 忽略 */
|
|
714
725
|
}
|
|
@@ -724,11 +735,11 @@ const MOBILE_JS = `(() => {
|
|
|
724
735
|
})();
|
|
725
736
|
`;
|
|
726
737
|
|
|
727
|
-
const INJECTION = '<link rel="stylesheet" href="/
|
|
738
|
+
const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
|
|
728
739
|
|
|
729
740
|
// 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
|
|
730
741
|
// 调试页上一键即可设置,页面坏了也点得到。
|
|
731
|
-
const MOBILE_OFF_COOKIE = 'dsh-
|
|
742
|
+
const MOBILE_OFF_COOKIE = 'dsh-homing-off';
|
|
732
743
|
|
|
733
744
|
const DEBUG_HTML = `<!doctype html>
|
|
734
745
|
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
@@ -763,6 +774,7 @@ const DEBUG_HTML = `<!doctype html>
|
|
|
763
774
|
<body><div class="wrap">
|
|
764
775
|
<h1>调试页</h1>
|
|
765
776
|
<p class="sub">这一页不依赖移动端样式,界面被改坏时也能打开。</p>
|
|
777
|
+
<p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
|
|
766
778
|
{{message}}
|
|
767
779
|
|
|
768
780
|
<h2>状态</h2>
|
|
@@ -803,8 +815,8 @@ const DEBUG_HTML = `<!doctype html>
|
|
|
803
815
|
|
|
804
816
|
<h2>快捷入口</h2>
|
|
805
817
|
<div class="card">
|
|
806
|
-
<a class="btn ghost" href="/
|
|
807
|
-
<a class="btn ghost" href="/
|
|
818
|
+
<a class="btn ghost" href="/dsh_homing/account">账户设置</a>
|
|
819
|
+
<a class="btn ghost" href="/dsh_homing/devices">设备管理</a>
|
|
808
820
|
<a class="btn ghost" href="/logout">退出登录</a>
|
|
809
821
|
</div>
|
|
810
822
|
</div>
|
|
@@ -877,7 +889,8 @@ const ACCOUNT_HTML = `<!doctype html>
|
|
|
877
889
|
</style></head>
|
|
878
890
|
<body><div class="wrap">
|
|
879
891
|
<h1>账户设置</h1>
|
|
880
|
-
<p class="sub"><a href="/
|
|
892
|
+
<p class="sub"><a href="/dsh_homing/devices">设备管理(吊销/删除已配对设备)→</a></p>
|
|
893
|
+
<p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
|
|
881
894
|
<div class="muted">用户名:{{username}}</div>
|
|
882
895
|
{{message}}
|
|
883
896
|
|
|
@@ -969,7 +982,7 @@ const LOGIN_HTML = `<!doctype html>
|
|
|
969
982
|
<button type="submit">登录</button>
|
|
970
983
|
</form>
|
|
971
984
|
{{message}}
|
|
972
|
-
<div class="hint">登录一次后 3 天内免登录 · <a href="/
|
|
985
|
+
<div class="hint">登录一次后 3 天内免登录 · <a href="/dsh_homing/reset" style="color:#7aa7ff">忘记密码?</a></div>
|
|
973
986
|
</div></body></html>`;
|
|
974
987
|
|
|
975
988
|
const RESET_HTML = `<!doctype html>
|
|
@@ -999,7 +1012,7 @@ const RESET_HTML = `<!doctype html>
|
|
|
999
1012
|
<input type="hidden" name="action" value="request">
|
|
1000
1013
|
<button type="submit">获取重置码</button>
|
|
1001
1014
|
</form>
|
|
1002
|
-
<p style="margin-top:10px">生成后在你电脑上打开:<br><code>$DSH_HOME/integrations/dsh-
|
|
1015
|
+
<p style="margin-top:10px">生成后在你电脑上打开:<br><code>$DSH_HOME/integrations/dsh-homing/reset-code.txt</code><br>(文件里就一行「重置码:XXXX」)</p>
|
|
1003
1016
|
</div>
|
|
1004
1017
|
|
|
1005
1018
|
<div class="card">
|
|
@@ -1024,7 +1037,7 @@ function sendLogin(res, message = '', requireTotp = false) {
|
|
|
1024
1037
|
'cache-control': 'no-store',
|
|
1025
1038
|
// 登录页的安全头:禁止被嵌入(防点击劫持)、禁止外链、限制表单只能提交给自己
|
|
1026
1039
|
'x-frame-options': 'DENY',
|
|
1027
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
1040
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
1028
1041
|
'x-content-type-options': 'nosniff',
|
|
1029
1042
|
'referrer-policy': 'no-referrer',
|
|
1030
1043
|
});
|
|
@@ -1174,12 +1187,12 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1174
1187
|
return Number.isFinite(expiresAt) && expiresAt > Date.now() ? expiresAt : 0;
|
|
1175
1188
|
}
|
|
1176
1189
|
|
|
1177
|
-
/* ---- 逐设备令牌(dsh-device)----------------------------------------
|
|
1190
|
+
/* ---- 逐设备令牌(dsh-homing-device)----------------------------------------
|
|
1178
1191
|
* 入口令牌 ?k= 只用来「配对」一次:配对后发一枚设备令牌 Cookie,
|
|
1179
1192
|
* 之后由设备表放行。设备表在 devices.json,可单独吊销某一台,
|
|
1180
1193
|
* 吊销后下一次请求就失效——丢手机不用改密码、也不用重启。
|
|
1181
1194
|
*/
|
|
1182
|
-
const DEVICE_COOKIE = 'dsh-device';
|
|
1195
|
+
const DEVICE_COOKIE = 'dsh-homing-device';
|
|
1183
1196
|
const DEVICE_SECONDS = 180 * 24 * 60 * 60;
|
|
1184
1197
|
// 设备表缓存按 mtime 失效:手工改 devices.json(比如在电脑上直接吊销)
|
|
1185
1198
|
// 也会在下一个请求立刻生效,不用重启。
|
|
@@ -1263,9 +1276,10 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1263
1276
|
const touchActivity = createActivityRecorder(dir);
|
|
1264
1277
|
|
|
1265
1278
|
const handler = async (req, res) => {
|
|
1266
|
-
|
|
1279
|
+
|
|
1280
|
+
const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
|
|
1267
1281
|
// 任何来自浏览器的请求都算"人在用"(静态资源除外,避免预加载把空闲判断拖长)
|
|
1268
|
-
if (!/^\/(?:
|
|
1282
|
+
if (!/^\/(?:dsh_homing\/alive|assets?\/|favicon)/u.test(url.pathname)) touchActivity('request');
|
|
1269
1283
|
// 写操作来源校验:
|
|
1270
1284
|
// - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
|
|
1271
1285
|
// - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
|
|
@@ -1274,10 +1288,9 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1274
1288
|
const originCheck = checkUnsafeOrigin(req);
|
|
1275
1289
|
if (!originCheck.ok) {
|
|
1276
1290
|
const ownPath = url.pathname === '/login' || url.pathname === '/logout'
|
|
1277
|
-
|| url.pathname.startsWith('/
|
|
1291
|
+
|| url.pathname.startsWith('/dsh_homing/')
|
|
1278
1292
|
|| url.pathname === '/files' || url.pathname.startsWith('/files/')
|
|
1279
1293
|
|| url.pathname === '/git' || url.pathname.startsWith('/git/')
|
|
1280
|
-
|| url.pathname === '/shell' || url.pathname.startsWith('/shell/')
|
|
1281
1294
|
|| url.pathname === '/term' || url.pathname.startsWith('/term/')
|
|
1282
1295
|
|| url.pathname === '/debug' || url.pathname.startsWith('/debug/');
|
|
1283
1296
|
appendAudit(dir, 'origin-check', {
|
|
@@ -1295,18 +1308,18 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1295
1308
|
}
|
|
1296
1309
|
}
|
|
1297
1310
|
|
|
1298
|
-
if (url.pathname === '/
|
|
1311
|
+
if (url.pathname === '/dsh_homing/mobile.css') {
|
|
1299
1312
|
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' });
|
|
1300
1313
|
res.end(MOBILE_CSS);
|
|
1301
1314
|
return;
|
|
1302
1315
|
}
|
|
1303
|
-
if (url.pathname === '/
|
|
1316
|
+
if (url.pathname === '/dsh_homing/mobile.js') {
|
|
1304
1317
|
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
1305
1318
|
res.end(MOBILE_JS);
|
|
1306
1319
|
return;
|
|
1307
1320
|
}
|
|
1308
1321
|
// 局域网证书(公开,不含任何秘密):手机装上它就能消除"不安全"警告并挡住中间人
|
|
1309
|
-
if ((url.pathname === '/
|
|
1322
|
+
if ((url.pathname === '/dsh_homing/ca.crt' || url.pathname === '/dsh_homing/ca.der') && caCertPath && fs.existsSync(caCertPath)) {
|
|
1310
1323
|
// 鸿蒙 / 部分安卓要求 DER(.cer),iOS 和多数安卓吃 PEM(.crt):两种都给
|
|
1311
1324
|
const wantDer = url.pathname.endsWith('.der');
|
|
1312
1325
|
res.writeHead(200, {
|
|
@@ -1335,14 +1348,14 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1335
1348
|
|
|
1336
1349
|
// 登录 / 登出 / 账户页 / 重置密码:这些本身就有各自的凭据保护,不再要求入口暗号
|
|
1337
1350
|
const isLoginPath = url.pathname === '/login' || url.pathname === '/logout'
|
|
1338
|
-
|| url.pathname === '/
|
|
1339
|
-
|| url.pathname === '/
|
|
1351
|
+
|| url.pathname === '/dsh_homing/account' || url.pathname === '/dsh_homing/reset'
|
|
1352
|
+
|| url.pathname === '/dsh_homing/devices'
|
|
1340
1353
|
|| url.pathname === '/files' || url.pathname.startsWith('/files/')
|
|
1341
|
-
|| url.pathname === '/debug' || url.pathname === '/
|
|
1342
|
-
|| url.pathname.startsWith('/debug/') || url.pathname.startsWith('/
|
|
1354
|
+
|| url.pathname === '/debug' || url.pathname === '/dsh_homing/debug'
|
|
1355
|
+
|| url.pathname.startsWith('/debug/') || url.pathname.startsWith('/dsh_homing/debug/');
|
|
1343
1356
|
|
|
1344
1357
|
// 重置密码:忘掉密码时用,凭据是「能在运行 DSH 的电脑上读到重置码」
|
|
1345
|
-
if (url.pathname === '/
|
|
1358
|
+
if (url.pathname === '/dsh_homing/reset') {
|
|
1346
1359
|
const ip = clientKey(req);
|
|
1347
1360
|
const resetFile = path.join(dir, 'reset-code.txt');
|
|
1348
1361
|
const issueCode = () => {
|
|
@@ -1408,7 +1421,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1408
1421
|
'content-type': 'text/html; charset=utf-8',
|
|
1409
1422
|
'cache-control': 'no-store',
|
|
1410
1423
|
'x-frame-options': 'DENY',
|
|
1411
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
1424
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
1412
1425
|
'x-content-type-options': 'nosniff',
|
|
1413
1426
|
'referrer-policy': 'no-referrer',
|
|
1414
1427
|
});
|
|
@@ -1432,7 +1445,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1432
1445
|
'content-type': 'text/html; charset=utf-8',
|
|
1433
1446
|
'cache-control': 'no-store',
|
|
1434
1447
|
'x-frame-options': 'DENY',
|
|
1435
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
1448
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
1436
1449
|
'x-content-type-options': 'nosniff',
|
|
1437
1450
|
'referrer-policy': 'no-referrer',
|
|
1438
1451
|
});
|
|
@@ -1461,8 +1474,58 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1461
1474
|
}
|
|
1462
1475
|
}
|
|
1463
1476
|
|
|
1477
|
+
// 自检:把"兜底转发"这一段的状态暴露出来,便于定位 404
|
|
1478
|
+
if (url.pathname === '/dsh_homing/selfcheck') {
|
|
1479
|
+
const up = getUpstreamPort();
|
|
1480
|
+
const authority = up ? '127.0.0.1:' + up : null;
|
|
1481
|
+
let cookieName = null;
|
|
1482
|
+
let accepted = null;
|
|
1483
|
+
let upstreamStatus = null;
|
|
1484
|
+
let sample = null;
|
|
1485
|
+
try {
|
|
1486
|
+
const minted = authority ? await mintCookie(authority) : undefined;
|
|
1487
|
+
cookieName = minted ? minted.name : null;
|
|
1488
|
+
if (authority && minted) {
|
|
1489
|
+
accepted = await new Promise((resolve) => {
|
|
1490
|
+
const probe = http.request({
|
|
1491
|
+
host: '127.0.0.1', port: up, path: '/', method: 'GET',
|
|
1492
|
+
headers: { host: authority, cookie: minted.name + '=' + minted.value },
|
|
1493
|
+
timeout: 5000,
|
|
1494
|
+
}, (res) => { upstreamStatus = res.statusCode; res.resume(); res.on('end', () => resolve(res.statusCode === 200)); });
|
|
1495
|
+
probe.on('timeout', () => { probe.destroy(); resolve(false); });
|
|
1496
|
+
probe.on('error', () => resolve(false));
|
|
1497
|
+
probe.end();
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
const direct = await new Promise((resolve) => {
|
|
1501
|
+
const req2 = http.request({ host: '127.0.0.1', port: up, path: '/', method: 'GET', headers: { host: authority ?? '' }, timeout: 5000 }, (res) => {
|
|
1502
|
+
const chunks = [];
|
|
1503
|
+
res.on('data', (c) => chunks.push(c));
|
|
1504
|
+
res.on('end', () => resolve({ status: res.statusCode, head: Buffer.concat(chunks).toString('utf8').slice(0, 120) }));
|
|
1505
|
+
});
|
|
1506
|
+
req2.on('timeout', () => { req2.destroy(); resolve({ status: 'timeout' }); });
|
|
1507
|
+
req2.on('error', (e) => resolve({ status: 'error: ' + e.code }));
|
|
1508
|
+
req2.end();
|
|
1509
|
+
});
|
|
1510
|
+
sample = direct;
|
|
1511
|
+
} catch (error) {
|
|
1512
|
+
sample = { error: String(error?.message ?? error) };
|
|
1513
|
+
}
|
|
1514
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1515
|
+
res.end(JSON.stringify({
|
|
1516
|
+
upstreamPort: up ?? null,
|
|
1517
|
+
authority,
|
|
1518
|
+
cookieName,
|
|
1519
|
+
cookieAccepted: accepted,
|
|
1520
|
+
upstreamRootStatusNoCookie: upstreamStatus,
|
|
1521
|
+
upstreamSample: sample,
|
|
1522
|
+
pluginVersion: PLUGIN_VERSION,
|
|
1523
|
+
}, null, 2));
|
|
1524
|
+
return;
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1464
1527
|
// 活跃度信标:手机端打字/滑动时上报,重启脚本据此避免打断用户
|
|
1465
|
-
if (url.pathname === '/
|
|
1528
|
+
if (url.pathname === '/dsh_homing/alive' && (req.method === 'POST' || req.method === 'GET')) {
|
|
1466
1529
|
touchActivity('beacon');
|
|
1467
1530
|
res.writeHead(204, { 'cache-control': 'no-store' });
|
|
1468
1531
|
res.end();
|
|
@@ -1471,7 +1534,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1471
1534
|
|
|
1472
1535
|
// 真终端:/term(xterm.js + 本机 sshd 的 PTY)。需要登录。
|
|
1473
1536
|
if (url.pathname === '/term' || url.pathname.startsWith('/term/')) {
|
|
1474
|
-
if (!sessionValid(req)) {
|
|
1537
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1475
1538
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1476
1539
|
res.end();
|
|
1477
1540
|
return;
|
|
@@ -1647,159 +1710,8 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1647
1710
|
}
|
|
1648
1711
|
|
|
1649
1712
|
// 终端:执行任意 shell 命令(手机端的 Git Bash)。需要登录。
|
|
1650
|
-
if (url.pathname === '/shell' || url.pathname === '/shell/complete' || url.pathname === '/shell/run') {
|
|
1651
|
-
if (!sessionValid(req)) {
|
|
1652
|
-
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1653
|
-
res.end();
|
|
1654
|
-
return;
|
|
1655
|
-
}
|
|
1656
|
-
const sendShell = (pageHtml) => {
|
|
1657
|
-
res.writeHead(200, {
|
|
1658
|
-
'content-type': 'text/html; charset=utf-8',
|
|
1659
|
-
'cache-control': 'no-store',
|
|
1660
|
-
'x-frame-options': 'DENY',
|
|
1661
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'",
|
|
1662
|
-
'x-content-type-options': 'nosniff',
|
|
1663
|
-
'referrer-policy': 'no-referrer',
|
|
1664
|
-
});
|
|
1665
|
-
res.end(pageHtml);
|
|
1666
|
-
};
|
|
1667
|
-
const dshHomeShell = path.resolve(dir, '..', '..');
|
|
1668
|
-
const wsIndex = filebrowse.workspaceIndex(dshHomeShell);
|
|
1669
|
-
const shellName = shellrun.findBash() === null ? 'cmd.exe' : 'bash';
|
|
1670
|
-
|
|
1671
|
-
if (url.pathname === '/shell/complete') {
|
|
1672
|
-
const cwdParam = url.searchParams.get('cwd') ?? filebrowse.HOME;
|
|
1673
|
-
const line = url.searchParams.get('line') ?? '';
|
|
1674
|
-
const items = shellrun.completeCandidates(cwdParam, line);
|
|
1675
|
-
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1676
|
-
res.end(JSON.stringify(items));
|
|
1677
|
-
return;
|
|
1678
|
-
}
|
|
1679
|
-
|
|
1680
|
-
// 终端页用:执行命令并返回 JSON(页面不刷新)
|
|
1681
|
-
if (url.pathname === '/shell/run' && req.method === 'POST') {
|
|
1682
|
-
let payload = {};
|
|
1683
|
-
try {
|
|
1684
|
-
payload = JSON.parse(await readBody(req, 64 * 1024));
|
|
1685
|
-
} catch {
|
|
1686
|
-
payload = {};
|
|
1687
|
-
}
|
|
1688
|
-
const commandText = String(payload.command ?? '');
|
|
1689
|
-
const baseCwd = String(payload.cwd ?? wsIndex.defaultPath ?? filebrowse.HOME);
|
|
1690
|
-
const terminal = sharedSession(baseCwd);
|
|
1691
|
-
const sendJson = (data) => {
|
|
1692
|
-
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1693
|
-
res.end(JSON.stringify(data));
|
|
1694
|
-
};
|
|
1695
|
-
if (payload.reset === true) {
|
|
1696
|
-
resetSharedSession();
|
|
1697
|
-
appendAudit(dir, 'shell-reset', {});
|
|
1698
|
-
sendJson({ ok: true, code: 0, output: '会话已重置', cwd: terminal.info().cwd });
|
|
1699
|
-
return;
|
|
1700
|
-
}
|
|
1701
|
-
// Ctrl+C:中断当前命令(杀掉 bash 及子进程树后重启)
|
|
1702
|
-
if (payload.interrupt === true) {
|
|
1703
|
-
appendAudit(dir, 'shell-interrupt', {});
|
|
1704
|
-
const stopped = terminal.interrupt();
|
|
1705
|
-
sendJson({
|
|
1706
|
-
ok: true,
|
|
1707
|
-
code: null,
|
|
1708
|
-
interrupted: true,
|
|
1709
|
-
output: stopped.output,
|
|
1710
|
-
cwd: terminal.info().cwd,
|
|
1711
|
-
branch: '',
|
|
1712
|
-
});
|
|
1713
|
-
return;
|
|
1714
|
-
}
|
|
1715
|
-
appendAudit(dir, 'shell-run', { cwd: baseCwd, command: commandText });
|
|
1716
|
-
const result = await terminal.run(commandText);
|
|
1717
|
-
terminal.record({
|
|
1718
|
-
command: commandText,
|
|
1719
|
-
output: String(result.output ?? ''),
|
|
1720
|
-
code: result.code ?? null,
|
|
1721
|
-
ok: result.ok !== false,
|
|
1722
|
-
timeout: result.timeout === true,
|
|
1723
|
-
cwd: result.cwd ?? baseCwd,
|
|
1724
|
-
});
|
|
1725
|
-
const afterBranch = gitrun.isRepo(terminal.info().cwd)
|
|
1726
|
-
? await gitrun.runGit(terminal.info().cwd, ['branch', '--show-current'])
|
|
1727
|
-
: null;
|
|
1728
|
-
sendJson({
|
|
1729
|
-
ok: result.ok !== false,
|
|
1730
|
-
code: result.code ?? null,
|
|
1731
|
-
output: result.output ?? '',
|
|
1732
|
-
cwd: terminal.info().cwd,
|
|
1733
|
-
branch: afterBranch !== null && afterBranch.ok ? afterBranch.output.trim() : '',
|
|
1734
|
-
timeout: result.timeout === true,
|
|
1735
|
-
});
|
|
1736
|
-
return;
|
|
1737
|
-
}
|
|
1738
|
-
|
|
1739
|
-
// 简易终端已下线:GET 一律跳到真终端 /term(保留 POST 接口兼容旧页面)
|
|
1740
|
-
if (req.method === 'GET') {
|
|
1741
|
-
const query = url.searchParams.toString();
|
|
1742
|
-
res.writeHead(303, { location: '/term' + (query === '' ? '' : '?' + query), 'cache-control': 'no-store' });
|
|
1743
|
-
res.end();
|
|
1744
|
-
return;
|
|
1745
|
-
}
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
if (req.method === 'POST') {
|
|
1749
|
-
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
1750
|
-
let cwd = form.get('cwd') ?? filebrowse.HOME;
|
|
1751
|
-
const command = form.get('command') ?? '';
|
|
1752
|
-
if (form.get('action') === 'reset') {
|
|
1753
|
-
resetSharedSession();
|
|
1754
|
-
appendAudit(dir, 'shell-reset', {});
|
|
1755
|
-
const fresh = sharedSession(cwd);
|
|
1756
|
-
sendShell(renderShellPage({
|
|
1757
|
-
cwd: fresh.info().cwd,
|
|
1758
|
-
shellName: 'bash · 常驻会话(已重置)',
|
|
1759
|
-
result: { ok: true, code: 0, output: '会话已重置:环境变量清空,当前目录保持' },
|
|
1760
|
-
}));
|
|
1761
|
-
return;
|
|
1762
|
-
}
|
|
1763
|
-
// 支持 cd:只改工作目录,不真的执行
|
|
1764
|
-
const nextCwd = shellrun.parseCd(command, cwd);
|
|
1765
|
-
if (nextCwd !== null) {
|
|
1766
|
-
const exists = (() => {
|
|
1767
|
-
try {
|
|
1768
|
-
return fs.statSync(nextCwd).isDirectory();
|
|
1769
|
-
} catch {
|
|
1770
|
-
return false;
|
|
1771
|
-
}
|
|
1772
|
-
})();
|
|
1773
|
-
sendShell(renderShellPage({
|
|
1774
|
-
cwd: exists ? nextCwd : cwd,
|
|
1775
|
-
command: '',
|
|
1776
|
-
shellName,
|
|
1777
|
-
result: { ok: exists, code: exists ? 0 : 1, output: exists ? nextCwd : '目录不存在:' + nextCwd },
|
|
1778
|
-
}));
|
|
1779
|
-
return;
|
|
1780
|
-
}
|
|
1781
|
-
appendAudit(dir, 'shell-run', { cwd, command });
|
|
1782
|
-
// 常驻会话:cd / export / 函数定义都跨命令保留
|
|
1783
|
-
const session = sharedSession(cwd);
|
|
1784
|
-
if (cwd !== session.info().cwd) {
|
|
1785
|
-
await session.run('cd "' + String(cwd).replaceAll('"', '""') + '"');
|
|
1786
|
-
}
|
|
1787
|
-
const result = await session.run(command);
|
|
1788
|
-
const info = session.info();
|
|
1789
|
-
sendShell(renderShellPage({
|
|
1790
|
-
cwd: info.cwd,
|
|
1791
|
-
command,
|
|
1792
|
-
result,
|
|
1793
|
-
shellName: info.running ? 'bash · 常驻会话' : 'bash · 会话已重启',
|
|
1794
|
-
history: [command],
|
|
1795
|
-
}));
|
|
1796
|
-
return;
|
|
1797
|
-
}
|
|
1798
|
-
}
|
|
1799
|
-
|
|
1800
|
-
// git 页:跑任意 git 子命令(不经过 shell),需要登录
|
|
1801
1713
|
if (url.pathname === '/git' || url.pathname === '/git/run') {
|
|
1802
|
-
if (!sessionValid(req)) {
|
|
1714
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1803
1715
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1804
1716
|
res.end();
|
|
1805
1717
|
return;
|
|
@@ -1809,7 +1721,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1809
1721
|
'content-type': 'text/html; charset=utf-8',
|
|
1810
1722
|
'cache-control': 'no-store',
|
|
1811
1723
|
'x-frame-options': 'DENY',
|
|
1812
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
1724
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
1813
1725
|
'x-content-type-options': 'nosniff',
|
|
1814
1726
|
'referrer-policy': 'no-referrer',
|
|
1815
1727
|
});
|
|
@@ -1860,8 +1772,11 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1860
1772
|
return;
|
|
1861
1773
|
}
|
|
1862
1774
|
|
|
1863
|
-
if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
|
|
1864
|
-
|
|
1775
|
+
if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
|
|
1776
|
+
|| url.pathname === '/files/rename'
|
|
1777
|
+
|| url.pathname === '/files/delete' || url.pathname === '/files/paste'
|
|
1778
|
+
|| url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
|
|
1779
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1865
1780
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1866
1781
|
res.end();
|
|
1867
1782
|
return;
|
|
@@ -1871,7 +1786,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1871
1786
|
'content-type': 'text/html; charset=utf-8',
|
|
1872
1787
|
'cache-control': 'no-store',
|
|
1873
1788
|
'x-frame-options': 'DENY',
|
|
1874
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
1789
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
1875
1790
|
'x-content-type-options': 'nosniff',
|
|
1876
1791
|
'referrer-policy': 'no-referrer',
|
|
1877
1792
|
});
|
|
@@ -1917,6 +1832,22 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1917
1832
|
return;
|
|
1918
1833
|
}
|
|
1919
1834
|
|
|
1835
|
+
if (url.pathname === '/files/rename' && req.method === 'POST') {
|
|
1836
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
1837
|
+
const target = form.get('path') ?? '';
|
|
1838
|
+
const name = form.get('name') ?? '';
|
|
1839
|
+
const result = filebrowse.renameEntry(target, name);
|
|
1840
|
+
appendAudit(dir, 'file-rename', { target, name, ok: result.ok, error: result.error ?? null });
|
|
1841
|
+
if (!result.ok) {
|
|
1842
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)) + '&msg=' + encodeURIComponent(result.error), 'cache-control': 'no-store' });
|
|
1843
|
+
res.end();
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(result.path)), 'cache-control': 'no-store' });
|
|
1847
|
+
res.end();
|
|
1848
|
+
return;
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1920
1851
|
if (url.pathname === '/files/run' && req.method === 'POST') {
|
|
1921
1852
|
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
1922
1853
|
const file = form.get('path') ?? '';
|
|
@@ -1933,16 +1864,16 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1933
1864
|
}
|
|
1934
1865
|
|
|
1935
1866
|
// 调试页:独立于移动端样式,页面被改坏时也能打开;需要登录。
|
|
1936
|
-
// 两个地址都能用:/debug(好记)和 /
|
|
1867
|
+
// 两个地址都能用:/debug(好记)和 /dsh_homing/debug(兼容旧链接)
|
|
1937
1868
|
const debugPrefix = url.pathname === '/debug' || url.pathname.startsWith('/debug/')
|
|
1938
1869
|
? '/debug'
|
|
1939
|
-
: url.pathname === '/
|
|
1940
|
-
? '/
|
|
1870
|
+
: url.pathname === '/dsh_homing/debug' || url.pathname.startsWith('/dsh_homing/debug/')
|
|
1871
|
+
? '/dsh_homing/debug'
|
|
1941
1872
|
: null;
|
|
1942
1873
|
const debugSub = debugPrefix === null ? null : url.pathname.slice(debugPrefix.length);
|
|
1943
1874
|
|
|
1944
1875
|
if (debugSub === '') {
|
|
1945
|
-
if (!sessionValid(req)) {
|
|
1876
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1946
1877
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1947
1878
|
res.end();
|
|
1948
1879
|
return;
|
|
@@ -1999,13 +1930,13 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
1999
1930
|
.replaceAll('{{errors}}', errors.length > 0 ? errors.map((line) => escapeHtml(line)).join('<br>') : '无')
|
|
2000
1931
|
.replaceAll('{{shots}}', shots.length === 0
|
|
2001
1932
|
? ''
|
|
2002
|
-
: `<div class="shots">${shots.map((name) => `<a href="${debugPrefix}/files/${encodeURIComponent(name)}" target="_blank"><img src="/
|
|
1933
|
+
: `<div class="shots">${shots.map((name) => `<a href="${debugPrefix}/files/${encodeURIComponent(name)}" target="_blank"><img src="/dsh_homing/debug/files/${encodeURIComponent(name)}" alt="${escapeHtml(name)}"></a>`).join('')}</div>`));
|
|
2003
1934
|
return;
|
|
2004
1935
|
}
|
|
2005
1936
|
|
|
2006
1937
|
// 上传截图:接收 dataURL,落盘到 debug/shots/
|
|
2007
1938
|
if (debugSub === '/upload' && req.method === 'POST') {
|
|
2008
|
-
if (!sessionValid(req)) {
|
|
1939
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2009
1940
|
res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2010
1941
|
res.end('未登录');
|
|
2011
1942
|
return;
|
|
@@ -2034,7 +1965,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2034
1965
|
|
|
2035
1966
|
// 查看已上传的截图
|
|
2036
1967
|
if (debugSub !== null && debugSub.startsWith('/files/') && req.method === 'GET') {
|
|
2037
|
-
if (!sessionValid(req)) {
|
|
1968
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2038
1969
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2039
1970
|
res.end();
|
|
2040
1971
|
return;
|
|
@@ -2062,7 +1993,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2062
1993
|
|
|
2063
1994
|
// 设备管理:需要登录。它在入口闸门的白名单里,所以即使把所有设备都吊销了,
|
|
2064
1995
|
// 你仍然能在电脑上登录后进来恢复,不会把自己彻底锁死。
|
|
2065
|
-
if (url.pathname === '/
|
|
1996
|
+
if (url.pathname === '/dsh_homing/devices') {
|
|
2066
1997
|
if (!sessionValid(req)) {
|
|
2067
1998
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2068
1999
|
res.end();
|
|
@@ -2082,7 +2013,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2082
2013
|
appendAudit(dir, `device-${action}`, { id, ip: clientKey(req) });
|
|
2083
2014
|
}
|
|
2084
2015
|
res.writeHead(303, {
|
|
2085
|
-
location: `/
|
|
2016
|
+
location: `/dsh_homing/devices?msg=${encodeURIComponent(result.changed ? '已更新。' : '没有变化。')}`,
|
|
2086
2017
|
'cache-control': 'no-store',
|
|
2087
2018
|
});
|
|
2088
2019
|
res.end();
|
|
@@ -2112,7 +2043,7 @@ function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCo
|
|
|
2112
2043
|
'content-type': 'text/html; charset=utf-8',
|
|
2113
2044
|
'cache-control': 'no-store',
|
|
2114
2045
|
'x-frame-options': 'DENY',
|
|
2115
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
2046
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
2116
2047
|
'x-content-type-options': 'nosniff',
|
|
2117
2048
|
'referrer-policy': 'no-referrer',
|
|
2118
2049
|
});
|
|
@@ -2133,7 +2064,7 @@ button.danger{background:#3a2226;border-color:#54303a;color:#f0b6bf}
|
|
|
2133
2064
|
a{color:#8ab4f8}
|
|
2134
2065
|
</style>
|
|
2135
2066
|
<h1>设备管理</h1>
|
|
2136
|
-
<p class="sub"><a href="/
|
|
2067
|
+
<p class="sub"><a href="/dsh_homing/account">← 返回账户设置</a></p>
|
|
2137
2068
|
<p class="sub">每台配对过的手机/浏览器各占一条。吊销后它的下一次请求立即失效,不用改密码、不用重启。</p>
|
|
2138
2069
|
${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
2139
2070
|
<table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
|
|
@@ -2144,14 +2075,34 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2144
2075
|
return;
|
|
2145
2076
|
}
|
|
2146
2077
|
|
|
2147
|
-
// 入口闸门:只认签名令牌或签名 Cookie
|
|
2078
|
+
// 入口闸门:只认签名令牌或签名 Cookie。
|
|
2079
|
+
// 浏览器(Accept 含 text/html)访问未放行路径时,**引导去登录**而不是给死胡同 404:
|
|
2080
|
+
// 登录成功即证明持有凭据,之后由登录分支自动补设备令牌(ensureDeviceCookie),
|
|
2081
|
+
// 用户不需要再去开外部配对链接。非浏览器的探测仍回 404,不暴露"这里有个门"。
|
|
2148
2082
|
if (!isLoginPath && !entryAllowed(req, url)) {
|
|
2083
|
+
try {
|
|
2084
|
+
const jar = readCookies(req.headers.cookie);
|
|
2085
|
+
appendAudit(dir, 'gate-redirect', {
|
|
2086
|
+
path: url.pathname,
|
|
2087
|
+
cookieNames: Object.keys(jar).join(','),
|
|
2088
|
+
hasDevice: Boolean(jar[DEVICE_COOKIE]),
|
|
2089
|
+
hasSession: Boolean(jar[SESSION_COOKIE]),
|
|
2090
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
|
|
2091
|
+
});
|
|
2092
|
+
} catch { /* 诊断不影响响应 */ }
|
|
2093
|
+
|
|
2094
|
+
const wantsHtml = String(req.headers.accept ?? '').includes('text/html');
|
|
2095
|
+
if (wantsHtml && (url.pathname === '/' || url.pathname === '')) {
|
|
2096
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2097
|
+
res.end();
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2149
2100
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2150
2101
|
res.end('Not Found\n');
|
|
2151
2102
|
return;
|
|
2152
2103
|
}
|
|
2153
2104
|
// 首次带 ?k= 进来:登记一台设备、发设备令牌,再 303 到干净 URL
|
|
2154
|
-
// (令牌不进地址栏/历史;之后靠 dsh-device Cookie 长期放行)
|
|
2105
|
+
// (令牌不进地址栏/历史;之后靠 dsh-homing-device Cookie 长期放行)
|
|
2155
2106
|
if (!isLoginPath && config.entryGate !== false) {
|
|
2156
2107
|
const token = url.searchParams.get('k');
|
|
2157
2108
|
if (token && entryExpiry(token) > 0 && currentDevice(req) === null) {
|
|
@@ -2171,7 +2122,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2171
2122
|
appendAudit(dir, 'device-paired', { id: created.record.id, name: created.record.name });
|
|
2172
2123
|
console.log(`[dsh-homing] 新设备已配对:${created.record.name} (${created.record.id})`);
|
|
2173
2124
|
url.searchParams.delete('k');
|
|
2174
|
-
|
|
2125
|
+
res.writeHead(303, {
|
|
2175
2126
|
location: `${url.pathname}${url.search}`,
|
|
2176
2127
|
'cache-control': 'no-store',
|
|
2177
2128
|
'set-cookie': `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
@@ -2298,11 +2249,28 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2298
2249
|
res.end();
|
|
2299
2250
|
return;
|
|
2300
2251
|
}
|
|
2301
|
-
if (!sessionValid(req)) {
|
|
2252
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2302
2253
|
if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
|
|
2303
2254
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2304
2255
|
res.end();
|
|
2305
2256
|
} else {
|
|
2257
|
+
// 诊断:把会话校验失败的细节记进审计,区分"没收到 cookie"与"收到但校验不过"
|
|
2258
|
+
try {
|
|
2259
|
+
const jar = readCookies(req.headers.cookie);
|
|
2260
|
+
const raw = jar[SESSION_COOKIE];
|
|
2261
|
+
const parts = typeof raw === 'string' ? raw.split('.') : [];
|
|
2262
|
+
const boundDevice = parts.length === 4 ? parts[2] : null;
|
|
2263
|
+
const known = boundDevice ? devices().devices.some((item) => item.id === boundDevice) : false;
|
|
2264
|
+
appendAudit(dir, 'session-invalid', {
|
|
2265
|
+
path: url.pathname,
|
|
2266
|
+
hasDeviceCookie: Boolean(jar[DEVICE_COOKIE]),
|
|
2267
|
+
hasSessionCookie: Boolean(raw),
|
|
2268
|
+
sessionShape: parts.length,
|
|
2269
|
+
boundDevice,
|
|
2270
|
+
deviceKnown: known,
|
|
2271
|
+
cookieNames: Object.keys(jar).join(','),
|
|
2272
|
+
});
|
|
2273
|
+
} catch { /* 诊断失败不影响响应 */ }
|
|
2306
2274
|
res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2307
2275
|
res.end('请先登录:/login\n');
|
|
2308
2276
|
}
|
|
@@ -2311,7 +2279,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2311
2279
|
}
|
|
2312
2280
|
|
|
2313
2281
|
// 账户页:改密码 / 开启二次验证 / 看登录记录(必须先登录)
|
|
2314
|
-
if (url.pathname === '/
|
|
2282
|
+
if (url.pathname === '/dsh_homing/account') {
|
|
2315
2283
|
const ip = clientKey(req);
|
|
2316
2284
|
if (!sessionValid(req)) {
|
|
2317
2285
|
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
@@ -2328,7 +2296,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2328
2296
|
{ encoding: 'utf8', mode: 0o600 },
|
|
2329
2297
|
);
|
|
2330
2298
|
const fail = (text) => {
|
|
2331
|
-
res.writeHead(303, { location: `/
|
|
2299
|
+
res.writeHead(303, { location: `/dsh_homing/account?msg=${encodeURIComponent(text)}`, 'cache-control': 'no-store' });
|
|
2332
2300
|
res.end();
|
|
2333
2301
|
};
|
|
2334
2302
|
|
|
@@ -2382,7 +2350,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2382
2350
|
if (action === 'totp-start') {
|
|
2383
2351
|
auth.totpPending = base32Encode(crypto.randomBytes(20));
|
|
2384
2352
|
save();
|
|
2385
|
-
res.writeHead(303, { location: '/
|
|
2353
|
+
res.writeHead(303, { location: '/dsh_homing/account', 'cache-control': 'no-store' });
|
|
2386
2354
|
res.end();
|
|
2387
2355
|
return;
|
|
2388
2356
|
}
|
|
@@ -2392,7 +2360,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2392
2360
|
delete auth.totpPending;
|
|
2393
2361
|
save();
|
|
2394
2362
|
appendAudit(dir, 'totp-cancelled', { ip });
|
|
2395
|
-
res.writeHead(303, { location: '/
|
|
2363
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2396
2364
|
res.end();
|
|
2397
2365
|
return;
|
|
2398
2366
|
}
|
|
@@ -2405,7 +2373,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2405
2373
|
delete auth.totpPending;
|
|
2406
2374
|
save();
|
|
2407
2375
|
appendAudit(dir, 'totp-enabled', { ip });
|
|
2408
|
-
res.writeHead(303, { location: '/
|
|
2376
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2409
2377
|
res.end();
|
|
2410
2378
|
return;
|
|
2411
2379
|
}
|
|
@@ -2416,7 +2384,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2416
2384
|
delete auth.totpPending;
|
|
2417
2385
|
save();
|
|
2418
2386
|
appendAudit(dir, 'totp-disabled', { ip });
|
|
2419
|
-
res.writeHead(303, { location: '/
|
|
2387
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2420
2388
|
res.end();
|
|
2421
2389
|
return;
|
|
2422
2390
|
}
|
|
@@ -2473,7 +2441,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2473
2441
|
'content-type': 'text/html; charset=utf-8',
|
|
2474
2442
|
'cache-control': 'no-store',
|
|
2475
2443
|
'x-frame-options': 'DENY',
|
|
2476
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
2444
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'; img-src 'self' data:",
|
|
2477
2445
|
'x-content-type-options': 'nosniff',
|
|
2478
2446
|
'referrer-policy': 'no-referrer',
|
|
2479
2447
|
...(deviceCookies.length > 0 ? { 'set-cookie': deviceCookies } : {}),
|
|
@@ -2583,7 +2551,7 @@ ${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>`
|
|
|
2583
2551
|
};
|
|
2584
2552
|
|
|
2585
2553
|
const onUpgrade = async (req, socket, head) => {
|
|
2586
|
-
const url = new URL(req.url ?? '/', 'http://dsh-
|
|
2554
|
+
const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
|
|
2587
2555
|
// WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
|
|
2588
2556
|
if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
|
|
2589
2557
|
socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
|
|
@@ -3013,7 +2981,7 @@ export function apply(ctx, rawConfig) {
|
|
|
3013
2981
|
// 所以用闭包延迟读取。
|
|
3014
2982
|
const mintCookie = createCookieMinter(ctx.credentials, () => port);
|
|
3015
2983
|
const warn = (message) => {
|
|
3016
|
-
ctx.logger?.('dsh-
|
|
2984
|
+
ctx.logger?.('dsh-homing')?.warn?.(message);
|
|
3017
2985
|
console.warn(`[dsh-homing] ${message}`);
|
|
3018
2986
|
};
|
|
3019
2987
|
if (config.serverHost) {
|
|
@@ -3261,12 +3229,12 @@ export function apply(ctx, rawConfig) {
|
|
|
3261
3229
|
entries.push(`公网 ${publicEntry}`);
|
|
3262
3230
|
entries.push(` 上面这条 ${Math.max(1, config.entryTokenTtlDays)} 天内有效;打开一次会种签名 Cookie,之后书签只存 https://域名/ 就行`);
|
|
3263
3231
|
}
|
|
3264
|
-
entries.push(`设备管理 ${scheme}://localhost:${config.listenPort}/
|
|
3232
|
+
entries.push(`设备管理 ${scheme}://localhost:${config.listenPort}/dsh_homing/devices`);
|
|
3265
3233
|
for (const ip of lanIpv4s()) {
|
|
3266
3234
|
entries.push(`局域网 ${scheme}://${ip}:${config.listenPort}/${query}`);
|
|
3267
3235
|
}
|
|
3268
3236
|
console.log(`[dsh-homing] 已启动(本地 ${scheme} ${config.bindAddress}:${config.listenPort} -> DSH 127.0.0.1:${port},TLS=${tls.mode})`);
|
|
3269
|
-
entries.push(`账户设置 ${scheme}://localhost:${config.listenPort}/
|
|
3237
|
+
entries.push(`账户设置 ${scheme}://localhost:${config.listenPort}/dsh_homing/account`);
|
|
3270
3238
|
for (const entry of entries) console.log(`[dsh-homing] ${entry}`);
|
|
3271
3239
|
try {
|
|
3272
3240
|
fs.writeFileSync(path.join(dir, 'entry.txt'), `# 更新于 ${new Date().toISOString()}\n${entries.join('\n')}\n`, 'utf8');
|