@andy.ian/dsh-homing 0.0.0-stage → 2.0.1
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/LICENSE +21 -0
- package/README.md +71 -2
- package/bin/auth.mjs +159 -0
- package/bin/backup.mjs +118 -0
- package/bin/bootstrap-server.mjs +436 -0
- package/bin/entry-link.mjs +69 -0
- package/bin/nginx-dsh.template.conf +91 -0
- package/bin/nginx-gate.conf +9 -0
- package/bin/nginx-ws-map.conf +5 -0
- package/bin/renew-cert.mjs +127 -0
- package/bin/supervisor.mjs +488 -0
- package/bin/watchdog.mjs +163 -0
- package/client.js +79 -0
- package/cordis.patch.yml +30 -0
- package/icon.svg +9 -0
- package/index.js +3526 -0
- package/lib/csrf.mjs +60 -0
- package/lib/devices.mjs +221 -0
- package/lib/files-page.mjs +592 -0
- package/lib/files.mjs +551 -0
- package/lib/git.mjs +154 -0
- package/lib/limits.mjs +135 -0
- package/lib/pty.mjs +361 -0
- package/lib/session.mjs +216 -0
- package/lib/shell-page.mjs +430 -0
- package/lib/shell.mjs +274 -0
- package/lib/term-app.js +318 -0
- package/lib/term-page.mjs +117 -0
- package/lib/vendor/fonts/JetBrainsMono-Regular.ttf +0 -0
- package/lib/vendor/fonts/jetbrains-mono-400.woff2 +0 -0
- package/lib/vendor/fonts/jetbrains-mono-700.woff2 +0 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/LICENSE +19 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/README.md +24 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js +2 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/lib/addon-fit.js.map +1 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/package.json +26 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/src/FitAddon.ts +90 -0
- package/lib/vendor/node_modules/@xterm/addon-fit/typings/addon-fit.d.ts +55 -0
- package/lib/vendor/node_modules/asn1/Jenkinsfile +65 -0
- package/lib/vendor/node_modules/asn1/LICENSE +19 -0
- package/lib/vendor/node_modules/asn1/README.md +50 -0
- package/lib/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
- package/lib/vendor/node_modules/asn1/lib/ber/index.js +27 -0
- package/lib/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
- package/lib/vendor/node_modules/asn1/lib/ber/types.js +36 -0
- package/lib/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
- package/lib/vendor/node_modules/asn1/lib/index.js +20 -0
- package/lib/vendor/node_modules/asn1/package.json +31 -0
- package/lib/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
- package/lib/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
- package/lib/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
- package/lib/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
- package/lib/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
- package/lib/vendor/node_modules/safer-buffer/LICENSE +21 -0
- package/lib/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
- package/lib/vendor/node_modules/safer-buffer/Readme.md +156 -0
- package/lib/vendor/node_modules/safer-buffer/dangerous.js +58 -0
- package/lib/vendor/node_modules/safer-buffer/package.json +34 -0
- package/lib/vendor/node_modules/safer-buffer/safer.js +77 -0
- package/lib/vendor/node_modules/safer-buffer/tests.js +406 -0
- package/lib/vendor/node_modules/ssh2/.eslintignore +4 -0
- package/lib/vendor/node_modules/ssh2/.eslintrc.js +5 -0
- package/lib/vendor/node_modules/ssh2/.github/workflows/ci.yml +110 -0
- package/lib/vendor/node_modules/ssh2/.github/workflows/lint.yml +27 -0
- package/lib/vendor/node_modules/ssh2/LICENSE +19 -0
- package/lib/vendor/node_modules/ssh2/README.md +1529 -0
- package/lib/vendor/node_modules/ssh2/SFTP.md +413 -0
- package/lib/vendor/node_modules/ssh2/examples/server-chat.js +238 -0
- package/lib/vendor/node_modules/ssh2/examples/sftp-server-download-only.js +134 -0
- package/lib/vendor/node_modules/ssh2/install.js +27 -0
- package/lib/vendor/node_modules/ssh2/lib/Channel.js +295 -0
- package/lib/vendor/node_modules/ssh2/lib/agent.js +1123 -0
- package/lib/vendor/node_modules/ssh2/lib/client.js +2176 -0
- package/lib/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
- package/lib/vendor/node_modules/ssh2/lib/index.js +44 -0
- package/lib/vendor/node_modules/ssh2/lib/keygen.js +582 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
- package/lib/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
- package/lib/vendor/node_modules/ssh2/lib/server.js +1380 -0
- package/lib/vendor/node_modules/ssh2/lib/utils.js +336 -0
- package/lib/vendor/node_modules/ssh2/package.json +49 -0
- package/lib/vendor/node_modules/ssh2/test/common.js +316 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/bad_rsa_private_key +26 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_cert.pem +33 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/https_key.pem +52 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_dsa +12 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_ecdsa +5 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa +15 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa.ppk +26 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/id_rsa_enc +30 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa +21 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc +22 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm +23 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_dsa_enc_gcm.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa +9 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc +10 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm +10 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ecdsa_enc_gcm.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519 +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_ed25519.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa +27 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc +28 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm +29 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_new_rsa_enc_gcm.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa +12 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc +15 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_dsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa +5 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_ecdsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa +27 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc +30 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.pub.result +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256 +54 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub +1 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.pub.result +6 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/openssh_old_rsa_enc_aes256.result +6 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc +17 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_dsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa +26 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc +18 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/ppk_rsa_enc.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub +9 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub +10 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa2.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub +11 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa3.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub +11 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa4.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub +8 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa5.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub +13 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/keyParser/rfc4716_rsa6.pub.result +7 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/openssh_new_rsa +27 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_dsa_key +12 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_ecdsa_key +5 -0
- package/lib/vendor/node_modules/ssh2/test/fixtures/ssh_host_rsa_key +15 -0
- package/lib/vendor/node_modules/ssh2/test/test-exec.js +578 -0
- package/lib/vendor/node_modules/ssh2/test/test-integration-openssh.js +486 -0
- package/lib/vendor/node_modules/ssh2/test/test-keygen.js +60 -0
- package/lib/vendor/node_modules/ssh2/test/test-misc-client-server.js +1460 -0
- package/lib/vendor/node_modules/ssh2/test/test-openssh.js +261 -0
- package/lib/vendor/node_modules/ssh2/test/test-protocol-crypto.js +631 -0
- package/lib/vendor/node_modules/ssh2/test/test-protocol-keyparser.js +177 -0
- package/lib/vendor/node_modules/ssh2/test/test-server-hostkeys.js +138 -0
- package/lib/vendor/node_modules/ssh2/test/test-sftp.js +842 -0
- package/lib/vendor/node_modules/ssh2/test/test-shell.js +109 -0
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent-openssh.js +110 -0
- package/lib/vendor/node_modules/ssh2/test/test-userauth-agent.js +171 -0
- package/lib/vendor/node_modules/ssh2/test/test-userauth.js +611 -0
- package/lib/vendor/node_modules/ssh2/test/test-worker-imports.js +25 -0
- package/lib/vendor/node_modules/ssh2/test/test.js +20 -0
- package/lib/vendor/node_modules/ssh2/util/build_pagent.bat +2 -0
- package/lib/vendor/node_modules/ssh2/util/pagent.c +88 -0
- package/lib/vendor/node_modules/ssh2/util/pagent.exe +0 -0
- package/lib/vendor/node_modules/tweetnacl/AUTHORS.md +27 -0
- package/lib/vendor/node_modules/tweetnacl/CHANGELOG.md +283 -0
- package/lib/vendor/node_modules/tweetnacl/LICENSE +24 -0
- package/lib/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
- package/lib/vendor/node_modules/tweetnacl/README.md +494 -0
- package/lib/vendor/node_modules/tweetnacl/nacl-fast.js +2391 -0
- package/lib/vendor/node_modules/tweetnacl/nacl-fast.min.js +1 -0
- package/lib/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
- package/lib/vendor/node_modules/tweetnacl/nacl.js +1178 -0
- package/lib/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
- package/lib/vendor/node_modules/tweetnacl/package.json +56 -0
- package/lib/vendor/xterm.css +218 -0
- package/lib/vendor/xterm.js +2 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/ops/watchdog/dsh-watchdog.ps1 +105 -0
- package/ops/watchdog/restart-hidden.vbs +7 -0
- package/ops/watchdog/restart-now.ps1 +261 -0
- package/ops/watchdog/run-hidden.vbs +4 -0
- package/package.json +71 -4
package/index.js
ADDED
|
@@ -0,0 +1,3526 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-waypoint —— 把本机 DSH 安全地开放到手机/微信浏览器(DSH Host 插件)
|
|
3
|
+
*
|
|
4
|
+
* 随 DSH 启动:Host 插件在 profile 装载时 apply() 运行,直接:
|
|
5
|
+
* 1. 从 ctx.webServer.getOrigin() 拿到 DSH 自己的端口(跨平台,不扫进程);
|
|
6
|
+
* 2. 从 ctx.credentials 读取浏览器会话签名密钥(跨平台,不解析 YAML);
|
|
7
|
+
* 3. 监听一个本机端口做反向代理:登录页 + 会话校验 + 注入 DSH 登录态 + 移动端补丁;
|
|
8
|
+
* 4. 用系统自带的 ssh 命令拉起反向隧道(Windows/Linux/macOS 都有),断线自动重连。
|
|
9
|
+
*
|
|
10
|
+
* 服务器侧仍是 nginx(TLS + func 闸门),见包内 server/ 目录。
|
|
11
|
+
*/
|
|
12
|
+
import http from 'node:http';
|
|
13
|
+
import https from 'node:https';
|
|
14
|
+
import nodeTls from 'node:tls';
|
|
15
|
+
import net from 'node:net';
|
|
16
|
+
import os from 'node:os';
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import zlib from 'node:zlib';
|
|
23
|
+
import * as deviceStore from './lib/devices.mjs';
|
|
24
|
+
import * as filebrowse from './lib/files.mjs';
|
|
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
|
+
import * as ptyrun from './lib/pty.mjs';
|
|
29
|
+
import { renderTermPage } from './lib/term-page.mjs';
|
|
30
|
+
import { renderShellPage as renderTerminalPage } from './lib/shell-page.mjs';
|
|
31
|
+
import { renderListing as renderFileListing, renderFile as renderFileView, renderRunPage, renderGitPage, renderEditPage, renderShellPage } from './lib/files-page.mjs';
|
|
32
|
+
import { checkUnsafeOrigin } from './lib/csrf.mjs';
|
|
33
|
+
import * as limits from './lib/limits.mjs';
|
|
34
|
+
|
|
35
|
+
export const name = 'dsh-homing';
|
|
36
|
+
|
|
37
|
+
// 插件版本(调试页显示用),读不到也不影响运行
|
|
38
|
+
const PLUGIN_VERSION = (() => {
|
|
39
|
+
try {
|
|
40
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
41
|
+
return JSON.parse(fs.readFileSync(path.join(here, 'package.json'), 'utf8')).version ?? 'unknown';
|
|
42
|
+
} catch {
|
|
43
|
+
return 'unknown';
|
|
44
|
+
}
|
|
45
|
+
})();
|
|
46
|
+
|
|
47
|
+
/** 需要 Host 提供的能力:HTTP 承载(取端口)与凭据存储(取会话密钥)。 */
|
|
48
|
+
export const inject = ['webServer', 'credentials'];
|
|
49
|
+
|
|
50
|
+
/* ------------------------------------------------------------------ *
|
|
51
|
+
* 配置
|
|
52
|
+
* ------------------------------------------------------------------ */
|
|
53
|
+
|
|
54
|
+
const DEFAULT_CONFIG = {
|
|
55
|
+
serverHost: '',
|
|
56
|
+
sshUser: 'ubuntu',
|
|
57
|
+
sshPort: 22,
|
|
58
|
+
sshKey: '',
|
|
59
|
+
listenPort: 8787,
|
|
60
|
+
remotePort: 0,
|
|
61
|
+
bindAddress: '::',
|
|
62
|
+
publicUrl: '',
|
|
63
|
+
funcValue: 'dsh-view',
|
|
64
|
+
// 入口令牌(?k=)有效期:过了就要重新生成链接
|
|
65
|
+
entryTokenTtlDays: 30,
|
|
66
|
+
// 令牌换来的入口 Cookie 有效期:书签只存干净 URL,靠它长期放行
|
|
67
|
+
entryCookieTtlDays: 180,
|
|
68
|
+
// 是否仍接受旧版常量暗号 ?func=。默认关闭——常亮的共享口令等于没有口令
|
|
69
|
+
legacyFunc: false,
|
|
70
|
+
// 请求体上限:TLS 透传后 nginx 不再解析 HTTP,这个值就是唯一的闸门
|
|
71
|
+
maxBodyBytes: 300 * 1024 * 1024,
|
|
72
|
+
// 登录失败递进延迟的封顶(毫秒);调小只影响暴力破解防护,不影响正常登录
|
|
73
|
+
loginMaxDelayMs: 8000,
|
|
74
|
+
// 单桶失败多少次后锁定该桶
|
|
75
|
+
loginPerKeyMax: 8,
|
|
76
|
+
// 最多允许多少台已配对设备(防止链接被滥用后设备表无限增长)
|
|
77
|
+
maxDevices: 20,
|
|
78
|
+
login: true,
|
|
79
|
+
syncPortFromServer: true,
|
|
80
|
+
tls: 'auto',
|
|
81
|
+
tlsCert: '',
|
|
82
|
+
tlsKey: '',
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
function normalizeConfig(raw) {
|
|
86
|
+
const config = { ...DEFAULT_CONFIG, ...(raw ?? {}) };
|
|
87
|
+
config.sshPort = Number(config.sshPort) || 22;
|
|
88
|
+
config.listenPort = Number(config.listenPort) || 8787;
|
|
89
|
+
// 服务器侧端口与 nginx 的 proxy_pass 必须一致,默认固定 8787;本机 listenPort 可以单独改
|
|
90
|
+
config.remotePort = Number(config.remotePort) || 8787;
|
|
91
|
+
config.maxBodyBytes = Number(config.maxBodyBytes) > 0 ? Number(config.maxBodyBytes) : 300 * 1024 * 1024;
|
|
92
|
+
if (!config.sshKey) config.sshKey = path.join(os.homedir(), '.ssh', 'dsh_tunnel');
|
|
93
|
+
return config;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ------------------------------------------------------------------ *
|
|
97
|
+
* 数据目录(跨平台:$DSH_HOME/integrations/dsh-homing)
|
|
98
|
+
* ------------------------------------------------------------------ */
|
|
99
|
+
|
|
100
|
+
/** 本机所有局域网 IPv4,用来在日志里给出「同一个 Wi-Fi 用哪条地址」。 */
|
|
101
|
+
function lanIpv4s() {
|
|
102
|
+
const out = [];
|
|
103
|
+
for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
|
|
104
|
+
// 跳过 WSL / VMware / VirtualBox 这类虚拟网卡,只留真实局域网地址
|
|
105
|
+
if (/^(vEthernet|VMware|VirtualBox|Hyper-V|Loopback|WSL)/iu.test(name)) continue;
|
|
106
|
+
for (const addr of addrs ?? []) {
|
|
107
|
+
if (addr.family === 'IPv4' && !addr.internal) out.push(addr.address);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 追加一条审计记录(JSON Lines,5MB 轮转)。只记事件与来源,不记密码/验证码。 */
|
|
114
|
+
function appendAudit(dir, event, fields = {}) {
|
|
115
|
+
try {
|
|
116
|
+
const file = path.join(dir, 'audit.log');
|
|
117
|
+
const line = `${JSON.stringify({ t: new Date().toISOString(), event, ...fields })}\n`;
|
|
118
|
+
try {
|
|
119
|
+
if (fs.statSync(file).size > 5 * 1024 * 1024) fs.renameSync(file, `${file}.1`);
|
|
120
|
+
} catch { /* 文件还不存在 */ }
|
|
121
|
+
fs.appendFileSync(file, line, 'utf8');
|
|
122
|
+
} catch { /* 审计写失败不影响服务 */ }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 发送告警:写审计 + 可选 webhook(企业微信/飞书/Slack 的机器人地址都吃 JSON)。 */
|
|
126
|
+
function sendAlert(dir, config, title, text) {
|
|
127
|
+
appendAudit(dir, 'alert', { title, text });
|
|
128
|
+
const url = config?.alertWebhook;
|
|
129
|
+
if (!url) return;
|
|
130
|
+
try {
|
|
131
|
+
fetch(url, {
|
|
132
|
+
method: 'POST',
|
|
133
|
+
headers: { 'content-type': 'application/json' },
|
|
134
|
+
body: JSON.stringify({ msgtype: 'text', text: { content: `[dsh-homing] ${title}\n${text}` } }),
|
|
135
|
+
signal: AbortSignal.timeout(8000),
|
|
136
|
+
}).catch(() => {});
|
|
137
|
+
} catch { /* fetch 不可用就只留审计 */ }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function dataDir() {
|
|
141
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
|
|
142
|
+
const legacyDir = path.join(home, 'integrations', 'dsh-homing');
|
|
143
|
+
const dir = path.join(home, 'integrations', 'dsh-homing');
|
|
144
|
+
// 数据目录随插件改名:旧目录存在而新目录不存在时,自动迁过去。
|
|
145
|
+
// 只 rename 一次;旧目录里的设备表/密码/证书全部保留,已配对设备不会掉线。
|
|
146
|
+
try {
|
|
147
|
+
if (fs.existsSync(legacyDir) && !fs.existsSync(dir)) {
|
|
148
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
149
|
+
fs.renameSync(legacyDir, dir);
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
// 迁移失败就退回旧目录,不能因为改名把服务弄挂
|
|
153
|
+
if (fs.existsSync(legacyDir)) {
|
|
154
|
+
return legacyDir;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
158
|
+
return dir;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const base64url = (buffer) => Buffer.from(buffer).toString('base64')
|
|
162
|
+
.replaceAll('+', '-')
|
|
163
|
+
.replaceAll('/', '_')
|
|
164
|
+
.replace(/=+$/u, '');
|
|
165
|
+
|
|
166
|
+
const safeEqual = (a, b) => {
|
|
167
|
+
const left = Buffer.from(String(a));
|
|
168
|
+
const right = Buffer.from(String(b));
|
|
169
|
+
return left.length === right.length && crypto.timingSafeEqual(left, right);
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/** 模块级:入口令牌签名(apply 里的启动打印和 createBridge 都要用)。 */
|
|
173
|
+
function signEntryFor(sessionKeyBase64, expiresAt) {
|
|
174
|
+
const body = base64url(String(expiresAt));
|
|
175
|
+
const mac = base64url(crypto.createHmac('sha256', Buffer.from(sessionKeyBase64, 'base64')).update(`entry:${body}`).digest());
|
|
176
|
+
return `${body}.${mac}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 模块级:入口令牌校验,返回 0 表示无效。 */
|
|
180
|
+
function entryExpiryFor(sessionKeyBase64, value) {
|
|
181
|
+
if (typeof value !== 'string') return 0;
|
|
182
|
+
const [body, mac] = value.split('.');
|
|
183
|
+
if (!body || !mac) return 0;
|
|
184
|
+
const expected = base64url(crypto.createHmac('sha256', Buffer.from(sessionKeyBase64, 'base64')).update(`entry:${body}`).digest());
|
|
185
|
+
if (!safeEqual(mac, expected)) return 0;
|
|
186
|
+
const expiresAt = Number(Buffer.from(body.replaceAll('-', '+').replaceAll('_', '/'), 'base64').toString('utf8'));
|
|
187
|
+
return Number.isFinite(expiresAt) && expiresAt > Date.now() ? expiresAt : 0;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function readCookies(headerValue) {
|
|
191
|
+
const out = {};
|
|
192
|
+
if (!headerValue) return out;
|
|
193
|
+
for (const segment of String(headerValue).split(';')) {
|
|
194
|
+
const at = segment.indexOf('=');
|
|
195
|
+
if (at === -1) continue;
|
|
196
|
+
out[segment.slice(0, at).trim()] = segment.slice(at + 1).trim();
|
|
197
|
+
}
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/* ------------------------------------------------------------------ *
|
|
202
|
+
* 账号(存本机,scrypt 哈希)
|
|
203
|
+
* ------------------------------------------------------------------ */
|
|
204
|
+
|
|
205
|
+
const SESSION_COOKIE = 'dsh-homing-session';
|
|
206
|
+
const SESSION_SECONDS = 3 * 24 * 60 * 60;
|
|
207
|
+
|
|
208
|
+
function loadAuth(dir) {
|
|
209
|
+
const file = path.join(dir, 'auth.json');
|
|
210
|
+
try {
|
|
211
|
+
const record = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
212
|
+
if (record.username && record.salt && record.hash && record.sessionKey) return record;
|
|
213
|
+
} catch {
|
|
214
|
+
// 落到下面:生成一个默认账号并打印
|
|
215
|
+
}
|
|
216
|
+
const password = base64url(crypto.randomBytes(9));
|
|
217
|
+
const salt = crypto.randomBytes(16);
|
|
218
|
+
const record = {
|
|
219
|
+
username: 'dsh',
|
|
220
|
+
salt: salt.toString('base64'),
|
|
221
|
+
hash: base64url(crypto.scryptSync(password, salt, 64)),
|
|
222
|
+
sessionKey: base64url(crypto.randomBytes(32)),
|
|
223
|
+
updatedAt: new Date().toISOString(),
|
|
224
|
+
};
|
|
225
|
+
fs.writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
226
|
+
// 不把明文密码打进日志(日志可能被复制、上报、进聊天记录),只写进仅本人可读的文件
|
|
227
|
+
const credentialFile = path.join(dir, 'auth-initial.txt');
|
|
228
|
+
try {
|
|
229
|
+
fs.writeFileSync(credentialFile, `用户名:${record.username}\n密码:${password}\n(登录成功后请删除本文件)\n`, { encoding: 'utf8', mode: 0o600 });
|
|
230
|
+
console.log(`[dsh-homing] 已生成登录账号 —— 用户名 ${record.username},密码见 ${credentialFile}(改:${file})`);
|
|
231
|
+
} catch {
|
|
232
|
+
console.log(`[dsh-homing] 已生成登录账号 —— 用户名 ${record.username},密码:${password}(写文件失败,仅此一次打印)`);
|
|
233
|
+
}
|
|
234
|
+
return record;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/* ------------------------------------------------------------------ *
|
|
238
|
+
* DSH 浏览器会话 Cookie(从 ctx.credentials 读签名密钥)
|
|
239
|
+
* ------------------------------------------------------------------ */
|
|
240
|
+
|
|
241
|
+
const BROWSER_SESSION_KEY = 'client-connection/browser-session';
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 帮浏览器签一个 DSH 自己的会话 cookie(它只认自己签的)。
|
|
245
|
+
*
|
|
246
|
+
* 坑:DSH 会校验 payload 里的 expiresAt,**超出它自己的上限就直接 401**。
|
|
247
|
+
* 2026-11 版实测:1/3/7 天通过,14/30 天被拒。之前这里写死 30 天,
|
|
248
|
+
* DSH 收紧上限后所有转发请求 401(手机能开终端页、打不开 DSH 主页面)。
|
|
249
|
+
*
|
|
250
|
+
* 但把 30 改成 7 仍然是"猜"——DSH 再调一次还会坏。所以改成**自动探测**:
|
|
251
|
+
* 首次需要时按候选值从大到小试签一次,真正打一次上游,取第一个返回 200 的档位,
|
|
252
|
+
* 按 authority 缓存(每个进程/端口独立)。探测成本只有几次本地请求。
|
|
253
|
+
*/
|
|
254
|
+
const COOKIE_TTL_CANDIDATES_MS = [
|
|
255
|
+
30 * 24 * 60 * 60 * 1000,
|
|
256
|
+
14 * 24 * 60 * 60 * 1000,
|
|
257
|
+
7 * 24 * 60 * 60 * 1000,
|
|
258
|
+
3 * 24 * 60 * 60 * 1000,
|
|
259
|
+
24 * 60 * 60 * 1000,
|
|
260
|
+
6 * 60 * 60 * 1000,
|
|
261
|
+
60 * 60 * 1000,
|
|
262
|
+
];
|
|
263
|
+
/** 探测失败时的保守兜底(DSH 任何版本都接受的一天) */
|
|
264
|
+
const COOKIE_TTL_FALLBACK_MS = 24 * 60 * 60 * 1000;
|
|
265
|
+
|
|
266
|
+
/** 用给定密钥/有效期签一个 cookie(纯函数,方便探测复用) */
|
|
267
|
+
function signBrowserCookie({ authority, secret, ttlMs }) {
|
|
268
|
+
const name = 'dsh-auth-' + base64url(crypto.createHash('sha256').update(authority).digest());
|
|
269
|
+
const issuedAt = Date.now();
|
|
270
|
+
const expiresAt = issuedAt + ttlMs;
|
|
271
|
+
const body = base64url(Buffer.from(JSON.stringify({ version: 1, authority, issuedAt, expiresAt }), 'utf8'));
|
|
272
|
+
const signature = base64url(crypto.createHmac('sha256', secret).update(body).digest());
|
|
273
|
+
return { name, value: `v1.${body}.${signature}` };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** 拿这个 cookie 请求一次上游首页,看 DSH 认不认(只读一次性判断) */
|
|
277
|
+
function probeCookieAccepted({ port, authority, cookie }) {
|
|
278
|
+
return new Promise((resolve) => {
|
|
279
|
+
const req = http.request({
|
|
280
|
+
host: '127.0.0.1',
|
|
281
|
+
port,
|
|
282
|
+
path: '/',
|
|
283
|
+
method: 'GET',
|
|
284
|
+
headers: { host: authority, cookie: `${cookie.name}=${cookie.value}` },
|
|
285
|
+
timeout: 5000,
|
|
286
|
+
}, (res) => {
|
|
287
|
+
res.resume();
|
|
288
|
+
res.on('end', () => resolve(res.statusCode === 200));
|
|
289
|
+
});
|
|
290
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
291
|
+
req.on('error', () => resolve(false));
|
|
292
|
+
req.end();
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/* ------------------------------------------------------------------ *
|
|
297
|
+
* 活跃度信标:重启脚本据此判断"能不能安全重启"
|
|
298
|
+
* ------------------------------------------------------------------ */
|
|
299
|
+
|
|
300
|
+
/** 写入最近一次用户交互时间(节流 1 秒,避免高频写盘) */
|
|
301
|
+
function createActivityRecorder(dir) {
|
|
302
|
+
const file = path.join(dir, 'activity.json');
|
|
303
|
+
let lastWrite = 0;
|
|
304
|
+
return function touch(kind) {
|
|
305
|
+
const now = Date.now();
|
|
306
|
+
if (now - lastWrite < 1000) return;
|
|
307
|
+
lastWrite = now;
|
|
308
|
+
try {
|
|
309
|
+
fs.writeFileSync(file, JSON.stringify({ at: now, kind, pid: process.pid }) + '\n', 'utf8');
|
|
310
|
+
} catch {
|
|
311
|
+
// 写不进去就算了,重启脚本会退化成只看会话文件
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function createCookieMinter(credentials, getUpstreamPort) {
|
|
317
|
+
let cached;
|
|
318
|
+
/** authority -> { ttlMs, at }:探测结果按 authority(= host:port)缓存 */
|
|
319
|
+
const ttlByAuthority = new Map();
|
|
320
|
+
|
|
321
|
+
async function secretNow() {
|
|
322
|
+
const now = Date.now();
|
|
323
|
+
if (!cached || now - cached.at > 60_000) {
|
|
324
|
+
const record = await credentials.readRecord(BROWSER_SESSION_KEY);
|
|
325
|
+
const secretText = record?.payload?.secret;
|
|
326
|
+
if (typeof secretText !== 'string' || !secretText) return undefined;
|
|
327
|
+
const normalized = secretText.replaceAll('-', '+').replaceAll('_', '/');
|
|
328
|
+
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
|
|
329
|
+
cached = { at: now, secret: Buffer.from(padded, 'base64') };
|
|
330
|
+
}
|
|
331
|
+
return cached.secret;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async function ttlFor(authority, secret) {
|
|
335
|
+
const hit = ttlByAuthority.get(authority);
|
|
336
|
+
// 一小时内复用;DSH 上限变化只会发生在它自己重启之后,那时 authority 也会变
|
|
337
|
+
if (hit && Date.now() - hit.at < 60 * 60 * 1000) return hit.ttlMs;
|
|
338
|
+
const port = getUpstreamPort();
|
|
339
|
+
if (!port) return COOKIE_TTL_FALLBACK_MS;
|
|
340
|
+
for (const ttlMs of COOKIE_TTL_CANDIDATES_MS) {
|
|
341
|
+
const accepted = await probeCookieAccepted({
|
|
342
|
+
port,
|
|
343
|
+
authority,
|
|
344
|
+
cookie: signBrowserCookie({ authority, secret, ttlMs }),
|
|
345
|
+
});
|
|
346
|
+
if (accepted) {
|
|
347
|
+
ttlByAuthority.set(authority, { ttlMs, at: Date.now() });
|
|
348
|
+
return ttlMs;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
ttlByAuthority.set(authority, { ttlMs: COOKIE_TTL_FALLBACK_MS, at: Date.now() });
|
|
352
|
+
return COOKIE_TTL_FALLBACK_MS;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return async function mint(authority) {
|
|
356
|
+
const secret = await secretNow();
|
|
357
|
+
if (!secret) return undefined;
|
|
358
|
+
const ttlMs = await ttlFor(authority, secret);
|
|
359
|
+
return signBrowserCookie({ authority, secret, ttlMs });
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/* ------------------------------------------------------------------ *
|
|
364
|
+
* 移动端补丁
|
|
365
|
+
* ------------------------------------------------------------------ */
|
|
366
|
+
|
|
367
|
+
const MOBILE_CSS = `html { -webkit-text-size-adjust: 100%; }
|
|
368
|
+
@media (max-width: 760px) {
|
|
369
|
+
[aria-label="打开右侧边栏"] { display: none !important; }
|
|
370
|
+
[class*="_frame"] { min-width: 0; }
|
|
371
|
+
|
|
372
|
+
/* 隐藏时只把侧边栏那一列压成 0,主内容自然占满;其余布局仍归应用自己算 */
|
|
373
|
+
html[data-dsh-homing-nav="hidden"] [class*="_frame"] {
|
|
374
|
+
grid-template-columns: 0 1fr 0 !important;
|
|
375
|
+
transition: none !important;
|
|
376
|
+
}
|
|
377
|
+
html[data-dsh-homing-nav="hidden"] [class*="sidebarCol"] {
|
|
378
|
+
min-width: 0 !important;
|
|
379
|
+
overflow: hidden !important;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/* 侧边栏完全隐藏时,左上角探出的小耳朵(磁吸感):点它恢复完整侧边栏 */
|
|
383
|
+
.dsh-homing-ear {
|
|
384
|
+
position: fixed;
|
|
385
|
+
left: 0;
|
|
386
|
+
top: 16px;
|
|
387
|
+
width: 16px;
|
|
388
|
+
height: 40px;
|
|
389
|
+
z-index: 62;
|
|
390
|
+
display: none;
|
|
391
|
+
align-items: center;
|
|
392
|
+
justify-content: center;
|
|
393
|
+
padding: 0;
|
|
394
|
+
border: 1px solid rgba(255, 255, 255, 0.14);
|
|
395
|
+
border-left: 0;
|
|
396
|
+
border-radius: 0 10px 10px 0;
|
|
397
|
+
background: rgba(30, 34, 42, 0.72);
|
|
398
|
+
color: #aeb5c2;
|
|
399
|
+
font-size: 14px;
|
|
400
|
+
line-height: 1;
|
|
401
|
+
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
|
|
402
|
+
-webkit-tap-highlight-color: transparent;
|
|
403
|
+
user-select: none;
|
|
404
|
+
touch-action: manipulation;
|
|
405
|
+
}
|
|
406
|
+
.dsh-homing-ear:active { background: rgba(60, 66, 78, 0.95); color: #e8eaed; }
|
|
407
|
+
}
|
|
408
|
+
`;
|
|
409
|
+
|
|
410
|
+
const MOBILE_JS = `(() => {
|
|
411
|
+
const narrow = () => window.innerWidth <= 760
|
|
412
|
+
const root = document.documentElement
|
|
413
|
+
const frame = () => document.querySelector('[class*="_frame"]')
|
|
414
|
+
const mainCol = () => { const f = frame(); return f ? f.children[1] : null }
|
|
415
|
+
const sidebar = () => document.querySelector('[class*="sidebarCol"]')
|
|
416
|
+
const openBtn = () => document.querySelector('[aria-label="打开侧边栏"]')
|
|
417
|
+
const collapseBtn = () => document.querySelector('[aria-label="收起侧边栏"]')
|
|
418
|
+
const isHidden = () => root.getAttribute('data-dsh-homing-nav') === 'hidden'
|
|
419
|
+
// 我们自己去点应用按钮时,要绕过下面那个捕获拦截,否则会自己拦自己、无限递归
|
|
420
|
+
let quietClick = false
|
|
421
|
+
const clickQuietly = (btn) => {
|
|
422
|
+
if (btn === null) return
|
|
423
|
+
quietClick = true
|
|
424
|
+
try { btn.click() } finally { setTimeout(() => { quietClick = false }, 0) }
|
|
425
|
+
}
|
|
426
|
+
const widthOf = (node) => (node ? node.getBoundingClientRect().width : 0)
|
|
427
|
+
|
|
428
|
+
// 三态:expanded(完整) / rail(图标栏) / hidden(完全隐藏)
|
|
429
|
+
const stateOf = () => {
|
|
430
|
+
if (isHidden()) return 'hidden'
|
|
431
|
+
return widthOf(sidebar()) > 70 ? 'expanded' : 'rail'
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const hide = () => {
|
|
435
|
+
if (!narrow()) return false
|
|
436
|
+
const before = widthOf(mainCol())
|
|
437
|
+
root.setAttribute('data-dsh-homing-nav', 'hidden')
|
|
438
|
+
const after = widthOf(mainCol())
|
|
439
|
+
if (!(after > before + 10)) {
|
|
440
|
+
root.removeAttribute('data-dsh-homing-nav')
|
|
441
|
+
console.warn('[dsh-homing] 侧边栏隐藏未生效,已自动撤销')
|
|
442
|
+
updateEar()
|
|
443
|
+
return false
|
|
444
|
+
}
|
|
445
|
+
updateEar()
|
|
446
|
+
return true
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
const showAttribute = () => {
|
|
450
|
+
root.removeAttribute('data-dsh-homing-nav')
|
|
451
|
+
updateEar()
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
const toExpanded = () => {
|
|
455
|
+
clickQuietly(openBtn())
|
|
456
|
+
setTimeout(() => { showAttribute(); updateEar() }, 80)
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const toRail = () => {
|
|
460
|
+
showAttribute()
|
|
461
|
+
clickQuietly(collapseBtn())
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const toHidden = () => {
|
|
465
|
+
clickQuietly(collapseBtn())
|
|
466
|
+
hide()
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// 应用自带的开关:按 完整 → 图标栏 → 隐藏 循环
|
|
470
|
+
const cycle = () => {
|
|
471
|
+
const state = stateOf()
|
|
472
|
+
if (state === 'expanded') toRail()
|
|
473
|
+
else if (state === 'rail') toHidden()
|
|
474
|
+
else toExpanded()
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// 隐藏时左上角探出的小耳朵,点它恢复完整侧边栏
|
|
478
|
+
let ear = null
|
|
479
|
+
const EAR_HEIGHT = 40
|
|
480
|
+
// 对齐到应用自带开关的竖直中心(它在侧边栏里,即使侧边栏被压成 0 也能量到)
|
|
481
|
+
const placeEar = () => {
|
|
482
|
+
if (ear === null) return
|
|
483
|
+
const anchor = collapseBtn() ?? openBtn()
|
|
484
|
+
if (anchor === null) return
|
|
485
|
+
const rect = anchor.getBoundingClientRect()
|
|
486
|
+
if (rect.height === 0 && rect.width === 0) return
|
|
487
|
+
const top = Math.round(rect.top + rect.height / 2 - EAR_HEIGHT / 2)
|
|
488
|
+
ear.style.top = Math.max(2, top) + 'px'
|
|
489
|
+
}
|
|
490
|
+
const updateEar = () => {
|
|
491
|
+
if (ear === null) return
|
|
492
|
+
ear.style.display = narrow() && isHidden() ? 'flex' : 'none'
|
|
493
|
+
placeEar()
|
|
494
|
+
}
|
|
495
|
+
const installEar = () => {
|
|
496
|
+
ear = document.createElement('button')
|
|
497
|
+
ear.type = 'button'
|
|
498
|
+
ear.className = 'dsh-homing-ear'
|
|
499
|
+
ear.setAttribute('aria-label', '展开侧边栏')
|
|
500
|
+
ear.textContent = '›'
|
|
501
|
+
ear.addEventListener('click', (event) => {
|
|
502
|
+
event.preventDefault()
|
|
503
|
+
event.stopPropagation()
|
|
504
|
+
toExpanded()
|
|
505
|
+
setTimeout(updateEar, 120)
|
|
506
|
+
})
|
|
507
|
+
document.body.appendChild(ear)
|
|
508
|
+
placeEar()
|
|
509
|
+
updateEar()
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// 拦截应用自带开关的点击(捕获阶段,先于应用自己的处理)
|
|
513
|
+
document.addEventListener('click', (event) => {
|
|
514
|
+
if (quietClick) return
|
|
515
|
+
if (!narrow()) return
|
|
516
|
+
const target = event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')
|
|
517
|
+
if (target === null) return
|
|
518
|
+
event.preventDefault()
|
|
519
|
+
event.stopPropagation()
|
|
520
|
+
cycle()
|
|
521
|
+
setTimeout(updateEar, 200)
|
|
522
|
+
}, true)
|
|
523
|
+
|
|
524
|
+
// 记住最后点过的工作区:切换工作区必然有一次点击,这是最可靠的信号。
|
|
525
|
+
// 存的只是名字,由服务端映射成路径;对不上就退回默认工作区。
|
|
526
|
+
const LAST_WS_KEY = 'dsh-homing:last-workspace'
|
|
527
|
+
document.addEventListener('click', (event) => {
|
|
528
|
+
const node = event.target
|
|
529
|
+
if (node === null || typeof node.closest !== 'function') return
|
|
530
|
+
const item = node.closest('[role="menuitem"]')
|
|
531
|
+
const side = node.closest('[class*="sidebarCol"]')
|
|
532
|
+
const candidate = item ?? (side === null ? null : node.closest('button, [role="treeitem"], [class*="session"], [class*="item"], div'))
|
|
533
|
+
if (candidate === null) return
|
|
534
|
+
const text = (candidate.textContent || '').replace(/\s+/g, ' ').trim()
|
|
535
|
+
if (text === '' || text.length > 40) return
|
|
536
|
+
// 排除操作类菜单项,只记看起来像工作区名字的
|
|
537
|
+
if (/文件资源管理器|VS Code|Git Bash|添加工作区|新会话|搜索|设置|插件|自动化任务|更多|账号|退出/u.test(text)) return
|
|
538
|
+
try { window.localStorage.setItem(LAST_WS_KEY, text) } catch { /* 隐私模式 */ }
|
|
539
|
+
}, true)
|
|
540
|
+
|
|
541
|
+
// 标题栏里那个「文件夹 + 小箭头」是分裂按钮:
|
|
542
|
+
// 点箭头出菜单(我们已按文字拦截),点文件夹图标则直接在本机打开目录,手机上看不到。
|
|
543
|
+
// 这里按结构识别:带 aria-haspopup 的按钮和文件夹图标在同一个父容器里,
|
|
544
|
+
// 那么点这个容器里的任何按钮,都按"打开工作区目录"处理。
|
|
545
|
+
const folderHost = () => {
|
|
546
|
+
for (const node of document.querySelectorAll('[aria-haspopup]')) {
|
|
547
|
+
const rect = node.getBoundingClientRect()
|
|
548
|
+
if (rect.width === 0 || rect.height === 0) continue
|
|
549
|
+
if (rect.top > 130) continue
|
|
550
|
+
const host = node.parentElement
|
|
551
|
+
if (host === null) continue
|
|
552
|
+
const buttons = host.querySelectorAll('button, [role="button"]')
|
|
553
|
+
if (buttons.length > 0 && buttons.length <= 3) return host
|
|
554
|
+
}
|
|
555
|
+
return null
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
// 当前会话标题:从标题栏(页面顶部、class 里带 title/tab/header 的元素)取最长的文本。
|
|
559
|
+
// 用它去反查会话记录里的 cwd,就能打开"当前会话所属工作区"的目录。
|
|
560
|
+
const currentSessionTitle = () => {
|
|
561
|
+
let best = ''
|
|
562
|
+
for (const node of document.querySelectorAll('div, span, h1, h2, header')) {
|
|
563
|
+
const rect = node.getBoundingClientRect()
|
|
564
|
+
if (rect.width === 0 || rect.height === 0) continue
|
|
565
|
+
if (rect.top > 120 || rect.height > 44) continue
|
|
566
|
+
const cls = String(node.className || '')
|
|
567
|
+
if (!/title|tab|header|crumb|label/iu.test(cls)) continue
|
|
568
|
+
const text = (node.textContent || '').trim()
|
|
569
|
+
if (text.length < 2 || text.length > 60) continue
|
|
570
|
+
if (text.length > best.length) best = text
|
|
571
|
+
}
|
|
572
|
+
return best
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// 应用把"当前会话"存在 localStorage 里,直接读它 —— 这是确定值,不靠猜。
|
|
576
|
+
const currentSessionId = () => {
|
|
577
|
+
try {
|
|
578
|
+
const raw = window.localStorage.getItem('dsh.sessions.current')
|
|
579
|
+
if (raw === null) return ''
|
|
580
|
+
const parsed = JSON.parse(raw)
|
|
581
|
+
const id = parsed && typeof parsed.sessionId === 'string' ? parsed.sessionId : ''
|
|
582
|
+
return /^session-[A-Za-z0-9-]+$/u.test(id) ? id : ''
|
|
583
|
+
} catch {
|
|
584
|
+
return ''
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const goFiles = () => {
|
|
589
|
+
const session = currentSessionId()
|
|
590
|
+
if (session !== '') {
|
|
591
|
+
window.location.href = '/files?session=' + encodeURIComponent(session)
|
|
592
|
+
return
|
|
593
|
+
}
|
|
594
|
+
let hint = ''
|
|
595
|
+
try { hint = currentSessionTitle() || window.localStorage.getItem('dsh-homing:last-workspace') || '' } catch { hint = '' }
|
|
596
|
+
window.location.href = '/files' + (hint === '' ? '' : '?hint=' + encodeURIComponent(hint))
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
document.addEventListener('click', (event) => {
|
|
600
|
+
const host = folderHost()
|
|
601
|
+
if (host === null) return
|
|
602
|
+
const target = event.target
|
|
603
|
+
if (target === null || typeof target.closest !== 'function') return
|
|
604
|
+
const button = target.closest('button, [role="button"]')
|
|
605
|
+
if (button === null || !host.contains(button)) return
|
|
606
|
+
// 带 aria-haspopup 的是那个小箭头:放行,让应用的菜单正常弹出。
|
|
607
|
+
// 菜单里的「文件资源管理器」由另一段按文字拦截。
|
|
608
|
+
if (button.hasAttribute('aria-haspopup')) return
|
|
609
|
+
event.preventDefault()
|
|
610
|
+
event.stopPropagation()
|
|
611
|
+
goFiles()
|
|
612
|
+
}, true)
|
|
613
|
+
|
|
614
|
+
// 应用下拉里的「文件资源管理器 / VS Code / Git Bash」是在本机启动桌面程序,
|
|
615
|
+
// 手机上看不到。这里把「文件资源管理器」接到我们的 /files 页面;
|
|
616
|
+
// 另外两项给一条提示,避免点了没反应。
|
|
617
|
+
const desktopOnly = (event) => {
|
|
618
|
+
const node = event.target
|
|
619
|
+
if (node === null || typeof node.closest !== 'function') return
|
|
620
|
+
const item = node.closest('[role="menuitem"], button, li, div')
|
|
621
|
+
const text = item === null ? '' : (item.textContent || '').trim()
|
|
622
|
+
if (text === '') return
|
|
623
|
+
if (text.includes('文件资源管理器')) {
|
|
624
|
+
event.preventDefault()
|
|
625
|
+
event.stopPropagation()
|
|
626
|
+
// 尽量从属性里挖工作区路径,挖不到就让文件页自己决定默认目录
|
|
627
|
+
let target = ''
|
|
628
|
+
for (const holder of [item, ...(item.querySelectorAll('[data-path], [title]') || [])]) {
|
|
629
|
+
if (holder === null) continue
|
|
630
|
+
const dataPath = holder.getAttribute && holder.getAttribute('data-path')
|
|
631
|
+
const title = holder.getAttribute && holder.getAttribute('title')
|
|
632
|
+
if (dataPath) { target = dataPath; break }
|
|
633
|
+
if (title && /^[A-Za-z]:[\\/]|^\//u.test(title)) { target = title; break }
|
|
634
|
+
}
|
|
635
|
+
// 带上当前选中的工作区名,服务端会映射成路径;映射不到就落到默认工作区
|
|
636
|
+
let remembered = ''
|
|
637
|
+
try { remembered = window.localStorage.getItem(LAST_WS_KEY) || '' } catch { /* 隐私模式 */ }
|
|
638
|
+
const selected = remembered !== '' ? remembered : (() => {
|
|
639
|
+
const side = document.querySelector('[class*="sidebarCol"]')
|
|
640
|
+
if (side === null) return ''
|
|
641
|
+
let best = ''
|
|
642
|
+
for (const node of side.querySelectorAll('[class*="selected"], [class*="active"], [aria-current]')) {
|
|
643
|
+
const text = (node.textContent || '').trim()
|
|
644
|
+
if (text === '' || text.length > 40) continue
|
|
645
|
+
if (best === '' || text.length < best.length) best = text
|
|
646
|
+
}
|
|
647
|
+
return best
|
|
648
|
+
})()
|
|
649
|
+
const session = currentSessionId()
|
|
650
|
+
const query = target ? '?path=' + encodeURIComponent(target)
|
|
651
|
+
: session !== '' ? '?session=' + encodeURIComponent(session)
|
|
652
|
+
: '?hint=' + encodeURIComponent(currentSessionTitle() || selected || '')
|
|
653
|
+
window.location.href = '/files' + query
|
|
654
|
+
return
|
|
655
|
+
}
|
|
656
|
+
if (text.includes('VS Code')) {
|
|
657
|
+
// 手机上用文件页 + 编辑功能代替(点文件旁的 ✏️ 可改可存)
|
|
658
|
+
event.preventDefault()
|
|
659
|
+
event.stopPropagation()
|
|
660
|
+
const session = currentSessionId()
|
|
661
|
+
window.location.href = '/files' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
|
|
662
|
+
return
|
|
663
|
+
}
|
|
664
|
+
if (text.includes('Git Bash')) {
|
|
665
|
+
// 手机上用 /git 页代替:可执行任意 git 命令
|
|
666
|
+
event.preventDefault()
|
|
667
|
+
event.stopPropagation()
|
|
668
|
+
const session = currentSessionId()
|
|
669
|
+
window.location.href = '/term' + (session === '' ? '' : '?session=' + encodeURIComponent(session))
|
|
670
|
+
return
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
document.addEventListener('click', desktopOnly, true)
|
|
674
|
+
|
|
675
|
+
let lastRight = 0
|
|
676
|
+
const closeRightBar = () => {
|
|
677
|
+
if (!narrow()) return
|
|
678
|
+
if (document.querySelector('[data-rightbar-collapsed="false"]') === null) return
|
|
679
|
+
if (Date.now() - lastRight < 2500) return
|
|
680
|
+
const button = document.querySelector('[aria-label="收起右侧边栏"]')
|
|
681
|
+
if (button === null) return
|
|
682
|
+
lastRight = Date.now()
|
|
683
|
+
button.click()
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// 点侧边栏里的会话后,回到完全隐藏
|
|
687
|
+
document.addEventListener('click', (event) => {
|
|
688
|
+
if (!narrow() || isHidden()) return
|
|
689
|
+
const side = sidebar()
|
|
690
|
+
if (side === null || !side.contains(event.target)) return
|
|
691
|
+
const collapse = collapseBtn()
|
|
692
|
+
if (collapse !== null && collapse.contains(event.target)) return
|
|
693
|
+
if (event.target.closest('[aria-label="收起侧边栏"], [aria-label="打开侧边栏"]')) return
|
|
694
|
+
setTimeout(() => toHidden(), 260)
|
|
695
|
+
}, false)
|
|
696
|
+
|
|
697
|
+
window.addEventListener('resize', () => { updateEar(); if (!narrow()) showAttribute() })
|
|
698
|
+
|
|
699
|
+
const start = () => {
|
|
700
|
+
if (!narrow()) { closeRightBar(); return }
|
|
701
|
+
installEar()
|
|
702
|
+
const collapse = collapseBtn()
|
|
703
|
+
if (collapse !== null) collapse.click()
|
|
704
|
+
setTimeout(() => {
|
|
705
|
+
hide()
|
|
706
|
+
closeRightBar()
|
|
707
|
+
}, 350)
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/* ---------- ALIVE_BEACON ----------
|
|
711
|
+
* 告诉插件"用户正在操作":重启脚本据此判断能否安全重启。
|
|
712
|
+
* 手机上打字/滑动手势不会修改会话文件,只有这个信标能反映"人在用"。
|
|
713
|
+
* 节流 2 秒,页面隐藏时不发(后台标签页不算活跃)。
|
|
714
|
+
*/
|
|
715
|
+
const ALIVE_INTERVAL = 2000
|
|
716
|
+
let aliveAt = 0
|
|
717
|
+
const alive = () => {
|
|
718
|
+
const now = Date.now()
|
|
719
|
+
if (now - aliveAt < ALIVE_INTERVAL) return
|
|
720
|
+
aliveAt = now
|
|
721
|
+
try {
|
|
722
|
+
if (document.visibilityState === 'hidden') return
|
|
723
|
+
const body = JSON.stringify({ at: now, path: location.pathname })
|
|
724
|
+
if (navigator.sendBeacon) navigator.sendBeacon('/dsh_homing/alive', body)
|
|
725
|
+
else fetch('/dsh_homing/alive', { method: 'POST', headers: { 'content-type': 'application/json' }, body, keepalive: true }).catch(() => {})
|
|
726
|
+
} catch (error) {
|
|
727
|
+
/* 忽略 */
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
document.addEventListener('keydown', alive, true)
|
|
731
|
+
document.addEventListener('pointerdown', alive, true)
|
|
732
|
+
document.addEventListener('input', alive, true)
|
|
733
|
+
document.addEventListener('compositionstart', alive, true)
|
|
734
|
+
window.addEventListener('focus', alive, true)
|
|
735
|
+
|
|
736
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start)
|
|
737
|
+
else start()
|
|
738
|
+
})();
|
|
739
|
+
`;
|
|
740
|
+
|
|
741
|
+
const INJECTION = '<link rel="stylesheet" href="/dsh_homing/mobile.css"><script defer src="/dsh_homing/mobile.js"></script>';
|
|
742
|
+
|
|
743
|
+
// 紧急开关:带这个 Cookie 时桥接不注入移动端样式,回到 DSH 原生布局。
|
|
744
|
+
// 调试页上一键即可设置,页面坏了也点得到。
|
|
745
|
+
const MOBILE_OFF_COOKIE = 'dsh-homing-off';
|
|
746
|
+
|
|
747
|
+
const DEBUG_HTML = `<!doctype html>
|
|
748
|
+
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
749
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
750
|
+
<title>调试 · DSH 手机入口</title>
|
|
751
|
+
<style>
|
|
752
|
+
:root { color-scheme: dark; }
|
|
753
|
+
body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
|
|
754
|
+
.wrap { max-width: 620px; margin: 0 auto; padding: 20px 16px 60px; }
|
|
755
|
+
h1 { font-size: 19px; margin: 6px 0 2px; }
|
|
756
|
+
h2 { font-size: 14px; margin: 26px 0 8px; color:#9aa4b2; font-weight: 600; }
|
|
757
|
+
.sub { color:#8b93a1; font-size: 13px; margin: 4px 0 0; }
|
|
758
|
+
.card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:14px; margin-top:10px; }
|
|
759
|
+
.row { display:flex; justify-content:space-between; gap:12px; padding:6px 0; font-size:13px; border-bottom:1px solid #21262f; }
|
|
760
|
+
.row:last-child { border-bottom:0; }
|
|
761
|
+
.k { color:#8b93a1; flex:0 0 auto; }
|
|
762
|
+
.v { color:#e8eaed; text-align:right; word-break:break-all; }
|
|
763
|
+
.ok { color:#7ee2a8; }
|
|
764
|
+
.warn { color:#f2c14e; }
|
|
765
|
+
.bad { color:#ff9b9b; }
|
|
766
|
+
button, .btn { display:block; width:100%; margin-top:10px; padding:12px; border:0; border-radius:10px;
|
|
767
|
+
background:#4f7cff; color:#fff; font-size:15px; font-weight:600; text-align:center; text-decoration:none; box-sizing:border-box; }
|
|
768
|
+
button.danger { background:#7a2f38; }
|
|
769
|
+
button.ghost, .btn.ghost { background:#2a2f3a; color:#c7cdd8; }
|
|
770
|
+
.msg { margin-top:12px; padding:10px 12px; border-radius:10px; background:rgba(79,124,255,.12);
|
|
771
|
+
border:1px solid rgba(79,124,255,.35); color:#b8ccff; font-size:13px; }
|
|
772
|
+
.shots { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; }
|
|
773
|
+
.shots a { display:block; width:88px; }
|
|
774
|
+
.shots img { width:88px; height:88px; object-fit:cover; border-radius:8px; border:1px solid #262b36; }
|
|
775
|
+
code { background:#1d2229; padding:1px 5px; border-radius:4px; font-size:12px; }
|
|
776
|
+
</style></head>
|
|
777
|
+
<body><div class="wrap">
|
|
778
|
+
<h1>调试页</h1>
|
|
779
|
+
<p class="sub">这一页不依赖移动端样式,界面被改坏时也能打开。</p>
|
|
780
|
+
<p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
|
|
781
|
+
{{message}}
|
|
782
|
+
|
|
783
|
+
<h2>状态</h2>
|
|
784
|
+
<div class="card">
|
|
785
|
+
<div class="row"><span class="k">版本</span><span class="v">{{version}}</span></div>
|
|
786
|
+
<div class="row"><span class="k">移动端样式</span><span class="v {{mobileClass}}">{{mobileOff}}</span></div>
|
|
787
|
+
<div class="row"><span class="k">视口</span><span class="v">{{viewport}}</span></div>
|
|
788
|
+
<div class="row"><span class="k">User-Agent</span><span class="v">{{ua}}</span></div>
|
|
789
|
+
<div class="row"><span class="k">在用设备</span><span class="v">{{devices}}</span></div>
|
|
790
|
+
<div class="row"><span class="k">服务端时间</span><span class="v">{{now}}</span></div>
|
|
791
|
+
</div>
|
|
792
|
+
|
|
793
|
+
<h2>紧急恢复</h2>
|
|
794
|
+
<div class="card">
|
|
795
|
+
<p class="sub">界面错乱、黑屏、按钮点不动时,先关掉移动端样式,回到 DSH 原生布局。</p>
|
|
796
|
+
<form method="post">
|
|
797
|
+
<input type="hidden" name="action" value="{{toggleAction}}">
|
|
798
|
+
<button type="submit" class="{{toggleClass}}">{{toggleLabel}}</button>
|
|
799
|
+
</form>
|
|
800
|
+
<a class="btn ghost" href="/">打开首页</a>
|
|
801
|
+
</div>
|
|
802
|
+
|
|
803
|
+
<h2>上传截图</h2>
|
|
804
|
+
<div class="card">
|
|
805
|
+
<p class="sub">选一张截图,上传后我这边可以直接读取查看。</p>
|
|
806
|
+
<input id="file" type="file" accept="image/*" style="width:100%; margin-top:8px; font-size:14px">
|
|
807
|
+
<button id="send" type="button">上传</button>
|
|
808
|
+
<div id="result" class="sub"></div>
|
|
809
|
+
{{shots}}
|
|
810
|
+
</div>
|
|
811
|
+
|
|
812
|
+
<h2>诊断</h2>
|
|
813
|
+
<div class="card">
|
|
814
|
+
<div class="row"><span class="k">样式文件</span><span class="v">{{cssInfo}}</span></div>
|
|
815
|
+
<div class="row"><span class="k">脚本文件</span><span class="v">{{jsInfo}}</span></div>
|
|
816
|
+
<div class="row"><span class="k">最近错误</span><span class="v">{{errors}}</span></div>
|
|
817
|
+
</div>
|
|
818
|
+
|
|
819
|
+
<h2>快捷入口</h2>
|
|
820
|
+
<div class="card">
|
|
821
|
+
<a class="btn ghost" href="/dsh_homing/account">账户设置</a>
|
|
822
|
+
<a class="btn ghost" href="/dsh_homing/devices">设备管理</a>
|
|
823
|
+
<a class="btn ghost" href="/logout">退出登录</a>
|
|
824
|
+
</div>
|
|
825
|
+
</div>
|
|
826
|
+
<script>
|
|
827
|
+
(() => {
|
|
828
|
+
const input = document.getElementById('file')
|
|
829
|
+
const button = document.getElementById('send')
|
|
830
|
+
const result = document.getElementById('result')
|
|
831
|
+
if (!input || !button || !result) return
|
|
832
|
+
button.addEventListener('click', async () => {
|
|
833
|
+
const file = input.files && input.files[0]
|
|
834
|
+
if (!file) { result.textContent = '先选一张图片。'; return }
|
|
835
|
+
if (file.size > 12 * 1024 * 1024) { result.textContent = '图片太大(上限 12MB)。'; return }
|
|
836
|
+
result.textContent = '读取中…'
|
|
837
|
+
const dataUrl = await new Promise((resolve, reject) => {
|
|
838
|
+
const reader = new FileReader()
|
|
839
|
+
reader.onload = () => resolve(String(reader.result))
|
|
840
|
+
reader.onerror = () => reject(new Error('读取失败'))
|
|
841
|
+
reader.readAsDataURL(file)
|
|
842
|
+
}).catch((error) => { result.textContent = error.message; return null })
|
|
843
|
+
if (!dataUrl) return
|
|
844
|
+
result.textContent = '上传中…'
|
|
845
|
+
try {
|
|
846
|
+
const res = await fetch(location.pathname.replace(/\/$/u, '') + '/upload', {
|
|
847
|
+
method: 'POST',
|
|
848
|
+
headers: { 'content-type': 'application/json' },
|
|
849
|
+
body: JSON.stringify({ name: file.name, dataUrl }),
|
|
850
|
+
})
|
|
851
|
+
const text = await res.text()
|
|
852
|
+
if (!res.ok) { result.textContent = '失败:' + text.slice(0, 200); return }
|
|
853
|
+
const data = JSON.parse(text)
|
|
854
|
+
result.innerHTML = '已保存:<code>' + data.file + '</code>'
|
|
855
|
+
const img = document.createElement('img')
|
|
856
|
+
img.src = location.pathname.replace(/\/$/u, '') + '/files/' + encodeURIComponent(data.file)
|
|
857
|
+
img.style.cssText = 'width:88px;height:88px;object-fit:cover;border-radius:8px;border:1px solid #262b36;margin-top:8px'
|
|
858
|
+
document.querySelector('.shots')?.appendChild(img) ?? result.appendChild(img)
|
|
859
|
+
} catch (error) {
|
|
860
|
+
result.textContent = '网络错误:' + error.message
|
|
861
|
+
}
|
|
862
|
+
})
|
|
863
|
+
})()
|
|
864
|
+
</script>
|
|
865
|
+
</body></html>
|
|
866
|
+
`;
|
|
867
|
+
|
|
868
|
+
/* ------------------------------------------------------------------ *
|
|
869
|
+
* 登录页
|
|
870
|
+
* ------------------------------------------------------------------ */
|
|
871
|
+
|
|
872
|
+
const ACCOUNT_HTML = `<!doctype html>
|
|
873
|
+
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
874
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
875
|
+
<title>账户 · DSH 手机入口</title>
|
|
876
|
+
<style>
|
|
877
|
+
:root { color-scheme: dark; }
|
|
878
|
+
body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
|
|
879
|
+
.wrap { max-width: 640px; margin: 0 auto; padding: 24px 18px 48px; }
|
|
880
|
+
h1 { font-size: 20px; margin: 8px 0 4px; }
|
|
881
|
+
h2 { font-size: 15px; margin: 28px 0 8px; color:#9aa4b2; font-weight:600; }
|
|
882
|
+
.card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:18px; margin-top:12px; }
|
|
883
|
+
label { display:block; font-size:13px; color:#9aa4b2; margin:12px 0 6px; }
|
|
884
|
+
input { width:100%; box-sizing:border-box; padding:11px 12px; border-radius:9px; border:1px solid #333a48; background:#0f1115; color:#e8eaed; font-size:16px; }
|
|
885
|
+
button { margin-top:14px; padding:11px 16px; border-radius:9px; border:0; background:#3b82f6; color:#fff; font-size:15px; }
|
|
886
|
+
button.danger { background:#b91c1c; }
|
|
887
|
+
.msg { background:#1d2a1f; border:1px solid #2f5136; color:#a7e3b3; padding:10px 12px; border-radius:9px; margin-bottom:8px; font-size:14px; }
|
|
888
|
+
.secret, .uri { word-break: break-all; font-family: ui-monospace, Consolas, monospace; font-size:13px; background:#0f1115; border:1px solid #333a48; border-radius:9px; padding:10px; margin:10px 0; }
|
|
889
|
+
.muted { color:#9aa4b2; font-size:13px; }
|
|
890
|
+
ul { padding-left:18px; margin:8px 0 0; font-size:13px; color:#9aa4b2; }
|
|
891
|
+
a { color:#7aa7ff; }
|
|
892
|
+
</style></head>
|
|
893
|
+
<body><div class="wrap">
|
|
894
|
+
<h1>账户设置</h1>
|
|
895
|
+
<p class="sub"><a href="/dsh_homing/devices">设备管理(吊销/删除已配对设备)→</a></p>
|
|
896
|
+
<p class="sub"><a href="/">← 返回 DSH</a> · <a href="/term">终端</a> · <a href="/files">文件</a> · <a href="/git">Git</a></p>
|
|
897
|
+
<div class="muted">用户名:{{username}}</div>
|
|
898
|
+
{{message}}
|
|
899
|
+
|
|
900
|
+
<h2>修改密码</h2>
|
|
901
|
+
<div class="card">
|
|
902
|
+
<form method="post">
|
|
903
|
+
<input type="hidden" name="action" value="password">
|
|
904
|
+
<label>当前密码</label><input type="password" name="current" autocomplete="current-password" required>
|
|
905
|
+
<label>新密码(至少 10 位)</label><input type="password" name="next" autocomplete="new-password" required>
|
|
906
|
+
<label>再输一次新密码</label><input type="password" name="confirm" autocomplete="new-password" required>
|
|
907
|
+
<button type="submit">保存新密码</button>
|
|
908
|
+
</form>
|
|
909
|
+
<div class="muted" style="margin-top:10px">改完会让其他设备上的登录立即失效,本机保持登录。</div>
|
|
910
|
+
</div>
|
|
911
|
+
|
|
912
|
+
<h2>二次验证(TOTP)</h2>
|
|
913
|
+
<div class="card">
|
|
914
|
+
<div class="muted">状态:{{totpState}}</div>
|
|
915
|
+
{{totpBlock}}
|
|
916
|
+
</div>
|
|
917
|
+
|
|
918
|
+
<h2>最近的登录记录</h2>
|
|
919
|
+
<div class="card"><ul>{{audit}}</ul></div>
|
|
920
|
+
|
|
921
|
+
<p><a href="/">← 返回 DSH</a></p>
|
|
922
|
+
</div></body></html>`;
|
|
923
|
+
|
|
924
|
+
function escapeHtml(value) {
|
|
925
|
+
return String(value)
|
|
926
|
+
.replaceAll('&', '&')
|
|
927
|
+
.replaceAll('<', '<')
|
|
928
|
+
.replaceAll('>', '>')
|
|
929
|
+
.replaceAll('"', '"');
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
const BASE32_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
933
|
+
|
|
934
|
+
function base32Encode(buffer) {
|
|
935
|
+
let bits = 0;
|
|
936
|
+
let value = 0;
|
|
937
|
+
let out = '';
|
|
938
|
+
for (const byte of buffer) {
|
|
939
|
+
value = (value << 8) | byte;
|
|
940
|
+
bits += 8;
|
|
941
|
+
while (bits >= 5) {
|
|
942
|
+
out += BASE32_ALPHABET[(value >>> (bits - 5)) & 31];
|
|
943
|
+
bits -= 5;
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
if (bits > 0) out += BASE32_ALPHABET[(value << (5 - bits)) & 31];
|
|
947
|
+
return out;
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
const LOGIN_HTML = `<!doctype html>
|
|
951
|
+
<html lang="zh-CN"><head>
|
|
952
|
+
<meta charset="utf-8">
|
|
953
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
|
954
|
+
<meta name="robots" content="noindex, nofollow">
|
|
955
|
+
<title>登录 · DSH</title>
|
|
956
|
+
<style>
|
|
957
|
+
:root { color-scheme: dark; }
|
|
958
|
+
* { box-sizing: border-box; }
|
|
959
|
+
body { margin: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
|
960
|
+
background: #0e1014; color: #e6e8ec; font: 15px/1.5 -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
|
961
|
+
padding: 24px 16px calc(24px + env(safe-area-inset-bottom)); }
|
|
962
|
+
.card { width: 100%; max-width: 360px; background: #171a21; border: 1px solid #262b36; border-radius: 16px; padding: 24px 20px;
|
|
963
|
+
box-shadow: 0 12px 40px rgba(0,0,0,.45); }
|
|
964
|
+
h1 { margin: 0 0 4px; font-size: 19px; font-weight: 600; }
|
|
965
|
+
p.sub { margin: 0 0 20px; color: #8b93a3; font-size: 13px; }
|
|
966
|
+
label { display: block; margin: 14px 0 6px; color: #a9b1c1; font-size: 13px; }
|
|
967
|
+
input { width: 100%; padding: 12px 13px; border-radius: 10px; border: 1px solid #2c3341; background: #0f1218;
|
|
968
|
+
color: #e6e8ec; font-size: 16px; outline: none; }
|
|
969
|
+
input:focus { border-color: #4f7cff; box-shadow: 0 0 0 3px rgba(79,124,255,.18); }
|
|
970
|
+
button { width: 100%; margin-top: 20px; padding: 13px; border: 0; border-radius: 10px; background: #4f7cff;
|
|
971
|
+
color: #fff; font-size: 16px; font-weight: 600; }
|
|
972
|
+
.err { margin-top: 14px; padding: 10px 12px; border-radius: 10px; background: rgba(255,80,80,.1);
|
|
973
|
+
border: 1px solid rgba(255,80,80,.35); color: #ff9b9b; font-size: 13px; }
|
|
974
|
+
.hint { margin-top: 18px; color: #6b7383; font-size: 12px; text-align: center; }
|
|
975
|
+
</style></head>
|
|
976
|
+
<body><div class="card">
|
|
977
|
+
<h1>DeepSeek Harness</h1>
|
|
978
|
+
<p class="sub">请输入本机设置的账号密码</p>
|
|
979
|
+
<form method="post" action="/login">
|
|
980
|
+
<label for="u">用户名</label>
|
|
981
|
+
<input id="u" name="username" autocomplete="username" autocapitalize="off" autocorrect="off" required>
|
|
982
|
+
<label for="p">密码</label>
|
|
983
|
+
<input id="p" name="password" type="password" autocomplete="current-password" required>
|
|
984
|
+
{{totp}}
|
|
985
|
+
<button type="submit">登录</button>
|
|
986
|
+
</form>
|
|
987
|
+
{{message}}
|
|
988
|
+
<div class="hint">登录一次后 3 天内免登录 · <a href="/dsh_homing/reset" style="color:#7aa7ff">忘记密码?</a></div>
|
|
989
|
+
</div></body></html>`;
|
|
990
|
+
|
|
991
|
+
const RESET_HTML = `<!doctype html>
|
|
992
|
+
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
993
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
994
|
+
<title>重置密码 · DSH 手机入口</title>
|
|
995
|
+
<style>
|
|
996
|
+
:root { color-scheme: dark; }
|
|
997
|
+
body { margin:0; font-family: system-ui, -apple-system, "Noto Sans SC", sans-serif; background:#0f1115; color:#e8eaed; }
|
|
998
|
+
.wrap { max-width: 460px; margin: 0 auto; padding: 32px 18px; }
|
|
999
|
+
h1 { font-size: 20px; margin: 0 0 6px; }
|
|
1000
|
+
p { color:#9aa4b2; font-size:14px; line-height:1.6; }
|
|
1001
|
+
.card { background:#171a21; border:1px solid #262b36; border-radius:12px; padding:18px; margin-top:14px; }
|
|
1002
|
+
label { display:block; font-size:13px; color:#9aa4b2; margin:12px 0 6px; }
|
|
1003
|
+
input { width:100%; box-sizing:border-box; padding:11px 12px; border-radius:9px; border:1px solid #333a48; background:#0f1115; color:#e8eaed; font-size:16px; }
|
|
1004
|
+
button { margin-top:14px; padding:11px 16px; border-radius:9px; border:0; background:#3b82f6; color:#fff; font-size:15px; }
|
|
1005
|
+
.msg { background:#2a2618; border:1px solid #514a2a; color:#e8d99a; padding:10px 12px; border-radius:9px; margin:12px 0 0; font-size:14px; }
|
|
1006
|
+
a { color:#7aa7ff; }
|
|
1007
|
+
</style></head>
|
|
1008
|
+
<body><div class="wrap">
|
|
1009
|
+
<h1>重置密码</h1>
|
|
1010
|
+
<p>重置需要在<strong>运行 DSH 的那台电脑</strong>上取一个重置码——这确保只有能碰到这台机器的人才能重置。</p>
|
|
1011
|
+
{{message}}
|
|
1012
|
+
|
|
1013
|
+
<div class="card">
|
|
1014
|
+
<form method="post">
|
|
1015
|
+
<input type="hidden" name="action" value="request">
|
|
1016
|
+
<button type="submit">获取重置码</button>
|
|
1017
|
+
</form>
|
|
1018
|
+
<p style="margin-top:10px">生成后在你电脑上打开:<br><code>$DSH_HOME/integrations/dsh-homing/reset-code.txt</code><br>(文件里就一行「重置码:XXXX」)</p>
|
|
1019
|
+
</div>
|
|
1020
|
+
|
|
1021
|
+
<div class="card">
|
|
1022
|
+
<form method="post">
|
|
1023
|
+
<input type="hidden" name="action" value="apply">
|
|
1024
|
+
<label>重置码</label><input name="code" autocapitalize="characters" required>
|
|
1025
|
+
<label>新密码(至少 10 位)</label><input type="password" name="next" autocomplete="new-password" required>
|
|
1026
|
+
<label>再输一次新密码</label><input type="password" name="confirm" autocomplete="new-password" required>
|
|
1027
|
+
<button type="submit">重置</button>
|
|
1028
|
+
</form>
|
|
1029
|
+
</div>
|
|
1030
|
+
|
|
1031
|
+
<p style="margin-top:16px"><a href="/login">← 返回登录</a></p>
|
|
1032
|
+
</div></body></html>`;
|
|
1033
|
+
|
|
1034
|
+
const TOTP_FIELD = `<label for="c">验证码</label>
|
|
1035
|
+
<input id="c" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]*" maxlength="6" placeholder="验证器里的 6 位数字" required>`;
|
|
1036
|
+
|
|
1037
|
+
function sendLogin(res, message = '', requireTotp = false) {
|
|
1038
|
+
res.writeHead(200, {
|
|
1039
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1040
|
+
'cache-control': 'no-store',
|
|
1041
|
+
// 登录页的安全头:禁止被嵌入(防点击劫持)、禁止外链、限制表单只能提交给自己
|
|
1042
|
+
'x-frame-options': 'DENY',
|
|
1043
|
+
'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:",
|
|
1044
|
+
'x-content-type-options': 'nosniff',
|
|
1045
|
+
'referrer-policy': 'no-referrer',
|
|
1046
|
+
});
|
|
1047
|
+
res.end(LOGIN_HTML.replace('{{totp}}', requireTotp ? TOTP_FIELD : '').replace('{{message}}', message));
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
/**
|
|
1051
|
+
* 登录限速用的客户端标识。
|
|
1052
|
+
* 经隧道进来时 socket 一律是 127.0.0.1,真正的来源在 nginx 写的 X-Forwarded-For 里;
|
|
1053
|
+
* 只有 socket 是回环时才信任该头,避免局域网客户端伪造它绕过限速。
|
|
1054
|
+
*/
|
|
1055
|
+
function clientKey(req) {
|
|
1056
|
+
const socket = req.socket.remoteAddress ?? '';
|
|
1057
|
+
const isLoopback = socket === '::1' || socket === '127.0.0.1' || socket.startsWith('::ffff:127.');
|
|
1058
|
+
if (isLoopback) {
|
|
1059
|
+
const forwarded = String(req.headers['x-forwarded-for'] ?? '').split(',')[0].trim();
|
|
1060
|
+
if (forwarded) return forwarded;
|
|
1061
|
+
}
|
|
1062
|
+
return socket;
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
function readBody(req, limit = 8192) {
|
|
1066
|
+
return new Promise((resolve) => {
|
|
1067
|
+
let size = 0;
|
|
1068
|
+
const chunks = [];
|
|
1069
|
+
req.on('data', (chunk) => {
|
|
1070
|
+
size += chunk.length;
|
|
1071
|
+
if (size > limit) {
|
|
1072
|
+
req.destroy();
|
|
1073
|
+
resolve('');
|
|
1074
|
+
return;
|
|
1075
|
+
}
|
|
1076
|
+
chunks.push(chunk);
|
|
1077
|
+
});
|
|
1078
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
1079
|
+
req.on('error', () => resolve(''));
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
/* ------------------------------------------------------------------ *
|
|
1084
|
+
* 反向代理
|
|
1085
|
+
* ------------------------------------------------------------------ */
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* TOTP(RFC 6238):HMAC-SHA1、30 秒一步、6 位数字,容忍前后各一步时钟偏差。
|
|
1089
|
+
* 与常见验证器(Google Authenticator / 1Password / Bitwarden)兼容。
|
|
1090
|
+
*/
|
|
1091
|
+
function base32Decode(input) {
|
|
1092
|
+
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
1093
|
+
const clean = String(input).toUpperCase().replace(/[^A-Z2-7]/gu, '');
|
|
1094
|
+
let bits = 0;
|
|
1095
|
+
let value = 0;
|
|
1096
|
+
const out = [];
|
|
1097
|
+
for (const char of clean) {
|
|
1098
|
+
value = (value << 5) | alphabet.indexOf(char);
|
|
1099
|
+
bits += 5;
|
|
1100
|
+
if (bits >= 8) {
|
|
1101
|
+
out.push((value >>> (bits - 8)) & 0xff);
|
|
1102
|
+
bits -= 8;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
return Buffer.from(out);
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function totpAt(secret, step) {
|
|
1109
|
+
const counter = Buffer.alloc(8);
|
|
1110
|
+
counter.writeBigUInt64BE(BigInt(step));
|
|
1111
|
+
const digest = crypto.createHmac('sha1', base32Decode(secret)).update(counter).digest();
|
|
1112
|
+
const offset = digest[digest.length - 1] & 0x0f;
|
|
1113
|
+
const binary = ((digest[offset] & 0x7f) << 24) | ((digest[offset + 1] & 0xff) << 16) | ((digest[offset + 2] & 0xff) << 8) | (digest[offset + 3] & 0xff);
|
|
1114
|
+
return String(binary % 1_000_000).padStart(6, '0');
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
function currentTotpStep() {
|
|
1118
|
+
return Math.floor(Date.now() / 30_000);
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
function verifyTotp(secret, code, lastStep) {
|
|
1122
|
+
const normalized = String(code).replace(/\s+/gu, '');
|
|
1123
|
+
if (!/^\d{6}$/u.test(normalized)) return false;
|
|
1124
|
+
const now = currentTotpStep();
|
|
1125
|
+
for (const step of [now - 1, now, now + 1]) {
|
|
1126
|
+
if (step <= lastStep) continue;
|
|
1127
|
+
if (safeEqual(normalized, totpAt(secret, step))) return true;
|
|
1128
|
+
}
|
|
1129
|
+
return false;
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function createBridge({ getUpstreamPort, mintCookie, auth, config, dir, secureCookies, caCertPath }) {
|
|
1133
|
+
const loginFailures = new Map();
|
|
1134
|
+
// 记住上一次验证码用过的时间步,防止同一个 6 位码在 30 秒窗口内被重放
|
|
1135
|
+
let lastTotpStep = 0;
|
|
1136
|
+
// 重置码状态:{ code, expiresAt, attempts }
|
|
1137
|
+
let resetState = { code: '', expiresAt: 0, attempts: 0 };
|
|
1138
|
+
|
|
1139
|
+
function passwordMatches(password) {
|
|
1140
|
+
const salt = Buffer.from(auth.salt, 'base64');
|
|
1141
|
+
return safeEqual(base64url(crypto.scryptSync(password, salt, 64)), auth.hash);
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
// 会话与设备绑定:体是 <过期时间>.<设备id>,这样吊销设备就能让它立刻掉线
|
|
1145
|
+
function signSession(expiresAt, deviceId) {
|
|
1146
|
+
const body = `${base64url(String(expiresAt))}.${deviceId}`;
|
|
1147
|
+
const mac = base64url(crypto.createHmac('sha256', Buffer.from(auth.sessionKey, 'base64')).update(body).digest());
|
|
1148
|
+
return `v1.${body}.${mac}`;
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function sessionValid(req) {
|
|
1152
|
+
const value = readCookies(req.headers.cookie)[SESSION_COOKIE];
|
|
1153
|
+
if (!value) return false;
|
|
1154
|
+
const [version, expiresPart, deviceId, mac] = value.split('.');
|
|
1155
|
+
if (version !== 'v1' || !expiresPart || !deviceId || !mac) return false;
|
|
1156
|
+
const body = `${expiresPart}.${deviceId}`;
|
|
1157
|
+
const expected = base64url(crypto.createHmac('sha256', Buffer.from(auth.sessionKey, 'base64')).update(body).digest());
|
|
1158
|
+
if (!safeEqual(mac, expected)) return false;
|
|
1159
|
+
const expiresAt = Number(Buffer.from(expiresPart.replaceAll('-', '+').replaceAll('_', '/'), 'base64').toString('utf8'));
|
|
1160
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return false;
|
|
1161
|
+
// 设备被吊销或删除 -> 它的会话立即失效(不用改密码就能踢掉单台设备)
|
|
1162
|
+
const device = devices().devices.find((item) => item.id === deviceId);
|
|
1163
|
+
return Boolean(device) && device.revokedAt === null;
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
|
|
1167
|
+
/* 入口令牌:HMAC 签名 + 过期,替代原来的常量 ?func= 和可伪造的 dshview=1 */
|
|
1168
|
+
/* ---- 入口令牌(?k=)签名:HMAC + 过期 ---------------------------------
|
|
1169
|
+
* 令牌 = base64url(到期毫秒) + '.' + base64url(HMAC-SHA256(sessionKey, 'entry:'+body))
|
|
1170
|
+
* 换 sessionKey 即作废所有已发出的链接。
|
|
1171
|
+
*/
|
|
1172
|
+
function entryKey() {
|
|
1173
|
+
return Buffer.from(auth.sessionKey, 'base64');
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
function signEntry(expiresAt) {
|
|
1177
|
+
const body = base64url(String(expiresAt));
|
|
1178
|
+
const mac = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
|
|
1179
|
+
return `${body}.${mac}`;
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
/** 校验令牌,返回到期时间;伪造、残缺、过期一律返回 0。 */
|
|
1183
|
+
function entryExpiry(value) {
|
|
1184
|
+
if (typeof value !== 'string') return 0;
|
|
1185
|
+
const [body, mac] = value.split('.');
|
|
1186
|
+
if (!body || !mac) return 0;
|
|
1187
|
+
const expected = base64url(crypto.createHmac('sha256', entryKey()).update(`entry:${body}`).digest());
|
|
1188
|
+
if (!safeEqual(mac, expected)) return 0;
|
|
1189
|
+
const expiresAt = Number(Buffer.from(body.replaceAll('-', '+').replaceAll('_', '/'), 'base64').toString('utf8'));
|
|
1190
|
+
return Number.isFinite(expiresAt) && expiresAt > Date.now() ? expiresAt : 0;
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
/* ---- 逐设备令牌(dsh-homing-device)----------------------------------------
|
|
1194
|
+
* 入口令牌 ?k= 只用来「配对」一次:配对后发一枚设备令牌 Cookie,
|
|
1195
|
+
* 之后由设备表放行。设备表在 devices.json,可单独吊销某一台,
|
|
1196
|
+
* 吊销后下一次请求就失效——丢手机不用改密码、也不用重启。
|
|
1197
|
+
*/
|
|
1198
|
+
const DEVICE_COOKIE = 'dsh-homing-device';
|
|
1199
|
+
const DEVICE_SECONDS = 180 * 24 * 60 * 60;
|
|
1200
|
+
// 设备表缓存按 mtime 失效:手工改 devices.json(比如在电脑上直接吊销)
|
|
1201
|
+
// 也会在下一个请求立刻生效,不用重启。
|
|
1202
|
+
let deviceCache = { mtime: -1, state: null };
|
|
1203
|
+
const devices = () => {
|
|
1204
|
+
let mtime = 0;
|
|
1205
|
+
try {
|
|
1206
|
+
mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
|
|
1207
|
+
} catch {
|
|
1208
|
+
mtime = 0;
|
|
1209
|
+
}
|
|
1210
|
+
if (deviceCache.state === null || deviceCache.mtime !== mtime) {
|
|
1211
|
+
deviceCache = { mtime, state: deviceStore.loadState(dir) };
|
|
1212
|
+
}
|
|
1213
|
+
return deviceCache.state;
|
|
1214
|
+
};
|
|
1215
|
+
// 已登录(会话有效)但还没有设备令牌时,自动补一台并返回 Cookie。
|
|
1216
|
+
// 目的:登录过的设备都应出现在设备管理页、可单独吊销;
|
|
1217
|
+
// 改密码吊销全部设备后,重新登录/打开账户页也不会看到空列表。
|
|
1218
|
+
const ensureDeviceCookie = (req, cookies) => {
|
|
1219
|
+
const existing = currentDevice(req);
|
|
1220
|
+
if (existing !== null) return existing.id;
|
|
1221
|
+
const maxDevices = Number(config.maxDevices) > 0 ? Number(config.maxDevices) : 20;
|
|
1222
|
+
if (deviceStore.partition(devices()).active.length >= maxDevices) return null;
|
|
1223
|
+
const paired = deviceStore.createDevice(devices(), {
|
|
1224
|
+
userAgent: String(req.headers['user-agent'] ?? ''),
|
|
1225
|
+
ip: clientKey(req),
|
|
1226
|
+
});
|
|
1227
|
+
persistDevices(paired.state);
|
|
1228
|
+
const ttlDays = Number(config.entryCookieTtlDays) > 0 ? Number(config.entryCookieTtlDays) : 180;
|
|
1229
|
+
cookies.push(`${DEVICE_COOKIE}=${paired.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${ttlDays * 86_400}${secureCookies ? '; Secure' : ''}`);
|
|
1230
|
+
appendAudit(dir, 'device-paired', { id: paired.record.id, via: 'auto', name: paired.record.name });
|
|
1231
|
+
return paired.record.id;
|
|
1232
|
+
};
|
|
1233
|
+
const persistDevices = (next) => {
|
|
1234
|
+
const saved = deviceStore.saveState(dir, next);
|
|
1235
|
+
let mtime = 0;
|
|
1236
|
+
try {
|
|
1237
|
+
mtime = fs.statSync(deviceStore.devicesFile(dir)).mtimeMs;
|
|
1238
|
+
} catch {
|
|
1239
|
+
mtime = 0;
|
|
1240
|
+
}
|
|
1241
|
+
deviceCache = { mtime, state: saved };
|
|
1242
|
+
return saved;
|
|
1243
|
+
};
|
|
1244
|
+
|
|
1245
|
+
function currentDevice(req) {
|
|
1246
|
+
const token = readCookies(req.headers.cookie)[DEVICE_COOKIE];
|
|
1247
|
+
if (!token) return null;
|
|
1248
|
+
// touch=false:热路径不写盘,lastSeen 只在配对时和打开设备页时更新
|
|
1249
|
+
return deviceStore.verifyToken(devices(), token, { touch: false });
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
function entryAllowed(req, url) {
|
|
1253
|
+
if (config.entryGate === false) return true;
|
|
1254
|
+
if (currentDevice(req) !== null) return true;
|
|
1255
|
+
const token = url.searchParams.get('k');
|
|
1256
|
+
if (token && entryExpiry(token) > 0) return true;
|
|
1257
|
+
// 旧版常量暗号:只有显式打开兼容才认,默认不认
|
|
1258
|
+
if (config.legacyFunc && config.funcValue && url.searchParams.get('func') === config.funcValue) return true;
|
|
1259
|
+
// 已登录的会话不受入口闸影响,避免把自己锁在门外
|
|
1260
|
+
return sessionValid(req);
|
|
1261
|
+
}
|
|
1262
|
+
async function rewriteHeaders(headers, authority) {
|
|
1263
|
+
const out = { ...headers };
|
|
1264
|
+
out.host = authority;
|
|
1265
|
+
if (typeof out.origin === 'string') out.origin = `http://${authority}`;
|
|
1266
|
+
if (typeof out.referer === 'string') {
|
|
1267
|
+
out.referer = out.referer.replace(/^https?:\/\/[^/]+/u, `http://${authority}`);
|
|
1268
|
+
}
|
|
1269
|
+
const kept = String(out.cookie ?? '')
|
|
1270
|
+
.split(';')
|
|
1271
|
+
.map((segment) => segment.trim())
|
|
1272
|
+
.filter((segment) => segment.length > 0 && !segment.startsWith('dsh-auth-'));
|
|
1273
|
+
const minted = await mintCookie(authority);
|
|
1274
|
+
if (minted) kept.push(`${minted.name}=${minted.value}`);
|
|
1275
|
+
out.cookie = kept.join('; ');
|
|
1276
|
+
return out;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
const touchActivity = createActivityRecorder(dir);
|
|
1280
|
+
|
|
1281
|
+
const handler = async (req, res) => {
|
|
1282
|
+
|
|
1283
|
+
const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
|
|
1284
|
+
// 任何来自浏览器的请求都算"人在用"(静态资源除外,避免预加载把空闲判断拖长)
|
|
1285
|
+
if (!/^\/(?:dsh_homing\/alive|assets?\/|favicon)/u.test(url.pathname)) touchActivity('request');
|
|
1286
|
+
// 写操作来源校验:
|
|
1287
|
+
// - 代理到 DSH 的请求必须严格校验(代理会改写 Origin/Referer,上游的同源检查形同虚设);
|
|
1288
|
+
// - 本插件自己的页面(登录/账户/设备)只记录不阻断:它的 Cookie 都是 SameSite=Lax,
|
|
1289
|
+
// 跨站 POST 根本带不上来,而微信内置浏览器会发 Origin: null,
|
|
1290
|
+
// 强制校验会让「生成密钥」这类按钮直接 403。
|
|
1291
|
+
const originCheck = checkUnsafeOrigin(req);
|
|
1292
|
+
if (!originCheck.ok) {
|
|
1293
|
+
const ownPath = url.pathname === '/login' || url.pathname === '/logout'
|
|
1294
|
+
|| url.pathname.startsWith('/dsh_homing/')
|
|
1295
|
+
|| url.pathname === '/files' || url.pathname.startsWith('/files/')
|
|
1296
|
+
|| url.pathname === '/git' || url.pathname.startsWith('/git/')
|
|
1297
|
+
|| url.pathname === '/shell' || url.pathname.startsWith('/shell/')
|
|
1298
|
+
|| url.pathname === '/term' || url.pathname.startsWith('/term/')
|
|
1299
|
+
|| url.pathname === '/debug' || url.pathname.startsWith('/debug/');
|
|
1300
|
+
appendAudit(dir, 'origin-check', {
|
|
1301
|
+
path: url.pathname,
|
|
1302
|
+
method: req.method,
|
|
1303
|
+
reason: originCheck.reason,
|
|
1304
|
+
origin: String(req.headers.origin ?? ''),
|
|
1305
|
+
host: String(req.headers.host ?? ''),
|
|
1306
|
+
verdict: ownPath ? 'allowed-own-path' : 'blocked',
|
|
1307
|
+
});
|
|
1308
|
+
if (!ownPath) {
|
|
1309
|
+
res.writeHead(403, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
1310
|
+
res.end('Forbidden\n');
|
|
1311
|
+
return;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
if (url.pathname === '/dsh_homing/mobile.css') {
|
|
1316
|
+
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' });
|
|
1317
|
+
res.end(MOBILE_CSS);
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
if (url.pathname === '/dsh_homing/mobile.js') {
|
|
1321
|
+
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' });
|
|
1322
|
+
res.end(MOBILE_JS);
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
// 局域网证书(公开,不含任何秘密):手机装上它就能消除"不安全"警告并挡住中间人
|
|
1326
|
+
if ((url.pathname === '/dsh_homing/ca.crt' || url.pathname === '/dsh_homing/ca.der') && caCertPath && fs.existsSync(caCertPath)) {
|
|
1327
|
+
// 鸿蒙 / 部分安卓要求 DER(.cer),iOS 和多数安卓吃 PEM(.crt):两种都给
|
|
1328
|
+
const wantDer = url.pathname.endsWith('.der');
|
|
1329
|
+
res.writeHead(200, {
|
|
1330
|
+
'content-type': 'application/x-x509-ca-cert',
|
|
1331
|
+
'content-disposition': `attachment; filename="dsh-waypoint-ca.${wantDer ? 'der' : 'crt'}"`,
|
|
1332
|
+
'cache-control': 'no-store',
|
|
1333
|
+
});
|
|
1334
|
+
if (!wantDer) {
|
|
1335
|
+
res.end(fs.readFileSync(caCertPath));
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
try {
|
|
1339
|
+
const openssl = findOpenssl();
|
|
1340
|
+
const derFile = path.join(path.dirname(caCertPath), 'ca-cert.der');
|
|
1341
|
+
if (!fs.existsSync(derFile)) {
|
|
1342
|
+
spawnSync(openssl, ['x509', '-in', caCertPath, '-outform', 'DER', '-out', derFile], { stdio: 'ignore', windowsHide: true });
|
|
1343
|
+
}
|
|
1344
|
+
if (fs.existsSync(derFile)) {
|
|
1345
|
+
res.end(fs.readFileSync(derFile));
|
|
1346
|
+
return;
|
|
1347
|
+
}
|
|
1348
|
+
} catch { /* 转换失败就退回 PEM */ }
|
|
1349
|
+
res.end(fs.readFileSync(caCertPath));
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
// 登录 / 登出 / 账户页 / 重置密码:这些本身就有各自的凭据保护,不再要求入口暗号
|
|
1354
|
+
const isLoginPath = url.pathname === '/login' || url.pathname === '/logout'
|
|
1355
|
+
|| url.pathname === '/dsh_homing/account' || url.pathname === '/dsh_homing/reset'
|
|
1356
|
+
|| url.pathname === '/dsh_homing/devices'
|
|
1357
|
+
|| url.pathname === '/files' || url.pathname.startsWith('/files/')
|
|
1358
|
+
|| url.pathname === '/debug' || url.pathname === '/dsh_homing/debug'
|
|
1359
|
+
|| url.pathname.startsWith('/debug/') || url.pathname.startsWith('/dsh_homing/debug/');
|
|
1360
|
+
|
|
1361
|
+
// 重置密码:忘掉密码时用,凭据是「能在运行 DSH 的电脑上读到重置码」
|
|
1362
|
+
if (url.pathname === '/dsh_homing/reset') {
|
|
1363
|
+
const ip = clientKey(req);
|
|
1364
|
+
const resetFile = path.join(dir, 'reset-code.txt');
|
|
1365
|
+
const issueCode = () => {
|
|
1366
|
+
// 10 分钟内复用同一个码(防止有人狂点「获取」把你的码刷掉),
|
|
1367
|
+
// 但每次都要重写文件:文件可能被删掉或没生成成功
|
|
1368
|
+
if (!resetState.code || resetState.expiresAt <= Date.now()) {
|
|
1369
|
+
const code = base32Encode(crypto.randomBytes(5));
|
|
1370
|
+
resetState = { code, expiresAt: Date.now() + 10 * 60 * 1000, attempts: 0 };
|
|
1371
|
+
appendAudit(dir, 'password-reset-request', { ip });
|
|
1372
|
+
console.log(`[dsh-homing] 密码重置码:${code}(写入 ${resetFile},10 分钟内有效)`);
|
|
1373
|
+
}
|
|
1374
|
+
try {
|
|
1375
|
+
fs.writeFileSync(
|
|
1376
|
+
resetFile,
|
|
1377
|
+
`重置码:${resetState.code}\n有效期至:${new Date(resetState.expiresAt).toLocaleString('zh-CN')}\n用完即失效。\n`,
|
|
1378
|
+
{ encoding: 'utf8', mode: 0o600 },
|
|
1379
|
+
);
|
|
1380
|
+
} catch { /* 写不进文件就只留控制台日志 */ }
|
|
1381
|
+
return resetState.code;
|
|
1382
|
+
};
|
|
1383
|
+
|
|
1384
|
+
let message = '';
|
|
1385
|
+
if (req.method === 'POST') {
|
|
1386
|
+
const form = new URLSearchParams(await readBody(req));
|
|
1387
|
+
const action = form.get('action') ?? '';
|
|
1388
|
+
if (action === 'request') {
|
|
1389
|
+
issueCode();
|
|
1390
|
+
message = '重置码已生成:在运行 DSH 的电脑上查看 reset-code.txt(或 DSH 控制台日志),10 分钟内有效。';
|
|
1391
|
+
} else if (action === 'apply') {
|
|
1392
|
+
const code = (form.get('code') ?? '').trim().toUpperCase();
|
|
1393
|
+
const next = form.get('next') ?? '';
|
|
1394
|
+
const confirm = form.get('confirm') ?? '';
|
|
1395
|
+
if (!resetState.code || resetState.expiresAt <= Date.now()) {
|
|
1396
|
+
message = '重置码已过期,请重新获取。';
|
|
1397
|
+
} else if (resetState.attempts >= 5) {
|
|
1398
|
+
message = '尝试次数过多,请重新获取重置码。';
|
|
1399
|
+
resetState = { code: '', expiresAt: 0, attempts: 0 };
|
|
1400
|
+
} else if (!safeEqual(code, resetState.code)) {
|
|
1401
|
+
resetState.attempts += 1;
|
|
1402
|
+
message = '重置码不正确。';
|
|
1403
|
+
appendAudit(dir, 'password-reset-fail', { ip });
|
|
1404
|
+
} else if (next.length < 10) {
|
|
1405
|
+
message = '新密码至少 10 位。';
|
|
1406
|
+
} else if (next !== confirm) {
|
|
1407
|
+
message = '两次输入的新密码不一致。';
|
|
1408
|
+
} else {
|
|
1409
|
+
const salt = crypto.randomBytes(16);
|
|
1410
|
+
auth.salt = salt.toString('base64');
|
|
1411
|
+
auth.hash = base64url(crypto.scryptSync(next, salt, 64));
|
|
1412
|
+
auth.sessionKey = base64url(crypto.randomBytes(32));
|
|
1413
|
+
auth.updatedAt = new Date().toISOString();
|
|
1414
|
+
fs.writeFileSync(path.join(dir, 'auth.json'), `${JSON.stringify(auth, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
1415
|
+
resetState = { code: '', expiresAt: 0, attempts: 0 };
|
|
1416
|
+
try { fs.rmSync(resetFile, { force: true }); } catch { /* ignore */ }
|
|
1417
|
+
appendAudit(dir, 'password-reset-ok', { ip });
|
|
1418
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1419
|
+
res.end();
|
|
1420
|
+
return;
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
res.writeHead(200, {
|
|
1425
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1426
|
+
'cache-control': 'no-store',
|
|
1427
|
+
'x-frame-options': 'DENY',
|
|
1428
|
+
'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:",
|
|
1429
|
+
'x-content-type-options': 'nosniff',
|
|
1430
|
+
'referrer-policy': 'no-referrer',
|
|
1431
|
+
});
|
|
1432
|
+
res.end(RESET_HTML
|
|
1433
|
+
.replaceAll('{{message}}', message ? `<div class="msg">${escapeHtml(message)}</div>` : '')
|
|
1434
|
+
.replaceAll('{{hasCode}}', resetState.code && resetState.expiresAt > Date.now() ? '1' : '0'));
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
// 文件浏览 / 执行。独立页面(不依赖移动端样式),需要登录。
|
|
1439
|
+
// 注意:这里能执行本机程序,所以全部动作都写审计。
|
|
1440
|
+
// 编辑:GET 出编辑页,POST 保存。需要登录。
|
|
1441
|
+
if (url.pathname === '/files/edit') {
|
|
1442
|
+
if (!sessionValid(req)) {
|
|
1443
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1444
|
+
res.end();
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
const sendEdit = (pageHtml) => {
|
|
1448
|
+
res.writeHead(200, {
|
|
1449
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1450
|
+
'cache-control': 'no-store',
|
|
1451
|
+
'x-frame-options': 'DENY',
|
|
1452
|
+
'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:",
|
|
1453
|
+
'x-content-type-options': 'nosniff',
|
|
1454
|
+
'referrer-policy': 'no-referrer',
|
|
1455
|
+
});
|
|
1456
|
+
res.end(pageHtml);
|
|
1457
|
+
};
|
|
1458
|
+
|
|
1459
|
+
if (req.method === 'GET') {
|
|
1460
|
+
const file = url.searchParams.get('path') ?? '';
|
|
1461
|
+
sendEdit(renderEditPage({ info: filebrowse.readTextFile(file) }));
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
if (req.method === 'POST') {
|
|
1466
|
+
const form = new URLSearchParams(await readBody(req, 1024 * 1024));
|
|
1467
|
+
const file = form.get('path') ?? '';
|
|
1468
|
+
const text = form.get('text') ?? '';
|
|
1469
|
+
const saved = filebrowse.writeTextFile(file, text);
|
|
1470
|
+
appendAudit(dir, 'file-save', { path: file, bytes: saved.size ?? 0, ok: saved.ok });
|
|
1471
|
+
const info = filebrowse.readTextFile(file);
|
|
1472
|
+
sendEdit(renderEditPage({
|
|
1473
|
+
info,
|
|
1474
|
+
message: saved.ok ? '已保存' : saved.error,
|
|
1475
|
+
isError: !saved.ok,
|
|
1476
|
+
}));
|
|
1477
|
+
return;
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
// 自检:把"兜底转发"这一段的状态暴露出来,便于定位 404
|
|
1482
|
+
if (url.pathname === '/dsh_homing/selfcheck') {
|
|
1483
|
+
const up = getUpstreamPort();
|
|
1484
|
+
const authority = up ? '127.0.0.1:' + up : null;
|
|
1485
|
+
let cookieName = null;
|
|
1486
|
+
let accepted = null;
|
|
1487
|
+
let upstreamStatus = null;
|
|
1488
|
+
let sample = null;
|
|
1489
|
+
try {
|
|
1490
|
+
const minted = authority ? await mintCookie(authority) : undefined;
|
|
1491
|
+
cookieName = minted ? minted.name : null;
|
|
1492
|
+
if (authority && minted) {
|
|
1493
|
+
accepted = await new Promise((resolve) => {
|
|
1494
|
+
const probe = http.request({
|
|
1495
|
+
host: '127.0.0.1', port: up, path: '/', method: 'GET',
|
|
1496
|
+
headers: { host: authority, cookie: minted.name + '=' + minted.value },
|
|
1497
|
+
timeout: 5000,
|
|
1498
|
+
}, (res) => { upstreamStatus = res.statusCode; res.resume(); res.on('end', () => resolve(res.statusCode === 200)); });
|
|
1499
|
+
probe.on('timeout', () => { probe.destroy(); resolve(false); });
|
|
1500
|
+
probe.on('error', () => resolve(false));
|
|
1501
|
+
probe.end();
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
const direct = await new Promise((resolve) => {
|
|
1505
|
+
const req2 = http.request({ host: '127.0.0.1', port: up, path: '/', method: 'GET', headers: { host: authority ?? '' }, timeout: 5000 }, (res) => {
|
|
1506
|
+
const chunks = [];
|
|
1507
|
+
res.on('data', (c) => chunks.push(c));
|
|
1508
|
+
res.on('end', () => resolve({ status: res.statusCode, head: Buffer.concat(chunks).toString('utf8').slice(0, 120) }));
|
|
1509
|
+
});
|
|
1510
|
+
req2.on('timeout', () => { req2.destroy(); resolve({ status: 'timeout' }); });
|
|
1511
|
+
req2.on('error', (e) => resolve({ status: 'error: ' + e.code }));
|
|
1512
|
+
req2.end();
|
|
1513
|
+
});
|
|
1514
|
+
sample = direct;
|
|
1515
|
+
} catch (error) {
|
|
1516
|
+
sample = { error: String(error?.message ?? error) };
|
|
1517
|
+
}
|
|
1518
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1519
|
+
res.end(JSON.stringify({
|
|
1520
|
+
upstreamPort: up ?? null,
|
|
1521
|
+
authority,
|
|
1522
|
+
cookieName,
|
|
1523
|
+
cookieAccepted: accepted,
|
|
1524
|
+
upstreamRootStatusNoCookie: upstreamStatus,
|
|
1525
|
+
upstreamSample: sample,
|
|
1526
|
+
pluginVersion: PLUGIN_VERSION,
|
|
1527
|
+
}, null, 2));
|
|
1528
|
+
return;
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1531
|
+
// 活跃度信标:手机端打字/滑动时上报,重启脚本据此避免打断用户
|
|
1532
|
+
if (url.pathname === '/dsh_homing/alive' && (req.method === 'POST' || req.method === 'GET')) {
|
|
1533
|
+
touchActivity('beacon');
|
|
1534
|
+
res.writeHead(204, { 'cache-control': 'no-store' });
|
|
1535
|
+
res.end();
|
|
1536
|
+
return;
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
// 真终端:/term(xterm.js + 本机 sshd 的 PTY)。需要登录。
|
|
1540
|
+
if (url.pathname === '/term' || url.pathname.startsWith('/term/')) {
|
|
1541
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1542
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1543
|
+
res.end();
|
|
1544
|
+
return;
|
|
1545
|
+
}
|
|
1546
|
+
const dshHomeTerm = path.resolve(dir, '..', '..');
|
|
1547
|
+
|
|
1548
|
+
const sendTerm = (pageHtml) => {
|
|
1549
|
+
res.writeHead(200, {
|
|
1550
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1551
|
+
'cache-control': 'no-store',
|
|
1552
|
+
'x-frame-options': 'DENY',
|
|
1553
|
+
'content-security-policy': "default-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; img-src 'self' data:; font-src 'self'; form-action 'self'; base-uri 'none'",
|
|
1554
|
+
'x-content-type-options': 'nosniff',
|
|
1555
|
+
'referrer-policy': 'no-referrer',
|
|
1556
|
+
});
|
|
1557
|
+
res.end(pageHtml);
|
|
1558
|
+
};
|
|
1559
|
+
|
|
1560
|
+
const sendAsset = (file, type) => {
|
|
1561
|
+
try {
|
|
1562
|
+
const body = fs.readFileSync(file);
|
|
1563
|
+
res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
|
|
1564
|
+
res.end(body);
|
|
1565
|
+
} catch {
|
|
1566
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
1567
|
+
res.end('not found');
|
|
1568
|
+
}
|
|
1569
|
+
};
|
|
1570
|
+
|
|
1571
|
+
// 静态资源
|
|
1572
|
+
if (url.pathname === '/term/vendor/xterm.js') {
|
|
1573
|
+
sendAsset(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vendor', 'xterm.js'), 'text/javascript; charset=utf-8');
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
if (url.pathname === '/term/vendor/xterm.css') {
|
|
1577
|
+
sendAsset(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vendor', 'xterm.css'), 'text/css; charset=utf-8');
|
|
1578
|
+
return;
|
|
1579
|
+
}
|
|
1580
|
+
if (url.pathname === '/term/vendor/addon-fit.js') {
|
|
1581
|
+
sendAsset(
|
|
1582
|
+
path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vendor', 'node_modules', '@xterm', 'addon-fit', 'lib', 'addon-fit.js'),
|
|
1583
|
+
'text/javascript; charset=utf-8',
|
|
1584
|
+
);
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1587
|
+
if (url.pathname.startsWith('/term/vendor/fonts/')) {
|
|
1588
|
+
const name = path.basename(url.pathname);
|
|
1589
|
+
const isWoff = name.endsWith('.woff2');
|
|
1590
|
+
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'vendor', 'fonts', name);
|
|
1591
|
+
// ttf 用于"另存为/手动安装",woff2 用于页面内嵌
|
|
1592
|
+
sendAsset(
|
|
1593
|
+
file,
|
|
1594
|
+
isWoff ? 'font/woff2' : 'font/ttf',
|
|
1595
|
+
);
|
|
1596
|
+
return;
|
|
1597
|
+
}
|
|
1598
|
+
if (url.pathname === '/term/app.js') {
|
|
1599
|
+
sendAsset(path.join(path.dirname(fileURLToPath(import.meta.url)), 'lib', 'term-app.js'), 'text/javascript; charset=utf-8');
|
|
1600
|
+
return;
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
// 输入
|
|
1604
|
+
if (url.pathname === '/term/input' && req.method === 'POST') {
|
|
1605
|
+
let payload = {};
|
|
1606
|
+
try {
|
|
1607
|
+
payload = JSON.parse(await readBody(req, 64 * 1024));
|
|
1608
|
+
} catch {
|
|
1609
|
+
payload = {};
|
|
1610
|
+
}
|
|
1611
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
1612
|
+
const ok = terminal.write(String(payload.data ?? ''));
|
|
1613
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1614
|
+
res.end(JSON.stringify({ ok }));
|
|
1615
|
+
return;
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
// 窗口尺寸变化(等价于拖拽 Git Bash 窗口)
|
|
1619
|
+
if (url.pathname === '/term/resize' && req.method === 'POST') {
|
|
1620
|
+
let payload = {};
|
|
1621
|
+
try {
|
|
1622
|
+
payload = JSON.parse(await readBody(req, 4096));
|
|
1623
|
+
} catch {
|
|
1624
|
+
payload = {};
|
|
1625
|
+
}
|
|
1626
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
1627
|
+
const ok = terminal.resize(payload.cols, payload.rows);
|
|
1628
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1629
|
+
res.end(JSON.stringify({ ok, size: terminal.size }));
|
|
1630
|
+
return;
|
|
1631
|
+
}
|
|
1632
|
+
|
|
1633
|
+
// 重置
|
|
1634
|
+
if (url.pathname === '/term/reset' && req.method === 'POST') {
|
|
1635
|
+
await ptyrun.resetPtyTerminal({ dshHome: dshHomeTerm });
|
|
1636
|
+
appendAudit(dir, 'term-reset', {});
|
|
1637
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1638
|
+
res.end(JSON.stringify({ ok: true }));
|
|
1639
|
+
return;
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
// 输出流(SSE)
|
|
1643
|
+
if (url.pathname === '/term/stream' && req.method === 'GET') {
|
|
1644
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm });
|
|
1645
|
+
const since = Number(url.searchParams.get('since') ?? '0') || 0;
|
|
1646
|
+
res.writeHead(200, {
|
|
1647
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
1648
|
+
'cache-control': 'no-store, no-transform',
|
|
1649
|
+
connection: 'keep-alive',
|
|
1650
|
+
'x-accel-buffering': 'no',
|
|
1651
|
+
'x-frame-options': 'DENY',
|
|
1652
|
+
'content-security-policy': "default-src 'none'",
|
|
1653
|
+
});
|
|
1654
|
+
const flush = (text, seq) => {
|
|
1655
|
+
if (text === '') return;
|
|
1656
|
+
try {
|
|
1657
|
+
res.write('data: ' + JSON.stringify({ seq, text }) + '\n\n');
|
|
1658
|
+
} catch {
|
|
1659
|
+
// 连接已断
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
const backlog = terminal.since(since);
|
|
1663
|
+
if (backlog !== '') flush(backlog, terminal.latestSeq);
|
|
1664
|
+
const unsubscribe = terminal.subscribe((text, seq) => flush(text, seq));
|
|
1665
|
+
const heartbeat = setInterval(() => {
|
|
1666
|
+
try {
|
|
1667
|
+
res.write(': ping\n\n');
|
|
1668
|
+
} catch {
|
|
1669
|
+
clearInterval(heartbeat);
|
|
1670
|
+
}
|
|
1671
|
+
}, 15000);
|
|
1672
|
+
const cleanup = () => {
|
|
1673
|
+
clearInterval(heartbeat);
|
|
1674
|
+
unsubscribe();
|
|
1675
|
+
};
|
|
1676
|
+
req.on('close', cleanup);
|
|
1677
|
+
res.on('close', cleanup);
|
|
1678
|
+
return;
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// 页面
|
|
1682
|
+
if (url.pathname === '/term' && req.method === 'GET') {
|
|
1683
|
+
const index = filebrowse.workspaceIndex(dshHomeTerm);
|
|
1684
|
+
const asked = url.searchParams.get('path');
|
|
1685
|
+
const termSession = url.searchParams.get('session');
|
|
1686
|
+
const cwd = asked
|
|
1687
|
+
?? (termSession === null ? null : filebrowse.workspacePathForSessionId(dshHomeTerm, termSession))
|
|
1688
|
+
?? index.defaultPath
|
|
1689
|
+
?? filebrowse.HOME;
|
|
1690
|
+
// 先确保 sshd 与终端会话就绪,失败也要把页面开出来(页面上会显示状态)
|
|
1691
|
+
let connected = false;
|
|
1692
|
+
try {
|
|
1693
|
+
const terminal = await ptyrun.sharedPtyTerminal({ dshHome: dshHomeTerm, cwd });
|
|
1694
|
+
// 会话是常驻的:从别的会话进来时,让终端切到那个工作区(和 PC 上点文件夹一致)
|
|
1695
|
+
if (terminal.cwd !== undefined && terminal.cwd !== cwd) {
|
|
1696
|
+
terminal.changeDir(cwd);
|
|
1697
|
+
}
|
|
1698
|
+
connected = true;
|
|
1699
|
+
} catch (error) {
|
|
1700
|
+
appendAudit(dir, 'term-error', { message: String(error?.message ?? error) });
|
|
1701
|
+
}
|
|
1702
|
+
sendTerm(renderTermPage({
|
|
1703
|
+
cwd,
|
|
1704
|
+
user: process.env.USERNAME ?? '',
|
|
1705
|
+
host: os.hostname(),
|
|
1706
|
+
connected,
|
|
1707
|
+
}));
|
|
1708
|
+
return;
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
res.writeHead(303, { location: '/term', 'cache-control': 'no-store' });
|
|
1712
|
+
res.end();
|
|
1713
|
+
return;
|
|
1714
|
+
}
|
|
1715
|
+
|
|
1716
|
+
// 终端:执行任意 shell 命令(手机端的 Git Bash)。需要登录。
|
|
1717
|
+
if (url.pathname === '/shell' || url.pathname === '/shell/complete' || url.pathname === '/shell/run') {
|
|
1718
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1719
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1720
|
+
res.end();
|
|
1721
|
+
return;
|
|
1722
|
+
}
|
|
1723
|
+
const sendShell = (pageHtml) => {
|
|
1724
|
+
res.writeHead(200, {
|
|
1725
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1726
|
+
'cache-control': 'no-store',
|
|
1727
|
+
'x-frame-options': 'DENY',
|
|
1728
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'none'",
|
|
1729
|
+
'x-content-type-options': 'nosniff',
|
|
1730
|
+
'referrer-policy': 'no-referrer',
|
|
1731
|
+
});
|
|
1732
|
+
res.end(pageHtml);
|
|
1733
|
+
};
|
|
1734
|
+
const dshHomeShell = path.resolve(dir, '..', '..');
|
|
1735
|
+
const wsIndex = filebrowse.workspaceIndex(dshHomeShell);
|
|
1736
|
+
const shellName = shellrun.findBash() === null ? 'cmd.exe' : 'bash';
|
|
1737
|
+
|
|
1738
|
+
if (url.pathname === '/shell/complete') {
|
|
1739
|
+
const cwdParam = url.searchParams.get('cwd') ?? filebrowse.HOME;
|
|
1740
|
+
const line = url.searchParams.get('line') ?? '';
|
|
1741
|
+
const items = shellrun.completeCandidates(cwdParam, line);
|
|
1742
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1743
|
+
res.end(JSON.stringify(items));
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
// 终端页用:执行命令并返回 JSON(页面不刷新)
|
|
1748
|
+
if (url.pathname === '/shell/run' && req.method === 'POST') {
|
|
1749
|
+
let payload = {};
|
|
1750
|
+
try {
|
|
1751
|
+
payload = JSON.parse(await readBody(req, 64 * 1024));
|
|
1752
|
+
} catch {
|
|
1753
|
+
payload = {};
|
|
1754
|
+
}
|
|
1755
|
+
const commandText = String(payload.command ?? '');
|
|
1756
|
+
const baseCwd = String(payload.cwd ?? wsIndex.defaultPath ?? filebrowse.HOME);
|
|
1757
|
+
const terminal = sharedSession(baseCwd);
|
|
1758
|
+
const sendJson = (data) => {
|
|
1759
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
1760
|
+
res.end(JSON.stringify(data));
|
|
1761
|
+
};
|
|
1762
|
+
if (payload.reset === true) {
|
|
1763
|
+
resetSharedSession();
|
|
1764
|
+
appendAudit(dir, 'shell-reset', {});
|
|
1765
|
+
sendJson({ ok: true, code: 0, output: '会话已重置', cwd: terminal.info().cwd });
|
|
1766
|
+
return;
|
|
1767
|
+
}
|
|
1768
|
+
// Ctrl+C:中断当前命令(杀掉 bash 及子进程树后重启)
|
|
1769
|
+
if (payload.interrupt === true) {
|
|
1770
|
+
appendAudit(dir, 'shell-interrupt', {});
|
|
1771
|
+
const stopped = terminal.interrupt();
|
|
1772
|
+
sendJson({
|
|
1773
|
+
ok: true,
|
|
1774
|
+
code: null,
|
|
1775
|
+
interrupted: true,
|
|
1776
|
+
output: stopped.output,
|
|
1777
|
+
cwd: terminal.info().cwd,
|
|
1778
|
+
branch: '',
|
|
1779
|
+
});
|
|
1780
|
+
return;
|
|
1781
|
+
}
|
|
1782
|
+
appendAudit(dir, 'shell-run', { cwd: baseCwd, command: commandText });
|
|
1783
|
+
const result = await terminal.run(commandText);
|
|
1784
|
+
terminal.record({
|
|
1785
|
+
command: commandText,
|
|
1786
|
+
output: String(result.output ?? ''),
|
|
1787
|
+
code: result.code ?? null,
|
|
1788
|
+
ok: result.ok !== false,
|
|
1789
|
+
timeout: result.timeout === true,
|
|
1790
|
+
cwd: result.cwd ?? baseCwd,
|
|
1791
|
+
});
|
|
1792
|
+
const afterBranch = gitrun.isRepo(terminal.info().cwd)
|
|
1793
|
+
? await gitrun.runGit(terminal.info().cwd, ['branch', '--show-current'])
|
|
1794
|
+
: null;
|
|
1795
|
+
sendJson({
|
|
1796
|
+
ok: result.ok !== false,
|
|
1797
|
+
code: result.code ?? null,
|
|
1798
|
+
output: result.output ?? '',
|
|
1799
|
+
cwd: terminal.info().cwd,
|
|
1800
|
+
branch: afterBranch !== null && afterBranch.ok ? afterBranch.output.trim() : '',
|
|
1801
|
+
timeout: result.timeout === true,
|
|
1802
|
+
});
|
|
1803
|
+
return;
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
// 简易终端已下线:GET 一律跳到真终端 /term(保留 POST 接口兼容旧页面)
|
|
1807
|
+
if (req.method === 'GET') {
|
|
1808
|
+
const query = url.searchParams.toString();
|
|
1809
|
+
res.writeHead(303, { location: '/term' + (query === '' ? '' : '?' + query), 'cache-control': 'no-store' });
|
|
1810
|
+
res.end();
|
|
1811
|
+
return;
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
|
|
1815
|
+
if (req.method === 'POST') {
|
|
1816
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
1817
|
+
let cwd = form.get('cwd') ?? filebrowse.HOME;
|
|
1818
|
+
const command = form.get('command') ?? '';
|
|
1819
|
+
if (form.get('action') === 'reset') {
|
|
1820
|
+
resetSharedSession();
|
|
1821
|
+
appendAudit(dir, 'shell-reset', {});
|
|
1822
|
+
const fresh = sharedSession(cwd);
|
|
1823
|
+
sendShell(renderShellPage({
|
|
1824
|
+
cwd: fresh.info().cwd,
|
|
1825
|
+
shellName: 'bash · 常驻会话(已重置)',
|
|
1826
|
+
result: { ok: true, code: 0, output: '会话已重置:环境变量清空,当前目录保持' },
|
|
1827
|
+
}));
|
|
1828
|
+
return;
|
|
1829
|
+
}
|
|
1830
|
+
// 支持 cd:只改工作目录,不真的执行
|
|
1831
|
+
const nextCwd = shellrun.parseCd(command, cwd);
|
|
1832
|
+
if (nextCwd !== null) {
|
|
1833
|
+
const exists = (() => {
|
|
1834
|
+
try {
|
|
1835
|
+
return fs.statSync(nextCwd).isDirectory();
|
|
1836
|
+
} catch {
|
|
1837
|
+
return false;
|
|
1838
|
+
}
|
|
1839
|
+
})();
|
|
1840
|
+
sendShell(renderShellPage({
|
|
1841
|
+
cwd: exists ? nextCwd : cwd,
|
|
1842
|
+
command: '',
|
|
1843
|
+
shellName,
|
|
1844
|
+
result: { ok: exists, code: exists ? 0 : 1, output: exists ? nextCwd : '目录不存在:' + nextCwd },
|
|
1845
|
+
}));
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
appendAudit(dir, 'shell-run', { cwd, command });
|
|
1849
|
+
// 常驻会话:cd / export / 函数定义都跨命令保留
|
|
1850
|
+
const session = sharedSession(cwd);
|
|
1851
|
+
if (cwd !== session.info().cwd) {
|
|
1852
|
+
await session.run('cd "' + String(cwd).replaceAll('"', '""') + '"');
|
|
1853
|
+
}
|
|
1854
|
+
const result = await session.run(command);
|
|
1855
|
+
const info = session.info();
|
|
1856
|
+
sendShell(renderShellPage({
|
|
1857
|
+
cwd: info.cwd,
|
|
1858
|
+
command,
|
|
1859
|
+
result,
|
|
1860
|
+
shellName: info.running ? 'bash · 常驻会话' : 'bash · 会话已重启',
|
|
1861
|
+
history: [command],
|
|
1862
|
+
}));
|
|
1863
|
+
return;
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
// git 页:跑任意 git 子命令(不经过 shell),需要登录
|
|
1868
|
+
if (url.pathname === '/git' || url.pathname === '/git/run') {
|
|
1869
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1870
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1871
|
+
res.end();
|
|
1872
|
+
return;
|
|
1873
|
+
}
|
|
1874
|
+
const sendGit = (pageHtml) => {
|
|
1875
|
+
res.writeHead(200, {
|
|
1876
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1877
|
+
'cache-control': 'no-store',
|
|
1878
|
+
'x-frame-options': 'DENY',
|
|
1879
|
+
'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:",
|
|
1880
|
+
'x-content-type-options': 'nosniff',
|
|
1881
|
+
'referrer-policy': 'no-referrer',
|
|
1882
|
+
});
|
|
1883
|
+
res.end(pageHtml);
|
|
1884
|
+
};
|
|
1885
|
+
|
|
1886
|
+
if (url.pathname === '/git' && req.method === 'GET') {
|
|
1887
|
+
const dshHome = path.resolve(dir, '..', '..');
|
|
1888
|
+
const index = filebrowse.workspaceIndex(dshHome);
|
|
1889
|
+
const asked = url.searchParams.get('path');
|
|
1890
|
+
const gitSession = url.searchParams.get('session');
|
|
1891
|
+
const repoPath = asked
|
|
1892
|
+
?? (gitSession === null ? null : filebrowse.workspacePathForSessionId(dshHome, gitSession))
|
|
1893
|
+
?? index.defaultPath
|
|
1894
|
+
?? filebrowse.HOME;
|
|
1895
|
+
const summary = gitrun.isRepo(repoPath) ? await gitrun.repoSummary(repoPath) : null;
|
|
1896
|
+
sendGit(renderGitPage({
|
|
1897
|
+
repoPath,
|
|
1898
|
+
summary,
|
|
1899
|
+
suggestions: gitrun.suggestionsFor(summary),
|
|
1900
|
+
repoPaths: index.list.map((item) => item.path),
|
|
1901
|
+
message: summary === null ? '这个路径不是 git 仓库' : '',
|
|
1902
|
+
}));
|
|
1903
|
+
return;
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
if (url.pathname === '/git/run' && req.method === 'POST') {
|
|
1907
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
1908
|
+
const repoPath = form.get('path') ?? '';
|
|
1909
|
+
const args = form.get('args') ?? '';
|
|
1910
|
+
appendAudit(dir, 'git-run', { path: repoPath, args });
|
|
1911
|
+
const summary = gitrun.isRepo(repoPath) ? await gitrun.repoSummary(repoPath) : null;
|
|
1912
|
+
const result = gitrun.isRepo(repoPath)
|
|
1913
|
+
? await gitrun.runGit(repoPath, args)
|
|
1914
|
+
: { ok: false, error: '这个路径不是 git 仓库' };
|
|
1915
|
+
sendGit(renderGitPage({
|
|
1916
|
+
repoPath,
|
|
1917
|
+
summary,
|
|
1918
|
+
args,
|
|
1919
|
+
result,
|
|
1920
|
+
suggestions: gitrun.suggestionsFor(summary),
|
|
1921
|
+
}));
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
|
|
1925
|
+
res.writeHead(303, { location: '/git', 'cache-control': 'no-store' });
|
|
1926
|
+
res.end();
|
|
1927
|
+
return;
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
if (url.pathname === '/files' || url.pathname === '/files/view' || url.pathname === '/files/run'
|
|
1931
|
+
|| url.pathname === '/files/ask' || url.pathname === '/files/rename'
|
|
1932
|
+
|| url.pathname === '/files/delete' || url.pathname === '/files/paste'
|
|
1933
|
+
|| url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') {
|
|
1934
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
1935
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
1936
|
+
res.end();
|
|
1937
|
+
return;
|
|
1938
|
+
}
|
|
1939
|
+
const sendHtml = (page) => {
|
|
1940
|
+
res.writeHead(200, {
|
|
1941
|
+
'content-type': 'text/html; charset=utf-8',
|
|
1942
|
+
'cache-control': 'no-store',
|
|
1943
|
+
'x-frame-options': 'DENY',
|
|
1944
|
+
'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:",
|
|
1945
|
+
'x-content-type-options': 'nosniff',
|
|
1946
|
+
'referrer-policy': 'no-referrer',
|
|
1947
|
+
});
|
|
1948
|
+
res.end(page);
|
|
1949
|
+
};
|
|
1950
|
+
|
|
1951
|
+
if (url.pathname === '/files' && req.method === 'GET') {
|
|
1952
|
+
const dshHome = path.resolve(dir, '..', '..');
|
|
1953
|
+
const index = filebrowse.workspaceIndex(dshHome);
|
|
1954
|
+
const asked = url.searchParams.get('path');
|
|
1955
|
+
const sessionId = url.searchParams.get('session');
|
|
1956
|
+
const hint = url.searchParams.get('hint') ?? url.searchParams.get('workspace');
|
|
1957
|
+
// 优先级:显式路径 > 工作区名 > 会话标题 > 默认工作区 > 主目录
|
|
1958
|
+
const target = asked
|
|
1959
|
+
?? (sessionId === null ? null : filebrowse.workspacePathForSessionId(dshHome, sessionId))
|
|
1960
|
+
?? (sessionId === null ? null : filebrowse.sessionCwdById(dshHome, sessionId))
|
|
1961
|
+
?? (hint === null ? null : index.find(hint))
|
|
1962
|
+
?? (hint === null ? null : filebrowse.workspacePathForSessionTitle(dshHome, hint))
|
|
1963
|
+
?? (hint === null ? null : filebrowse.sessionCwd(dshHome, hint))
|
|
1964
|
+
?? index.defaultPath
|
|
1965
|
+
?? filebrowse.HOME;
|
|
1966
|
+
const info = filebrowse.listDirectory(target);
|
|
1967
|
+
appendAudit(dir, 'file-list', { path: info.path });
|
|
1968
|
+
sendHtml(renderFileListing({
|
|
1969
|
+
info,
|
|
1970
|
+
home: filebrowse.HOME,
|
|
1971
|
+
dataDir: dir,
|
|
1972
|
+
workspaces: index.list,
|
|
1973
|
+
}));
|
|
1974
|
+
return;
|
|
1975
|
+
}
|
|
1976
|
+
|
|
1977
|
+
if (url.pathname === '/files/view' && req.method === 'GET') {
|
|
1978
|
+
const info = filebrowse.readTextFile(url.searchParams.get('path') ?? '');
|
|
1979
|
+
appendAudit(dir, 'file-view', { path: info.path });
|
|
1980
|
+
sendHtml(renderFileView({ info }));
|
|
1981
|
+
return;
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
if (url.pathname === '/files/run' && req.method === 'GET') {
|
|
1985
|
+
const file = url.searchParams.get('path') ?? '';
|
|
1986
|
+
sendHtml(renderRunPage({ file }));
|
|
1987
|
+
return;
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
if (url.pathname === '/files/ask' && req.method === 'GET') {
|
|
1991
|
+
const target = url.searchParams.get('path') ?? '';
|
|
1992
|
+
const name = path.basename(target);
|
|
1993
|
+
const dir = path.dirname(target);
|
|
1994
|
+
const esc = (v) => String(v).replace(/[&<>"]/gu, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);
|
|
1995
|
+
sendHtml(`<!doctype html><html lang="zh-CN"><head><meta charset="utf-8">
|
|
1996
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
1997
|
+
<title>操作</title><style>
|
|
1998
|
+
body{background:#12161d;color:#dbe2ea;font:15px/1.5 system-ui;margin:0;padding:16px}
|
|
1999
|
+
h1{font-size:18px;margin:0 0 12px}
|
|
2000
|
+
.card{background:#1a1f27;border:1px solid #2b3340;border-radius:10px;padding:14px;margin-bottom:12px}
|
|
2001
|
+
input{width:100%;box-sizing:border-box;padding:11px;border-radius:8px;border:1px solid #39424f;background:#0f1319;color:#e6edf5;font-size:15px}
|
|
2002
|
+
button{width:100%;margin-top:10px;padding:12px;border-radius:8px;border:0;background:#4f7cff;color:#fff;font-size:15px;font-weight:600}
|
|
2003
|
+
a.btn{display:block;padding:11px;border-radius:8px;background:#2a2f3a;color:#c7cdd8;text-decoration:none;text-align:center;margin-top:8px}
|
|
2004
|
+
.path{color:#8b93a1;font-size:12px;word-break:break-all;margin-bottom:8px}
|
|
2005
|
+
</style></head><body>
|
|
2006
|
+
<h1>⋯ 操作</h1>
|
|
2007
|
+
<div class="card"><div class="path">${esc(target)}</div>
|
|
2008
|
+
<form method="post" action="/files/rename">
|
|
2009
|
+
<input type="hidden" name="path" value="${esc(target)}">
|
|
2010
|
+
<input type="text" name="name" value="${esc(name)}" autofocus>
|
|
2011
|
+
<button type="submit">重命名</button>
|
|
2012
|
+
</form></div>
|
|
2013
|
+
<a class="btn" href="/files?path=${encodeURIComponent(dir)}">返回所在目录</a>
|
|
2014
|
+
<a class="btn" href="/files/view?path=${encodeURIComponent(target)}">查看内容</a>
|
|
2015
|
+
<a class="btn" href="/">返回 DSH</a>
|
|
2016
|
+
</body></html>`);
|
|
2017
|
+
return;
|
|
2018
|
+
}
|
|
2019
|
+
|
|
2020
|
+
if ((url.pathname === '/files/mkdir' || url.pathname === '/files/newfile') && req.method === 'POST') {
|
|
2021
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
2022
|
+
const targetDir = form.get('dir') ?? '';
|
|
2023
|
+
const name = form.get('name') ?? '';
|
|
2024
|
+
const isDir = url.pathname === '/files/mkdir';
|
|
2025
|
+
const result = filebrowse.createEntry(targetDir, name, isDir);
|
|
2026
|
+
appendAudit(dir, isDir ? 'file-mkdir' : 'file-newfile', { dir: targetDir, name, ok: result.ok, error: result.error ?? null });
|
|
2027
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(targetDir), 'cache-control': 'no-store' });
|
|
2028
|
+
res.end();
|
|
2029
|
+
return;
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
if (url.pathname === '/files/paste' && req.method === 'POST') {
|
|
2033
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
2034
|
+
const src = form.get('src') ?? '';
|
|
2035
|
+
const dir = form.get('dir') ?? '';
|
|
2036
|
+
const op = form.get('op') === 'cut' ? 'cut' : 'copy';
|
|
2037
|
+
const result = op === 'cut' ? filebrowse.moveInto(src, dir) : filebrowse.copyInto(src, dir);
|
|
2038
|
+
appendAudit(dir, op === 'cut' ? 'file-move' : 'file-paste', { src, dir, ok: result.ok, target: result.path ?? null, error: result.error ?? null });
|
|
2039
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(dir), 'cache-control': 'no-store' });
|
|
2040
|
+
res.end();
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
if (url.pathname === '/files/delete' && req.method === 'POST') {
|
|
2045
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
2046
|
+
const target = form.get('path') ?? '';
|
|
2047
|
+
const result = filebrowse.deleteEntry(target);
|
|
2048
|
+
appendAudit(dir, 'file-delete', { target, ok: result.ok, error: result.error ?? null });
|
|
2049
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)), 'cache-control': 'no-store' });
|
|
2050
|
+
res.end();
|
|
2051
|
+
return;
|
|
2052
|
+
}
|
|
2053
|
+
|
|
2054
|
+
if (url.pathname === '/files/rename' && req.method === 'POST') {
|
|
2055
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
2056
|
+
const target = form.get('path') ?? '';
|
|
2057
|
+
const name = form.get('name') ?? '';
|
|
2058
|
+
const result = filebrowse.renameEntry(target, name);
|
|
2059
|
+
appendAudit(dir, 'file-rename', { target, name, ok: result.ok, error: result.error ?? null });
|
|
2060
|
+
if (!result.ok) {
|
|
2061
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(target)) + '&msg=' + encodeURIComponent(result.error), 'cache-control': 'no-store' });
|
|
2062
|
+
res.end();
|
|
2063
|
+
return;
|
|
2064
|
+
}
|
|
2065
|
+
res.writeHead(303, { location: '/files?path=' + encodeURIComponent(path.dirname(result.path)), 'cache-control': 'no-store' });
|
|
2066
|
+
res.end();
|
|
2067
|
+
return;
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
if (url.pathname === '/files/run' && req.method === 'POST') {
|
|
2071
|
+
const form = new URLSearchParams(await readBody(req, 64 * 1024));
|
|
2072
|
+
const file = form.get('path') ?? '';
|
|
2073
|
+
const args = form.get('args') ?? '';
|
|
2074
|
+
appendAudit(dir, 'file-run', { file, args });
|
|
2075
|
+
const result = await filebrowse.runFile(file, args);
|
|
2076
|
+
sendHtml(renderRunPage({ file, args, result }));
|
|
2077
|
+
return;
|
|
2078
|
+
}
|
|
2079
|
+
|
|
2080
|
+
res.writeHead(303, { location: '/files', 'cache-control': 'no-store' });
|
|
2081
|
+
res.end();
|
|
2082
|
+
return;
|
|
2083
|
+
}
|
|
2084
|
+
|
|
2085
|
+
// 调试页:独立于移动端样式,页面被改坏时也能打开;需要登录。
|
|
2086
|
+
// 两个地址都能用:/debug(好记)和 /dsh_homing/debug(兼容旧链接)
|
|
2087
|
+
const debugPrefix = url.pathname === '/debug' || url.pathname.startsWith('/debug/')
|
|
2088
|
+
? '/debug'
|
|
2089
|
+
: url.pathname === '/dsh_homing/debug' || url.pathname.startsWith('/dsh_homing/debug/')
|
|
2090
|
+
? '/dsh_homing/debug'
|
|
2091
|
+
: null;
|
|
2092
|
+
const debugSub = debugPrefix === null ? null : url.pathname.slice(debugPrefix.length);
|
|
2093
|
+
|
|
2094
|
+
if (debugSub === '') {
|
|
2095
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2096
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2097
|
+
res.end();
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2100
|
+
const message = url.searchParams.get('msg') ?? '';
|
|
2101
|
+
if (req.method === 'POST') {
|
|
2102
|
+
const form = new URLSearchParams(await readBody(req));
|
|
2103
|
+
const action = form.get('action') ?? '';
|
|
2104
|
+
const cookieBase = `Path=/; SameSite=Lax${secureCookies ? '; Secure' : ''}`;
|
|
2105
|
+
if (action === 'mobile-off' || action === 'mobile-on') {
|
|
2106
|
+
const value = action === 'mobile-off' ? '1' : '';
|
|
2107
|
+
const maxAge = action === 'mobile-off' ? 31_536_000 : 0;
|
|
2108
|
+
res.writeHead(303, {
|
|
2109
|
+
location: `${debugPrefix}?msg=${encodeURIComponent(action === 'mobile-off' ? '已关闭移动端样式,回到原生布局' : '已重新启用移动端样式')}`,
|
|
2110
|
+
'cache-control': 'no-store',
|
|
2111
|
+
'set-cookie': `${MOBILE_OFF_COOKIE}=${value}; ${cookieBase}; Max-Age=${maxAge}`,
|
|
2112
|
+
});
|
|
2113
|
+
res.end();
|
|
2114
|
+
return;
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
const off = readCookies(req.headers.cookie)[MOBILE_OFF_COOKIE] === '1';
|
|
2118
|
+
const shotsDir = path.join(dir, 'debug', 'shots');
|
|
2119
|
+
let shots = [];
|
|
2120
|
+
try { shots = fs.readdirSync(shotsDir).filter((n) => /.(png|jpe?g|webp)$/iu.test(n)).sort().reverse().slice(0, 12); } catch { /* 还没有 */ }
|
|
2121
|
+
let errors = [];
|
|
2122
|
+
try {
|
|
2123
|
+
errors = fs.readFileSync(path.join(dir, 'debug', 'errors.log'), 'utf8').trim().split('\n').filter(Boolean).slice(-3).reverse();
|
|
2124
|
+
} catch { /* 没有日志 */ }
|
|
2125
|
+
const row = (k, v, cls) => `<div class="row"><span class="k">${k}</span><span class="v ${cls ?? ''}">${v}</span></div>`;
|
|
2126
|
+
const deviceCount = deviceStore.partition(devices()).active.length;
|
|
2127
|
+
res.writeHead(200, {
|
|
2128
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2129
|
+
'cache-control': 'no-store',
|
|
2130
|
+
'x-frame-options': 'DENY',
|
|
2131
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; script-src 'unsafe-inline'; form-action 'self'; base-uri 'none'",
|
|
2132
|
+
'x-content-type-options': 'nosniff',
|
|
2133
|
+
'referrer-policy': 'no-referrer',
|
|
2134
|
+
});
|
|
2135
|
+
res.end(DEBUG_HTML
|
|
2136
|
+
.replaceAll('{{message}}', message ? `<div class="msg">${escapeHtml(message)}</div>` : '')
|
|
2137
|
+
.replaceAll('{{version}}', escapeHtml(String(PLUGIN_VERSION)))
|
|
2138
|
+
.replaceAll('{{mobileClass}}', off ? 'warn' : 'ok')
|
|
2139
|
+
.replaceAll('{{mobileOff}}', off ? '已关闭(原生布局)' : '已启用')
|
|
2140
|
+
.replaceAll('{{viewport}}', '由浏览器填写')
|
|
2141
|
+
.replaceAll('{{ua}}', escapeHtml(String(req.headers['user-agent'] ?? '').slice(0, 160)))
|
|
2142
|
+
.replaceAll('{{devices}}', String(deviceCount))
|
|
2143
|
+
.replaceAll('{{now}}', new Date().toISOString().replace('T', ' ').slice(0, 19))
|
|
2144
|
+
.replaceAll('{{toggleAction}}', off ? 'mobile-on' : 'mobile-off')
|
|
2145
|
+
.replaceAll('{{toggleLabel}}', off ? '重新启用移动端样式' : '关闭移动端样式(回到原生布局)')
|
|
2146
|
+
.replaceAll('{{toggleClass}}', off ? '' : 'danger')
|
|
2147
|
+
.replaceAll('{{cssInfo}}', `${MOBILE_CSS.length} 字节`)
|
|
2148
|
+
.replaceAll('{{jsInfo}}', `${MOBILE_JS.length} 字节`)
|
|
2149
|
+
.replaceAll('{{errors}}', errors.length > 0 ? errors.map((line) => escapeHtml(line)).join('<br>') : '无')
|
|
2150
|
+
.replaceAll('{{shots}}', shots.length === 0
|
|
2151
|
+
? ''
|
|
2152
|
+
: `<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>`));
|
|
2153
|
+
return;
|
|
2154
|
+
}
|
|
2155
|
+
|
|
2156
|
+
// 上传截图:接收 dataURL,落盘到 debug/shots/
|
|
2157
|
+
if (debugSub === '/upload' && req.method === 'POST') {
|
|
2158
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2159
|
+
res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2160
|
+
res.end('未登录');
|
|
2161
|
+
return;
|
|
2162
|
+
}
|
|
2163
|
+
let parsed = null;
|
|
2164
|
+
try { parsed = JSON.parse(await readBody(req, 16 * 1024 * 1024)); } catch { parsed = null; }
|
|
2165
|
+
const match = parsed && typeof parsed.dataUrl === 'string'
|
|
2166
|
+
? /^data:image\/(png|jpeg|webp);base64,([A-Za-z0-9+/=]+)$/u.exec(parsed.dataUrl)
|
|
2167
|
+
: null;
|
|
2168
|
+
if (match === null) {
|
|
2169
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2170
|
+
res.end('只接受 png/jpeg/webp 的 dataURL');
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
const ext = match[1] === 'jpeg' ? 'jpg' : match[1];
|
|
2174
|
+
const stamp = new Date().toISOString().replace(/[:.]/gu, '-').slice(0, 19);
|
|
2175
|
+
const shotsDir = path.join(dir, 'debug', 'shots');
|
|
2176
|
+
fs.mkdirSync(shotsDir, { recursive: true });
|
|
2177
|
+
const name = `${stamp}.${ext}`;
|
|
2178
|
+
fs.writeFileSync(path.join(shotsDir, name), Buffer.from(match[2], 'base64'));
|
|
2179
|
+
appendAudit(dir, 'debug-shot', { file: name, bytes: match[2].length });
|
|
2180
|
+
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
2181
|
+
res.end(JSON.stringify({ ok: true, file: name }));
|
|
2182
|
+
return;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
// 查看已上传的截图
|
|
2186
|
+
if (debugSub !== null && debugSub.startsWith('/files/') && req.method === 'GET') {
|
|
2187
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2188
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2189
|
+
res.end();
|
|
2190
|
+
return;
|
|
2191
|
+
}
|
|
2192
|
+
const name = decodeURIComponent(debugSub.slice('/files/'.length));
|
|
2193
|
+
if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|webp)$/u.test(name)) {
|
|
2194
|
+
res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2195
|
+
res.end('文件名不合法');
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
const file = path.join(dir, 'debug', 'shots', name);
|
|
2199
|
+
if (!fs.existsSync(file)) {
|
|
2200
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2201
|
+
res.end('没有这张图');
|
|
2202
|
+
return;
|
|
2203
|
+
}
|
|
2204
|
+
const ext = path.extname(name).slice(1).toLowerCase();
|
|
2205
|
+
res.writeHead(200, {
|
|
2206
|
+
'content-type': ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : 'image/jpeg',
|
|
2207
|
+
'cache-control': 'no-store',
|
|
2208
|
+
});
|
|
2209
|
+
res.end(fs.readFileSync(file));
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
// 设备管理:需要登录。它在入口闸门的白名单里,所以即使把所有设备都吊销了,
|
|
2214
|
+
// 你仍然能在电脑上登录后进来恢复,不会把自己彻底锁死。
|
|
2215
|
+
if (url.pathname === '/dsh_homing/devices') {
|
|
2216
|
+
if (!sessionValid(req)) {
|
|
2217
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2218
|
+
res.end();
|
|
2219
|
+
return;
|
|
2220
|
+
}
|
|
2221
|
+
const message = url.searchParams.get('msg') ?? '';
|
|
2222
|
+
if (req.method === 'POST') {
|
|
2223
|
+
const form = new URLSearchParams(await readBody(req));
|
|
2224
|
+
const action = form.get('action') ?? '';
|
|
2225
|
+
const id = form.get('id') ?? '';
|
|
2226
|
+
let result = { changed: false, state: devices() };
|
|
2227
|
+
if (action === 'revoke') result = deviceStore.revokeDevice(devices(), id);
|
|
2228
|
+
else if (action === 'remove') result = deviceStore.removeDevice(devices(), id);
|
|
2229
|
+
else if (action === 'rename') result = deviceStore.renameDevice(devices(), id, form.get('name') ?? '');
|
|
2230
|
+
if (result.changed) {
|
|
2231
|
+
persistDevices(result.state);
|
|
2232
|
+
appendAudit(dir, `device-${action}`, { id, ip: clientKey(req) });
|
|
2233
|
+
}
|
|
2234
|
+
res.writeHead(303, {
|
|
2235
|
+
location: `/dsh_homing/devices?msg=${encodeURIComponent(result.changed ? '已更新。' : '没有变化。')}`,
|
|
2236
|
+
'cache-control': 'no-store',
|
|
2237
|
+
});
|
|
2238
|
+
res.end();
|
|
2239
|
+
return;
|
|
2240
|
+
}
|
|
2241
|
+
const { active, revoked } = deviceStore.partition(devices());
|
|
2242
|
+
const current = currentDevice(req);
|
|
2243
|
+
const row = (device, ops) => `<tr><td><b>${escapeHtml(device.name)}</b><div class="id">${device.id}</div></td>`
|
|
2244
|
+
+ `<td>${device.lastSeenAt ? escapeHtml(device.lastSeenAt.slice(0, 16).replace('T', ' ')) : '—'}`
|
|
2245
|
+
+ `<div class="id">${escapeHtml(device.lastIp ?? '')}</div></td>`
|
|
2246
|
+
+ `<td>${device.createdAt.slice(0, 10)}</td><td>${ops}</td></tr>`;
|
|
2247
|
+
const activeRows = active.length === 0
|
|
2248
|
+
? '<tr><td colspan="4" class="muted">还没有配对设备。</td></tr>'
|
|
2249
|
+
: active.map((device) => {
|
|
2250
|
+
const isCurrent = current !== null && current.id === device.id;
|
|
2251
|
+
return row(device,
|
|
2252
|
+
(isCurrent ? '<span class="badge">当前设备</span> ' : '')
|
|
2253
|
+
+ `<form method="post" style="display:inline"><input type="hidden" name="id" value="${device.id}">`
|
|
2254
|
+
+ '<input type="hidden" name="action" value="revoke"><button>吊销</button></form>'
|
|
2255
|
+
+ `<form method="post" style="display:inline"><input type="hidden" name="id" value="${device.id}">`
|
|
2256
|
+
+ '<input type="hidden" name="action" value="remove"><button class="danger">删除</button></form>');
|
|
2257
|
+
}).join('');
|
|
2258
|
+
const revokedRows = revoked.length === 0 ? '' : revoked.map((device) => row(device,
|
|
2259
|
+
`<form method="post" style="display:inline"><input type="hidden" name="id" value="${device.id}">`
|
|
2260
|
+
+ '<input type="hidden" name="action" value="remove"><button>删除记录</button></form>')).join('');
|
|
2261
|
+
res.writeHead(200, {
|
|
2262
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2263
|
+
'cache-control': 'no-store',
|
|
2264
|
+
'x-frame-options': 'DENY',
|
|
2265
|
+
'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:",
|
|
2266
|
+
'x-content-type-options': 'nosniff',
|
|
2267
|
+
'referrer-policy': 'no-referrer',
|
|
2268
|
+
});
|
|
2269
|
+
res.end(`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
2270
|
+
<title>设备管理</title>
|
|
2271
|
+
<style>
|
|
2272
|
+
:root{color-scheme:dark}body{font:16px/1.6 -apple-system,system-ui,"Segoe UI",Roboto,sans-serif;margin:0;padding:24px;background:#15171c;color:#e6e8ee}
|
|
2273
|
+
h1{font-size:20px;margin:0 0 6px}p.sub{color:#9aa3b2;margin:0 0 22px;font-size:14px}
|
|
2274
|
+
table{width:100%;border-collapse:collapse;font-size:14px}th,td{text-align:left;padding:10px 8px;border-bottom:1px solid #262a33;vertical-align:top}
|
|
2275
|
+
th{color:#9aa3b2;font-weight:500;font-size:12px}
|
|
2276
|
+
.id{color:#6b7280;font-size:12px;font-family:ui-monospace,Consolas,monospace}
|
|
2277
|
+
button{background:#2b3140;color:#e6e8ee;border:1px solid #3a4152;border-radius:8px;padding:6px 12px;font-size:13px;cursor:pointer}
|
|
2278
|
+
button:hover{background:#353c4d}.muted{color:#6b7280}
|
|
2279
|
+
.msg{background:#1e2a1f;border:1px solid #2f4a33;color:#a5d6a7;padding:10px 12px;border-radius:8px;margin-bottom:16px;font-size:14px}
|
|
2280
|
+
h2{font-size:15px;color:#9aa3b2;margin:28px 0 6px}
|
|
2281
|
+
.badge{display:inline-block;background:#1f3a2b;color:#8fd8a8;border-radius:6px;padding:2px 8px;font-size:12px;margin-right:6px}
|
|
2282
|
+
button.danger{background:#3a2226;border-color:#54303a;color:#f0b6bf}
|
|
2283
|
+
a{color:#8ab4f8}
|
|
2284
|
+
</style>
|
|
2285
|
+
<h1>设备管理</h1>
|
|
2286
|
+
<p class="sub"><a href="/dsh_homing/account">← 返回账户设置</a></p>
|
|
2287
|
+
<p class="sub">每台配对过的手机/浏览器各占一条。吊销后它的下一次请求立即失效,不用改密码、不用重启。</p>
|
|
2288
|
+
${message ? `<div class="msg">${escapeHtml(message)}</div>` : ''}
|
|
2289
|
+
<table><thead><tr><th>设备</th><th>最后活跃</th><th>配对日期</th><th></th></tr></thead>
|
|
2290
|
+
<tbody>${activeRows}</tbody></table>
|
|
2291
|
+
${revokedRows ? `<h2>已吊销</h2><table><tbody>${revokedRows}</tbody></table>` : ''}
|
|
2292
|
+
<p class="sub" style="margin-top:26px">要新增设备:把带 <code>?k=</code> 的入口链接发到那台手机,打开一次即完成配对。<br>
|
|
2293
|
+
入口链接:在电脑上运行 <code>node bin/entry-link.mjs</code>。</p>`);
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
// 入口闸门:只认签名令牌或签名 Cookie。
|
|
2298
|
+
// 浏览器(Accept 含 text/html)访问未放行路径时,**引导去登录**而不是给死胡同 404:
|
|
2299
|
+
// 登录成功即证明持有凭据,之后由登录分支自动补设备令牌(ensureDeviceCookie),
|
|
2300
|
+
// 用户不需要再去开外部配对链接。非浏览器的探测仍回 404,不暴露"这里有个门"。
|
|
2301
|
+
if (!isLoginPath && !entryAllowed(req, url)) {
|
|
2302
|
+
try {
|
|
2303
|
+
const jar = readCookies(req.headers.cookie);
|
|
2304
|
+
appendAudit(dir, 'gate-redirect', {
|
|
2305
|
+
path: url.pathname,
|
|
2306
|
+
cookieNames: Object.keys(jar).join(','),
|
|
2307
|
+
hasDevice: Boolean(jar[DEVICE_COOKIE]),
|
|
2308
|
+
hasSession: Boolean(jar[SESSION_COOKIE]),
|
|
2309
|
+
ua: String(req.headers['user-agent'] ?? '').slice(0, 40),
|
|
2310
|
+
});
|
|
2311
|
+
} catch { /* 诊断不影响响应 */ }
|
|
2312
|
+
|
|
2313
|
+
const wantsHtml = String(req.headers.accept ?? '').includes('text/html');
|
|
2314
|
+
if (wantsHtml && (url.pathname === '/' || url.pathname === '')) {
|
|
2315
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2316
|
+
res.end();
|
|
2317
|
+
return;
|
|
2318
|
+
}
|
|
2319
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2320
|
+
res.end('Not Found\n');
|
|
2321
|
+
return;
|
|
2322
|
+
}
|
|
2323
|
+
// 首次带 ?k= 进来:登记一台设备、发设备令牌,再 303 到干净 URL
|
|
2324
|
+
// (令牌不进地址栏/历史;之后靠 dsh-homing-device Cookie 长期放行)
|
|
2325
|
+
if (!isLoginPath && config.entryGate !== false) {
|
|
2326
|
+
const token = url.searchParams.get('k');
|
|
2327
|
+
if (token && entryExpiry(token) > 0 && currentDevice(req) === null) {
|
|
2328
|
+
const activeCount = deviceStore.partition(devices()).active.length;
|
|
2329
|
+
const maxDevices = Number(config.maxDevices) > 0 ? Number(config.maxDevices) : 20;
|
|
2330
|
+
if (activeCount >= maxDevices) {
|
|
2331
|
+
appendAudit(dir, 'device-pair-refused', { activeCount, maxDevices });
|
|
2332
|
+
res.writeHead(429, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2333
|
+
res.end(`已配对设备达到上限(${maxDevices} 台),请先在设备管理页删除不用的设备。\n`);
|
|
2334
|
+
return;
|
|
2335
|
+
}
|
|
2336
|
+
const created = deviceStore.createDevice(devices(), {
|
|
2337
|
+
userAgent: String(req.headers['user-agent'] ?? ''),
|
|
2338
|
+
ip: clientKey(req),
|
|
2339
|
+
});
|
|
2340
|
+
persistDevices(created.state);
|
|
2341
|
+
appendAudit(dir, 'device-paired', { id: created.record.id, name: created.record.name });
|
|
2342
|
+
console.log(`[dsh-homing] 新设备已配对:${created.record.name} (${created.record.id})`);
|
|
2343
|
+
url.searchParams.delete('k');
|
|
2344
|
+
res.writeHead(303, {
|
|
2345
|
+
location: `${url.pathname}${url.search}`,
|
|
2346
|
+
'cache-control': 'no-store',
|
|
2347
|
+
'set-cookie': `${DEVICE_COOKIE}=${created.token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${DEVICE_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
2348
|
+
});
|
|
2349
|
+
res.end();
|
|
2350
|
+
return;
|
|
2351
|
+
}
|
|
2352
|
+
} // 登录
|
|
2353
|
+
if (config.login) {
|
|
2354
|
+
const ip = clientKey(req);
|
|
2355
|
+
if (url.pathname === '/login') {
|
|
2356
|
+
if (req.method === 'POST') {
|
|
2357
|
+
const deviceForLimit = currentDevice(req);
|
|
2358
|
+
const limitKey = deviceForLimit ? deviceForLimit.id : null;
|
|
2359
|
+
const now = Date.now();
|
|
2360
|
+
limits.pruneEntries(loginFailures, now);
|
|
2361
|
+
|
|
2362
|
+
// 硬锁只对「已验证设备」生效。unpaired 是所有人共享的桶,
|
|
2363
|
+
// 锁它等于给攻击者一个挡住所有新设备的开关。
|
|
2364
|
+
const bucket = limitKey ? loginFailures.get(limitKey) : undefined;
|
|
2365
|
+
if (limitKey && limits.isBlocked(bucket, now)) {
|
|
2366
|
+
const wait = limits.blockSecondsLeft(bucket, now);
|
|
2367
|
+
appendAudit(dir, 'login-blocked', { key: limitKey });
|
|
2368
|
+
res.writeHead(429, {
|
|
2369
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
2370
|
+
'cache-control': 'no-store',
|
|
2371
|
+
'retry-after': String(wait),
|
|
2372
|
+
});
|
|
2373
|
+
res.end(`尝试次数过多,请 ${Math.ceil(wait / 60)} 分钟后再试。\n`);
|
|
2374
|
+
return;
|
|
2375
|
+
}
|
|
2376
|
+
|
|
2377
|
+
// 延迟的「惩罚归属」按身份分开:
|
|
2378
|
+
// - 已配对设备:只看自己桶里的失败次数 → 匿名洪水拖不到你
|
|
2379
|
+
// - 匿名请求:共用全局桶(只延迟、不锁定)→ 洪水只惩罚陌生访客
|
|
2380
|
+
const maxDelay = Number(config.loginMaxDelayMs) || limits.DEFAULTS.maxDelayMs;
|
|
2381
|
+
const globalEntry = loginFailures.get('__global__');
|
|
2382
|
+
const globalRecent = globalEntry && now - globalEntry.first < limits.DEFAULTS.windowMs ? globalEntry.count : 0;
|
|
2383
|
+
const delayBase = limitKey ? (bucket ? bucket.count : 0) : globalRecent;
|
|
2384
|
+
const delayMs = limits.delayForFailures(delayBase, maxDelay);
|
|
2385
|
+
if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
2386
|
+
|
|
2387
|
+
const form = new URLSearchParams(await readBody(req));
|
|
2388
|
+
const username = form.get('username') ?? '';
|
|
2389
|
+
const password = form.get('password') ?? '';
|
|
2390
|
+
const code = (form.get('code') ?? '').trim();
|
|
2391
|
+
const ok = safeEqual(username, auth.username) && password.length > 0 && password.length <= 256 && passwordMatches(password);
|
|
2392
|
+
|
|
2393
|
+
const recordFailure = (event) => {
|
|
2394
|
+
if (limitKey) {
|
|
2395
|
+
// 已配对设备:只记自己的桶,互不影响
|
|
2396
|
+
loginFailures.set(limitKey, limits.registerFailure(loginFailures.get(limitKey), Date.now(), { perKeyMax: Number(config.loginPerKeyMax) || limits.DEFAULTS.perKeyMax }));
|
|
2397
|
+
} else {
|
|
2398
|
+
// 匿名:只记全局桶(只用来算延迟,永不锁定)
|
|
2399
|
+
loginFailures.set('__global__', limits.bumpCounter(loginFailures.get('__global__'), Date.now()));
|
|
2400
|
+
}
|
|
2401
|
+
appendAudit(dir, event, { key: limitKey ?? 'unpaired' });
|
|
2402
|
+
};
|
|
2403
|
+
const clearFailures = () => {
|
|
2404
|
+
if (limitKey) loginFailures.delete(limitKey);
|
|
2405
|
+
loginFailures.delete('__global__');
|
|
2406
|
+
};
|
|
2407
|
+
|
|
2408
|
+
if (ok && auth.totpSecret) {
|
|
2409
|
+
if (!verifyTotp(auth.totpSecret, code, lastTotpStep)) {
|
|
2410
|
+
recordFailure('totp-fail');
|
|
2411
|
+
sendLogin(res, '<div class="err">验证码不正确。</div>', true);
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
lastTotpStep = currentTotpStep();
|
|
2415
|
+
}
|
|
2416
|
+
if (ok) {
|
|
2417
|
+
clearFailures();
|
|
2418
|
+
// 登录成功说明密码/验证器都已就位:把落盘的明文凭据(密码、TOTP 密钥)删掉
|
|
2419
|
+
appendAudit(dir, 'login-ok', { ip, ua: String(req.headers['user-agent'] ?? '').slice(0, 120) });
|
|
2420
|
+
for (const name of ['auth-initial.txt', 'auth-totp.txt']) {
|
|
2421
|
+
try {
|
|
2422
|
+
fs.rmSync(path.join(dir, name), { force: true });
|
|
2423
|
+
} catch { /* 删不掉就留着,不影响登录 */ }
|
|
2424
|
+
}
|
|
2425
|
+
// 登录成功即视为「这台设备可信」:顺便补齐设备令牌
|
|
2426
|
+
const cookies = [];
|
|
2427
|
+
const sessionDevice = ensureDeviceCookie(req, cookies);
|
|
2428
|
+
if (!sessionDevice) {
|
|
2429
|
+
sendLogin(res, '<div class="err">设备数量已达上限,请先在设备管理页删除不用的设备。</div>', Boolean(auth.totpSecret));
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
2432
|
+
cookies.unshift(
|
|
2433
|
+
`${SESSION_COOKIE}=${signSession(Date.now() + SESSION_SECONDS * 1000, sessionDevice)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_SECONDS}${secureCookies ? '; Secure' : ''}`,
|
|
2434
|
+
);
|
|
2435
|
+
res.writeHead(303, {
|
|
2436
|
+
location: '/',
|
|
2437
|
+
'cache-control': 'no-store',
|
|
2438
|
+
'set-cookie': cookies,
|
|
2439
|
+
});
|
|
2440
|
+
res.end();
|
|
2441
|
+
return;
|
|
2442
|
+
}
|
|
2443
|
+
recordFailure('login-fail');
|
|
2444
|
+
sendLogin(res, '<div class="err">用户名或密码不正确。</div>', Boolean(auth.totpSecret));
|
|
2445
|
+
return;
|
|
2446
|
+
}
|
|
2447
|
+
if (sessionValid(req)) {
|
|
2448
|
+
const cookies = [];
|
|
2449
|
+
ensureDeviceCookie(req, cookies);
|
|
2450
|
+
res.writeHead(303, {
|
|
2451
|
+
location: '/',
|
|
2452
|
+
'cache-control': 'no-store',
|
|
2453
|
+
...(cookies.length > 0 ? { 'set-cookie': cookies } : {}),
|
|
2454
|
+
});
|
|
2455
|
+
res.end();
|
|
2456
|
+
return;
|
|
2457
|
+
}
|
|
2458
|
+
sendLogin(res, '', Boolean(auth.totpSecret));
|
|
2459
|
+
return;
|
|
2460
|
+
}
|
|
2461
|
+
if (url.pathname === '/logout') {
|
|
2462
|
+
appendAudit(dir, 'logout', { ip: clientKey(req) });
|
|
2463
|
+
res.writeHead(303, {
|
|
2464
|
+
location: '/login',
|
|
2465
|
+
'cache-control': 'no-store',
|
|
2466
|
+
'set-cookie': `${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`,
|
|
2467
|
+
});
|
|
2468
|
+
res.end();
|
|
2469
|
+
return;
|
|
2470
|
+
}
|
|
2471
|
+
if (!sessionValid(req) && currentDevice(req) === null) {
|
|
2472
|
+
if (req.method === 'GET' && String(req.headers.accept ?? '').includes('text/html')) {
|
|
2473
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2474
|
+
res.end();
|
|
2475
|
+
} else {
|
|
2476
|
+
// 诊断:把会话校验失败的细节记进审计,区分"没收到 cookie"与"收到但校验不过"
|
|
2477
|
+
try {
|
|
2478
|
+
const jar = readCookies(req.headers.cookie);
|
|
2479
|
+
const raw = jar[SESSION_COOKIE];
|
|
2480
|
+
const parts = typeof raw === 'string' ? raw.split('.') : [];
|
|
2481
|
+
const boundDevice = parts.length === 4 ? parts[2] : null;
|
|
2482
|
+
const known = boundDevice ? devices().devices.some((item) => item.id === boundDevice) : false;
|
|
2483
|
+
appendAudit(dir, 'session-invalid', {
|
|
2484
|
+
path: url.pathname,
|
|
2485
|
+
hasDeviceCookie: Boolean(jar[DEVICE_COOKIE]),
|
|
2486
|
+
hasSessionCookie: Boolean(raw),
|
|
2487
|
+
sessionShape: parts.length,
|
|
2488
|
+
boundDevice,
|
|
2489
|
+
deviceKnown: known,
|
|
2490
|
+
cookieNames: Object.keys(jar).join(','),
|
|
2491
|
+
});
|
|
2492
|
+
} catch { /* 诊断失败不影响响应 */ }
|
|
2493
|
+
res.writeHead(401, { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' });
|
|
2494
|
+
res.end('请先登录:/login\n');
|
|
2495
|
+
}
|
|
2496
|
+
return;
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
|
|
2500
|
+
// 账户页:改密码 / 开启二次验证 / 看登录记录(必须先登录)
|
|
2501
|
+
if (url.pathname === '/dsh_homing/account') {
|
|
2502
|
+
const ip = clientKey(req);
|
|
2503
|
+
if (!sessionValid(req)) {
|
|
2504
|
+
res.writeHead(303, { location: '/login', 'cache-control': 'no-store' });
|
|
2505
|
+
res.end();
|
|
2506
|
+
return;
|
|
2507
|
+
}
|
|
2508
|
+
const message = url.searchParams.get('ok') === '1' ? '已保存。' : (url.searchParams.get('msg') ?? '');
|
|
2509
|
+
if (req.method === 'POST') {
|
|
2510
|
+
const form = new URLSearchParams(await readBody(req));
|
|
2511
|
+
const action = form.get('action') ?? '';
|
|
2512
|
+
const save = () => fs.writeFileSync(
|
|
2513
|
+
path.join(dir, 'auth.json'),
|
|
2514
|
+
`${JSON.stringify(auth, null, 2)}\n`,
|
|
2515
|
+
{ encoding: 'utf8', mode: 0o600 },
|
|
2516
|
+
);
|
|
2517
|
+
const fail = (text) => {
|
|
2518
|
+
res.writeHead(303, { location: `/dsh_homing/account?msg=${encodeURIComponent(text)}`, 'cache-control': 'no-store' });
|
|
2519
|
+
res.end();
|
|
2520
|
+
};
|
|
2521
|
+
|
|
2522
|
+
if (action === 'password') {
|
|
2523
|
+
const current = form.get('current') ?? '';
|
|
2524
|
+
const next = form.get('next') ?? '';
|
|
2525
|
+
const confirm = form.get('confirm') ?? '';
|
|
2526
|
+
if (!passwordMatches(current)) {
|
|
2527
|
+
appendAudit(dir, 'password-change-fail', { ip });
|
|
2528
|
+
fail('当前密码不正确');
|
|
2529
|
+
return;
|
|
2530
|
+
}
|
|
2531
|
+
if (next.length < 10) { fail('新密码至少 10 位'); return; }
|
|
2532
|
+
if (next !== confirm) { fail('两次输入的新密码不一致'); return; }
|
|
2533
|
+
const salt = crypto.randomBytes(16);
|
|
2534
|
+
auth.salt = salt.toString('base64');
|
|
2535
|
+
auth.hash = base64url(crypto.scryptSync(next, salt, 64));
|
|
2536
|
+
// 换密码同时换会话密钥 → 所有旧的登录会话 Cookie 立即失效(含其他设备)
|
|
2537
|
+
auth.sessionKey = base64url(crypto.randomBytes(32));
|
|
2538
|
+
auth.updatedAt = new Date().toISOString();
|
|
2539
|
+
save();
|
|
2540
|
+
|
|
2541
|
+
// 设备令牌与 sessionKey 无关(独立哈希落盘),必须显式吊销:
|
|
2542
|
+
// 否则「改密码」只把旧设备踢出登录态,它照样能过入口闸。
|
|
2543
|
+
// 保留当前请求者那一台,其余全部吊销。
|
|
2544
|
+
// 改密码 = 全面重置:连当前这台也一起吊销,所有浏览器都必须重新登录
|
|
2545
|
+
const deviceSnapshot = devices();
|
|
2546
|
+
let revokedDevices = 0;
|
|
2547
|
+
for (const device of deviceSnapshot.devices) {
|
|
2548
|
+
if (device.revokedAt === null) {
|
|
2549
|
+
device.revokedAt = new Date().toISOString();
|
|
2550
|
+
revokedDevices += 1;
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
if (revokedDevices > 0) persistDevices(deviceSnapshot);
|
|
2554
|
+
|
|
2555
|
+
appendAudit(dir, 'password-change', { ip, revokedDevices, allDevicesRevoked: true });
|
|
2556
|
+
res.writeHead(303, {
|
|
2557
|
+
// 不再换发新会话:连当前浏览器也要重新登录
|
|
2558
|
+
location: '/login',
|
|
2559
|
+
'cache-control': 'no-store',
|
|
2560
|
+
'set-cookie': [
|
|
2561
|
+
`${SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`,
|
|
2562
|
+
`${DEVICE_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0${secureCookies ? '; Secure' : ''}`,
|
|
2563
|
+
],
|
|
2564
|
+
});
|
|
2565
|
+
res.end();
|
|
2566
|
+
return;
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
if (action === 'totp-start') {
|
|
2570
|
+
auth.totpPending = base32Encode(crypto.randomBytes(20));
|
|
2571
|
+
save();
|
|
2572
|
+
res.writeHead(303, { location: '/dsh_homing/account', 'cache-control': 'no-store' });
|
|
2573
|
+
res.end();
|
|
2574
|
+
return;
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
if (action === 'totp-cancel') {
|
|
2578
|
+
if (!auth.totpPending) { fail('没有待确认的密钥'); return; }
|
|
2579
|
+
delete auth.totpPending;
|
|
2580
|
+
save();
|
|
2581
|
+
appendAudit(dir, 'totp-cancelled', { ip });
|
|
2582
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2583
|
+
res.end();
|
|
2584
|
+
return;
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
if (action === 'totp-confirm') {
|
|
2588
|
+
const code = (form.get('code') ?? '').trim();
|
|
2589
|
+
if (!auth.totpPending) { fail('没有待确认的密钥,请重新点「生成」'); return; }
|
|
2590
|
+
if (!verifyTotp(auth.totpPending, code, 0)) { fail('验证码不对,请用验证器里最新的 6 位'); return; }
|
|
2591
|
+
auth.totpSecret = auth.totpPending;
|
|
2592
|
+
delete auth.totpPending;
|
|
2593
|
+
save();
|
|
2594
|
+
appendAudit(dir, 'totp-enabled', { ip });
|
|
2595
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2596
|
+
res.end();
|
|
2597
|
+
return;
|
|
2598
|
+
}
|
|
2599
|
+
|
|
2600
|
+
if (action === 'totp-disable') {
|
|
2601
|
+
if (!passwordMatches(form.get('current') ?? '')) { fail('当前密码不正确'); return; }
|
|
2602
|
+
delete auth.totpSecret;
|
|
2603
|
+
delete auth.totpPending;
|
|
2604
|
+
save();
|
|
2605
|
+
appendAudit(dir, 'totp-disabled', { ip });
|
|
2606
|
+
res.writeHead(303, { location: '/dsh_homing/account?ok=1', 'cache-control': 'no-store' });
|
|
2607
|
+
res.end();
|
|
2608
|
+
return;
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
fail('未知操作');
|
|
2612
|
+
return;
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
let recent = [];
|
|
2616
|
+
try {
|
|
2617
|
+
recent = fs.readFileSync(path.join(dir, 'audit.log'), 'utf8').trim().split('\n').slice(-8).reverse();
|
|
2618
|
+
} catch { /* 还没有日志 */ }
|
|
2619
|
+
const totpOn = Boolean(auth.totpSecret);
|
|
2620
|
+
const pending = auth.totpPending;
|
|
2621
|
+
const otpauth = pending
|
|
2622
|
+
? `otpauth://totp/${encodeURIComponent('DSH Homing')}:${encodeURIComponent(auth.username)}?secret=${pending}&issuer=${encodeURIComponent('DSH Homing')}&algorithm=SHA1&digits=6&period=30`
|
|
2623
|
+
: '';
|
|
2624
|
+
const html = ACCOUNT_HTML
|
|
2625
|
+
.replaceAll('{{username}}', escapeHtml(auth.username))
|
|
2626
|
+
.replaceAll('{{message}}', message ? `<div class="msg">${escapeHtml(message)}</div>` : '')
|
|
2627
|
+
.replaceAll('{{totpState}}', totpOn ? '已开启' : (pending ? '待确认(按下面的步骤录入验证器)' : '未开启'))
|
|
2628
|
+
.replaceAll('{{totpBlock}}', totpOn
|
|
2629
|
+
? `<p>当前已开启二次验证。</p>
|
|
2630
|
+
<form method="post"><input type="hidden" name="action" value="totp-disable">
|
|
2631
|
+
<label>当前密码(关闭前确认身份)</label><input type="password" name="current" required>
|
|
2632
|
+
<button type="submit" class="danger">关闭二次验证</button></form>
|
|
2633
|
+
<p class="sub" style="margin-top:10px;color:#9aa3b2;font-size:13px">关闭后只靠密码登录。如果是为了换一部手机,建议先生成新密钥开启,再关闭旧的。</p>`
|
|
2634
|
+
: pending
|
|
2635
|
+
? `<p>把下面这串密钥录入验证器(Google Authenticator / Microsoft Authenticator / 1Password,类型选「基于时间 TOTP」),再输入它显示的 6 位码完成开启。</p>
|
|
2636
|
+
<div class="secret">${escapeHtml(pending)}</div>
|
|
2637
|
+
<div class="uri">${escapeHtml(otpauth)}</div>
|
|
2638
|
+
<form method="post">
|
|
2639
|
+
<label>验证器里的 6 位验证码</label><input name="code" inputmode="numeric" maxlength="6" required>
|
|
2640
|
+
<div style="display:flex;gap:8px;margin-top:20px">
|
|
2641
|
+
<button type="submit" name="action" value="totp-confirm" style="margin-top:0;flex:1">确认开启</button>
|
|
2642
|
+
<button type="submit" name="action" value="totp-cancel" formnovalidate style="margin-top:0;flex:1;background:#2a2f3a;color:#c7cdd8">取消</button>
|
|
2643
|
+
</div></form>`
|
|
2644
|
+
: `<p>开启后每次登录都要输入验证器里的 6 位码,即使密码泄露也进不来。</p>
|
|
2645
|
+
<form method="post"><input type="hidden" name="action" value="totp-start">
|
|
2646
|
+
<button type="submit">生成密钥</button></form>`)
|
|
2647
|
+
.replaceAll('{{audit}}', recent.length
|
|
2648
|
+
? recent.map((line) => {
|
|
2649
|
+
try {
|
|
2650
|
+
const item = JSON.parse(line);
|
|
2651
|
+
return `<li><code>${escapeHtml(item.t)}</code> ${escapeHtml(item.event)}</li>`;
|
|
2652
|
+
} catch {
|
|
2653
|
+
return '';
|
|
2654
|
+
}
|
|
2655
|
+
}).join('')
|
|
2656
|
+
: '<li>暂无记录</li>');
|
|
2657
|
+
const deviceCookies = [];
|
|
2658
|
+
ensureDeviceCookie(req, deviceCookies);
|
|
2659
|
+
res.writeHead(200, {
|
|
2660
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2661
|
+
'cache-control': 'no-store',
|
|
2662
|
+
'x-frame-options': 'DENY',
|
|
2663
|
+
'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:",
|
|
2664
|
+
'x-content-type-options': 'nosniff',
|
|
2665
|
+
'referrer-policy': 'no-referrer',
|
|
2666
|
+
...(deviceCookies.length > 0 ? { 'set-cookie': deviceCookies } : {}),
|
|
2667
|
+
});
|
|
2668
|
+
res.end(html);
|
|
2669
|
+
return;
|
|
2670
|
+
}
|
|
2671
|
+
|
|
2672
|
+
const port = getUpstreamPort();
|
|
2673
|
+
if (!port) {
|
|
2674
|
+
res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2675
|
+
res.end('DSH 的 Web 服务还没就绪。\n');
|
|
2676
|
+
return;
|
|
2677
|
+
}
|
|
2678
|
+
|
|
2679
|
+
const authority = `127.0.0.1:${port}`;
|
|
2680
|
+
const headers = await rewriteHeaders(req.headers, authority);
|
|
2681
|
+
// 体积上限:TLS 透传后 nginx 不再解析 HTTP,client_max_body_size 已失效,这里补回来
|
|
2682
|
+
const declaredLength = limits.checkDeclaredLength(req.headers['content-length'], config.maxBodyBytes);
|
|
2683
|
+
if (declaredLength.over) {
|
|
2684
|
+
appendAudit(dir, 'body-too-large', { declared: declaredLength.declared, limit: declaredLength.limit });
|
|
2685
|
+
// 先回响应再断连:先 destroy 会让客户端只看到连接重置、拿不到 413
|
|
2686
|
+
res.writeHead(413, {
|
|
2687
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
2688
|
+
'cache-control': 'no-store',
|
|
2689
|
+
connection: 'close',
|
|
2690
|
+
});
|
|
2691
|
+
res.end(`请求体超过上限(${Math.round(declaredLength.limit / 1024 / 1024)} MB)。\n`, () => { req.destroy(); });
|
|
2692
|
+
return;
|
|
2693
|
+
}
|
|
2694
|
+
const upstream = http.request({
|
|
2695
|
+
host: '127.0.0.1',
|
|
2696
|
+
port,
|
|
2697
|
+
method: req.method,
|
|
2698
|
+
path: req.url,
|
|
2699
|
+
headers,
|
|
2700
|
+
timeout: 0,
|
|
2701
|
+
}, (upstreamRes) => {
|
|
2702
|
+
const contentType = String(upstreamRes.headers['content-type'] ?? '');
|
|
2703
|
+
if (contentType.includes('text/html')) {
|
|
2704
|
+
const chunks = [];
|
|
2705
|
+
upstreamRes.on('data', (chunk) => chunks.push(chunk));
|
|
2706
|
+
upstreamRes.on('end', () => {
|
|
2707
|
+
let raw = Buffer.concat(chunks);
|
|
2708
|
+
const encoding = String(upstreamRes.headers['content-encoding'] ?? '').toLowerCase();
|
|
2709
|
+
try {
|
|
2710
|
+
if (encoding === 'gzip') raw = zlib.gunzipSync(raw);
|
|
2711
|
+
else if (encoding === 'br') raw = zlib.brotliDecompressSync(raw);
|
|
2712
|
+
else if (encoding === 'deflate') raw = zlib.inflateSync(raw);
|
|
2713
|
+
} catch {
|
|
2714
|
+
// 解不开就原样返回
|
|
2715
|
+
}
|
|
2716
|
+
const injectionOff = readCookies(req.headers.cookie)[MOBILE_OFF_COOKIE] === '1';
|
|
2717
|
+
const html = injectionOff
|
|
2718
|
+
? raw.toString('utf8')
|
|
2719
|
+
: raw.toString('utf8').replace('</head>', `${INJECTION}</head>`);
|
|
2720
|
+
const body = Buffer.from(html, 'utf8');
|
|
2721
|
+
const outHeaders = { ...upstreamRes.headers };
|
|
2722
|
+
delete outHeaders['content-encoding'];
|
|
2723
|
+
delete outHeaders['transfer-encoding'];
|
|
2724
|
+
outHeaders['content-length'] = String(body.length);
|
|
2725
|
+
res.writeHead(upstreamRes.statusCode ?? 200, outHeaders);
|
|
2726
|
+
res.end(body);
|
|
2727
|
+
});
|
|
2728
|
+
return;
|
|
2729
|
+
}
|
|
2730
|
+
// 透传模式下 nginx 不再加缓存头,由插件补上(手机端第二次打开快很多)
|
|
2731
|
+
const staticHeaders = { ...upstreamRes.headers };
|
|
2732
|
+
if (url.pathname.startsWith('/assets/')) {
|
|
2733
|
+
staticHeaders['cache-control'] = 'public, max-age=31536000, immutable';
|
|
2734
|
+
} else if (url.pathname.startsWith('/plugins/')) {
|
|
2735
|
+
staticHeaders['cache-control'] = 'public, max-age=604800';
|
|
2736
|
+
}
|
|
2737
|
+
staticHeaders['strict-transport-security'] = 'max-age=31536000';
|
|
2738
|
+
res.writeHead(upstreamRes.statusCode ?? 502, staticHeaders);
|
|
2739
|
+
upstreamRes.pipe(res);
|
|
2740
|
+
});
|
|
2741
|
+
|
|
2742
|
+
upstream.on('error', (error) => {
|
|
2743
|
+
if (!res.headersSent) {
|
|
2744
|
+
res.writeHead(502, { 'content-type': 'text/plain; charset=utf-8' });
|
|
2745
|
+
res.end(`上游 DSH 不可达:${error.message}\n`);
|
|
2746
|
+
} else {
|
|
2747
|
+
res.destroy();
|
|
2748
|
+
}
|
|
2749
|
+
});
|
|
2750
|
+
req.pipe(upstream);
|
|
2751
|
+
// 分块上传(没有 content-length)时也能截断
|
|
2752
|
+
const bodySize = limits.createByteCounter(config.maxBodyBytes);
|
|
2753
|
+
req.on('data', (chunk) => {
|
|
2754
|
+
if (!bodySize.add(chunk.length)) return;
|
|
2755
|
+
appendAudit(dir, 'body-too-large', { streamed: bodySize.total, limit: bodySize.limit });
|
|
2756
|
+
upstream.destroy();
|
|
2757
|
+
if (!res.headersSent) {
|
|
2758
|
+
res.writeHead(413, {
|
|
2759
|
+
'content-type': 'text/plain; charset=utf-8',
|
|
2760
|
+
'cache-control': 'no-store',
|
|
2761
|
+
connection: 'close',
|
|
2762
|
+
});
|
|
2763
|
+
res.end('请求体超过上限。\n', () => { req.destroy(); });
|
|
2764
|
+
} else {
|
|
2765
|
+
res.destroy();
|
|
2766
|
+
req.destroy();
|
|
2767
|
+
}
|
|
2768
|
+
});
|
|
2769
|
+
req.on('aborted', () => upstream.destroy());
|
|
2770
|
+
};
|
|
2771
|
+
|
|
2772
|
+
const onUpgrade = async (req, socket, head) => {
|
|
2773
|
+
const url = new URL(req.url ?? '/', 'http://dsh-homing.invalid');
|
|
2774
|
+
// WebSocket 握手同样校验来源:跨站页面可以发起带 Cookie 的 WS 连接
|
|
2775
|
+
if (!checkUnsafeOrigin({ method: 'POST', headers: req.headers }).ok) {
|
|
2776
|
+
socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
if (!entryAllowed(req, url)) {
|
|
2780
|
+
socket.end('HTTP/1.1 403 Forbidden\r\ncontent-length: 0\r\n\r\n');
|
|
2781
|
+
return;
|
|
2782
|
+
}
|
|
2783
|
+
if (config.login && !sessionValid(req)) {
|
|
2784
|
+
socket.end('HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\n\r\n');
|
|
2785
|
+
return;
|
|
2786
|
+
}
|
|
2787
|
+
const port = getUpstreamPort();
|
|
2788
|
+
if (!port) {
|
|
2789
|
+
socket.end('HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\n\r\n');
|
|
2790
|
+
return;
|
|
2791
|
+
}
|
|
2792
|
+
const authority = `127.0.0.1:${port}`;
|
|
2793
|
+
const headers = await rewriteHeaders(req.headers, authority);
|
|
2794
|
+
const lines = [];
|
|
2795
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
2796
|
+
if (value === undefined) continue;
|
|
2797
|
+
for (const item of Array.isArray(value) ? value : [value]) lines.push(`${key}: ${item}`);
|
|
2798
|
+
}
|
|
2799
|
+
const requestText = `${req.method} ${req.url} HTTP/1.1\r\n${lines.join('\r\n')}\r\n\r\n`;
|
|
2800
|
+
const upstream = net.connect({ host: '127.0.0.1', port }, () => {
|
|
2801
|
+
upstream.write(requestText, 'latin1');
|
|
2802
|
+
if (head?.length) upstream.write(head);
|
|
2803
|
+
upstream.pipe(socket);
|
|
2804
|
+
socket.pipe(upstream);
|
|
2805
|
+
});
|
|
2806
|
+
upstream.on('error', () => socket.destroy());
|
|
2807
|
+
socket.on('error', () => upstream.destroy());
|
|
2808
|
+
socket.on('close', () => upstream.destroy());
|
|
2809
|
+
};
|
|
2810
|
+
|
|
2811
|
+
return { handler, onUpgrade };
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
/* ------------------------------------------------------------------ *
|
|
2815
|
+
* SSH 反向隧道(跨平台)
|
|
2816
|
+
* ------------------------------------------------------------------ */
|
|
2817
|
+
|
|
2818
|
+
function findSsh() {
|
|
2819
|
+
const candidates = process.platform === 'win32'
|
|
2820
|
+
? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'), 'ssh.exe', 'ssh']
|
|
2821
|
+
: ['/usr/bin/ssh', '/usr/local/bin/ssh', 'ssh'];
|
|
2822
|
+
for (const candidate of candidates) {
|
|
2823
|
+
if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
|
|
2824
|
+
return candidate;
|
|
2825
|
+
}
|
|
2826
|
+
return undefined;
|
|
2827
|
+
}
|
|
2828
|
+
|
|
2829
|
+
/**
|
|
2830
|
+
* 在服务器上跑一段脚本(base64 送达,以 root 执行),返回 stdout。
|
|
2831
|
+
* 只用于只读操作。
|
|
2832
|
+
*/
|
|
2833
|
+
function runServerScript(config, script, timeoutMs = 20000) {
|
|
2834
|
+
return new Promise((resolve) => {
|
|
2835
|
+
const ssh = findSsh();
|
|
2836
|
+
if (!ssh || !config.serverHost) {
|
|
2837
|
+
resolve(undefined);
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
const remote = `printf '%s' '${Buffer.from(script, 'utf8').toString('base64')}' | base64 -d | sudo -n sh`;
|
|
2841
|
+
const child = spawn(ssh, [
|
|
2842
|
+
'-i', config.sshKey,
|
|
2843
|
+
'-p', String(config.sshPort),
|
|
2844
|
+
'-o', 'BatchMode=yes',
|
|
2845
|
+
'-o', 'IdentitiesOnly=yes',
|
|
2846
|
+
'-o', 'StrictHostKeyChecking=accept-new',
|
|
2847
|
+
`${config.sshUser}@${config.serverHost}`,
|
|
2848
|
+
remote,
|
|
2849
|
+
], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
2850
|
+
let out = '';
|
|
2851
|
+
child.stdout.on('data', (chunk) => { out += String(chunk); });
|
|
2852
|
+
child.on('error', () => resolve(undefined));
|
|
2853
|
+
const timer = setTimeout(() => {
|
|
2854
|
+
try { child.kill(); } catch { /* ignore */ }
|
|
2855
|
+
resolve(undefined);
|
|
2856
|
+
}, timeoutMs);
|
|
2857
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
2858
|
+
child.on('close', () => {
|
|
2859
|
+
clearTimeout(timer);
|
|
2860
|
+
resolve(out);
|
|
2861
|
+
});
|
|
2862
|
+
});
|
|
2863
|
+
}
|
|
2864
|
+
|
|
2865
|
+
/**
|
|
2866
|
+
* 一次 SSH 拿到服务器的运行状态:
|
|
2867
|
+
* nginx 是否 active、proxy_pass 指向哪些端口、证书到期时间。
|
|
2868
|
+
* 服务器是唯一权威——本地 remotePort 和它不一致时以它为准。
|
|
2869
|
+
*/
|
|
2870
|
+
function readServerHealth(config) {
|
|
2871
|
+
return new Promise((resolve) => {
|
|
2872
|
+
const ssh = findSsh();
|
|
2873
|
+
if (!ssh || !config.serverHost) {
|
|
2874
|
+
resolve(undefined);
|
|
2875
|
+
return;
|
|
2876
|
+
}
|
|
2877
|
+
// 用 base64 把脚本送过去执行,彻底避开引号地狱;脚本以 root 运行(只读检查)
|
|
2878
|
+
const script = [
|
|
2879
|
+
'echo "nginx=$(systemctl is-active nginx 2>/dev/null)"',
|
|
2880
|
+
`echo "proxy=$(sudo -n grep -hE '127\\.0\\.0\\.1:[0-9]+' /etc/nginx/sites-enabled/* /etc/nginx/stream.d/*.conf 2>/dev/null | grep -vE '^[[:space:]]*#|default' | grep -oE '127\\.0\\.0\\.1:[0-9]+' 2>/dev/null | cut -d: -f2 | sort -u | paste -sd, -)"`,
|
|
2881
|
+
`echo "passthrough=$(sudo -n grep -l 'listen 443' /etc/nginx/stream.d/*.conf >/dev/null 2>&1 && echo yes || echo no)"`,
|
|
2882
|
+
'for f in /etc/letsencrypt/live/*/fullchain.pem; do',
|
|
2883
|
+
' d=$(basename "$(dirname "$f")")',
|
|
2884
|
+
' e=$(openssl x509 -enddate -noout -in "$f" 2>/dev/null | cut -d= -f2)',
|
|
2885
|
+
' [ -n "$e" ] && echo "cert=$d|$(date -d "$e" +%s)"',
|
|
2886
|
+
'done',
|
|
2887
|
+
].join('\n');
|
|
2888
|
+
const remote = `printf '%s' '${Buffer.from(script, 'utf8').toString('base64')}' | base64 -d | sudo -n sh`;
|
|
2889
|
+
const child = spawn(ssh, [
|
|
2890
|
+
'-i', config.sshKey,
|
|
2891
|
+
'-p', String(config.sshPort),
|
|
2892
|
+
'-o', 'BatchMode=yes',
|
|
2893
|
+
'-o', 'IdentitiesOnly=yes',
|
|
2894
|
+
'-o', 'StrictHostKeyChecking=accept-new',
|
|
2895
|
+
`${config.sshUser}@${config.serverHost}`,
|
|
2896
|
+
remote,
|
|
2897
|
+
], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
2898
|
+
let out = '';
|
|
2899
|
+
child.stdout.on('data', (chunk) => { out += String(chunk); });
|
|
2900
|
+
child.on('error', () => resolve(undefined));
|
|
2901
|
+
child.on('close', () => {
|
|
2902
|
+
const health = { nginx: undefined, ports: [], certs: [] };
|
|
2903
|
+
for (const line of out.split(/\r?\n/u)) {
|
|
2904
|
+
const at = line.indexOf('=');
|
|
2905
|
+
if (at === -1) continue;
|
|
2906
|
+
const key = line.slice(0, at).trim();
|
|
2907
|
+
const value = line.slice(at + 1).trim();
|
|
2908
|
+
if (key === 'nginx') health.nginx = value;
|
|
2909
|
+
else if (key === 'passthrough') health.passthrough = value === 'yes';
|
|
2910
|
+
else if (key === 'proxy') health.ports = value.split(',').map((item) => Number(item)).filter((item) => Number.isInteger(item) && item > 0);
|
|
2911
|
+
else if (key === 'cert') {
|
|
2912
|
+
const [domain, end] = value.split('|');
|
|
2913
|
+
if (domain && end) health.certs.push({ domain, endEpoch: Number(end) });
|
|
2914
|
+
}
|
|
2915
|
+
}
|
|
2916
|
+
resolve(health);
|
|
2917
|
+
});
|
|
2918
|
+
});
|
|
2919
|
+
}
|
|
2920
|
+
|
|
2921
|
+
/** 把服务器上发现的端口写回本机 settings.json。 */
|
|
2922
|
+
function persistRemotePort(dir, port) {
|
|
2923
|
+
const file = path.join(dir, 'settings.json');
|
|
2924
|
+
let current = {};
|
|
2925
|
+
try {
|
|
2926
|
+
current = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
2927
|
+
} catch {
|
|
2928
|
+
current = {};
|
|
2929
|
+
}
|
|
2930
|
+
current.remotePort = port;
|
|
2931
|
+
fs.writeFileSync(file, `${JSON.stringify(current, null, 2)}\n`, 'utf8');
|
|
2932
|
+
}
|
|
2933
|
+
|
|
2934
|
+
function createTunnel({ getConfig, dir }) {
|
|
2935
|
+
let child;
|
|
2936
|
+
let lastError = '';
|
|
2937
|
+
let stopped = false;
|
|
2938
|
+
let restartTimer;
|
|
2939
|
+
const logFile = path.join(dir, 'tunnel.log');
|
|
2940
|
+
|
|
2941
|
+
function log(message) {
|
|
2942
|
+
const line = `${new Date().toISOString()} ${message}`;
|
|
2943
|
+
try {
|
|
2944
|
+
const size = fs.existsSync(logFile) ? fs.statSync(logFile).size : 0;
|
|
2945
|
+
if (size > 1024 * 1024) fs.writeFileSync(logFile, '', 'utf8');
|
|
2946
|
+
fs.appendFileSync(logFile, `${line}\n`, 'utf8');
|
|
2947
|
+
} catch { /* 日志失败不影响隧道 */ }
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2950
|
+
function start() {
|
|
2951
|
+
const config = getConfig();
|
|
2952
|
+
if (stopped || !config.serverHost) return;
|
|
2953
|
+
const ssh = findSsh();
|
|
2954
|
+
if (!ssh) {
|
|
2955
|
+
log('找不到 ssh 命令,隧道不可用(Windows 需启用 OpenSSH 客户端,Linux/macOS 一般自带)');
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
2958
|
+
const args = [
|
|
2959
|
+
'-N',
|
|
2960
|
+
'-i', config.sshKey,
|
|
2961
|
+
'-p', String(config.sshPort),
|
|
2962
|
+
'-o', 'IdentitiesOnly=yes',
|
|
2963
|
+
'-o', 'BatchMode=yes',
|
|
2964
|
+
'-o', 'PreferredAuthentications=publickey',
|
|
2965
|
+
'-o', 'ExitOnForwardFailure=yes',
|
|
2966
|
+
'-o', 'ServerAliveInterval=30',
|
|
2967
|
+
'-o', 'ServerAliveCountMax=3',
|
|
2968
|
+
'-o', 'StrictHostKeyChecking=accept-new',
|
|
2969
|
+
'-R', `127.0.0.1:${config.remotePort}:127.0.0.1:${config.listenPort}`,
|
|
2970
|
+
`${config.sshUser}@${config.serverHost}`,
|
|
2971
|
+
];
|
|
2972
|
+
log(`启动隧道:服务器 127.0.0.1:${config.remotePort} <- 本机 127.0.0.1:${config.listenPort}(${config.sshUser}@${config.serverHost})`);
|
|
2973
|
+
lastError = '';
|
|
2974
|
+
child = spawn(ssh, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
2975
|
+
child.stdout?.on('data', (chunk) => log(String(chunk).trim()));
|
|
2976
|
+
child.stderr?.on('data', (chunk) => {
|
|
2977
|
+
const text = String(chunk).trim();
|
|
2978
|
+
if (text) lastError = text;
|
|
2979
|
+
log(text);
|
|
2980
|
+
});
|
|
2981
|
+
child.on('error', (error) => log(`隧道进程错误:${error.message}`));
|
|
2982
|
+
child.on('exit', (code) => {
|
|
2983
|
+
child = undefined;
|
|
2984
|
+
if (stopped) return;
|
|
2985
|
+
const portConflict = /remote port forwarding failed/u.test(lastError);
|
|
2986
|
+
log(`隧道退出(code=${code}),5 秒后重连`);
|
|
2987
|
+
if (portConflict) {
|
|
2988
|
+
// 上一次连接没干净退出时,服务器上的 sshd 会一直占着端口,导致新连接永远失败。
|
|
2989
|
+
// 清掉那个残留会话再重试,避免陷入"每 5 秒失败一次"的死循环。
|
|
2990
|
+
releaseStaleForward();
|
|
2991
|
+
}
|
|
2992
|
+
restartTimer = setTimeout(start, 5000);
|
|
2993
|
+
});
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
/** 杀掉服务器上占着本端口的残留 sshd 会话(只针对 sshd-session)。 */
|
|
2997
|
+
function releaseStaleForward() {
|
|
2998
|
+
const cfg = getConfig();
|
|
2999
|
+
const script = [
|
|
3000
|
+
`pids=$(sudo -n ss -ltnp 2>/dev/null | grep ':${cfg.remotePort} ' | grep -oE 'pid=[0-9]+' | cut -d= -f2 | sort -u)`,
|
|
3001
|
+
'[ -z "$pids" ] && exit 0',
|
|
3002
|
+
'for p in $pids; do',
|
|
3003
|
+
' name=$(ps -p "$p" -o comm= 2>/dev/null)',
|
|
3004
|
+
' if [ "$name" = "sshd-session" ] || [ "$name" = "sshd" ]; then',
|
|
3005
|
+
' sudo -n kill -9 "$p" && echo "released stale sshd session $p"',
|
|
3006
|
+
' fi',
|
|
3007
|
+
'done',
|
|
3008
|
+
].join('\n');
|
|
3009
|
+
runServerScript(cfg, script, 10000).then((output) => {
|
|
3010
|
+
if (output && output.trim()) log(output.trim());
|
|
3011
|
+
}).catch(() => { /* 清理失败就继续重试 */ });
|
|
3012
|
+
}
|
|
3013
|
+
|
|
3014
|
+
function stop() {
|
|
3015
|
+
stopped = true;
|
|
3016
|
+
if (restartTimer) { clearTimeout(restartTimer); restartTimer = undefined; }
|
|
3017
|
+
if (child) {
|
|
3018
|
+
try { child.kill(); } catch { /* ignore */ }
|
|
3019
|
+
child = undefined;
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
|
|
3023
|
+
/** 配置变了:杀掉旧 ssh 并用新配置立刻重连(不用重启 DSH)。 */
|
|
3024
|
+
function restart() {
|
|
3025
|
+
stop();
|
|
3026
|
+
stopped = false;
|
|
3027
|
+
start();
|
|
3028
|
+
}
|
|
3029
|
+
|
|
3030
|
+
return { start, stop, restart };
|
|
3031
|
+
}
|
|
3032
|
+
|
|
3033
|
+
/* ------------------------------------------------------------------ *
|
|
3034
|
+
* 本机 TLS(局域网也要加密,不允许明文)
|
|
3035
|
+
* ------------------------------------------------------------------ */
|
|
3036
|
+
|
|
3037
|
+
/** 本机所有可用的局域网/回环地址,用来写进证书的 SAN。 */
|
|
3038
|
+
function certNames() {
|
|
3039
|
+
const names = new Set(['localhost', '127.0.0.1']);
|
|
3040
|
+
for (const [iface, addrs] of Object.entries(os.networkInterfaces())) {
|
|
3041
|
+
for (const addr of addrs ?? []) {
|
|
3042
|
+
if (addr.internal) continue;
|
|
3043
|
+
names.add(addr.address);
|
|
3044
|
+
names.add(iface);
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
return [...names];
|
|
3048
|
+
}
|
|
3049
|
+
|
|
3050
|
+
function findOpenssl() {
|
|
3051
|
+
const candidates = process.platform === 'win32'
|
|
3052
|
+
? [
|
|
3053
|
+
path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'usr', 'bin', 'openssl.exe'),
|
|
3054
|
+
path.join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'Git', 'mingw64', 'bin', 'openssl.exe'),
|
|
3055
|
+
'openssl.exe',
|
|
3056
|
+
'openssl',
|
|
3057
|
+
]
|
|
3058
|
+
: ['/usr/bin/openssl', '/usr/local/bin/openssl', '/opt/homebrew/bin/openssl', 'openssl'];
|
|
3059
|
+
for (const candidate of candidates) {
|
|
3060
|
+
if (candidate.includes(path.sep) && !fs.existsSync(candidate)) continue;
|
|
3061
|
+
return candidate;
|
|
3062
|
+
}
|
|
3063
|
+
return undefined;
|
|
3064
|
+
}
|
|
3065
|
+
|
|
3066
|
+
/** 没有现成证书时,用 openssl 生一张自签证书(一次生成,长期复用)。 */
|
|
3067
|
+
function ensureSelfSigned(dir) {
|
|
3068
|
+
const certPath = path.join(dir, 'self-cert.pem');
|
|
3069
|
+
const keyPath = path.join(dir, 'self-key.pem');
|
|
3070
|
+
if (fs.existsSync(certPath) && fs.existsSync(keyPath)) return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };
|
|
3071
|
+
|
|
3072
|
+
const openssl = findOpenssl();
|
|
3073
|
+
if (!openssl) return undefined;
|
|
3074
|
+
|
|
3075
|
+
const san = certNames().flatMap((name) => {
|
|
3076
|
+
if (/^\d+\.\d+\.\d+\.\d+$/u.test(name)) return [`IP:${name}`];
|
|
3077
|
+
if (name.includes(':')) return [`IP:${name}`];
|
|
3078
|
+
return [`DNS:${name}`];
|
|
3079
|
+
}).join(',');
|
|
3080
|
+
const args = [
|
|
3081
|
+
'req', '-x509', '-newkey', 'rsa:2048', '-nodes',
|
|
3082
|
+
'-keyout', keyPath, '-out', certPath,
|
|
3083
|
+
'-days', '825', '-subj', '/CN=dsh-waypoint',
|
|
3084
|
+
'-addext', `subjectAltName=${san}`,
|
|
3085
|
+
];
|
|
3086
|
+
const result = spawnSync(openssl, args, { stdio: 'ignore', windowsHide: true });
|
|
3087
|
+
if (result.status !== 0 || !fs.existsSync(certPath) || !fs.existsSync(keyPath)) return undefined;
|
|
3088
|
+
try {
|
|
3089
|
+
fs.chmodSync(keyPath, 0o600);
|
|
3090
|
+
} catch { /* Windows 忽略权限 */ }
|
|
3091
|
+
return { cert: fs.readFileSync(certPath), key: fs.readFileSync(keyPath) };
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
/**
|
|
3095
|
+
* 局域网证书:用一台本机 CA 签叶子证书。
|
|
3096
|
+
* 把 ca-cert.pem 装进手机信任库一次,之后中间人拿别的证书就会直接报错(自签叶子做不到这一点)。
|
|
3097
|
+
*/
|
|
3098
|
+
function ensureLocalCa(dir) {
|
|
3099
|
+
const caCert = path.join(dir, 'ca-cert.pem');
|
|
3100
|
+
const caKey = path.join(dir, 'ca-key.pem');
|
|
3101
|
+
const leafCert = path.join(dir, 'server-cert.pem');
|
|
3102
|
+
const leafKey = path.join(dir, 'server-key.pem');
|
|
3103
|
+
const sanFile = path.join(dir, 'server-san.txt');
|
|
3104
|
+
|
|
3105
|
+
const openssl = findOpenssl();
|
|
3106
|
+
if (!openssl) return undefined;
|
|
3107
|
+
|
|
3108
|
+
const san = certNames().map((name) => {
|
|
3109
|
+
if (/^\d+\.\d+\.\d+\.\d+$/u.test(name) || name.includes(':')) return `IP:${name}`;
|
|
3110
|
+
return `DNS:${name}`;
|
|
3111
|
+
}).join(',');
|
|
3112
|
+
const currentSan = fs.existsSync(sanFile) ? fs.readFileSync(sanFile, 'utf8').trim() : '';
|
|
3113
|
+
const ready = fs.existsSync(caCert) && fs.existsSync(caKey) && fs.existsSync(leafCert) && fs.existsSync(leafKey);
|
|
3114
|
+
if (ready && currentSan === san) {
|
|
3115
|
+
return { cert: fs.readFileSync(leafCert), key: fs.readFileSync(leafKey), caCertPath: caCert };
|
|
3116
|
+
}
|
|
3117
|
+
|
|
3118
|
+
const quiet = { stdio: 'ignore', windowsHide: true };
|
|
3119
|
+
if (!fs.existsSync(caCert) || !fs.existsSync(caKey)) {
|
|
3120
|
+
const result = spawnSync(openssl, [
|
|
3121
|
+
'req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '3650',
|
|
3122
|
+
'-keyout', caKey, '-out', caCert, '-subj', '/CN=dsh-waypoint Local CA',
|
|
3123
|
+
], quiet);
|
|
3124
|
+
if (result.status !== 0) return undefined;
|
|
3125
|
+
}
|
|
3126
|
+
|
|
3127
|
+
const csr = path.join(dir, 'server.csr');
|
|
3128
|
+
const ext = path.join(dir, 'server-ext.cnf');
|
|
3129
|
+
fs.writeFileSync(ext, `subjectAltName=${san}\n`, 'utf8');
|
|
3130
|
+
if (spawnSync(openssl, ['req', '-newkey', 'rsa:2048', '-nodes', '-keyout', leafKey, '-out', csr, '-subj', '/CN=dsh-waypoint'], quiet).status !== 0) return undefined;
|
|
3131
|
+
if (spawnSync(openssl, ['x509', '-req', '-in', csr, '-CA', caCert, '-CAkey', caKey, '-CAcreateserial', '-days', '825', '-out', leafCert, '-extfile', ext], quiet).status !== 0) return undefined;
|
|
3132
|
+
fs.writeFileSync(sanFile, san, 'utf8');
|
|
3133
|
+
try {
|
|
3134
|
+
fs.chmodSync(caKey, 0o600);
|
|
3135
|
+
fs.chmodSync(leafKey, 0o600);
|
|
3136
|
+
} catch { /* Windows 忽略权限 */ }
|
|
3137
|
+
return { cert: fs.readFileSync(leafCert), key: fs.readFileSync(leafKey), caCertPath: caCert };
|
|
3138
|
+
}
|
|
3139
|
+
|
|
3140
|
+
/**
|
|
3141
|
+
* 按配置解析 TLS。
|
|
3142
|
+
* - 默认用本机 CA 签的叶子证书(局域网地址用这个);
|
|
3143
|
+
* - 配了 tlsPublicCert/tlsPublicKey 时,对公网域名用那张真证书(SNI 选择),
|
|
3144
|
+
* 这样服务器只做 TCP 透传、TLS 直接终止在本机。
|
|
3145
|
+
*/
|
|
3146
|
+
function resolveTls(config, dir, warn) {
|
|
3147
|
+
if (config.tls === 'off') return { mode: 'off' };
|
|
3148
|
+
if (config.tls === 'files') {
|
|
3149
|
+
if (!config.tlsCert || !config.tlsKey) throw new Error('tls=files 需要同时配置 tlsCert 和 tlsKey');
|
|
3150
|
+
return {
|
|
3151
|
+
mode: 'files',
|
|
3152
|
+
options: { cert: fs.readFileSync(config.tlsCert), key: fs.readFileSync(config.tlsKey) },
|
|
3153
|
+
};
|
|
3154
|
+
}
|
|
3155
|
+
const generated = ensureLocalCa(dir) ?? ensureSelfSigned(dir);
|
|
3156
|
+
if (!generated) {
|
|
3157
|
+
warn('找不到 openssl,无法生成本机证书;为避免明文传输,监听已跳过。可配置 tls=files 提供证书,或 tls=off 明确允许明文。');
|
|
3158
|
+
return { mode: 'failed' };
|
|
3159
|
+
}
|
|
3160
|
+
let publicContext;
|
|
3161
|
+
if (config.tlsPublicCert && config.tlsPublicKey && fs.existsSync(config.tlsPublicCert) && fs.existsSync(config.tlsPublicKey)) {
|
|
3162
|
+
try {
|
|
3163
|
+
publicContext = nodeTls.createSecureContext({
|
|
3164
|
+
cert: fs.readFileSync(config.tlsPublicCert),
|
|
3165
|
+
key: fs.readFileSync(config.tlsPublicKey),
|
|
3166
|
+
});
|
|
3167
|
+
} catch (error) {
|
|
3168
|
+
warn(`公网证书加载失败:${error.message}`);
|
|
3169
|
+
}
|
|
3170
|
+
}
|
|
3171
|
+
return {
|
|
3172
|
+
mode: generated.caCertPath ? 'local-ca' : 'self',
|
|
3173
|
+
options: generated,
|
|
3174
|
+
caCertPath: generated.caCertPath,
|
|
3175
|
+
publicContext,
|
|
3176
|
+
};
|
|
3177
|
+
}
|
|
3178
|
+
|
|
3179
|
+
/* ------------------------------------------------------------------ *
|
|
3180
|
+
* 插件入口
|
|
3181
|
+
* ------------------------------------------------------------------ */
|
|
3182
|
+
|
|
3183
|
+
export function apply(ctx, rawConfig) {
|
|
3184
|
+
const dir = dataDir();
|
|
3185
|
+
const settingsPath = path.join(dir, 'settings.json');
|
|
3186
|
+
|
|
3187
|
+
/** 读取本机 settings.json(覆盖包里的默认配置;文件不存在就用默认)。 */
|
|
3188
|
+
function readSettings() {
|
|
3189
|
+
try {
|
|
3190
|
+
const parsed = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
|
|
3191
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
3192
|
+
} catch {
|
|
3193
|
+
return {};
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
|
|
3197
|
+
const config = normalizeConfig({ ...rawConfig, ...readSettings() });
|
|
3198
|
+
const auth = loadAuth(dir);
|
|
3199
|
+
// mintCookie 需要知道上游端口才能探测 DSH 接受的 cookie 有效期;port 在下面才算出来,
|
|
3200
|
+
// 所以用闭包延迟读取。
|
|
3201
|
+
const mintCookie = createCookieMinter(ctx.credentials, () => port);
|
|
3202
|
+
const warn = (message) => {
|
|
3203
|
+
ctx.logger?.('dsh-homing')?.warn?.(message);
|
|
3204
|
+
console.warn(`[dsh-homing] ${message}`);
|
|
3205
|
+
};
|
|
3206
|
+
if (config.serverHost) {
|
|
3207
|
+
console.log(`[dsh-homing] 服务器地址:${config.serverHost}:${config.sshPort}(${settingsPath} 可改)`);
|
|
3208
|
+
}
|
|
3209
|
+
|
|
3210
|
+
let port;
|
|
3211
|
+
try {
|
|
3212
|
+
const origin = new URL(ctx.webServer.getOrigin());
|
|
3213
|
+
port = Number(origin.port) || (origin.protocol === 'https:' ? 443 : 80);
|
|
3214
|
+
} catch (error) {
|
|
3215
|
+
warn(`取不到 DSH 端口:${error.message}`);
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
const tls = resolveTls(config, dir, warn);
|
|
3219
|
+
if (tls.mode === 'failed') return;
|
|
3220
|
+
if (tls.caCertPath) {
|
|
3221
|
+
console.log(`[dsh-homing] 局域网证书由本机 CA 签发;把它装进手机信任库可消除警告:${tls.caCertPath}`);
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
const { handler, onUpgrade } = createBridge({
|
|
3225
|
+
getUpstreamPort: () => port,
|
|
3226
|
+
mintCookie,
|
|
3227
|
+
auth,
|
|
3228
|
+
config,
|
|
3229
|
+
dir,
|
|
3230
|
+
secureCookies: tls.mode !== 'off',
|
|
3231
|
+
caCertPath: tls.caCertPath,
|
|
3232
|
+
});
|
|
3233
|
+
|
|
3234
|
+
let publicHost = '';
|
|
3235
|
+
try {
|
|
3236
|
+
publicHost = new URL(config.publicUrl).hostname.toLowerCase();
|
|
3237
|
+
} catch {
|
|
3238
|
+
// publicUrl 不是合法 URL:只按本机证书提供服务
|
|
3239
|
+
}
|
|
3240
|
+
const localContext = tls.mode === 'off' ? undefined : nodeTls.createSecureContext(tls.options);
|
|
3241
|
+
const server = tls.mode === 'off'
|
|
3242
|
+
? http.createServer(handler)
|
|
3243
|
+
: https.createServer({
|
|
3244
|
+
...tls.options,
|
|
3245
|
+
// 按 SNI 选证书:公网域名用真证书,其余(局域网 IP)用本机 CA 签的证书
|
|
3246
|
+
SNICallback: (servername, callback) => {
|
|
3247
|
+
if (tls.publicContext && publicHost && servername && servername.toLowerCase() === publicHost) {
|
|
3248
|
+
callback(null, tls.publicContext);
|
|
3249
|
+
return;
|
|
3250
|
+
}
|
|
3251
|
+
callback(null, localContext);
|
|
3252
|
+
},
|
|
3253
|
+
}, handler);
|
|
3254
|
+
server.on('upgrade', onUpgrade);
|
|
3255
|
+
server.requestTimeout = 0;
|
|
3256
|
+
server.headersTimeout = 0;
|
|
3257
|
+
server.keepAliveTimeout = 65000;
|
|
3258
|
+
|
|
3259
|
+
const tunnel = createTunnel({ getConfig: () => config, dir });
|
|
3260
|
+
const scheme = tls.mode === 'off' ? 'http' : 'https';
|
|
3261
|
+
|
|
3262
|
+
/**
|
|
3263
|
+
* 从服务器同步公网证书(透传模式下 TLS 在本机终止,续期发生在服务器)。
|
|
3264
|
+
* 只有内容变化时才写盘并热替换 SNI 上下文,不重启监听。
|
|
3265
|
+
*/
|
|
3266
|
+
/**
|
|
3267
|
+
* 公网证书由本机私钥签发(CSR 模式),服务器上没有私钥,所以这里只做到期检查:
|
|
3268
|
+
* 剩余不足 30 天就提示运行 bin/renew-cert.mjs。
|
|
3269
|
+
*/
|
|
3270
|
+
/** 重新加载本机证书文件到 SNI 上下文(续期后调用,不断开现有连接)。 */
|
|
3271
|
+
const reloadPublicContext = () => {
|
|
3272
|
+
if (!config.tlsPublicCert || !config.tlsPublicKey) return false;
|
|
3273
|
+
try {
|
|
3274
|
+
tls.publicContext = nodeTls.createSecureContext({
|
|
3275
|
+
cert: fs.readFileSync(config.tlsPublicCert),
|
|
3276
|
+
key: fs.readFileSync(config.tlsPublicKey),
|
|
3277
|
+
});
|
|
3278
|
+
return true;
|
|
3279
|
+
} catch (error) {
|
|
3280
|
+
warn(`重新加载证书失败:${error.message}`);
|
|
3281
|
+
return false;
|
|
3282
|
+
}
|
|
3283
|
+
};
|
|
3284
|
+
|
|
3285
|
+
let renewing = false;
|
|
3286
|
+
/**
|
|
3287
|
+
* 公网证书由本机私钥签发(CSR 模式),服务器上没有私钥。
|
|
3288
|
+
* 剩余不足 30 天时自动跑 bin/renew-cert.mjs,成功后热替换上下文。
|
|
3289
|
+
*/
|
|
3290
|
+
/* ---- 续期失败退避 -------------------------------------------------
|
|
3291
|
+
* CSR 模式每次续期都是一张新证书(certbot --csr 不更新同一 lineage),
|
|
3292
|
+
* 失败后若每 6 小时重试,很容易撞 Let's Encrypt 的「同域名证书」速率限制
|
|
3293
|
+
* (5 张/周),撞上就只能干等一周。这里做指数退避:6h → 12h → 24h → 48h → 72h。
|
|
3294
|
+
*/
|
|
3295
|
+
const RENEW_STATE_FILE = path.join(dir, 'renew-state.json');
|
|
3296
|
+
const RENEW_BASE_MS = 6 * 3600_000;
|
|
3297
|
+
const RENEW_MAX_MS = 72 * 3600_000;
|
|
3298
|
+
|
|
3299
|
+
function readRenewState() {
|
|
3300
|
+
try {
|
|
3301
|
+
const parsed = JSON.parse(fs.readFileSync(RENEW_STATE_FILE, 'utf8'));
|
|
3302
|
+
return parsed && typeof parsed === 'object' ? parsed : {};
|
|
3303
|
+
} catch {
|
|
3304
|
+
return {};
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
|
|
3308
|
+
function writeRenewState(next) {
|
|
3309
|
+
try {
|
|
3310
|
+
fs.writeFileSync(RENEW_STATE_FILE, `${JSON.stringify(next, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 });
|
|
3311
|
+
} catch (error) {
|
|
3312
|
+
warn(`写入续期状态失败:${error.message}`);
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3315
|
+
|
|
3316
|
+
function markRenewSuccess() {
|
|
3317
|
+
writeRenewState({ failures: 0, nextAttemptAt: 0, lastSuccessAt: new Date().toISOString() });
|
|
3318
|
+
}
|
|
3319
|
+
|
|
3320
|
+
function markRenewFailure(output) {
|
|
3321
|
+
const previous = readRenewState();
|
|
3322
|
+
const failures = Number(previous.failures || 0) + 1;
|
|
3323
|
+
const delay = Math.min(RENEW_BASE_MS * 2 ** Math.min(failures - 1, 5), RENEW_MAX_MS);
|
|
3324
|
+
writeRenewState({
|
|
3325
|
+
failures,
|
|
3326
|
+
nextAttemptAt: Date.now() + delay,
|
|
3327
|
+
lastAttemptAt: new Date().toISOString(),
|
|
3328
|
+
lastError: String(output ?? '').trim().split('\n').slice(-5).join('\n'),
|
|
3329
|
+
});
|
|
3330
|
+
warn(`自动续期连续失败 ${failures} 次,${Math.round(delay / 3_600_000)} 小时后重试(避免撞 Let's Encrypt 速率限制)`);
|
|
3331
|
+
}
|
|
3332
|
+
|
|
3333
|
+
const checkPublicCert = async () => {
|
|
3334
|
+
if (!config.tlsPublicCert || !fs.existsSync(config.tlsPublicCert)) return;
|
|
3335
|
+
let days;
|
|
3336
|
+
try {
|
|
3337
|
+
const cert = new nodeTls.X509Certificate(fs.readFileSync(config.tlsPublicCert));
|
|
3338
|
+
days = Math.floor((new Date(cert.validTo).getTime() - Date.now()) / 86_400_000);
|
|
3339
|
+
if (days >= 30) {
|
|
3340
|
+
console.log(`[dsh-homing] 公网证书剩余 ${days} 天(到期 ${cert.validTo})`);
|
|
3341
|
+
return;
|
|
3342
|
+
}
|
|
3343
|
+
} catch (error) {
|
|
3344
|
+
warn(`公网证书读取失败:${error.message}`);
|
|
3345
|
+
return;
|
|
3346
|
+
}
|
|
3347
|
+
if (config.autoRenewCert === false) {
|
|
3348
|
+
warn(`公网证书只剩 ${days} 天(已关闭自动续期)`);
|
|
3349
|
+
return;
|
|
3350
|
+
}
|
|
3351
|
+
if (renewing) return;
|
|
3352
|
+
// 上次失败后的退避窗口内不重试
|
|
3353
|
+
const renewState = readRenewState();
|
|
3354
|
+
if (renewState.nextAttemptAt && Date.now() < renewState.nextAttemptAt) {
|
|
3355
|
+
const minutes = Math.ceil((renewState.nextAttemptAt - Date.now()) / 60_000);
|
|
3356
|
+
warn(`自动续期暂停中(已连续失败 ${renewState.failures || 0} 次,${minutes} 分钟后重试)`);
|
|
3357
|
+
return;
|
|
3358
|
+
}
|
|
3359
|
+
renewing = true;
|
|
3360
|
+
console.log(`[dsh-homing] 公网证书只剩 ${days} 天,开始自动续期`);
|
|
3361
|
+
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'renew-cert.mjs');
|
|
3362
|
+
const child = spawn(process.execPath, [script], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
3363
|
+
let output = '';
|
|
3364
|
+
child.stdout?.on('data', (chunk) => { output += String(chunk); });
|
|
3365
|
+
child.stderr?.on('data', (chunk) => { output += String(chunk); });
|
|
3366
|
+
await new Promise((resolve) => {
|
|
3367
|
+
child.on('close', resolve);
|
|
3368
|
+
child.on('error', resolve);
|
|
3369
|
+
});
|
|
3370
|
+
renewing = false;
|
|
3371
|
+
if (output.includes('已安装') && reloadPublicContext()) {
|
|
3372
|
+
markRenewSuccess();
|
|
3373
|
+
console.log('[dsh-homing] 证书已自动续期并生效');
|
|
3374
|
+
} else {
|
|
3375
|
+
markRenewFailure(output);
|
|
3376
|
+
warn(`自动续期失败,请手动运行 renew-cert.mjs:${output.trim().split('\n').slice(-3).join(' / ')}`);
|
|
3377
|
+
sendAlert(dir, config, '证书自动续期失败', output.trim().split('\n').slice(-5).join('\n'));
|
|
3378
|
+
}
|
|
3379
|
+
};
|
|
3380
|
+
/** 服务器健康检查 + 端口对齐:状态只在变化时记一行,避免刷日志。 */
|
|
3381
|
+
let lastHealthSignature;
|
|
3382
|
+
const syncRemotePort = async () => {
|
|
3383
|
+
const health = await readServerHealth(config);
|
|
3384
|
+
if (!health) return;
|
|
3385
|
+
|
|
3386
|
+
const port = health.ports.length === 1 ? health.ports[0] : undefined;
|
|
3387
|
+
if (config.syncPortFromServer !== false && port && port !== config.remotePort) {
|
|
3388
|
+
console.log(`[dsh-homing] 服务器反代端口是 ${port},本地是 ${config.remotePort},按服务器更新本地配置`);
|
|
3389
|
+
config.remotePort = port;
|
|
3390
|
+
try {
|
|
3391
|
+
persistRemotePort(dir, port);
|
|
3392
|
+
} catch (error) {
|
|
3393
|
+
warn(`写回 settings.json 失败:${error.message}`);
|
|
3394
|
+
}
|
|
3395
|
+
tunnel.restart();
|
|
3396
|
+
}
|
|
3397
|
+
|
|
3398
|
+
const problems = [];
|
|
3399
|
+
if (health.nginx && health.nginx !== 'active') problems.push(`nginx 未运行(${health.nginx})`);
|
|
3400
|
+
if (health.ports.length === 0) problems.push('nginx 里找不到 proxy_pass');
|
|
3401
|
+
if (health.ports.length > 1) problems.push(`nginx 的 proxy_pass 有多个端口:${health.ports.join(', ')}`);
|
|
3402
|
+
if (port && port !== config.remotePort) problems.push(`端口不一致:服务器 ${port} / 本地 ${config.remotePort}`);
|
|
3403
|
+
for (const cert of health.certs) {
|
|
3404
|
+
const days = Math.floor((cert.endEpoch * 1000 - Date.now()) / 86_400_000);
|
|
3405
|
+
if (days < 14) problems.push(`证书 ${cert.domain} 只剩 ${days} 天`);
|
|
3406
|
+
}
|
|
3407
|
+
|
|
3408
|
+
const signature = problems.join(';') || 'ok';
|
|
3409
|
+
if (signature === lastHealthSignature) return;
|
|
3410
|
+
lastHealthSignature = signature;
|
|
3411
|
+
const summary = `服务器 ${config.sshUser}@${config.serverHost}:nginx=${health.nginx ?? '?'}${health.passthrough ? '(透传)' : ''} proxy=${health.ports.join(',') || '-'} cert=${health.certs.map((cert) => `${cert.domain}(${Math.floor((cert.endEpoch * 1000 - Date.now()) / 86_400_000)}天)`).join(',') || '-'}`;
|
|
3412
|
+
if (problems.length > 0) {
|
|
3413
|
+
warn(`健康检查发现 ${problems.length} 个问题:${problems.join(';')}(${summary})`);
|
|
3414
|
+
sendAlert(dir, config, '入口健康检查异常', problems.join(';'));
|
|
3415
|
+
try {
|
|
3416
|
+
const domainName = new URL(config.publicUrl).hostname;
|
|
3417
|
+
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'bootstrap-server.mjs');
|
|
3418
|
+
warn(`若服务器尚未配置,运行:node "${script}" --server ${config.serverHost} --domain ${domainName} --install-key`);
|
|
3419
|
+
} catch {
|
|
3420
|
+
// publicUrl 不是合法 URL 就跳过这条提示
|
|
3421
|
+
}
|
|
3422
|
+
} else {
|
|
3423
|
+
console.log(`[dsh-homing] 健康检查通过 —— ${summary}`);
|
|
3424
|
+
}
|
|
3425
|
+
try {
|
|
3426
|
+
fs.appendFileSync(path.join(dir, 'health.log'), `${new Date().toISOString()} ${problems.length ? problems.join(';') : 'ok'} ${summary}\n`, 'utf8');
|
|
3427
|
+
} catch { /* 日志失败不影响 */ }
|
|
3428
|
+
};
|
|
3429
|
+
|
|
3430
|
+
ctx.effect(() => {
|
|
3431
|
+
let syncTimer;
|
|
3432
|
+
let listeningOnce = false;
|
|
3433
|
+
const onListening = () => {
|
|
3434
|
+
// 重试路径上万一重复触发,也不能把隧道和定时器起两遍
|
|
3435
|
+
if (listeningOnce) return;
|
|
3436
|
+
listeningOnce = true;
|
|
3437
|
+
const freshToken = signEntryFor(auth.sessionKey, Date.now() + Math.max(1, config.entryTokenTtlDays) * 86_400_000);
|
|
3438
|
+
const query = freshToken ? `?k=${freshToken}` : '';
|
|
3439
|
+
const entries = [];
|
|
3440
|
+
if (config.publicUrl) {
|
|
3441
|
+
let publicEntry = config.publicUrl;
|
|
3442
|
+
try {
|
|
3443
|
+
const u = new URL(publicEntry);
|
|
3444
|
+
u.searchParams.delete('func');
|
|
3445
|
+
if (freshToken) u.searchParams.set('k', freshToken);
|
|
3446
|
+
publicEntry = u.toString();
|
|
3447
|
+
} catch { /* publicUrl 不是合法 URL 就原样打印 */ }
|
|
3448
|
+
entries.push(`公网 ${publicEntry}`);
|
|
3449
|
+
entries.push(` 上面这条 ${Math.max(1, config.entryTokenTtlDays)} 天内有效;打开一次会种签名 Cookie,之后书签只存 https://域名/ 就行`);
|
|
3450
|
+
}
|
|
3451
|
+
entries.push(`设备管理 ${scheme}://localhost:${config.listenPort}/dsh_homing/devices`);
|
|
3452
|
+
for (const ip of lanIpv4s()) {
|
|
3453
|
+
entries.push(`局域网 ${scheme}://${ip}:${config.listenPort}/${query}`);
|
|
3454
|
+
}
|
|
3455
|
+
console.log(`[dsh-homing] 已启动(本地 ${scheme} ${config.bindAddress}:${config.listenPort} -> DSH 127.0.0.1:${port},TLS=${tls.mode})`);
|
|
3456
|
+
entries.push(`账户设置 ${scheme}://localhost:${config.listenPort}/dsh_homing/account`);
|
|
3457
|
+
for (const entry of entries) console.log(`[dsh-homing] ${entry}`);
|
|
3458
|
+
try {
|
|
3459
|
+
fs.writeFileSync(path.join(dir, 'entry.txt'), `# 更新于 ${new Date().toISOString()}\n${entries.join('\n')}\n`, 'utf8');
|
|
3460
|
+
} catch { /* 写不进去不影响服务 */ }
|
|
3461
|
+
tunnel.start();
|
|
3462
|
+
// 起来之后跟服务器对一次端口,之后每 10 分钟看一次
|
|
3463
|
+
setTimeout(() => { syncRemotePort(); }, 3000);
|
|
3464
|
+
syncTimer = setInterval(() => { syncRemotePort(); }, 10 * 60 * 1000);
|
|
3465
|
+
// 证书续期发生在服务器,这里每 6 小时拉一次
|
|
3466
|
+
setTimeout(() => { checkPublicCert(); }, 6000);
|
|
3467
|
+
const certTimer = setInterval(() => { checkPublicCert(); }, 6 * 60 * 60 * 1000);
|
|
3468
|
+
if (typeof certTimer.unref === 'function') certTimer.unref();
|
|
3469
|
+
// 每周自动备份一次(含私钥,只留在本机 backups/ 目录)
|
|
3470
|
+
const backupScript = path.join(path.dirname(fileURLToPath(import.meta.url)), 'bin', 'backup.mjs');
|
|
3471
|
+
const backupOnce = () => {
|
|
3472
|
+
const job = spawn(process.execPath, [backupScript], { stdio: 'ignore', windowsHide: true });
|
|
3473
|
+
job.on('error', () => {});
|
|
3474
|
+
};
|
|
3475
|
+
const backupTimer = setInterval(backupOnce, 7 * 24 * 60 * 60 * 1000);
|
|
3476
|
+
if (typeof backupTimer.unref === 'function') backupTimer.unref();
|
|
3477
|
+
if (typeof syncTimer.unref === 'function') syncTimer.unref();
|
|
3478
|
+
};
|
|
3479
|
+
// 上一个实例还没完全退出时端口会被占用;此时不重试就永久失去监听,
|
|
3480
|
+
// 表现为"重启后手机连不上,但 DSH 本身正常"。
|
|
3481
|
+
let listenAttempt = 0;
|
|
3482
|
+
const startListening = () => {
|
|
3483
|
+
server.listen(config.listenPort, config.bindAddress, onListening);
|
|
3484
|
+
};
|
|
3485
|
+
server.on('error', (error) => {
|
|
3486
|
+
if (error && error.code === 'EADDRINUSE' && listenAttempt < 40) {
|
|
3487
|
+
listenAttempt += 1;
|
|
3488
|
+
const delay = Math.min(2000 * listenAttempt, 15000);
|
|
3489
|
+
warn(`端口 ${config.listenPort} 被占用(多半是上一个实例还没退出),${Math.round(delay / 1000)} 秒后重试(第 ${listenAttempt} 次)`);
|
|
3490
|
+
setTimeout(startListening, delay);
|
|
3491
|
+
return;
|
|
3492
|
+
}
|
|
3493
|
+
warn(`监听失败:${error && error.message ? error.message : String(error)}`);
|
|
3494
|
+
});
|
|
3495
|
+
startListening();
|
|
3496
|
+
|
|
3497
|
+
// 监听 settings.json:改了服务器地址/密钥/端口后,隧道自动用新配置重连(不用重启 DSH)
|
|
3498
|
+
let reloadTimer;
|
|
3499
|
+
let watcher;
|
|
3500
|
+
try {
|
|
3501
|
+
watcher = fs.watch(dir, (_event, filename) => {
|
|
3502
|
+
if (filename && filename !== 'settings.json') return;
|
|
3503
|
+
clearTimeout(reloadTimer);
|
|
3504
|
+
reloadTimer = setTimeout(() => {
|
|
3505
|
+
const before = `${config.serverHost}|${config.sshPort}|${config.sshUser}|${config.sshKey}|${config.listenPort}`;
|
|
3506
|
+
Object.assign(config, normalizeConfig({ ...rawConfig, ...readSettings() }));
|
|
3507
|
+
const after = `${config.serverHost}|${config.sshPort}|${config.sshUser}|${config.sshKey}|${config.listenPort}`;
|
|
3508
|
+
if (before !== after) {
|
|
3509
|
+
console.log(`[dsh-homing] 配置已更新,重启隧道:${config.sshUser}@${config.serverHost}:${config.sshPort}`);
|
|
3510
|
+
tunnel.restart();
|
|
3511
|
+
}
|
|
3512
|
+
}, 400);
|
|
3513
|
+
});
|
|
3514
|
+
} catch (error) {
|
|
3515
|
+
warn(`无法监听配置文件变更:${error.message}`);
|
|
3516
|
+
}
|
|
3517
|
+
|
|
3518
|
+
return () => {
|
|
3519
|
+
if (syncTimer) clearInterval(syncTimer);
|
|
3520
|
+
if (reloadTimer) clearTimeout(reloadTimer);
|
|
3521
|
+
try { watcher?.close(); } catch { /* ignore */ }
|
|
3522
|
+
tunnel.stop();
|
|
3523
|
+
server.close();
|
|
3524
|
+
};
|
|
3525
|
+
});
|
|
3526
|
+
}
|