dsh-napcat-keeper 2.8.2 → 2.9.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/CHANGELOG.md +25 -0
- package/README.md +19 -27
- package/lib/client.js +55 -101
- package/lib/index.js +472 -688
- package/package.json +3 -3
- package/scripts/selftest-qrpanel.mjs +260 -0
- package/scripts/smoke-client.mjs +57 -55
- package/scripts/selftest-setup.mjs +0 -210
package/lib/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* dsh-napcat-keeper —— NapCat 看门狗 v2.
|
|
2
|
+
* dsh-napcat-keeper —— NapCat 看门狗 v2.9.1(可发布通用版)
|
|
3
3
|
*
|
|
4
4
|
* 解决的问题:DSH 是桌面应用,重启 DSH 时 NapCat(QQ 协议端) 不会跟着起来,
|
|
5
5
|
* 于是 dsh-qq-bridge 一直轮询一个死端口,你在 QQ 里说的话就石沉大海。
|
|
@@ -58,7 +58,8 @@
|
|
|
58
58
|
* 和 DSH 自己的文件混在一起,一眼看不出哪些是插件产生的;
|
|
59
59
|
* - 现在统一落在 ~/.dsh/dsh-napcat-keeper/ 一个目录里,文件名去掉重复前缀:
|
|
60
60
|
* config.json / keeper.log / launch.log / state.json / lock.json / qr.png /
|
|
61
|
-
* env.bat / launch.vbs / autogen.bat / autogen-node.bat
|
|
61
|
+
* env.bat / launch.vbs / autogen.bat / autogen-node.bat;
|
|
62
|
+
* (2.9.1 起不再有 setup/ 那个「提权交接」脚本目录)
|
|
62
63
|
* - 老版本升级时 migrateLegacyFiles() 自动搬一次(能 rename 就 rename),
|
|
63
64
|
* 遗留的 *.bak、旧备份目录挪进 legacy/ 留档;计划任务里写死的旧路径由
|
|
64
65
|
* repairTaskActions() 用 /change 改指新位置,不 /end、不打扰正在跑的 QQ;
|
|
@@ -104,13 +105,12 @@
|
|
|
104
105
|
* - 改本插件任何 json/js 请用 write/edit 工具或 [IO.File]::WriteAllText + UTF8Encoding($false);
|
|
105
106
|
*
|
|
106
107
|
* v2.3.0:提权交接 —— 需要管理员的活,交给「你点一下」的脚本
|
|
107
|
-
* -
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* - 能做的事(needs):补启动脚本 / 写「记住密码」中间层 / 建计划任务 / 放行 OneBot 入站端口。
|
|
108
|
+
* - 2.9.1 已整块删除:这套「生成 plan.json + apply-admin.cmd 让人去双击」的机制是多余的。
|
|
109
|
+
* 它本来要做的几件事,插件自己早就能直接做完,且全都不需要管理员:
|
|
110
|
+
* 写 env.bat(writeEnvBat)/ 建计划任务(ensureTask,schtasks 用户级)/
|
|
111
|
+
* 补启动脚本(autogen.bat、autogen-node.bat 写在插件自己目录里)。
|
|
112
|
+
* 唯一真要管理员的是给 OneBot 端口开防火墙入站 —— 那一步也一并去掉,
|
|
113
|
+
* 需要放行时按 README「端口放行」那一节的 netsh 命令自己跑一次即可。
|
|
114
114
|
*
|
|
115
115
|
* v2.2.2:目录只认「人选」
|
|
116
116
|
* - 去掉「自动探测 NapCat Shell 目录」:不再替用户猜位置、也不再在配置里悄悄填,
|
|
@@ -171,7 +171,7 @@ import { homedir, tmpdir } from 'node:os'
|
|
|
171
171
|
import path from 'node:path'
|
|
172
172
|
|
|
173
173
|
export const name = 'napcat-keeper'
|
|
174
|
-
export const version = '2.
|
|
174
|
+
export const version = '2.9.1'
|
|
175
175
|
|
|
176
176
|
/** tools 用来注册 napcat_* 工具;webServer 用来挂设置界面接口。拿不到也不至于把 DSH 拖崩。 */
|
|
177
177
|
export const inject = ['tools', 'webServer']
|
|
@@ -260,6 +260,13 @@ const DEFAULTS = {
|
|
|
260
260
|
statePath: '',
|
|
261
261
|
/** 二维码副本(方便 agent 或你自己直接看图) */
|
|
262
262
|
qrCopyPath: '',
|
|
263
|
+
/**
|
|
264
|
+
* 扫码页:NapCat 要手机扫码时,点开就能看见一张会自己刷新的二维码。
|
|
265
|
+
* 默认开;只监听 127.0.0.1,不对外。
|
|
266
|
+
*/
|
|
267
|
+
qrPanelEnabled: true,
|
|
268
|
+
/** 扫码页端口(127.0.0.1 上) */
|
|
269
|
+
qrPanelPort: 8899,
|
|
263
270
|
/** qq-bridge 的 state 文件 */
|
|
264
271
|
bridgeStatePath: '',
|
|
265
272
|
/** 桥接 state 超过这么多秒没更新就提醒 */
|
|
@@ -332,7 +339,6 @@ const LEGACY_FILES = [
|
|
|
332
339
|
['napcat-autogen-node.bat', 'autogen-node.bat'],
|
|
333
340
|
['napcat-autogen.bat', 'autogen.bat'],
|
|
334
341
|
]
|
|
335
|
-
const LEGACY_DIRS = [['napcat-keeper-setup', 'setup']]
|
|
336
342
|
/** 老版本留在 ~/.dsh 根上的东西(没搬走的、配置备份、bom-backup 之类):统一归档进 legacy/ */
|
|
337
343
|
const LEGACY_LEFTOVER = /^(napcat-keeper[.-]|napcat-qr\.|napcat-autogen)/
|
|
338
344
|
|
|
@@ -434,14 +440,8 @@ function migrateLegacyFiles(dir) {
|
|
|
434
440
|
}
|
|
435
441
|
if (moveOne(path.join(home, oldName), path.join(target, newName))) moved += 1
|
|
436
442
|
}
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
const from = path.join(home, oldName)
|
|
440
|
-
if (existsSync(from) && !existsSync(path.join(target, newName)) && moveOne(from, path.join(target, newName))) {
|
|
441
|
-
moved += 1
|
|
442
|
-
}
|
|
443
|
-
} catch {}
|
|
444
|
-
}
|
|
443
|
+
// 2.9.1 起没有需要改名搬家的目录了(原来的 setup/ 提权交接目录整块删掉),
|
|
444
|
+
// 只留下面的归档兜底。旧版本留下的 ~/.dsh/dsh-napcat-keeper/setup/ 可以手动删。
|
|
445
445
|
// 兜底:还留在根上的(目标位已有同名文件、或者正被别的进程占用搬不动)一律归档进 legacy/,
|
|
446
446
|
// 别让它们继续躺在 ~/.dsh 根上冒充「插件还在用老布局」。这一趟搬不动的,下次启动再来。
|
|
447
447
|
try {
|
|
@@ -831,6 +831,8 @@ function normalizeConfig(cfg) {
|
|
|
831
831
|
cfg.probeIntervalSec = clampNum(cfg.probeIntervalSec, 10, 3600, 45)
|
|
832
832
|
cfg.launchGraceSec = clampNum(cfg.launchGraceSec, 20, 3600, 150)
|
|
833
833
|
cfg.qrFreshSec = clampNum(cfg.qrFreshSec, 30, 3600, 300)
|
|
834
|
+
cfg.qrPanelEnabled = cfg.qrPanelEnabled !== false && cfg.qrPanelEnabled !== 'false' && cfg.qrPanelEnabled !== 0
|
|
835
|
+
cfg.qrPanelPort = clampNum(cfg.qrPanelPort, 1024, 65535, 8899)
|
|
834
836
|
cfg.scanTimeoutSec = clampNum(cfg.scanTimeoutSec, 30, 7200, 300)
|
|
835
837
|
cfg.maxScanRetries = clampNum(cfg.maxScanRetries, 0, 20, 2)
|
|
836
838
|
cfg.stuckSec = clampNum(cfg.stuckSec, 60, 7200, 420)
|
|
@@ -2296,78 +2298,6 @@ function repairTaskActions(cfg) {
|
|
|
2296
2298
|
}
|
|
2297
2299
|
}
|
|
2298
2300
|
|
|
2299
|
-
/* ── 提权交接:插件不自己去要管理员,改成给你一个双击就行的脚本 ──────────────
|
|
2300
|
-
*
|
|
2301
|
-
* 为什么要这样:DSH 自己是普通权限进程。插件偶尔要做几件「可能要管理员」的事
|
|
2302
|
-
* (往 Program Files 里的 NapCat 目录补启动脚本、建计划任务、给 OneBot 端口开防火墙),
|
|
2303
|
-
* 而插件既不该、也没法替人按下 UAC 里那个「是」。
|
|
2304
|
-
*
|
|
2305
|
-
* 所以改成这样:
|
|
2306
|
-
* 1. 插件把要做的每一步写进 plan.json(步骤由插件自己生成,来源可信);
|
|
2307
|
-
* 2. 生成 apply.ps1:先数一遍「这些步骤里有没有真需要管理员的」,
|
|
2308
|
-
* 没有就直接干;有才 Start-Process -Verb RunAs 自我提权 ——
|
|
2309
|
-
* UAC 弹窗就是用户亲手点的那一下确认;
|
|
2310
|
-
* 3. 生成 apply-admin.cmd:双击入口,省得用户去右键「以管理员身份运行」;
|
|
2311
|
-
* 4. 每步结果写 result.json,设置页读回来说清楚哪条成了、哪条没成;
|
|
2312
|
-
* 5. 另外给一个 undo-admin.cmd,反着把插件建过的东西删掉。
|
|
2313
|
-
*
|
|
2314
|
-
* 所有产物只在 ~/.dsh/dsh-napcat-keeper/setup 一个目录里,整个删掉就等于撤回。
|
|
2315
|
-
*/
|
|
2316
|
-
|
|
2317
|
-
const SETUP_NEEDS = {
|
|
2318
|
-
launcher: {
|
|
2319
|
-
label: '补一个启动脚本',
|
|
2320
|
-
hint: '往 Shell 目录写 napcat.quick.auto.bat,直接调 NapCatWinBootMain.exe(目录里没有别的 bat 时才需要)',
|
|
2321
|
-
},
|
|
2322
|
-
envbat: {
|
|
2323
|
-
label: '写「记住密码」中间层',
|
|
2324
|
-
hint: 'napcat-keeper-env.bat:账号与密码走环境变量交给 NapCat,密码只落这一个文件',
|
|
2325
|
-
},
|
|
2326
|
-
task: {
|
|
2327
|
-
label: '建 / 重建计划任务',
|
|
2328
|
-
hint: '开机不靠 DSH 也能拉起 QQ;用户级任务,通常不需要管理员',
|
|
2329
|
-
},
|
|
2330
|
-
firewall: {
|
|
2331
|
-
label: '放行 OneBot 端口(入站)',
|
|
2332
|
-
hint: '别的设备要连这个端口时才需要;这条一定会弹 UAC',
|
|
2333
|
-
},
|
|
2334
|
-
}
|
|
2335
|
-
|
|
2336
|
-
function setupPaths() {
|
|
2337
|
-
const dir = path.join(keeperDir(), 'setup')
|
|
2338
|
-
migrateLegacyFiles()
|
|
2339
|
-
return {
|
|
2340
|
-
dir,
|
|
2341
|
-
ps1: path.join(dir, 'apply.ps1'),
|
|
2342
|
-
cmd: path.join(dir, 'apply-admin.cmd'),
|
|
2343
|
-
undoCmd: path.join(dir, 'undo-admin.cmd'),
|
|
2344
|
-
plan: path.join(dir, 'plan.json'),
|
|
2345
|
-
result: path.join(dir, 'result.json'),
|
|
2346
|
-
runLog: path.join(dir, 'run.log'),
|
|
2347
|
-
readme: path.join(dir, 'README.txt'),
|
|
2348
|
-
}
|
|
2349
|
-
}
|
|
2350
|
-
|
|
2351
|
-
/** 目录能不能写:自己不存在就往上看,找一个存在的祖先试(免得把「没建过」当成「不可写」) */
|
|
2352
|
-
function dirWritable(dir) {
|
|
2353
|
-
if (!dir) return false
|
|
2354
|
-
let probe = dir
|
|
2355
|
-
for (let i = 0; i < 8; i += 1) {
|
|
2356
|
-
if (existsSync(probe)) {
|
|
2357
|
-
try {
|
|
2358
|
-
accessSync(probe, fsConstants.W_OK)
|
|
2359
|
-
return true
|
|
2360
|
-
} catch {
|
|
2361
|
-
return false
|
|
2362
|
-
}
|
|
2363
|
-
}
|
|
2364
|
-
const up = path.dirname(probe)
|
|
2365
|
-
if (up === probe || !up) break
|
|
2366
|
-
probe = up
|
|
2367
|
-
}
|
|
2368
|
-
return false
|
|
2369
|
-
}
|
|
2370
|
-
|
|
2371
2301
|
/** findBootMain 会递归翻目录,设置页每次刷新都调太贵 —— 缓存 60 秒,换了 Shell 目录就重算 */
|
|
2372
2302
|
function cachedBootMain(cfg, maxAgeMs = 60000) {
|
|
2373
2303
|
const key = cfg.shellDir || ''
|
|
@@ -2424,532 +2354,11 @@ function procsLayout(cfg, p) {
|
|
|
2424
2354
|
return value
|
|
2425
2355
|
}
|
|
2426
2356
|
|
|
2427
|
-
/**
|
|
2428
|
-
function launcherBatLines(cfg, boot) {
|
|
2429
|
-
const account = batValue(cfg.launchAccount)
|
|
2430
|
-
const args = String(cfg.launchArgs || '').trim()
|
|
2431
|
-
return [
|
|
2432
|
-
'@echo off',
|
|
2433
|
-
'chcp 65001 >nul',
|
|
2434
|
-
'rem dsh-napcat-keeper 自动生成:目录里没有别的启动脚本时才用它,直接调 NapCatWinBootMain.exe',
|
|
2435
|
-
'cd /d "%~dp0"',
|
|
2436
|
-
`set "ACCOUNT=${account}"`,
|
|
2437
|
-
`start "" "${boot}"${account ? ` ${account}` : ''}${args ? ` ${args}` : ''}`,
|
|
2438
|
-
'',
|
|
2439
|
-
]
|
|
2440
|
-
}
|
|
2441
|
-
|
|
2442
|
-
/** 任务里那条命令(纯字符串版本:不写盘,供「脚本」复用 taskCommandLine 的规则) */
|
|
2357
|
+
/** 任务里那条命令(纯字符串版本:不写盘,供别处复用 taskCommandLine 的规则) */
|
|
2443
2358
|
function taskCommandLinePure(cfg, bat) {
|
|
2444
2359
|
return taskCmdLineOf(cfg, passwordActive(cfg) && bat ? envBatPath(cfg) : bat)
|
|
2445
2360
|
}
|
|
2446
2361
|
|
|
2447
|
-
/** 给设置页看的清单:每个需要能不能做、要不要管理员 */
|
|
2448
|
-
function needCatalog(cfg) {
|
|
2449
|
-
const boot = (() => {
|
|
2450
|
-
try {
|
|
2451
|
-
return cachedBootMain(cfg)
|
|
2452
|
-
} catch {
|
|
2453
|
-
return ''
|
|
2454
|
-
}
|
|
2455
|
-
})()
|
|
2456
|
-
const bat = resolveLauncherPath(cfg)
|
|
2457
|
-
return Object.entries(SETUP_NEEDS).map(([id, meta]) => {
|
|
2458
|
-
let ready = true
|
|
2459
|
-
let why = ''
|
|
2460
|
-
let needAdmin = false
|
|
2461
|
-
if (id === 'launcher') {
|
|
2462
|
-
ready = Boolean(boot)
|
|
2463
|
-
if (!boot) why = 'Shell 目录里没找到 NapCatWinBootMain.exe'
|
|
2464
|
-
needAdmin = Boolean(boot) && !dirWritable(cfg.shellDir)
|
|
2465
|
-
if (needAdmin) why = 'Shell 目录当前不可写(大概在 Program Files 里,要管理员)'
|
|
2466
|
-
} else if (id === 'envbat') {
|
|
2467
|
-
ready = passwordActive(cfg) && Boolean(bat)
|
|
2468
|
-
if (!passwordActive(cfg)) why = '先打开「记住密码」并填好账号'
|
|
2469
|
-
else if (!bat) why = '先在 Shell 目录里找到启动脚本'
|
|
2470
|
-
needAdmin = Boolean(ready) && !dirWritable(path.dirname(envBatPath(cfg)))
|
|
2471
|
-
} else if (id === 'task') {
|
|
2472
|
-
ready = Boolean(cfg.taskName) && Boolean(bat)
|
|
2473
|
-
if (!cfg.taskName) why = '先填计划任务名'
|
|
2474
|
-
else if (!bat) why = '先填 Shell 目录(找得到启动脚本才建任务)'
|
|
2475
|
-
} else if (id === 'firewall') {
|
|
2476
|
-
ready = Boolean(cfg.onebotPort)
|
|
2477
|
-
if (!ready) why = '先填 OneBot 端口'
|
|
2478
|
-
needAdmin = true
|
|
2479
|
-
}
|
|
2480
|
-
return { id, label: meta.label, hint: meta.hint, ready, why, needAdmin }
|
|
2481
|
-
})
|
|
2482
|
-
}
|
|
2483
|
-
|
|
2484
|
-
/** 把「要做的事」摊成步骤数组(plan.json 里的 steps) */
|
|
2485
|
-
function buildSetupSteps(cfg, wants) {
|
|
2486
|
-
const picked = Array.isArray(wants) && wants.length ? wants : Object.keys(SETUP_NEEDS)
|
|
2487
|
-
const want = new Set(picked.filter((id) => SETUP_NEEDS[id]))
|
|
2488
|
-
const steps = []
|
|
2489
|
-
const bat = resolveLauncherPath(cfg)
|
|
2490
|
-
|
|
2491
|
-
if (want.has('launcher')) {
|
|
2492
|
-
const boot = (() => {
|
|
2493
|
-
try {
|
|
2494
|
-
return cachedBootMain(cfg)
|
|
2495
|
-
} catch {
|
|
2496
|
-
return ''
|
|
2497
|
-
}
|
|
2498
|
-
})()
|
|
2499
|
-
if (boot) {
|
|
2500
|
-
const file = path.join(cfg.shellDir, 'napcat.quick.auto.bat')
|
|
2501
|
-
steps.push({
|
|
2502
|
-
id: 'launcher',
|
|
2503
|
-
label: '补启动脚本 napcat.quick.auto.bat',
|
|
2504
|
-
kind: 'writeFile',
|
|
2505
|
-
path: file,
|
|
2506
|
-
admin: !dirWritable(cfg.shellDir),
|
|
2507
|
-
note: '直接调 NapCatWinBootMain.exe,账号走环境变量',
|
|
2508
|
-
contentBase64: Buffer.from(launcherBatLines(cfg, boot).join('\r\n'), 'utf8').toString('base64'),
|
|
2509
|
-
})
|
|
2510
|
-
}
|
|
2511
|
-
}
|
|
2512
|
-
|
|
2513
|
-
if (want.has('envbat') && passwordActive(cfg) && bat) {
|
|
2514
|
-
const file = envBatPath(cfg)
|
|
2515
|
-
steps.push({
|
|
2516
|
-
id: 'envbat',
|
|
2517
|
-
label: '写「记住密码」中间层 napcat-keeper-env.bat',
|
|
2518
|
-
kind: 'writeFile',
|
|
2519
|
-
path: file,
|
|
2520
|
-
admin: !dirWritable(path.dirname(file)),
|
|
2521
|
-
note: '只在本机磁盘里,关掉「记住密码」或点「清除密码」就删',
|
|
2522
|
-
secret: true,
|
|
2523
|
-
contentBase64: Buffer.from(envBatLines(cfg, bat).join('\r\n'), 'utf8').toString('base64'),
|
|
2524
|
-
})
|
|
2525
|
-
}
|
|
2526
|
-
|
|
2527
|
-
if (want.has('task') && cfg.taskName && bat) {
|
|
2528
|
-
const requires = []
|
|
2529
|
-
let inner = ''
|
|
2530
|
-
if (cfg.hideConsole !== false) {
|
|
2531
|
-
const vbs = taskWrapperPath(cfg)
|
|
2532
|
-
const cmdLine = taskCommandLinePure(cfg, bat).replace(/"/g, '""')
|
|
2533
|
-
const body = [
|
|
2534
|
-
'Option Explicit',
|
|
2535
|
-
'Dim sh',
|
|
2536
|
-
'Set sh = CreateObject("WScript.Shell")',
|
|
2537
|
-
`sh.Run "${cmdLine}", 0, False`,
|
|
2538
|
-
'',
|
|
2539
|
-
].join('\r\n')
|
|
2540
|
-
steps.push({
|
|
2541
|
-
id: 'task-wrapper',
|
|
2542
|
-
label: '写无窗口壳 launch.vbs',
|
|
2543
|
-
kind: 'writeFile',
|
|
2544
|
-
path: vbs,
|
|
2545
|
-
admin: !dirWritable(path.dirname(vbs)),
|
|
2546
|
-
note: '计划任务跑它,桌面才不会挂一个黑框',
|
|
2547
|
-
contentBase64: Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(body, 'utf16le')]).toString(
|
|
2548
|
-
'base64',
|
|
2549
|
-
),
|
|
2550
|
-
})
|
|
2551
|
-
requires.push('task-wrapper')
|
|
2552
|
-
inner = `wscript.exe "${vbs}"`
|
|
2553
|
-
} else {
|
|
2554
|
-
inner = taskCommandLinePure(cfg, bat)
|
|
2555
|
-
}
|
|
2556
|
-
if (passwordActive(cfg)) requires.push('envbat')
|
|
2557
|
-
steps.push({
|
|
2558
|
-
id: 'task',
|
|
2559
|
-
label: `建计划任务「${cfg.taskName}」`,
|
|
2560
|
-
kind: 'scheduledTask',
|
|
2561
|
-
admin: false,
|
|
2562
|
-
note: '用户级任务,一般不需要管理员;系统策略挡着时脚本会把错误原样告诉你',
|
|
2563
|
-
requires,
|
|
2564
|
-
name: cfg.taskName,
|
|
2565
|
-
command: inner,
|
|
2566
|
-
})
|
|
2567
|
-
}
|
|
2568
|
-
|
|
2569
|
-
if (want.has('firewall') && cfg.onebotPort) {
|
|
2570
|
-
const port = Number(cfg.onebotPort) || 3000
|
|
2571
|
-
steps.push({
|
|
2572
|
-
id: 'firewall',
|
|
2573
|
-
label: `放行 TCP ${port} 入站`,
|
|
2574
|
-
kind: 'firewallRule',
|
|
2575
|
-
admin: true,
|
|
2576
|
-
note: '只有别的设备要连 OneBot 端口时才需要;这条一定会弹 UAC',
|
|
2577
|
-
name: `dsh-napcat-keeper OneBot ${port}`,
|
|
2578
|
-
port,
|
|
2579
|
-
})
|
|
2580
|
-
}
|
|
2581
|
-
return steps
|
|
2582
|
-
}
|
|
2583
|
-
|
|
2584
|
-
/** apply.ps1 的全文:这段是插件的固定产物,跟 plan.json 一起决定脚本会干什么 */
|
|
2585
|
-
function applyPs1Source() {
|
|
2586
|
-
return `# dsh-napcat-keeper 提权交接脚本(插件自动生成,改了也会被覆盖)
|
|
2587
|
-
# 双击同目录的 apply-admin.cmd 干活;想撤干净就双击 undo-admin.cmd。
|
|
2588
|
-
param([switch]$Elevated, [switch]$Undo)
|
|
2589
|
-
$ErrorActionPreference = 'Continue'
|
|
2590
|
-
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
2591
|
-
$planPath = Join-Path $here 'plan.json'
|
|
2592
|
-
$resultPath = Join-Path $here 'result.json'
|
|
2593
|
-
$runLog = Join-Path $here 'run.log'
|
|
2594
|
-
# run.log 只追加不滚动会长到没人看:超过 256KB 就换新的一份
|
|
2595
|
-
try {
|
|
2596
|
-
if ((Test-Path -LiteralPath $runLog) -and ((Get-Item -LiteralPath $runLog).Length -gt 262144)) {
|
|
2597
|
-
Remove-Item -LiteralPath $runLog -Force -ErrorAction SilentlyContinue
|
|
2598
|
-
}
|
|
2599
|
-
} catch {}
|
|
2600
|
-
|
|
2601
|
-
function Say($text) {
|
|
2602
|
-
$line = ('[{0}] {1}' -f (Get-Date -Format 'HH:mm:ss'), $text)
|
|
2603
|
-
Write-Host $line
|
|
2604
|
-
try { Add-Content -LiteralPath $runLog -Value $line -Encoding UTF8 } catch {}
|
|
2605
|
-
}
|
|
2606
|
-
|
|
2607
|
-
function Wait-Key {
|
|
2608
|
-
if ($env:NPK_NO_PAUSE -eq '1') { return }
|
|
2609
|
-
Write-Host ''
|
|
2610
|
-
Write-Host '按任意键关掉这个窗口。'
|
|
2611
|
-
try { $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') } catch {}
|
|
2612
|
-
}
|
|
2613
|
-
|
|
2614
|
-
if (-not (Test-Path -LiteralPath $planPath)) {
|
|
2615
|
-
Say 'plan.json 不在了 —— 回 DSH 设置页重新生成一次。'
|
|
2616
|
-
Wait-Key
|
|
2617
|
-
exit 2
|
|
2618
|
-
}
|
|
2619
|
-
|
|
2620
|
-
$plan = Get-Content -LiteralPath $planPath -Raw -Encoding UTF8 | ConvertFrom-Json
|
|
2621
|
-
$steps = @($plan.steps)
|
|
2622
|
-
$mode = 'apply'
|
|
2623
|
-
if ($Undo) {
|
|
2624
|
-
$mode = 'undo'
|
|
2625
|
-
$rev = @()
|
|
2626
|
-
for ($i = $steps.Count - 1; $i -ge 0; $i--) { $rev += $steps[$i] }
|
|
2627
|
-
$steps = $rev
|
|
2628
|
-
}
|
|
2629
|
-
|
|
2630
|
-
Say ('开始(' + $mode + '):' + $steps.Count + ' 步')
|
|
2631
|
-
|
|
2632
|
-
$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
|
2633
|
-
$needAdmin = @($steps | Where-Object { $_.admin -eq $true }).Count -gt 0
|
|
2634
|
-
|
|
2635
|
-
if ((!$Undo) -and $needAdmin -and (-not $admin) -and (-not $Elevated)) {
|
|
2636
|
-
Say '这批步骤里有要管理员才行的,马上弹 UAC —— 请点「是」;点「否」就什么都不改。'
|
|
2637
|
-
$argList = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ('"' + $PSCommandPath + '"'), '-Elevated')
|
|
2638
|
-
try {
|
|
2639
|
-
Start-Process -FilePath 'powershell.exe' -Verb RunAs -ArgumentList $argList
|
|
2640
|
-
Say '已经把活交给提权那个窗口了,跑完看同目录的 result.json。'
|
|
2641
|
-
} catch {
|
|
2642
|
-
Say '没拿到管理员权限(UAC 被拒或这台机器不给提权),这次什么都没改。'
|
|
2643
|
-
}
|
|
2644
|
-
Wait-Key
|
|
2645
|
-
exit 0
|
|
2646
|
-
}
|
|
2647
|
-
|
|
2648
|
-
$results = @()
|
|
2649
|
-
$failed = @{}
|
|
2650
|
-
foreach ($s in $steps) {
|
|
2651
|
-
$entry = [ordered]@{ id = $s.id; label = $s.label; ok = $false; skipped = $false; message = '' }
|
|
2652
|
-
if ((!$Undo) -and $s.requires) {
|
|
2653
|
-
$miss = @($s.requires | Where-Object { $failed.ContainsKey($_) })
|
|
2654
|
-
if ($miss.Count -gt 0) {
|
|
2655
|
-
$entry.skipped = $true
|
|
2656
|
-
$entry.message = '前一步没成(' + ($miss -join '、') + '),这步跳过'
|
|
2657
|
-
Say ('跳过 ' + $s.label + ':' + $entry.message)
|
|
2658
|
-
$results += $entry
|
|
2659
|
-
continue
|
|
2660
|
-
}
|
|
2661
|
-
}
|
|
2662
|
-
try {
|
|
2663
|
-
switch ($s.kind) {
|
|
2664
|
-
'writeFile' {
|
|
2665
|
-
if ($Undo) {
|
|
2666
|
-
if (Test-Path -LiteralPath $s.path) {
|
|
2667
|
-
Remove-Item -LiteralPath $s.path -Force
|
|
2668
|
-
$entry.message = '已删除'
|
|
2669
|
-
} else {
|
|
2670
|
-
$entry.message = '本来就没有'
|
|
2671
|
-
}
|
|
2672
|
-
} else {
|
|
2673
|
-
$dir = Split-Path -Parent $s.path
|
|
2674
|
-
if ($dir -and (-not (Test-Path -LiteralPath $dir))) { New-Item -ItemType Directory -Force -Path $dir | Out-Null }
|
|
2675
|
-
$bytes = [Convert]::FromBase64String($s.contentBase64)
|
|
2676
|
-
[IO.File]::WriteAllBytes($s.path, $bytes)
|
|
2677
|
-
if ($s.secret) { $entry.message = '已写入(内容不外显)' } else { $entry.message = '已写入' }
|
|
2678
|
-
}
|
|
2679
|
-
$entry.ok = $true
|
|
2680
|
-
}
|
|
2681
|
-
'mkdir' {
|
|
2682
|
-
if (-not $Undo) {
|
|
2683
|
-
New-Item -ItemType Directory -Force -Path $s.path | Out-Null
|
|
2684
|
-
$entry.message = '已建目录'
|
|
2685
|
-
} else {
|
|
2686
|
-
$entry.message = '不用撤'
|
|
2687
|
-
}
|
|
2688
|
-
$entry.ok = $true
|
|
2689
|
-
}
|
|
2690
|
-
'scheduledTask' {
|
|
2691
|
-
if ($Undo) {
|
|
2692
|
-
$null = & schtasks.exe /delete /tn $s.name /f 2>&1
|
|
2693
|
-
$entry.message = '任务已删(本来没有也算)'
|
|
2694
|
-
} else {
|
|
2695
|
-
# 先结束同名旧任务(正在跑时 /f 覆盖会被拒);/st 00:00 会带一句
|
|
2696
|
-
# 「时间已过」的自我提醒,成功时不必让用户看见,失败时才把原始输出抛出来
|
|
2697
|
-
$null = & schtasks.exe /end /tn $s.name 2>&1
|
|
2698
|
-
$createOut = (& schtasks.exe /create /tn $s.name /tr $s.command /sc ONCE /st 00:00 /f 2>&1 | Out-String)
|
|
2699
|
-
if ($LASTEXITCODE -ne 0) { throw ('schtasks 失败(退出码 ' + $LASTEXITCODE + '):' + $createOut.Trim()) }
|
|
2700
|
-
$entry.message = '任务已就绪'
|
|
2701
|
-
}
|
|
2702
|
-
$entry.ok = $true
|
|
2703
|
-
}
|
|
2704
|
-
'firewallRule' {
|
|
2705
|
-
if ($Undo) {
|
|
2706
|
-
Get-NetFirewallRule -DisplayName $s.name -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue
|
|
2707
|
-
$entry.message = '规则已删(本来没有也算)'
|
|
2708
|
-
} else {
|
|
2709
|
-
Get-NetFirewallRule -DisplayName $s.name -ErrorAction SilentlyContinue | Remove-NetFirewallRule -ErrorAction SilentlyContinue
|
|
2710
|
-
New-NetFirewallRule -DisplayName $s.name -Direction Inbound -Action Allow -Protocol TCP -LocalPort ([int]$s.port) -Profile Private, Domain -ErrorAction Stop | Out-Null
|
|
2711
|
-
$entry.message = ('已放行 TCP ' + [int]$s.port)
|
|
2712
|
-
}
|
|
2713
|
-
$entry.ok = $true
|
|
2714
|
-
}
|
|
2715
|
-
default {
|
|
2716
|
-
$entry.message = ('不认识的步骤类型 ' + $s.kind)
|
|
2717
|
-
}
|
|
2718
|
-
}
|
|
2719
|
-
} catch {
|
|
2720
|
-
$entry.ok = $false
|
|
2721
|
-
$entry.message = '出错:' + $_.Exception.Message
|
|
2722
|
-
}
|
|
2723
|
-
if (-not $entry.ok) { $failed[$s.id] = $true }
|
|
2724
|
-
if ($entry.ok) { Say ('好了 ' + $s.label) } else { Say ('没成 ' + $s.label + ':' + $entry.message) }
|
|
2725
|
-
$results += $entry
|
|
2726
|
-
}
|
|
2727
|
-
|
|
2728
|
-
$bad = @($results | Where-Object { -not $_.ok })
|
|
2729
|
-
$payload = [ordered]@{
|
|
2730
|
-
at = (Get-Date).ToString('o')
|
|
2731
|
-
mode = $mode
|
|
2732
|
-
elevated = $admin
|
|
2733
|
-
adminNeeded = $needAdmin
|
|
2734
|
-
ok = ($bad.Count -eq 0)
|
|
2735
|
-
results = $results
|
|
2736
|
-
}
|
|
2737
|
-
try {
|
|
2738
|
-
$json = $payload | ConvertTo-Json -Depth 8
|
|
2739
|
-
[IO.File]::WriteAllText($resultPath, $json, (New-Object System.Text.UTF8Encoding($false)))
|
|
2740
|
-
Say ('收工:' + $bad.Count + ' 步没成;结果已写回 result.json,回 DSH 设置页点「读结果」就行。')
|
|
2741
|
-
} catch {
|
|
2742
|
-
Say ('结果没写出来:' + $_.Exception.Message)
|
|
2743
|
-
}
|
|
2744
|
-
Wait-Key
|
|
2745
|
-
`
|
|
2746
|
-
}
|
|
2747
|
-
|
|
2748
|
-
/** 双击入口 .cmd:内容全 ASCII,cmd 才不会把它显示成乱码 */
|
|
2749
|
-
function setupCmdSource() {
|
|
2750
|
-
return [
|
|
2751
|
-
'@echo off',
|
|
2752
|
-
'rem dsh-napcat-keeper - elevation handoff (auto-generated; edits get overwritten)',
|
|
2753
|
-
'rem Double-click this file. PowerShell asks for admin only if the plan really needs it.',
|
|
2754
|
-
'title dsh-napcat-keeper setup',
|
|
2755
|
-
'cd /d "%~dp0"',
|
|
2756
|
-
'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0apply.ps1"',
|
|
2757
|
-
'if errorlevel 1 pause',
|
|
2758
|
-
'',
|
|
2759
|
-
].join('\r\n')
|
|
2760
|
-
}
|
|
2761
|
-
|
|
2762
|
-
function setupUndoCmdSource() {
|
|
2763
|
-
return [
|
|
2764
|
-
'@echo off',
|
|
2765
|
-
'rem dsh-napcat-keeper - undo what this plan created (reverse order)',
|
|
2766
|
-
'title dsh-napcat-keeper undo',
|
|
2767
|
-
'cd /d "%~dp0"',
|
|
2768
|
-
'powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0apply.ps1" -Undo',
|
|
2769
|
-
'if errorlevel 1 pause',
|
|
2770
|
-
'',
|
|
2771
|
-
].join('\r\n')
|
|
2772
|
-
}
|
|
2773
|
-
|
|
2774
|
-
/** 说明文件:给人看的,写清楚会动哪些文件、怎么撤回 */
|
|
2775
|
-
function setupReadmeText(cfg, plan) {
|
|
2776
|
-
const lines = [
|
|
2777
|
-
'dsh-napcat-keeper 提权交接目录',
|
|
2778
|
-
'',
|
|
2779
|
-
'这是什么:',
|
|
2780
|
-
' DSH 自己是普通权限进程,插件偶尔要做几件「可能要管理员」的事。',
|
|
2781
|
-
' 插件不自己去要管理员,而是把要做的事写在这里,由你双击一下、在 UAC 上点「是」。',
|
|
2782
|
-
'',
|
|
2783
|
-
'怎么用:',
|
|
2784
|
-
' 1) 双击 apply-admin.cmd;',
|
|
2785
|
-
' 2) 如果这批步骤需要管理员,会弹 UAC —— 点「是」;点「否」就什么都不会改;',
|
|
2786
|
-
' 3) 跑完回 DSH 设置页点「读结果」,能看到每一步成没成。',
|
|
2787
|
-
'',
|
|
2788
|
-
'想撤回:双击 undo-admin.cmd(按相反顺序把这次建的东西删掉)。',
|
|
2789
|
-
'',
|
|
2790
|
-
`生成时间:${plan.createdAt}`,
|
|
2791
|
-
`Shell 目录:${cfg.shellDir || '(未配置)'}`,
|
|
2792
|
-
`这批步骤${plan.needAdmin ? '需要' : '不需要'}管理员权限。`,
|
|
2793
|
-
'',
|
|
2794
|
-
'会动的文件 / 规则:',
|
|
2795
|
-
...plan.steps.map((s, i) => {
|
|
2796
|
-
const where = s.path || s.name || s.kind
|
|
2797
|
-
return ` ${i + 1}. [${s.kind}] ${where}${s.admin ? '(要管理员)' : ''}`
|
|
2798
|
-
}),
|
|
2799
|
-
'',
|
|
2800
|
-
'这几个文件里没有密码明文说明:napcat-keeper-env.bat 里有(那是给 NapCat 用的),',
|
|
2801
|
-
'所以这个目录别往外发;关掉「记住密码」或在设置页点「清除密码」就会删掉它。',
|
|
2802
|
-
'',
|
|
2803
|
-
]
|
|
2804
|
-
return lines.join('\r\n')
|
|
2805
|
-
}
|
|
2806
|
-
|
|
2807
|
-
/** 生成整套脚本,返回给设置页用的摘要(不含任何 secret 内容) */
|
|
2808
|
-
function writeSetupBundle(cfg, wants) {
|
|
2809
|
-
if (process.platform !== 'win32') {
|
|
2810
|
-
return { ok: false, error: '这套脚本只对 Windows 有意义' }
|
|
2811
|
-
}
|
|
2812
|
-
const steps = buildSetupSteps(cfg, wants)
|
|
2813
|
-
if (!steps.length) {
|
|
2814
|
-
return { ok: false, error: '这次一条可做的步骤都没有(先把 Shell 目录 / 账号 / 任务名填上)' }
|
|
2815
|
-
}
|
|
2816
|
-
const p = setupPaths()
|
|
2817
|
-
const plan = {
|
|
2818
|
-
plugin: 'dsh-napcat-keeper',
|
|
2819
|
-
version,
|
|
2820
|
-
createdAt: new Date().toISOString(),
|
|
2821
|
-
shellDir: cfg.shellDir || '',
|
|
2822
|
-
account: cfg.launchAccount || '',
|
|
2823
|
-
needAdmin: steps.some((s) => s.admin === true),
|
|
2824
|
-
steps,
|
|
2825
|
-
}
|
|
2826
|
-
try {
|
|
2827
|
-
mkdirSync(p.dir, { recursive: true })
|
|
2828
|
-
writeFileSync(p.plan, `${JSON.stringify(plan, null, 2)}\n`, 'utf8')
|
|
2829
|
-
// ps1 必须带 BOM:PowerShell 5.1 没有 BOM 会按 ANSI 解,中文全变乱码
|
|
2830
|
-
writeFileSync(
|
|
2831
|
-
p.ps1,
|
|
2832
|
-
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(applyPs1Source(), 'utf8')]),
|
|
2833
|
-
)
|
|
2834
|
-
writeFileSync(p.cmd, setupCmdSource(), 'utf8')
|
|
2835
|
-
writeFileSync(p.undoCmd, setupUndoCmdSource(), 'utf8')
|
|
2836
|
-
writeFileSync(
|
|
2837
|
-
p.readme,
|
|
2838
|
-
Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), Buffer.from(setupReadmeText(cfg, plan), 'utf8')]),
|
|
2839
|
-
)
|
|
2840
|
-
try {
|
|
2841
|
-
if (existsSync(p.result)) unlinkSync(p.result)
|
|
2842
|
-
} catch {}
|
|
2843
|
-
log(cfg, `setup bundle 写好了:${p.dir}(${steps.length} 步,needAdmin=${plan.needAdmin})`)
|
|
2844
|
-
} catch (error) {
|
|
2845
|
-
const msg = String((error && error.message) || error)
|
|
2846
|
-
log(cfg, `setup bundle 写不出来:${msg}`)
|
|
2847
|
-
return { ok: false, error: msg }
|
|
2848
|
-
}
|
|
2849
|
-
return {
|
|
2850
|
-
ok: true,
|
|
2851
|
-
dir: p.dir,
|
|
2852
|
-
cmd: p.cmd,
|
|
2853
|
-
ps1: p.ps1,
|
|
2854
|
-
undoCmd: p.undoCmd,
|
|
2855
|
-
needAdmin: plan.needAdmin,
|
|
2856
|
-
steps: steps.map(({ contentBase64, ...rest }) => rest),
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
|
|
2860
|
-
/** 读脚本写回来的结果(不存在就是「还没跑」) */
|
|
2861
|
-
function readSetupResult() {
|
|
2862
|
-
const p = setupPaths()
|
|
2863
|
-
try {
|
|
2864
|
-
if (!existsSync(p.result)) return null
|
|
2865
|
-
const text = readFileSync(p.result, 'utf8').replace(/^\uFEFF/, '')
|
|
2866
|
-
const parsed = JSON.parse(text)
|
|
2867
|
-
if (!parsed || typeof parsed !== 'object') return null
|
|
2868
|
-
let results = parsed.results
|
|
2869
|
-
if (!Array.isArray(results)) results = results ? [results] : []
|
|
2870
|
-
let mtimeMs = 0
|
|
2871
|
-
try {
|
|
2872
|
-
mtimeMs = statSync(p.result).mtimeMs
|
|
2873
|
-
} catch {}
|
|
2874
|
-
return {
|
|
2875
|
-
at: String(parsed.at || ''),
|
|
2876
|
-
mode: String(parsed.mode || 'apply'),
|
|
2877
|
-
elevated: Boolean(parsed.elevated),
|
|
2878
|
-
ok: Boolean(parsed.ok),
|
|
2879
|
-
mtimeMs,
|
|
2880
|
-
results: results.map((r) => ({
|
|
2881
|
-
id: String((r && r.id) || ''),
|
|
2882
|
-
label: String((r && r.label) || ''),
|
|
2883
|
-
ok: Boolean(r && r.ok),
|
|
2884
|
-
skipped: Boolean(r && r.skipped),
|
|
2885
|
-
message: String((r && r.message) || ''),
|
|
2886
|
-
})),
|
|
2887
|
-
}
|
|
2888
|
-
} catch {
|
|
2889
|
-
return null
|
|
2890
|
-
}
|
|
2891
|
-
}
|
|
2892
|
-
|
|
2893
|
-
/** 上一次生成的那份计划(给设置页显示「你上次要它做什么」) */
|
|
2894
|
-
function readSetupPlan() {
|
|
2895
|
-
const p = setupPaths()
|
|
2896
|
-
try {
|
|
2897
|
-
if (!existsSync(p.plan)) return null
|
|
2898
|
-
const parsed = JSON.parse(readFileSync(p.plan, 'utf8').replace(/^\uFEFF/, ''))
|
|
2899
|
-
if (!parsed || typeof parsed !== 'object') return null
|
|
2900
|
-
const steps = Array.isArray(parsed.steps) ? parsed.steps : []
|
|
2901
|
-
return {
|
|
2902
|
-
createdAt: String(parsed.createdAt || ''),
|
|
2903
|
-
needAdmin: Boolean(parsed.needAdmin),
|
|
2904
|
-
steps: steps.map((s) => ({
|
|
2905
|
-
id: String((s && s.id) || ''),
|
|
2906
|
-
label: String((s && s.label) || ''),
|
|
2907
|
-
kind: String((s && s.kind) || ''),
|
|
2908
|
-
where: String((s && (s.path || s.name)) || ''),
|
|
2909
|
-
admin: Boolean(s && s.admin),
|
|
2910
|
-
})),
|
|
2911
|
-
}
|
|
2912
|
-
} catch {
|
|
2913
|
-
return null
|
|
2914
|
-
}
|
|
2915
|
-
}
|
|
2916
|
-
|
|
2917
|
-
function setupState(cfg) {
|
|
2918
|
-
const p = setupPaths()
|
|
2919
|
-
let exists = false
|
|
2920
|
-
try {
|
|
2921
|
-
exists = existsSync(p.cmd)
|
|
2922
|
-
} catch {}
|
|
2923
|
-
return {
|
|
2924
|
-
dir: p.dir,
|
|
2925
|
-
cmdPath: p.cmd,
|
|
2926
|
-
ps1Path: p.ps1,
|
|
2927
|
-
undoCmdPath: p.undoCmd,
|
|
2928
|
-
exists,
|
|
2929
|
-
needs: needCatalog(cfg),
|
|
2930
|
-
plan: readSetupPlan(),
|
|
2931
|
-
lastRun: readSetupResult(),
|
|
2932
|
-
}
|
|
2933
|
-
}
|
|
2934
|
-
|
|
2935
|
-
/** 在资源管理器里选中那个 cmd(不是只打开目录,免得用户还得自己找) */
|
|
2936
|
-
function openSetupFolder() {
|
|
2937
|
-
const p = setupPaths()
|
|
2938
|
-
try {
|
|
2939
|
-
mkdirSync(p.dir, { recursive: true })
|
|
2940
|
-
const hasCmd = existsSync(p.cmd)
|
|
2941
|
-
const child = spawn('explorer.exe', [hasCmd ? `/select,${p.cmd}` : p.dir], {
|
|
2942
|
-
detached: true,
|
|
2943
|
-
stdio: 'ignore',
|
|
2944
|
-
windowsHide: false,
|
|
2945
|
-
})
|
|
2946
|
-
child.unref()
|
|
2947
|
-
return { ok: true, dir: p.dir, cmd: p.cmd, selected: hasCmd }
|
|
2948
|
-
} catch (error) {
|
|
2949
|
-
return { ok: false, error: String((error && error.message) || error), dir: p.dir }
|
|
2950
|
-
}
|
|
2951
|
-
}
|
|
2952
|
-
|
|
2953
2362
|
/** 把已经在跑的 NapCat 控制台窗口藏起来(老链条留下的黑框也能收掉,不用重启 QQ) */
|
|
2954
2363
|
function hideConsoleWindows(cfg) {
|
|
2955
2364
|
const ps = [
|
|
@@ -3588,6 +2997,19 @@ function registerTools(ctx, cfg) {
|
|
|
3588
2997
|
procs,
|
|
3589
2998
|
node: nodePublic(cfg),
|
|
3590
2999
|
qr,
|
|
3000
|
+
/** 要扫码时把这一页发给用户:优先独立小端口(任何浏览器都打得开),其次 DSH 路由 */
|
|
3001
|
+
qrPanel: {
|
|
3002
|
+
path: QR_PANEL_PATH,
|
|
3003
|
+
url: qrPanelPublic(cfg).url || QR_PANEL_PATH,
|
|
3004
|
+
running: qrPanelPublic(cfg).running,
|
|
3005
|
+
port: qrPanelPublic(cfg).port,
|
|
3006
|
+
note: qrPanelPublic(cfg).note,
|
|
3007
|
+
hint: health.online
|
|
3008
|
+
? '已登录,暂时用不上扫码页;下次掉线要扫码时同一个地址还能用。'
|
|
3009
|
+
: qrPanelPublic(cfg).url
|
|
3010
|
+
? '需要手机扫码时点开 qrPanel.url 那个地址(本机浏览器打开即可),二维码会自己换。'
|
|
3011
|
+
: '需要手机扫码时点开 qrPanel.path(挂在 DSH 地址后面),二维码会自己换。',
|
|
3012
|
+
},
|
|
3591
3013
|
bridge: bridgeAge(cfg),
|
|
3592
3014
|
autoLogin: {
|
|
3593
3015
|
rememberPassword: cfg.rememberPassword,
|
|
@@ -3628,7 +3050,9 @@ function registerTools(ctx, cfg) {
|
|
|
3628
3050
|
: qr && qr.ageSec <= cfg.qrFreshSec
|
|
3629
3051
|
? passwordActive(cfg)
|
|
3630
3052
|
? '离线,且在等扫码——但「记住密码」是开着的:看一眼日志里“快速登录错误”后面是不是仍回退到二维码(密码登录可能被腾讯要求验证)。'
|
|
3631
|
-
: '
|
|
3053
|
+
: '离线,且二维码是新的:需要手机扫码 —— 打开 ' +
|
|
3054
|
+
(qrPanelPublic(cfg).url || qrPanelPublic(cfg).path) +
|
|
3055
|
+
' 就是一张会自己刷新的码(设置 → napcat桥 顶上那条黄横幅也能点开)。或者打开「记住密码」让 NapCat 自己用密码登录。图片文件在 qrCopyPath。'
|
|
3632
3056
|
: '离线。看门狗会自动拉起;若 procs.dup 为 true 说明被重复拉起过,已自动去重。',
|
|
3633
3057
|
},
|
|
3634
3058
|
null,
|
|
@@ -3730,6 +3154,7 @@ function stop(cfg) {
|
|
|
3730
3154
|
state.timer = null
|
|
3731
3155
|
log(cfg, 'watchdog stopped')
|
|
3732
3156
|
}
|
|
3157
|
+
stopQrPanel(cfg, '插件停了')
|
|
3733
3158
|
}
|
|
3734
3159
|
|
|
3735
3160
|
function armTimer(cfg) {
|
|
@@ -3755,6 +3180,406 @@ function armTimer(cfg) {
|
|
|
3755
3180
|
|
|
3756
3181
|
const ROUTE = '/dsh-napcat-keeper'
|
|
3757
3182
|
|
|
3183
|
+
/** 扫码页地址(相对 DSH 那个地址):NapCat 要手机扫码时,用户点这个就能看见会自己刷新的二维码。 */
|
|
3184
|
+
const QR_PANEL_PATH = `${ROUTE}/qr`
|
|
3185
|
+
|
|
3186
|
+
/** NapCat 的码大约 2 分钟一换;页面按这个算「这张码还剩几秒」。 */
|
|
3187
|
+
const QR_TTL_SEC = 120
|
|
3188
|
+
|
|
3189
|
+
/**
|
|
3190
|
+
* 扫码页(纯字符串内嵌,不带任何静态文件)。
|
|
3191
|
+
* 图 / 状态 / 重拉 全走本插件自己的 /dsh-napcat-keeper/* 路由,所以不用另起端口,
|
|
3192
|
+
* DSH 换端口时这一页跟着换,链接永远有效。
|
|
3193
|
+
* 页面里用的都是相对路径(qr.png / qr-state / qr-restart)—— 挂在 /dsh-napcat-keeper/qr 下正好。
|
|
3194
|
+
*/
|
|
3195
|
+
const QR_PAGE_HTML = String.raw`<!doctype html>
|
|
3196
|
+
<html lang="zh-CN"><head><meta charset="utf-8">
|
|
3197
|
+
<title>NapCat 扫码登录</title>
|
|
3198
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
3199
|
+
<style>
|
|
3200
|
+
:root { --bg:#0f1420; --card:#161d2c; --fg:#e8eefc; --dim:#8b98b4; --ok:#41d392; --warn:#f5c451; --bad:#f0705f; }
|
|
3201
|
+
* { box-sizing: border-box; }
|
|
3202
|
+
body { margin:0; min-height:100vh; background:radial-gradient(1200px 600px at 50% -10%, #1b2740, var(--bg)); color:var(--fg);
|
|
3203
|
+
font:15px/1.6 "Microsoft YaHei UI", system-ui, sans-serif; display:flex; align-items:center; justify-content:center; padding:24px; }
|
|
3204
|
+
.card { width:min(560px,100%); background:var(--card); border:1px solid #24304a; border-radius:18px; padding:22px 22px 18px;
|
|
3205
|
+
box-shadow:0 20px 60px rgba(0,0,0,.45); }
|
|
3206
|
+
h1 { margin:0 0 2px; font-size:19px; font-weight:600; letter-spacing:.5px; }
|
|
3207
|
+
.sub { color:var(--dim); font-size:13px; margin-bottom:16px; }
|
|
3208
|
+
.qrwrap { position:relative; background:#fff; border-radius:14px; padding:14px; display:flex; justify-content:center; min-height:180px; }
|
|
3209
|
+
.qrwrap img { width:100%; max-width:340px; image-rendering:pixelated; display:block; }
|
|
3210
|
+
.overlay { position:absolute; inset:0; display:none; align-items:center; justify-content:center; border-radius:14px;
|
|
3211
|
+
background:rgba(15,20,32,.9); color:var(--fg); font-size:15px; text-align:center; padding:20px; }
|
|
3212
|
+
.overlay.show { display:flex; }
|
|
3213
|
+
.rows { margin:16px 0 4px; }
|
|
3214
|
+
.row { display:flex; justify-content:space-between; gap:12px; padding:6px 0; border-bottom:1px dashed #232e46; font-size:14px; }
|
|
3215
|
+
.row:last-child { border-bottom:none; }
|
|
3216
|
+
.k { color:var(--dim); }
|
|
3217
|
+
.v { font-variant-numeric:tabular-nums; text-align:right; word-break:break-all; }
|
|
3218
|
+
.dot { display:inline-block; width:8px; height:8px; border-radius:50%; margin-right:6px; vertical-align:1px; background:var(--dim); }
|
|
3219
|
+
.ok { color:var(--ok); } .warn { color:var(--warn); } .bad { color:var(--bad); }
|
|
3220
|
+
.ok .dot { background:var(--ok); } .warn .dot { background:var(--warn); } .bad .dot { background:var(--bad); }
|
|
3221
|
+
.bar { display:flex; gap:10px; margin-top:14px; flex-wrap:wrap; }
|
|
3222
|
+
.smsbox { display:none; margin-top:14px; padding:10px 12px; border-radius:10px;
|
|
3223
|
+
border:1px solid #b8860b; background:rgba(184,134,11,.12); }
|
|
3224
|
+
.smsbox.show { display:block; }
|
|
3225
|
+
.smstitle { color:var(--warn); font-size:13px; margin-bottom:4px; }
|
|
3226
|
+
.smlink { display:inline-block; margin-top:8px; padding:7px 12px; border-radius:8px;
|
|
3227
|
+
background:#2a3550; color:#cfe0ff; text-decoration:none; font-size:13px; }
|
|
3228
|
+
button, a.btn { flex:0 0 auto; cursor:pointer; border:1px solid #2d3b58; background:#1d2740; color:var(--fg);
|
|
3229
|
+
border-radius:10px; padding:9px 14px; font-size:14px; text-decoration:none; }
|
|
3230
|
+
button:hover, a.btn:hover { background:#243254; }
|
|
3231
|
+
button.primary { background:#2b6cf6; border-color:#2b6cf6; }
|
|
3232
|
+
button.primary:hover { background:#3a78ff; }
|
|
3233
|
+
.hint { color:var(--dim); font-size:12.5px; margin-top:10px; }
|
|
3234
|
+
</style></head>
|
|
3235
|
+
<body>
|
|
3236
|
+
<div class="card">
|
|
3237
|
+
<h1>NapCat 扫码登录</h1>
|
|
3238
|
+
<div class="sub">二维码每 2 秒自动换新的(NapCat 换码会跟着换,不用手动刷新页面)</div>
|
|
3239
|
+
|
|
3240
|
+
<div class="qrwrap">
|
|
3241
|
+
<img id="qr" alt="二维码还没出来" src="qr.png?t=0">
|
|
3242
|
+
<div class="overlay" id="ov"><div id="ovtext">等 NapCat 出码…</div></div>
|
|
3243
|
+
</div>
|
|
3244
|
+
|
|
3245
|
+
<div class="rows">
|
|
3246
|
+
<div class="row"><span class="k">OneBot 接口</span><span class="v" id="v-api">—</span></div>
|
|
3247
|
+
<div class="row"><span class="k">登录状态</span><span class="v" id="v-login">—</span></div>
|
|
3248
|
+
<div class="row"><span class="k">二维码</span><span class="v" id="v-qr">—</span></div>
|
|
3249
|
+
<div class="row"><span class="k">这张码还剩</span><span class="v" id="v-ttl">—</span></div>
|
|
3250
|
+
<div class="row"><span class="k">看门狗阶段</span><span class="v" id="v-phase">—</span></div>
|
|
3251
|
+
<div class="row"><span class="k">扫码重试</span><span class="v" id="v-retry">—</span></div>
|
|
3252
|
+
<div class="row"><span class="k">最近日志</span><span class="v" id="v-log">—</span></div>
|
|
3253
|
+
</div>
|
|
3254
|
+
|
|
3255
|
+
<div class="smsbox" id="smsbox">
|
|
3256
|
+
<div class="smstitle" id="sms-title">⚠ 这次登录要短信验证</div>
|
|
3257
|
+
<div class="hint">NapCat 的日志里给了验证链接,点开在同一台机器上完成就行。</div>
|
|
3258
|
+
<a class="smlink" id="sms-link" href="#" target="_blank" rel="noreferrer">打开验证页面</a>
|
|
3259
|
+
</div>
|
|
3260
|
+
|
|
3261
|
+
<div class="bar">
|
|
3262
|
+
<button class="primary" id="btn-restart">我要新码(重拉 NapCat)</button>
|
|
3263
|
+
<button id="btn-tick">立即刷新</button>
|
|
3264
|
+
</div>
|
|
3265
|
+
<div class="hint" id="hint">页面开着就行:扫码成功后这里会变绿。</div>
|
|
3266
|
+
</div>
|
|
3267
|
+
|
|
3268
|
+
<script>
|
|
3269
|
+
let restartedAt = 0;
|
|
3270
|
+
const $ = (id) => document.getElementById(id);
|
|
3271
|
+
const PHASES = { idle:'待机', online:'在线', launching:'正在拉起', starting:'正在启动',
|
|
3272
|
+
'need-scan':'在等你扫码', 'need-scan-giveup':'扫码放弃(重试到上限了)', 'reverse-wait':'等反向 WS 连进来',
|
|
3273
|
+
'reverse-giveup':'反向 WS 等不到客户端', 'need-token':'令牌不对', 'port-busy':'端口被占', offline:'离线' };
|
|
3274
|
+
|
|
3275
|
+
function fmt(sec) {
|
|
3276
|
+
if (sec === null || sec === undefined) return '—';
|
|
3277
|
+
if (sec < 60) return sec + ' 秒前';
|
|
3278
|
+
return Math.floor(sec / 60) + ' 分 ' + (sec % 60) + ' 秒前';
|
|
3279
|
+
}
|
|
3280
|
+
|
|
3281
|
+
async function tick() {
|
|
3282
|
+
$('qr').src = 'qr.png?t=' + Date.now();
|
|
3283
|
+
let s;
|
|
3284
|
+
try { s = await (await fetch('qr-state?t=' + Date.now(), { cache:'no-store' })).json() }
|
|
3285
|
+
catch (e) { $('hint').textContent = '接口没响应:' + e; return }
|
|
3286
|
+
|
|
3287
|
+
restartedAt = s.restartedAt || 0;
|
|
3288
|
+
const qr = s.qr || null;
|
|
3289
|
+
const age = qr ? qr.ageSec : null;
|
|
3290
|
+
const left = (age === null || age === undefined) ? null : Math.max(0, (s.qrTtlSec || 120) - age);
|
|
3291
|
+
const fresh = left !== null && left > 20;
|
|
3292
|
+
|
|
3293
|
+
$('v-api').className = 'v ' + (s.online ? 'ok' : 'warn');
|
|
3294
|
+
$('v-api').innerHTML = '<span class="dot"></span>' + (s.online ? '通(在线)' : '还没通') +
|
|
3295
|
+
(typeof s.portStatus === 'number' && s.portStatus ? ' · HTTP ' + s.portStatus : '');
|
|
3296
|
+
|
|
3297
|
+
$('v-qr').className = 'v ' + (age === null ? 'bad' : (fresh ? 'ok' : 'warn'));
|
|
3298
|
+
$('v-qr').innerHTML = '<span class="dot"></span>' + (age === null ? '还没有 qrcode.png' : '更新于 ' + fmt(age));
|
|
3299
|
+
|
|
3300
|
+
$('v-ttl').className = 'v ' + (left === null ? 'bad' : (left > 30 ? 'ok' : 'warn'));
|
|
3301
|
+
$('v-ttl').innerHTML = left === null ? '<span class="dot"></span>—'
|
|
3302
|
+
: '<span class="dot"></span>约 ' + left + ' 秒(到点自己换)';
|
|
3303
|
+
|
|
3304
|
+
$('v-phase').innerHTML = '<span class="dot"></span>' + (PHASES[s.phase] || s.phase || '—');
|
|
3305
|
+
$('v-retry').textContent = (s.scanRetries || 0) + ' 次';
|
|
3306
|
+
$('v-log').textContent = (s.logTail && s.logTail.length ? s.logTail[s.logTail.length - 1] : '—');
|
|
3307
|
+
|
|
3308
|
+
// 要短信验证的时候把腾讯那个验证链接直接摆出来(光有二维码扫不进去)。
|
|
3309
|
+
// 注意再叠一层 !s.online:老日志里的 ErrCode 会一直留着,在线时绝不能误报。
|
|
3310
|
+
const sms = s.sms || null;
|
|
3311
|
+
if (sms && sms.needSms && !s.online && (sms.url || sms.code)) {
|
|
3312
|
+
$('smsbox').classList.add('show');
|
|
3313
|
+
$('sms-title').textContent = sms.code ? ('⚠ 这次登录要短信验证(ErrCode ' + sms.code + ')') : '⚠ 这次登录要短信验证';
|
|
3314
|
+
const link = $('sms-link');
|
|
3315
|
+
if (sms.url) { link.href = sms.url; link.style.display = ''; }
|
|
3316
|
+
else { link.removeAttribute('href'); link.style.display = 'none'; }
|
|
3317
|
+
} else {
|
|
3318
|
+
$('smsbox').classList.remove('show');
|
|
3319
|
+
}
|
|
3320
|
+
|
|
3321
|
+
if (s.online) {
|
|
3322
|
+
$('v-login').className = 'v ok';
|
|
3323
|
+
$('v-login').innerHTML = '<span class="dot"></span>已登录 ' + (s.nickname || '') + '(' + (s.userId || '') + ')';
|
|
3324
|
+
$('ov').classList.remove('show');
|
|
3325
|
+
$('hint').textContent = '连上了,可以关掉这个页面了。';
|
|
3326
|
+
} else {
|
|
3327
|
+
$('v-login').className = 'v warn';
|
|
3328
|
+
$('v-login').innerHTML = '<span class="dot"></span>还没登录,等扫码';
|
|
3329
|
+
if (left !== null && left < 12) {
|
|
3330
|
+
$('ovtext').textContent = '这张码快过期了,等新的…';
|
|
3331
|
+
$('ov').classList.add('show');
|
|
3332
|
+
} else if (age === null) {
|
|
3333
|
+
$('ovtext').textContent = '等 NapCat 出码…';
|
|
3334
|
+
$('ov').classList.add('show');
|
|
3335
|
+
} else {
|
|
3336
|
+
$('ov').classList.remove('show');
|
|
3337
|
+
}
|
|
3338
|
+
$('hint').textContent = '手机 QQ →「我」→ 扫一扫。码约 2 分钟换一张,页面会自动跟着换。';
|
|
3339
|
+
}
|
|
3340
|
+
}
|
|
3341
|
+
|
|
3342
|
+
async function restart() {
|
|
3343
|
+
$('ovtext').textContent = '正在重拉 NapCat…';
|
|
3344
|
+
$('ov').classList.add('show');
|
|
3345
|
+
try { await fetch('qr-restart', { method: 'POST' }) } catch (e) {}
|
|
3346
|
+
setTimeout(() => { $('ov').classList.remove('show'); tick() }, 6000);
|
|
3347
|
+
setTimeout(tick, 14000);
|
|
3348
|
+
}
|
|
3349
|
+
|
|
3350
|
+
$('btn-restart').addEventListener('click', restart);
|
|
3351
|
+
$('btn-tick').addEventListener('click', tick);
|
|
3352
|
+
tick();
|
|
3353
|
+
setInterval(tick, 3000);
|
|
3354
|
+
</script>
|
|
3355
|
+
</body></html>`
|
|
3356
|
+
|
|
3357
|
+
/* --- 扫码页:一份处理,两个入口(DSH 路由 + 独立小端口) --------------- */
|
|
3358
|
+
|
|
3359
|
+
/**
|
|
3360
|
+
* 从 NapCat 自己的运行日志里抠「这次登录要不要短信验证」。
|
|
3361
|
+
* 它出码之后常常还跟一条 ErrCode + proofWaterUrl(腾讯的验证页),
|
|
3362
|
+
* 光有二维码扫不进去 —— 所以页面上得把这个链接直接摆出来。
|
|
3363
|
+
* 日志里混着 ANSI 码和 GBK 乱码,只按 ASCII 令牌匹配,读的时候用 latin1。
|
|
3364
|
+
*/
|
|
3365
|
+
function napcatRunLogInfo(cfg) {
|
|
3366
|
+
const dir = String((cfg && cfg.shellDir) || '').replace(/\\/g, '/')
|
|
3367
|
+
const files = []
|
|
3368
|
+
if (dir) {
|
|
3369
|
+
files.push(path.join(dir, '_run.log'))
|
|
3370
|
+
files.push(path.join(dir, 'napcat', '_run.log'))
|
|
3371
|
+
}
|
|
3372
|
+
files.push(path.join(keeperDir(), 'launch.log'))
|
|
3373
|
+
for (const file of files) {
|
|
3374
|
+
try {
|
|
3375
|
+
if (!existsSync(file)) continue
|
|
3376
|
+
const lines = readFileSync(file, 'latin1').split(/\r?\n/).filter(Boolean).slice(-200)
|
|
3377
|
+
const out = { file, code: null, text: '', url: '', success: false, needSms: false, at: '' }
|
|
3378
|
+
let codeAt = -1
|
|
3379
|
+
let okAt = -1
|
|
3380
|
+
let urlStamp = ''
|
|
3381
|
+
lines.forEach((line, i) => {
|
|
3382
|
+
const code = line.match(/ErrCode:\s*(\d+)/)
|
|
3383
|
+
if (code) {
|
|
3384
|
+
out.code = Number(code[1])
|
|
3385
|
+
codeAt = i
|
|
3386
|
+
out.text = line.replace(/\u001b\[[0-9;]*m/g, '').trim().slice(0, 240)
|
|
3387
|
+
}
|
|
3388
|
+
const cap = line.match(/proofWaterUrl:\s*(\S+)/)
|
|
3389
|
+
if (cap) {
|
|
3390
|
+
out.url = cap[1]
|
|
3391
|
+
urlStamp = (line.match(/^(\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})/) || [])[1] || ''
|
|
3392
|
+
}
|
|
3393
|
+
if (/Login Success|登录成功|ONLINE/i.test(line)) { out.success = true; okAt = i }
|
|
3394
|
+
const at = line.match(/^(\d{2}-\d{2}\s\d{2}:\d{2}:\d{2})/)
|
|
3395
|
+
if (at) out.at = at[1]
|
|
3396
|
+
})
|
|
3397
|
+
// 老日志里的 ErrCode 会一直挂着;只有「这次登录还没成功」才算数
|
|
3398
|
+
out.needSms = out.code !== null && codeAt > okAt
|
|
3399
|
+
// 验证链接有时效(几分钟就废),太老的别拿给主人点
|
|
3400
|
+
if (out.url && urlStamp) {
|
|
3401
|
+
const t = new Date(`${new Date().getFullYear()}-${urlStamp.replace(' ', 'T')}`).getTime()
|
|
3402
|
+
if (!Number.isFinite(t) || Date.now() - t > 30 * 60 * 1000) {
|
|
3403
|
+
out.urlStale = true
|
|
3404
|
+
out.url = ''
|
|
3405
|
+
}
|
|
3406
|
+
}
|
|
3407
|
+
return out
|
|
3408
|
+
} catch {}
|
|
3409
|
+
}
|
|
3410
|
+
return { file: '', code: null, text: '', url: '', success: false, at: '' }
|
|
3411
|
+
}
|
|
3412
|
+
|
|
3413
|
+
/** 扫码页轮询用的状态(轻量档,不跑子进程) */
|
|
3414
|
+
async function qrPageState(cfg) {
|
|
3415
|
+
const payload = await uiState(cfg, { light: true })
|
|
3416
|
+
const rt = (payload && payload.runtime) || {}
|
|
3417
|
+
return {
|
|
3418
|
+
ok: true,
|
|
3419
|
+
online: Boolean(rt.online),
|
|
3420
|
+
phase: rt.phase || '',
|
|
3421
|
+
mode: rt.mode || '',
|
|
3422
|
+
portStatus: rt.portStatus || 0,
|
|
3423
|
+
nickname: rt.nickname || '',
|
|
3424
|
+
userId: rt.userId || 0,
|
|
3425
|
+
qr: rt.qr || null,
|
|
3426
|
+
qrTtlSec: QR_TTL_SEC,
|
|
3427
|
+
scanRetries: rt.scanRetries || 0,
|
|
3428
|
+
restartedAt: state.lastLaunchAt ? new Date(state.lastLaunchAt).getTime() : 0,
|
|
3429
|
+
logTail: Array.isArray(payload && payload.log) ? payload.log : [],
|
|
3430
|
+
sms: napcatRunLogInfo(cfg),
|
|
3431
|
+
panel: { port: qrPanel.port || cfg.qrPanelPort, enabled: cfg.qrPanelEnabled !== false },
|
|
3432
|
+
now: Date.now(),
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3435
|
+
|
|
3436
|
+
/**
|
|
3437
|
+
* 扫码页的请求处理。路径先剥掉 DSH 那个前缀,于是:
|
|
3438
|
+
* /dsh-napcat-keeper/qr (DSH 路由)→ 页面
|
|
3439
|
+
* /qr / (独立端口) → 页面
|
|
3440
|
+
* 图片 / 状态 / 重拉同名共用。
|
|
3441
|
+
*/
|
|
3442
|
+
async function serveQrPage(req, res, cfg) {
|
|
3443
|
+
cfg = cfg || state.cfg
|
|
3444
|
+
let pathname = String((req && req.url) || '/')
|
|
3445
|
+
const qi = pathname.indexOf('?')
|
|
3446
|
+
if (qi >= 0) pathname = pathname.slice(0, qi)
|
|
3447
|
+
if (pathname.startsWith(ROUTE)) pathname = pathname.slice(ROUTE.length) || '/'
|
|
3448
|
+
if (!pathname) pathname = '/'
|
|
3449
|
+
|
|
3450
|
+
if (pathname === '/' || pathname === '/qr' || pathname === '/qr/') {
|
|
3451
|
+
res.statusCode = 200
|
|
3452
|
+
res.setHeader('content-type', 'text/html; charset=utf-8')
|
|
3453
|
+
res.setHeader('cache-control', 'no-store')
|
|
3454
|
+
res.end(QR_PAGE_HTML)
|
|
3455
|
+
return
|
|
3456
|
+
}
|
|
3457
|
+
|
|
3458
|
+
if (pathname === '/qr.png') {
|
|
3459
|
+
const info = qrInfo(cfg)
|
|
3460
|
+
if (!info || !info.file) {
|
|
3461
|
+
sendJson(res, 404, { ok: false, error: '还没有二维码(NapCat 没进扫码态,或者还没出码)' })
|
|
3462
|
+
return
|
|
3463
|
+
}
|
|
3464
|
+
let buf
|
|
3465
|
+
try {
|
|
3466
|
+
buf = readFileSync(info.file)
|
|
3467
|
+
} catch (error) {
|
|
3468
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
3469
|
+
return
|
|
3470
|
+
}
|
|
3471
|
+
res.statusCode = 200
|
|
3472
|
+
res.setHeader('content-type', 'image/png')
|
|
3473
|
+
res.setHeader('cache-control', 'no-store')
|
|
3474
|
+
res.setHeader('content-length', String(buf.length))
|
|
3475
|
+
res.end(buf)
|
|
3476
|
+
return
|
|
3477
|
+
}
|
|
3478
|
+
|
|
3479
|
+
if (pathname === '/qr-state') {
|
|
3480
|
+
sendJson(res, 200, await qrPageState(cfg))
|
|
3481
|
+
return
|
|
3482
|
+
}
|
|
3483
|
+
|
|
3484
|
+
if (pathname === '/qr-restart') {
|
|
3485
|
+
const ctx = state.ctx || null
|
|
3486
|
+
const result = ctx ? await doAction(ctx, cfg, 'restart', {}) : { said: '插件还没准备好,稍等一下再点' }
|
|
3487
|
+
sendJson(res, 200, { ok: true, said: (result && result.said) || '已让它重拉,新码大概十几秒后出来' })
|
|
3488
|
+
return
|
|
3489
|
+
}
|
|
3490
|
+
|
|
3491
|
+
sendJson(res, 404, { ok: false, error: '不认识的路径:' + pathname })
|
|
3492
|
+
}
|
|
3493
|
+
|
|
3494
|
+
/** 扫码页的独立小服务状态(跟着 globalThis 走:热重载时旧 server 会被关掉,不会越攒越多) */
|
|
3495
|
+
const QRPANEL_KEY = Symbol.for('dsh.napcat-keeper.qrpanel')
|
|
3496
|
+
const qrPanel =
|
|
3497
|
+
globalThis[QRPANEL_KEY] ||
|
|
3498
|
+
(globalThis[QRPANEL_KEY] = { server: null, port: 0, error: '', since: 0, note: '', serve: null })
|
|
3499
|
+
|
|
3500
|
+
/** 扫码页地址(给用户点的那个) */
|
|
3501
|
+
function qrPanelUrl(cfg) {
|
|
3502
|
+
const c = cfg || state.cfg || {}
|
|
3503
|
+
return c.qrPanelEnabled === false ? '' : `http://127.0.0.1:${c.qrPanelPort || 8899}/`
|
|
3504
|
+
}
|
|
3505
|
+
|
|
3506
|
+
function stopQrPanel(cfg, why = '') {
|
|
3507
|
+
const s = qrPanel.server
|
|
3508
|
+
qrPanel.server = null
|
|
3509
|
+
qrPanel.port = 0
|
|
3510
|
+
qrPanel.serve = null
|
|
3511
|
+
if (s) {
|
|
3512
|
+
try {
|
|
3513
|
+
s.close()
|
|
3514
|
+
} catch {}
|
|
3515
|
+
log(cfg || state.cfg, `扫码页已关${why ? '(' + why + ')' : ''}`)
|
|
3516
|
+
}
|
|
3517
|
+
}
|
|
3518
|
+
|
|
3519
|
+
/** 按配置把扫码页起起来;端口没变且已经在跑就什么都不做 */
|
|
3520
|
+
function startQrPanel(cfg) {
|
|
3521
|
+
if (!cfg || cfg.qrPanelEnabled === false) {
|
|
3522
|
+
stopQrPanel(cfg, '配置里关了')
|
|
3523
|
+
qrPanel.note = '关着(设置里可以打开)'
|
|
3524
|
+
return { ok: false, port: 0, note: qrPanel.note }
|
|
3525
|
+
}
|
|
3526
|
+
const port = Number(cfg.qrPanelPort) || 8899
|
|
3527
|
+
// ⚠ 热重载时旧 server 的闭包还指着**旧的** serveQrPage / QR_PAGE_HTML,
|
|
3528
|
+
// 光看「端口一样、还在听」就复用的话,页面永远是上一版。所以比函数身份:换模块了就重建。
|
|
3529
|
+
if (qrPanel.server && qrPanel.port === port && qrPanel.server.listening && qrPanel.serve === serveQrPage) {
|
|
3530
|
+
return { ok: true, port, note: qrPanel.note }
|
|
3531
|
+
}
|
|
3532
|
+
stopQrPanel(cfg, qrPanel.server ? '热重载换新代码' : '重启')
|
|
3533
|
+
try {
|
|
3534
|
+
const server = http.createServer((req, res) => {
|
|
3535
|
+
serveQrPage(req, res, state.cfg).catch((error) => {
|
|
3536
|
+
try {
|
|
3537
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
3538
|
+
} catch {}
|
|
3539
|
+
})
|
|
3540
|
+
})
|
|
3541
|
+
server.on('error', (error) => {
|
|
3542
|
+
qrPanel.error = String((error && error.message) || error)
|
|
3543
|
+
qrPanel.note = /EADDRINUSE/.test(qrPanel.error)
|
|
3544
|
+
? `端口 ${port} 被占了(改一个 qrPanelPort,或关掉占它的程序)`
|
|
3545
|
+
: '起不来:' + qrPanel.error
|
|
3546
|
+
log(state.cfg, '扫码页启动失败:' + qrPanel.note)
|
|
3547
|
+
qrPanel.server = null
|
|
3548
|
+
qrPanel.port = 0
|
|
3549
|
+
})
|
|
3550
|
+
server.listen(port, '127.0.0.1', () => {
|
|
3551
|
+
qrPanel.server = server
|
|
3552
|
+
qrPanel.port = port
|
|
3553
|
+
qrPanel.serve = serveQrPage
|
|
3554
|
+
qrPanel.error = ''
|
|
3555
|
+
qrPanel.since = Date.now()
|
|
3556
|
+
qrPanel.note = ''
|
|
3557
|
+
log(state.cfg, `扫码页已起:http://127.0.0.1:${port}/(要扫码时点开它)`)
|
|
3558
|
+
})
|
|
3559
|
+
server.unref?.()
|
|
3560
|
+
return { ok: true, port, note: '正在起' }
|
|
3561
|
+
} catch (error) {
|
|
3562
|
+
qrPanel.error = String((error && error.message) || error)
|
|
3563
|
+
qrPanel.note = '起不来:' + qrPanel.error
|
|
3564
|
+
log(state.cfg, '扫码页启动失败:' + qrPanel.note)
|
|
3565
|
+
return { ok: false, port: 0, note: qrPanel.note }
|
|
3566
|
+
}
|
|
3567
|
+
}
|
|
3568
|
+
|
|
3569
|
+
function qrPanelPublic(cfg) {
|
|
3570
|
+
const port = qrPanel.port || (cfg && cfg.qrPanelPort) || 8899
|
|
3571
|
+
const running = Boolean(qrPanel.server && qrPanel.server.listening)
|
|
3572
|
+
return {
|
|
3573
|
+
enabled: !(cfg && cfg.qrPanelEnabled === false),
|
|
3574
|
+
port,
|
|
3575
|
+
running,
|
|
3576
|
+
url: running ? `http://127.0.0.1:${port}/` : '',
|
|
3577
|
+
path: QR_PANEL_PATH,
|
|
3578
|
+
note: qrPanel.note || (running ? '' : '没在跑'),
|
|
3579
|
+
error: qrPanel.error || '',
|
|
3580
|
+
}
|
|
3581
|
+
}
|
|
3582
|
+
|
|
3758
3583
|
function readBody(req, limit = 262144) {
|
|
3759
3584
|
return new Promise((resolve) => {
|
|
3760
3585
|
let size = 0
|
|
@@ -3876,8 +3701,10 @@ const uiCache = {
|
|
|
3876
3701
|
bootMain: undefined,
|
|
3877
3702
|
bootMainKey: '',
|
|
3878
3703
|
bootMainAt: 0,
|
|
3879
|
-
|
|
3880
|
-
|
|
3704
|
+
/** procsLayout 的目录判形缓存(node 型 / 快登壳型) */
|
|
3705
|
+
layout: 'unknown',
|
|
3706
|
+
layoutKey: '',
|
|
3707
|
+
layoutAt: 0,
|
|
3881
3708
|
qr: null,
|
|
3882
3709
|
qrAt: 0,
|
|
3883
3710
|
log: null,
|
|
@@ -4021,24 +3848,11 @@ async function uiState(cfg, options = {}) {
|
|
|
4021
3848
|
},
|
|
4022
3849
|
scan: scanPublic(),
|
|
4023
3850
|
drives: cachedDrives(),
|
|
4024
|
-
|
|
3851
|
+
qrPanel: qrPanelPublic(cfg),
|
|
4025
3852
|
log: cachedLog(cfg, 40),
|
|
4026
3853
|
}
|
|
4027
3854
|
}
|
|
4028
3855
|
|
|
4029
|
-
/** 提权交接那块的状态:light(轮询)时放宽缓存,免得每 2 秒去翻一次 NapCat 目录 */
|
|
4030
|
-
function cachedSetup(cfg, light) {
|
|
4031
|
-
const maxAgeMs = light ? 10000 : 2000
|
|
4032
|
-
if (uiCache.setup && Date.now() - (uiCache.setupAt || 0) < maxAgeMs) return uiCache.setup
|
|
4033
|
-
try {
|
|
4034
|
-
uiCache.setup = setupState(cfg)
|
|
4035
|
-
} catch {
|
|
4036
|
-
uiCache.setup = uiCache.setup || null
|
|
4037
|
-
}
|
|
4038
|
-
uiCache.setupAt = Date.now()
|
|
4039
|
-
return uiCache.setup
|
|
4040
|
-
}
|
|
4041
|
-
|
|
4042
3856
|
/** 并发 /state 合并成一次:崩溃重挂载时不会叠加成一串请求。 */
|
|
4043
3857
|
function uiStateFull(cfg) {
|
|
4044
3858
|
if (uiCache.fullInflight) return uiCache.fullInflight
|
|
@@ -4125,6 +3939,12 @@ function saveAndApply(ctx, patch) {
|
|
|
4125
3939
|
}
|
|
4126
3940
|
}
|
|
4127
3941
|
armTimer(next)
|
|
3942
|
+
// 扫码页的开关/端口可能刚被改过,重新对一遍(端口没变时这里什么都不做)
|
|
3943
|
+
try {
|
|
3944
|
+
startQrPanel(next)
|
|
3945
|
+
} catch (error) {
|
|
3946
|
+
log(next, `扫码页重起失败:${String((error && error.message) || error)}`)
|
|
3947
|
+
}
|
|
4128
3948
|
if (next.enabled) {
|
|
4129
3949
|
tick(next).catch((error) => log(next, `tick after save error: ${String((error && error.message) || error)}`))
|
|
4130
3950
|
}
|
|
@@ -4195,53 +4015,6 @@ async function doAction(ctx, cfg, action, payload) {
|
|
|
4195
4015
|
: `密码已删,但任务重建失败:${made.error || ''}`,
|
|
4196
4016
|
}
|
|
4197
4017
|
}
|
|
4198
|
-
case 'makeSetup': {
|
|
4199
|
-
// 生成「提权交接」脚本:插件自己不动系统,把活写成脚本,由人点一下
|
|
4200
|
-
let wants = []
|
|
4201
|
-
if (payload && Array.isArray(payload.needs)) wants = payload.needs
|
|
4202
|
-
else if (payload && typeof payload.needs === 'string' && payload.needs.trim()) {
|
|
4203
|
-
wants = payload.needs.split(',').map((s) => s.trim()).filter(Boolean)
|
|
4204
|
-
}
|
|
4205
|
-
// 显式传了空数组 = 一条都没勾,别当成「全要」
|
|
4206
|
-
if (payload && Array.isArray(payload.needs) && payload.needs.length === 0) {
|
|
4207
|
-
return { said: '没勾任何要做的事 —— 先在「需要你点一下的脚本」里勾一条,再点生成' }
|
|
4208
|
-
}
|
|
4209
|
-
const made = writeSetupBundle(cfg, wants)
|
|
4210
|
-
uiCache.setup = null
|
|
4211
|
-
uiCache.setupAt = 0
|
|
4212
|
-
if (!made.ok) return { said: `没生成:${made.error}`, setup: made }
|
|
4213
|
-
if (payload && payload.open) openSetupFolder()
|
|
4214
|
-
const adminNote = made.needAdmin ? '(这批要点 UAC 的「是」)' : '(这几步不需要管理员,双击就跑)'
|
|
4215
|
-
return {
|
|
4216
|
-
said: `脚本写好了:${made.dir} —— 双击 apply-admin.cmd ${adminNote},跑完回来点「读结果」`,
|
|
4217
|
-
setup: made,
|
|
4218
|
-
}
|
|
4219
|
-
}
|
|
4220
|
-
case 'openSetup': {
|
|
4221
|
-
const r = openSetupFolder()
|
|
4222
|
-
uiCache.setup = null
|
|
4223
|
-
uiCache.setupAt = 0
|
|
4224
|
-
return { said: r.ok ? `已打开 ${r.dir}` : `打开失败:${r.error}`, opened: r }
|
|
4225
|
-
}
|
|
4226
|
-
case 'setupResult': {
|
|
4227
|
-
uiCache.setup = null
|
|
4228
|
-
uiCache.setupAt = 0
|
|
4229
|
-
const r = readSetupResult()
|
|
4230
|
-
if (!r) return { said: '还没跑过(目录里没有 result.json)' }
|
|
4231
|
-
const bad = r.results.filter((x) => !x.ok)
|
|
4232
|
-
const skipped = r.results.filter((x) => x.skipped)
|
|
4233
|
-
const head = r.mode === 'undo' ? '撤回结果' : '执行结果'
|
|
4234
|
-
return {
|
|
4235
|
-
said:
|
|
4236
|
-
`${head}:${r.results.length - bad.length}/${r.results.length} 步成` +
|
|
4237
|
-
(bad.length
|
|
4238
|
-
? `,没成:${bad.map((x) => `${x.label}(${x.message})`).join(';')}`
|
|
4239
|
-
: '') +
|
|
4240
|
-
(skipped.length ? `,跳过 ${skipped.length} 步` : '') +
|
|
4241
|
-
(r.elevated ? '|拿到管理员' : '|没用管理员'),
|
|
4242
|
-
setupRun: r,
|
|
4243
|
-
}
|
|
4244
|
-
}
|
|
4245
4018
|
case 'checkNode': {
|
|
4246
4019
|
// 清掉缓存再解析一次:用户刚装完 node / 刚改了路径时,想让结果立刻变
|
|
4247
4020
|
uiCache.node = null
|
|
@@ -4351,10 +4124,22 @@ function registerRoutes(ctx) {
|
|
|
4351
4124
|
const lines = match ? Number(match[1]) : 80
|
|
4352
4125
|
sendJson(res, 200, { ok: true, lines: logTail(state.cfg, lines) })
|
|
4353
4126
|
})
|
|
4127
|
+
|
|
4128
|
+
/*--- 扫码页 ---------------------------------------------------------
|
|
4129
|
+
* NapCat 要手机扫码的时候,用户点一个链接就能看见二维码(挑得到的那条都行):
|
|
4130
|
+
* /dsh-napcat-keeper/qr DSH 自己地址下的这一页(会自己刷新)
|
|
4131
|
+
* 127.0.0.1:qrPanelPort/ 同一个页面的独立小服务(默认 8899,任何浏览器都打得开)
|
|
4132
|
+
* 页面里的 qr.png / qr-state / qr-restart 两个入口共用同一份处理。
|
|
4133
|
+
*/
|
|
4134
|
+
route('/qr', async (req, res) => serveQrPage(req, res, state.cfg))
|
|
4135
|
+
route('/qr.png', async (req, res) => serveQrPage(req, res, state.cfg))
|
|
4136
|
+
route('/qr-state', async (req, res) => serveQrPage(req, res, state.cfg))
|
|
4137
|
+
route('/qr-restart', async (req, res) => serveQrPage(req, res, state.cfg))
|
|
4354
4138
|
}
|
|
4355
4139
|
|
|
4356
4140
|
export function apply(ctx, config) {
|
|
4357
4141
|
state.patchConfig = config || {}
|
|
4142
|
+
state.ctx = ctx
|
|
4358
4143
|
const cfg = resolveConfig(state.patchConfig)
|
|
4359
4144
|
state.cfg = cfg
|
|
4360
4145
|
const node = nodePublic(cfg)
|
|
@@ -4373,6 +4158,7 @@ export function apply(ctx, config) {
|
|
|
4373
4158
|
}
|
|
4374
4159
|
registerTools(ctx, cfg)
|
|
4375
4160
|
registerRoutes(ctx)
|
|
4161
|
+
startQrPanel(cfg)
|
|
4376
4162
|
armTimer(cfg)
|
|
4377
4163
|
if (typeof ctx?.on === 'function') {
|
|
4378
4164
|
try {
|
|
@@ -4443,20 +4229,18 @@ export const __internals = {
|
|
|
4443
4229
|
removeEnvBat,
|
|
4444
4230
|
envBatPath,
|
|
4445
4231
|
md5Hex,
|
|
4446
|
-
SETUP_NEEDS,
|
|
4447
|
-
setupPaths,
|
|
4448
|
-
needCatalog,
|
|
4449
|
-
buildSetupSteps,
|
|
4450
|
-
writeSetupBundle,
|
|
4451
|
-
readSetupResult,
|
|
4452
|
-
readSetupPlan,
|
|
4453
|
-
setupState,
|
|
4454
|
-
openSetupFolder,
|
|
4455
|
-
applyPs1Source,
|
|
4456
|
-
dirWritable,
|
|
4457
4232
|
cachedBootMain,
|
|
4458
4233
|
procsLayout,
|
|
4459
4234
|
taskCommandLine,
|
|
4460
4235
|
taskCommandLinePure,
|
|
4236
|
+
// 扫码页(要扫码时给用户点的那个页面)
|
|
4237
|
+
qrPageState,
|
|
4238
|
+
serveQrPage,
|
|
4239
|
+
startQrPanel,
|
|
4240
|
+
stopQrPanel,
|
|
4241
|
+
qrPanelPublic,
|
|
4242
|
+
qrPanelUrl,
|
|
4243
|
+
QR_PANEL_PATH,
|
|
4244
|
+
QR_TTL_SEC,
|
|
4461
4245
|
state,
|
|
4462
4246
|
}
|