dsh-napcat-keeper 2.8.2 → 2.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,210 +0,0 @@
1
- /**
2
- * 「提权交接」自检:在临时目录里造一个假的 NapCat 环境,
3
- * 走一遍 生成脚本 → 真跑 PowerShell → 读结果 → 撤销 的全流程。
4
- *
5
- * 全程不碰真实配置、不碰真实 NapCat 目录,也不需要管理员(这几步本来就不用)。
6
- * node scripts/selftest-setup.mjs
7
- */
8
- import { execFileSync } from 'node:child_process'
9
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
10
- import { tmpdir } from 'node:os'
11
- import path from 'node:path'
12
-
13
- const internals = (await import('../lib/index.js')).__internals
14
-
15
- const root = mkdtempSync(path.join(tmpdir(), 'npk-selftest-'))
16
- const fakeShell = path.join(root, 'NapCat.Selftest.Shell')
17
- const fakeLogDir = path.join(root, 'logs')
18
- mkdirSync(fakeShell, { recursive: true })
19
- mkdirSync(fakeLogDir, { recursive: true })
20
- // 假 NapCat:一个 bat + 一个 boot exe,够了
21
- writeFileSync(path.join(fakeShell, 'napcat.quick2.bat'), '@echo off\r\necho hi\r\n', 'utf8')
22
- writeFileSync(path.join(fakeShell, 'NapCatWinBootMain.exe'), '', 'utf8')
23
-
24
- const cfg = internals.resolveConfig({})
25
- cfg.shellDir = fakeShell
26
- cfg.launcherScript = 'napcat.quick2.bat'
27
- cfg.launcherLog = path.join(fakeLogDir, 'launch.log')
28
- cfg.taskName = 'NapCat-Keeper-Selftest'
29
- cfg.launchAccount = '10001'
30
- cfg.launchArgs = ''
31
- cfg.rememberPassword = true
32
- cfg.quickPassword = 'selftest-pass-123'
33
- cfg.hideConsole = true
34
- cfg.onebotPort = 3000
35
-
36
- let pass = 0
37
- let fail = 0
38
- const ok = (cond, name, extra = '') => {
39
- if (cond) {
40
- pass += 1
41
- console.log(` ✓ ${name}`)
42
- } else {
43
- fail += 1
44
- console.log(` ✗ ${name}${extra ? ' — ' + extra : ''}`)
45
- }
46
- }
47
-
48
- console.log(`临时目录:${root}\n`)
49
-
50
- /* 1. 需求清单 ------------------------------------------------------------- */
51
- console.log('1) needCatalog')
52
- const catalog = internals.needCatalog(cfg)
53
- ok(Array.isArray(catalog) && catalog.length === 4, '四项需要都在', JSON.stringify(catalog.map((c) => c.id)))
54
- ok(catalog.every((c) => c.id && c.label), '每项都有 id/label')
55
- ok(catalog.every((c) => c.ready), '假环境下四项都能做', JSON.stringify(catalog.filter((c) => !c.ready)))
56
- ok(catalog.find((c) => c.id === 'firewall').needAdmin === true, 'firewall 标了要管理员')
57
- ok(catalog.find((c) => c.id === 'task').needAdmin === false, 'task 不需要管理员')
58
-
59
- /* 2. 生成脚本 ------------------------------------------------------------- */
60
- console.log('\n2) writeSetupBundle')
61
- const made = internals.writeSetupBundle(cfg, ['launcher', 'envbat', 'task'])
62
- ok(made.ok === true, '生成成功', made.error || '')
63
- if (!made.ok) {
64
- console.log('生成失败,后面不用看了')
65
- process.exit(1)
66
- }
67
- const p = internals.setupPaths()
68
- ok(existsSync(p.ps1), 'apply.ps1 在')
69
- ok(existsSync(p.cmd), 'apply-admin.cmd 在')
70
- ok(existsSync(p.undoCmd), 'undo-admin.cmd 在')
71
- ok(existsSync(p.plan), 'plan.json 在')
72
- ok(existsSync(p.readme), 'README.txt 在')
73
- ok(made.needAdmin === false, '这批步骤不需要管理员', String(made.needAdmin))
74
- ok(!JSON.stringify(made.steps).includes('selftest-pass-123'), '返回给前端的摘要里没有密码明文')
75
-
76
- const ps1 = readFileSync(p.ps1)
77
- ok(ps1[0] === 0xef && ps1[1] === 0xbb && ps1[2] === 0xbf, 'apply.ps1 带 UTF-8 BOM')
78
- const ps1Text = ps1.toString('utf8')
79
- ok(ps1Text.includes('Start-Process -FilePath'), '脚本里有自我提权那一句')
80
- ok(ps1Text.includes('ConvertTo-Json'), '脚本会写回 result.json')
81
-
82
- const cmdText = readFileSync(p.cmd, 'utf8')
83
- ok(/^[\x00-\x7f]*$/.test(cmdText), 'cmd 是纯 ASCII(不会乱码)')
84
- ok(cmdText.includes('apply.ps1'), 'cmd 指向 apply.ps1')
85
-
86
- const plan = JSON.parse(readFileSync(p.plan, 'utf8'))
87
- ok(plan.steps.length === 4, '4 步:wrapper + envbat + launcher + task', String(plan.steps.length))
88
- ok(plan.needAdmin === false, 'plan 里 needAdmin 是 false')
89
- ok(
90
- plan.steps.some((s) => s.id === 'task' && Array.isArray(s.requires) && s.requires.includes('envbat')),
91
- 'task 依赖 envbat(失败就不建任务)',
92
- )
93
-
94
- /* 3. 真跑一遍(不提权) --------------------------------------------------- */
95
- console.log('\n3) 真跑 apply.ps1')
96
- const runPs = () =>
97
- execFileSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', p.ps1], {
98
- encoding: 'utf8',
99
- env: { ...process.env, NPK_NO_PAUSE: '1' },
100
- timeout: 120000,
101
- windowsHide: true,
102
- })
103
-
104
- let ranOut = ''
105
- try {
106
- ranOut = runPs()
107
- ok(true, '脚本跑完了(退出码 0)')
108
- } catch (error) {
109
- ok(false, '脚本报错', String((error && error.stdout) || (error && error.message) || error))
110
- console.log(String(ranOut))
111
- }
112
-
113
- const first = internals.readSetupResult()
114
- const amAdmin = (() => {
115
- try {
116
- return (
117
- execFileSync(
118
- 'powershell.exe',
119
- [
120
- '-NoProfile',
121
- '-Command',
122
- '([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)',
123
- ],
124
- { encoding: 'utf8', windowsHide: true },
125
- ).trim() === 'True'
126
- )
127
- } catch {
128
- return false
129
- }
130
- })()
131
- ok(Boolean(first), 'result.json 读得回来')
132
- if (first) {
133
- ok(first.mode === 'apply', 'mode = apply')
134
- ok(first.ok === true, '每步都成了', JSON.stringify(first.results.filter((r) => !r.ok)))
135
- ok(
136
- first.elevated === amAdmin,
137
- `elevated(${first.elevated}) 与当前进程是否管理员(${amAdmin}) 一致`,
138
- )
139
- ok(first.results.length === 4, '4 条结果')
140
- }
141
- ok(existsSync(path.join(fakeShell, 'napcat.quick.auto.bat')), 'launcher: 启动脚本写出来了')
142
- ok(existsSync(path.join(fakeLogDir, 'env.bat')), 'envbat: 中间层写出来了')
143
- ok(existsSync(path.join(fakeLogDir, 'launch.vbs')), 'task-wrapper: vbs 写出来了')
144
-
145
- const envBat = readFileSync(path.join(fakeLogDir, 'env.bat'), 'utf8')
146
- ok(envBat.includes('NAPCAT_QUICK_PASSWORD=selftest-pass-123'), 'env bat 里带密码(这是它的用途)')
147
- ok(envBat.includes('call "'), 'env bat 会 call 真启动脚本')
148
-
149
- const autoBat = readFileSync(path.join(fakeShell, 'napcat.quick.auto.bat'), 'utf8')
150
- ok(autoBat.includes('NapCatWinBootMain.exe'), '自动启动脚本调的是 boot main')
151
- ok(autoBat.includes('10001'), '自动启动脚本带账号')
152
-
153
- try {
154
- const q = execFileSync('schtasks.exe', ['/query', '/tn', cfg.taskName], {
155
- encoding: 'utf8',
156
- windowsHide: true,
157
- })
158
- ok(q.includes(cfg.taskName), '计划任务真的建上了')
159
- } catch (error) {
160
- ok(false, '计划任务没查着', String((error && error.message) || error))
161
- }
162
-
163
- /* 4. 再跑一次(幂等) ---------------------------------------------------- */
164
- console.log('\n4) 重复跑一次')
165
- try {
166
- runPs()
167
- const again = internals.readSetupResult()
168
- ok(again && again.ok === true, '第二次也全成(不炸)')
169
- } catch (error) {
170
- ok(false, '第二次跑报错', String((error && error.message) || error))
171
- }
172
-
173
- /* 5. 撤销 --------------------------------------------------------------- */
174
- console.log('\n5) undo')
175
- try {
176
- execFileSync(
177
- 'powershell.exe',
178
- ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', p.ps1, '-Undo'],
179
- { encoding: 'utf8', env: { ...process.env, NPK_NO_PAUSE: '1' }, timeout: 120000, windowsHide: true },
180
- )
181
- ok(true, 'undo 跑完')
182
- } catch (error) {
183
- ok(false, 'undo 报错', String((error && error.message) || error))
184
- }
185
- const undone = internals.readSetupResult()
186
- ok(undone && undone.mode === 'undo', 'result 里 mode = undo')
187
- ok(undone && undone.ok === true, '撤回每步都成', JSON.stringify(undone && undone.results.filter((r) => !r.ok)))
188
- ok(!existsSync(path.join(fakeShell, 'napcat.quick.auto.bat')), '启动脚本删掉了')
189
- ok(!existsSync(path.join(fakeLogDir, 'env.bat')), '中间层删掉了(密码不留在磁盘)')
190
- ok(!existsSync(path.join(fakeLogDir, 'launch.vbs')), 'vbs 删掉了')
191
- try {
192
- execFileSync('schtasks.exe', ['/query', '/tn', cfg.taskName], { stdio: 'ignore', windowsHide: true })
193
- ok(false, '计划任务还在(应该删掉)')
194
- } catch {
195
- ok(true, '计划任务删掉了')
196
- }
197
-
198
- /* 收尾 ---------------------------------------------------------------- */
199
- console.log('\n6) 再生成一次(留着给人点,也算看下真身)')
200
- const final = internals.writeSetupBundle(cfg, ['launcher', 'envbat', 'task'])
201
- ok(final.ok === true, '最后一次生成成功')
202
- ok(internals.readSetupResult() === null, '旧 result 被清掉(不会误读上一次)')
203
-
204
- try {
205
- rmSync(root, { recursive: true, force: true })
206
- } catch {}
207
- console.log(`\n临时目录已清:${root}`)
208
- console.log(`真身留在:${p.dir}`)
209
- console.log(`\n结果:${pass} 通过 / ${fail} 失败`)
210
- process.exit(fail === 0 ? 0 : 1)