@unihc/dsh-process-manager 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +59 -2
- package/catalog.js +571 -0
- package/client.js +1537 -0
- package/collector.js +145 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +42 -0
- package/icon.svg +10 -0
- package/index.js +255 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/model.js +481 -0
- package/native.js +863 -0
- package/operations.js +540 -0
- package/package.json +61 -4
package/native.js
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows data collection and fixed operations through PowerShell.
|
|
3
|
+
*
|
|
4
|
+
* Every script is a constant template. Request data travels as a Base64 JSON
|
|
5
|
+
* blob that the script parses after a strict allow-list check, so nothing a
|
|
6
|
+
* client sends is ever concatenated into PowerShell source. Results (and UAC
|
|
7
|
+
* elevation results) come back through a unique temp file because the host
|
|
8
|
+
* runs the child with stdio ignored.
|
|
9
|
+
*/
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
import { readFile, rm } from 'node:fs/promises'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { randomUUID } from 'node:crypto'
|
|
15
|
+
|
|
16
|
+
const POWERSHELL = 'powershell.exe'
|
|
17
|
+
const READ_TIMEOUT_MS = 45 * 1000
|
|
18
|
+
const OPERATION_TIMEOUT_MS = 90 * 1000
|
|
19
|
+
const ELEVATED_TIMEOUT_MS = 5 * 60 * 1000
|
|
20
|
+
|
|
21
|
+
export function isWindows() {
|
|
22
|
+
return process.platform === 'win32'
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function encodedCommand(script) {
|
|
26
|
+
return Buffer.from(script, 'utf16le').toString('base64')
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function payloadBase64(value) {
|
|
30
|
+
return Buffer.from(JSON.stringify(value ?? {}), 'utf8').toString('base64')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function psQuote(value) {
|
|
34
|
+
return `'${String(value).replace(/'/g, "''")}'`
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function resultPathFor(prefix) {
|
|
38
|
+
return path.join(os.tmpdir(), `dsh-proc-${prefix}-${randomUUID()}.json`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function resultWriter(resultPath) {
|
|
42
|
+
return `[IO.File]::WriteAllText(${psQuote(resultPath)}, ($r | ConvertTo-Json -Depth 8 -Compress), (New-Object System.Text.UTF8Encoding($false)))`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function failure(code, message, extra = {}) {
|
|
46
|
+
const error = new Error(message)
|
|
47
|
+
error.code = code
|
|
48
|
+
Object.assign(error, extra)
|
|
49
|
+
return error
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function spawnAndWait(args, { signal, timeoutMs }) {
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
let child
|
|
55
|
+
try {
|
|
56
|
+
child = spawn(POWERSHELL, args, { windowsHide: true, stdio: 'ignore' })
|
|
57
|
+
} catch (error) {
|
|
58
|
+
resolve({ code: -1, error })
|
|
59
|
+
return
|
|
60
|
+
}
|
|
61
|
+
let settled = false
|
|
62
|
+
let timer = null
|
|
63
|
+
const finish = (value) => {
|
|
64
|
+
if (settled) return
|
|
65
|
+
settled = true
|
|
66
|
+
if (timer !== null) clearTimeout(timer)
|
|
67
|
+
if (signal && onAbort) signal.removeEventListener('abort', onAbort)
|
|
68
|
+
resolve(value)
|
|
69
|
+
}
|
|
70
|
+
const onAbort = signal === undefined ? undefined : () => {
|
|
71
|
+
try { child.kill() } catch { /* already gone */ }
|
|
72
|
+
finish({ code: -3, error: failure('ABORTED', '操作已取消') })
|
|
73
|
+
}
|
|
74
|
+
timer = setTimeout(() => {
|
|
75
|
+
try { child.kill() } catch { /* already gone */ }
|
|
76
|
+
finish({ code: -2, error: failure('TIMEOUT', 'PowerShell 操作超时') })
|
|
77
|
+
}, timeoutMs)
|
|
78
|
+
if (signal) {
|
|
79
|
+
if (signal.aborted) {
|
|
80
|
+
onAbort()
|
|
81
|
+
return
|
|
82
|
+
}
|
|
83
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
84
|
+
}
|
|
85
|
+
child.on('error', error => finish({ code: -1, error }))
|
|
86
|
+
child.on('close', code => finish({ code }))
|
|
87
|
+
})
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function readJson(resultPath) {
|
|
91
|
+
try {
|
|
92
|
+
const text = await readFile(resultPath, 'utf8')
|
|
93
|
+
return JSON.parse(text.replace(/^\uFEFF/, ''))
|
|
94
|
+
} catch {
|
|
95
|
+
return undefined
|
|
96
|
+
} finally {
|
|
97
|
+
await rm(resultPath, { force: true }).catch(() => {})
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function runScript(body, { signal, timeoutMs = OPERATION_TIMEOUT_MS, prefix = 'op', elevate = false } = {}) {
|
|
102
|
+
if (!isWindows()) throw failure('UNSUPPORTED_PLATFORM', '该功能仅支持 Windows')
|
|
103
|
+
const resultPath = resultPathFor(prefix)
|
|
104
|
+
const script = `${body}\n${resultWriter(resultPath)}\n`
|
|
105
|
+
const encoded = encodedCommand(script)
|
|
106
|
+
if (elevate) {
|
|
107
|
+
const launcher = `$p = Start-Process -FilePath 'powershell.exe' -Verb RunAs -Wait -PassThru -ArgumentList '-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-EncodedCommand',${psQuote(encoded)}; if ($null -eq $p) { exit 1 }; exit $p.ExitCode`
|
|
108
|
+
await spawnAndWait(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', launcher], {
|
|
109
|
+
signal: undefined,
|
|
110
|
+
timeoutMs: ELEVATED_TIMEOUT_MS,
|
|
111
|
+
})
|
|
112
|
+
const result = await readJson(resultPath)
|
|
113
|
+
if (result === undefined) {
|
|
114
|
+
throw failure('ELEVATION_DENIED', '未获得管理员权限(UAC 被取消或被策略阻止),未做任何修改')
|
|
115
|
+
}
|
|
116
|
+
return result
|
|
117
|
+
}
|
|
118
|
+
const outcome = await spawnAndWait(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], {
|
|
119
|
+
signal,
|
|
120
|
+
timeoutMs,
|
|
121
|
+
})
|
|
122
|
+
if (outcome.code === -3) throw outcome.error
|
|
123
|
+
if (outcome.code === -2) throw outcome.error
|
|
124
|
+
const result = await readJson(resultPath)
|
|
125
|
+
if (result === undefined) {
|
|
126
|
+
throw failure('POWERSHELL_FAILED', 'PowerShell 没有返回结果,可能被安全软件拦截或脚本执行失败')
|
|
127
|
+
}
|
|
128
|
+
return result
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// Collection
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
const COLLECT_BODY = String.raw`
|
|
136
|
+
$ErrorActionPreference = 'SilentlyContinue'
|
|
137
|
+
$cores = [Environment]::ProcessorCount
|
|
138
|
+
$now = (Get-Date).ToString('o')
|
|
139
|
+
|
|
140
|
+
$first = @{}
|
|
141
|
+
foreach ($p in (Get-Process)) {
|
|
142
|
+
try { $first[[int]$p.Id] = [double]$p.CPU } catch { }
|
|
143
|
+
}
|
|
144
|
+
Start-Sleep -Milliseconds 400
|
|
145
|
+
$second = @{}
|
|
146
|
+
foreach ($p in (Get-Process)) {
|
|
147
|
+
try {
|
|
148
|
+
$id = [int]$p.Id
|
|
149
|
+
$second[$id] = [pscustomobject]@{
|
|
150
|
+
cpu = [double]$p.CPU
|
|
151
|
+
mem = [double]$p.WorkingSet64
|
|
152
|
+
win = [long]$p.MainWindowHandle
|
|
153
|
+
title = [string]$p.MainWindowTitle
|
|
154
|
+
}
|
|
155
|
+
} catch { }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function Resolve-ExePath([string]$commandText) {
|
|
159
|
+
if ([string]::IsNullOrWhiteSpace($commandText)) { return '' }
|
|
160
|
+
$textValue = $commandText.Trim()
|
|
161
|
+
if ($textValue.StartsWith('"')) {
|
|
162
|
+
$end = $textValue.IndexOf('"', 1)
|
|
163
|
+
if ($end -gt 1) { $candidate = $textValue.Substring(1, $end - 1) } else { $candidate = $textValue.Trim('"') }
|
|
164
|
+
return $candidate.Trim('"')
|
|
165
|
+
}
|
|
166
|
+
$parts = $textValue -split ' '
|
|
167
|
+
for ($index = 1; $index -le $parts.Count; $index++) {
|
|
168
|
+
$candidate = (($parts[0..($index - 1)]) -join ' ').Trim('"')
|
|
169
|
+
try { $expanded = [Environment]::ExpandEnvironmentVariables($candidate) } catch { $expanded = $candidate }
|
|
170
|
+
if (Test-Path -LiteralPath $expanded -PathType Leaf) { return $expanded.Trim('"') }
|
|
171
|
+
$token = ($parts[$index - 1]).Trim('"')
|
|
172
|
+
if ($token -match '\.(exe|com|bat|cmd|lnk|dll)$') { return $expanded.Trim('"') }
|
|
173
|
+
if ($token.StartsWith('-')) { break }
|
|
174
|
+
}
|
|
175
|
+
return (($parts[0] -replace '"', ''))
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
$versionCache = @{}
|
|
179
|
+
function Get-Publisher([string]$exePath) {
|
|
180
|
+
if ([string]::IsNullOrWhiteSpace($exePath)) { return '' }
|
|
181
|
+
if ($versionCache.ContainsKey($exePath)) { return [string]$versionCache[$exePath] }
|
|
182
|
+
$publisher = ''
|
|
183
|
+
try {
|
|
184
|
+
$info = [Diagnostics.FileVersionInfo]::GetVersionInfo($exePath)
|
|
185
|
+
$publisher = [string]$info.CompanyName
|
|
186
|
+
} catch { }
|
|
187
|
+
$versionCache[$exePath] = $publisher
|
|
188
|
+
return $publisher
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function Read-ApprovedMap([string]$hive, [string]$subKey) {
|
|
192
|
+
$map = @{}
|
|
193
|
+
$path = $hive + ':\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\' + $subKey
|
|
194
|
+
if (-not (Test-Path -LiteralPath $path)) { return $map }
|
|
195
|
+
try {
|
|
196
|
+
$values = Get-ItemProperty -LiteralPath $path
|
|
197
|
+
foreach ($property in $values.PSObject.Properties) {
|
|
198
|
+
if ($property.Name -like 'PS*') { continue }
|
|
199
|
+
$bytes = $property.Value
|
|
200
|
+
$state = 'unknown'
|
|
201
|
+
$raw = ''
|
|
202
|
+
if ($bytes -is [byte[]]) {
|
|
203
|
+
if ($bytes.Length -ge 1) {
|
|
204
|
+
if ($bytes[0] -eq 3) { $state = 'disabled' }
|
|
205
|
+
elseif ($bytes[0] -eq 2 -or $bytes[0] -eq 6) { $state = 'enabled' }
|
|
206
|
+
}
|
|
207
|
+
$raw = (($bytes | ForEach-Object { ([int]$_).ToString('X2') }) -join '')
|
|
208
|
+
}
|
|
209
|
+
$map[$property.Name] = [pscustomobject]@{ approved = $state; raw = $raw }
|
|
210
|
+
}
|
|
211
|
+
} catch { }
|
|
212
|
+
return $map
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
$runDefinitions = @(
|
|
216
|
+
@{ hive = 'HKCU'; key = 'Run'; path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'; approvedHive = 'HKCU'; approvedKey = 'Run' },
|
|
217
|
+
@{ hive = 'HKCU'; key = 'RunOnce'; path = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\RunOnce'; approvedHive = 'HKCU'; approvedKey = 'Run' },
|
|
218
|
+
@{ hive = 'HKLM'; key = 'Run'; path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'; approvedHive = 'HKLM'; approvedKey = 'Run' },
|
|
219
|
+
@{ hive = 'HKLM'; key = 'Run32'; path = 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'; approvedHive = 'HKLM'; approvedKey = 'Run32' },
|
|
220
|
+
@{ hive = 'HKLM'; key = 'RunOnce'; path = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\RunOnce'; approvedHive = 'HKLM'; approvedKey = 'Run' },
|
|
221
|
+
@{ hive = 'HKLM'; key = 'RunOnce32'; path = 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\RunOnce'; approvedHive = 'HKLM'; approvedKey = 'Run32' }
|
|
222
|
+
)
|
|
223
|
+
$approvedCache = @{}
|
|
224
|
+
$runEntries = New-Object System.Collections.ArrayList
|
|
225
|
+
foreach ($definition in $runDefinitions) {
|
|
226
|
+
if (-not (Test-Path -LiteralPath $definition.path)) { continue }
|
|
227
|
+
$cacheKey = $definition.approvedHive + '|' + $definition.approvedKey
|
|
228
|
+
if (-not $approvedCache.ContainsKey($cacheKey)) {
|
|
229
|
+
$approvedCache[$cacheKey] = Read-ApprovedMap $definition.approvedHive $definition.approvedKey
|
|
230
|
+
}
|
|
231
|
+
$approved = $approvedCache[$cacheKey]
|
|
232
|
+
try {
|
|
233
|
+
$item = Get-ItemProperty -LiteralPath $definition.path
|
|
234
|
+
foreach ($property in $item.PSObject.Properties) {
|
|
235
|
+
if ($property.Name -like 'PS*') { continue }
|
|
236
|
+
$command = [string]$property.Value
|
|
237
|
+
$exe = Resolve-ExePath $command
|
|
238
|
+
$state = 'enabled'
|
|
239
|
+
$raw = ''
|
|
240
|
+
if ($approved.ContainsKey($property.Name)) {
|
|
241
|
+
$state = $approved[$property.Name].approved
|
|
242
|
+
$raw = $approved[$property.Name].raw
|
|
243
|
+
}
|
|
244
|
+
[void]$runEntries.Add([pscustomobject]@{
|
|
245
|
+
hive = $definition.hive
|
|
246
|
+
key = $definition.key
|
|
247
|
+
name = [string]$property.Name
|
|
248
|
+
cmd = $command
|
|
249
|
+
exe = $exe
|
|
250
|
+
pub = Get-Publisher $exe
|
|
251
|
+
approved = $state
|
|
252
|
+
raw = $raw
|
|
253
|
+
})
|
|
254
|
+
}
|
|
255
|
+
} catch { }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
$folderEntries = New-Object System.Collections.ArrayList
|
|
259
|
+
$folderDefinitions = @(
|
|
260
|
+
@{ scope = 'user'; path = ($env:APPDATA + '\Microsoft\Windows\Start Menu\Programs\Startup'); approvedHive = 'HKCU' },
|
|
261
|
+
@{ scope = 'machine'; path = ($env:ProgramData + '\Microsoft\Windows\Start Menu\Programs\Startup'); approvedHive = 'HKLM' }
|
|
262
|
+
)
|
|
263
|
+
$shell = $null
|
|
264
|
+
try { $shell = New-Object -ComObject WScript.Shell } catch { }
|
|
265
|
+
foreach ($definition in $folderDefinitions) {
|
|
266
|
+
if (-not (Test-Path -LiteralPath $definition.path)) { continue }
|
|
267
|
+
$cacheKey = $definition.approvedHive + '|StartupFolder'
|
|
268
|
+
if (-not $approvedCache.ContainsKey($cacheKey)) {
|
|
269
|
+
$approvedCache[$cacheKey] = Read-ApprovedMap $definition.approvedHive 'StartupFolder'
|
|
270
|
+
}
|
|
271
|
+
$approved = $approvedCache[$cacheKey]
|
|
272
|
+
try {
|
|
273
|
+
foreach ($file in (Get-ChildItem -LiteralPath $definition.path -File -Force)) {
|
|
274
|
+
if ($file.Name -eq 'desktop.ini') { continue }
|
|
275
|
+
$target = ''
|
|
276
|
+
if ($shell -ne $null -and $file.Extension -ieq '.lnk') {
|
|
277
|
+
try { $target = [string]$shell.CreateShortcut($file.FullName).TargetPath } catch { }
|
|
278
|
+
}
|
|
279
|
+
$exe = $target
|
|
280
|
+
if ([string]::IsNullOrWhiteSpace($exe)) { $exe = $file.FullName }
|
|
281
|
+
$state = 'enabled'
|
|
282
|
+
$raw = ''
|
|
283
|
+
if ($approved.ContainsKey($file.Name)) {
|
|
284
|
+
$state = $approved[$file.Name].approved
|
|
285
|
+
$raw = $approved[$file.Name].raw
|
|
286
|
+
}
|
|
287
|
+
[void]$folderEntries.Add([pscustomobject]@{
|
|
288
|
+
scope = $definition.scope
|
|
289
|
+
file = $file.Name
|
|
290
|
+
path = $file.FullName
|
|
291
|
+
target = $target
|
|
292
|
+
exe = $exe
|
|
293
|
+
pub = Get-Publisher $exe
|
|
294
|
+
approved = $state
|
|
295
|
+
raw = $raw
|
|
296
|
+
})
|
|
297
|
+
}
|
|
298
|
+
} catch { }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
$taskEntries = New-Object System.Collections.ArrayList
|
|
302
|
+
try {
|
|
303
|
+
foreach ($task in (Get-ScheduledTask)) {
|
|
304
|
+
try {
|
|
305
|
+
$triggers = New-Object System.Collections.ArrayList
|
|
306
|
+
foreach ($trigger in $task.Triggers) {
|
|
307
|
+
$kind = [string]$trigger.CimClass.CimClassName
|
|
308
|
+
if ($kind -match 'LogonTrigger') { [void]$triggers.Add('logon') }
|
|
309
|
+
elseif ($kind -match 'BootTrigger') { [void]$triggers.Add('boot') }
|
|
310
|
+
}
|
|
311
|
+
if ($triggers.Count -eq 0) { continue }
|
|
312
|
+
$exec = ''
|
|
313
|
+
$arguments = ''
|
|
314
|
+
$action = @($task.Actions) | Select-Object -First 1
|
|
315
|
+
if ($action -ne $null) {
|
|
316
|
+
$exec = [string]$action.Execute
|
|
317
|
+
$arguments = [string]$action.Arguments
|
|
318
|
+
}
|
|
319
|
+
[void]$taskEntries.Add([pscustomobject]@{
|
|
320
|
+
path = [string]$task.TaskPath
|
|
321
|
+
name = [string]$task.TaskName
|
|
322
|
+
state = [string]$task.State
|
|
323
|
+
triggers = @($triggers | Select-Object -Unique)
|
|
324
|
+
exec = $exec
|
|
325
|
+
args = $arguments
|
|
326
|
+
author = [string]$task.Author
|
|
327
|
+
desc = [string]$task.Description
|
|
328
|
+
hidden = [bool]$task.Settings.Hidden
|
|
329
|
+
})
|
|
330
|
+
} catch { }
|
|
331
|
+
}
|
|
332
|
+
} catch { }
|
|
333
|
+
|
|
334
|
+
$serviceEntries = New-Object System.Collections.ArrayList
|
|
335
|
+
try {
|
|
336
|
+
foreach ($service in (Get-CimInstance Win32_Service)) {
|
|
337
|
+
try {
|
|
338
|
+
$type = [string]$service.ServiceType
|
|
339
|
+
if ($type -notin @('Own Process', 'Share Process', 'Interactive Process')) { continue }
|
|
340
|
+
$start = [string]$service.StartMode
|
|
341
|
+
$servicePath = [string]$service.PathName
|
|
342
|
+
if ($start -ne 'Auto') {
|
|
343
|
+
$isWindowsPath = $servicePath -match '^"?[A-Za-z]:\\Windows\\'
|
|
344
|
+
if ($start -ne 'Disabled' -or $isWindowsPath) { continue }
|
|
345
|
+
}
|
|
346
|
+
$delayed = $false
|
|
347
|
+
try {
|
|
348
|
+
$keyPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\' + $service.Name
|
|
349
|
+
$delayed = ((Get-ItemProperty -LiteralPath $keyPath -Name DelayedAutostart -ErrorAction Stop).DelayedAutostart -eq 1)
|
|
350
|
+
} catch { }
|
|
351
|
+
$exe = Resolve-ExePath $servicePath
|
|
352
|
+
[void]$serviceEntries.Add([pscustomobject]@{
|
|
353
|
+
name = [string]$service.Name
|
|
354
|
+
display = [string]$service.DisplayName
|
|
355
|
+
state = [string]$service.State
|
|
356
|
+
start = $start
|
|
357
|
+
pid = [int]$service.ProcessId
|
|
358
|
+
path = $servicePath
|
|
359
|
+
desc = [string]$service.Description
|
|
360
|
+
delayed = $delayed
|
|
361
|
+
type = $type
|
|
362
|
+
exe = $exe
|
|
363
|
+
pub = Get-Publisher $exe
|
|
364
|
+
})
|
|
365
|
+
} catch { }
|
|
366
|
+
}
|
|
367
|
+
} catch { }
|
|
368
|
+
|
|
369
|
+
$serviceByPid = @{}
|
|
370
|
+
foreach ($service in $serviceEntries) {
|
|
371
|
+
if ($service.pid -le 0) { continue }
|
|
372
|
+
if (-not $serviceByPid.ContainsKey($service.pid)) { $serviceByPid[$service.pid] = New-Object System.Collections.ArrayList }
|
|
373
|
+
[void]$serviceByPid[$service.pid].Add([pscustomobject]@{ n = $service.name; d = $service.display; ds = $service.desc })
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
$ownPid = [int]$PID
|
|
377
|
+
$processEntries = New-Object System.Collections.ArrayList
|
|
378
|
+
$infoCache = @{}
|
|
379
|
+
foreach ($process in (Get-CimInstance Win32_Process)) {
|
|
380
|
+
try {
|
|
381
|
+
$processId = [int]$process.ProcessId
|
|
382
|
+
if ($processId -eq $ownPid -or [int]$process.ParentProcessId -eq $ownPid) { continue }
|
|
383
|
+
$exePath = [string]$process.ExecutablePath
|
|
384
|
+
$info = $null
|
|
385
|
+
if ($exePath -ne '') {
|
|
386
|
+
if ($infoCache.ContainsKey($exePath)) { $info = $infoCache[$exePath] }
|
|
387
|
+
else {
|
|
388
|
+
try { $info = [Diagnostics.FileVersionInfo]::GetVersionInfo($exePath) } catch { $info = $null }
|
|
389
|
+
$infoCache[$exePath] = $info
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
$sample = $second[$processId]
|
|
393
|
+
$before = $first[$processId]
|
|
394
|
+
$cpuPercent = 0
|
|
395
|
+
if ($sample -ne $null -and $before -ne $null -and $cores -gt 0) {
|
|
396
|
+
$delta = [double]$sample.cpu - [double]$before
|
|
397
|
+
if ($delta -gt 0) { $cpuPercent = [math]::Round(($delta / 0.4 / $cores) * 100, 1) }
|
|
398
|
+
}
|
|
399
|
+
$started = ''
|
|
400
|
+
if ($process.CreationDate -ne $null) {
|
|
401
|
+
try { $started = ([datetime]$process.CreationDate).ToString('o') } catch { $started = [string]$process.CreationDate }
|
|
402
|
+
}
|
|
403
|
+
$hosted = @()
|
|
404
|
+
if ($serviceByPid.ContainsKey($processId)) { $hosted = @($serviceByPid[$processId]) }
|
|
405
|
+
[void]$processEntries.Add([pscustomobject]@{
|
|
406
|
+
pid = $processId
|
|
407
|
+
ppid = [int]$process.ParentProcessId
|
|
408
|
+
name = [string]$process.Name
|
|
409
|
+
path = $exePath
|
|
410
|
+
cmdline = [string]$process.CommandLine
|
|
411
|
+
company = if ($info) { [string]$info.CompanyName } else { '' }
|
|
412
|
+
product = if ($info) { [string]$info.ProductName } else { '' }
|
|
413
|
+
desc = if ($info) { [string]$info.FileDescription } else { '' }
|
|
414
|
+
version = if ($info) { [string]$info.FileVersion } else { '' }
|
|
415
|
+
started = $started
|
|
416
|
+
session = [int]$process.SessionId
|
|
417
|
+
window = if ($sample -ne $null -and $sample.win -ne 0) { 1 } else { 0 }
|
|
418
|
+
title = if ($sample -ne $null) { [string]$sample.title } else { '' }
|
|
419
|
+
mem = if ($sample -ne $null) { [double]$sample.mem } else { 0 }
|
|
420
|
+
cpu = $cpuPercent
|
|
421
|
+
svc = $hosted
|
|
422
|
+
})
|
|
423
|
+
} catch { }
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
$r = [pscustomobject]@{
|
|
427
|
+
ok = $true
|
|
428
|
+
collected_at = $now
|
|
429
|
+
cores = $cores
|
|
430
|
+
processes = @($processEntries)
|
|
431
|
+
startup = [pscustomobject]@{
|
|
432
|
+
run = @($runEntries)
|
|
433
|
+
folder = @($folderEntries)
|
|
434
|
+
tasks = @($taskEntries)
|
|
435
|
+
services = @($serviceEntries)
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
`
|
|
439
|
+
|
|
440
|
+
export async function collectSnapshot({ signal } = {}) {
|
|
441
|
+
const result = await runScript(COLLECT_BODY, { signal, timeoutMs: READ_TIMEOUT_MS, prefix: 'snapshot' })
|
|
442
|
+
if (result?.ok !== true) {
|
|
443
|
+
throw failure('POWERSHELL_FAILED', result?.message ?? '采集失败')
|
|
444
|
+
}
|
|
445
|
+
return result
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ---------------------------------------------------------------------------
|
|
449
|
+
// Stop processes
|
|
450
|
+
// ---------------------------------------------------------------------------
|
|
451
|
+
|
|
452
|
+
const STOP_BODY_TEMPLATE = String.raw`
|
|
453
|
+
$ErrorActionPreference = 'Stop'
|
|
454
|
+
function Fail([string]$code, [string]$message) {
|
|
455
|
+
throw [System.InvalidOperationException]::new($code + '|' + $message)
|
|
456
|
+
}
|
|
457
|
+
function Test-AccessDenied($exception) {
|
|
458
|
+
$current = $exception
|
|
459
|
+
$guard = 0
|
|
460
|
+
while ($current -ne $null -and $guard -lt 6) {
|
|
461
|
+
try { if ($current.HResult -eq -2147024891) { return $true } } catch { }
|
|
462
|
+
if ($current -is [System.UnauthorizedAccessException]) { return $true }
|
|
463
|
+
if ($current -is [System.ComponentModel.Win32Exception] -and $current.NativeErrorCode -eq 5) { return $true }
|
|
464
|
+
$current = $current.InnerException
|
|
465
|
+
$guard = $guard + 1
|
|
466
|
+
}
|
|
467
|
+
return $false
|
|
468
|
+
}
|
|
469
|
+
$payloadText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__'))
|
|
470
|
+
$request = $payloadText | ConvertFrom-Json
|
|
471
|
+
$r = [pscustomobject]@{ ok = $false; code = 'OP_FAILED'; message = '操作失败'; results = @() }
|
|
472
|
+
try {
|
|
473
|
+
$mode = [string]$request.mode
|
|
474
|
+
if ($mode -notin @('close', 'kill')) { Fail 'BAD_ARGS' '不支持的操作方式' }
|
|
475
|
+
$targets = @($request.targets)
|
|
476
|
+
if ($targets.Count -eq 0) { Fail 'BAD_ARGS' '没有目标进程' }
|
|
477
|
+
$protectNames = @($request.protect.names | ForEach-Object { ([string]$_).ToLowerInvariant() })
|
|
478
|
+
$protectPids = @($request.protect.pids | ForEach-Object { [int]$_ })
|
|
479
|
+
$live = @{}
|
|
480
|
+
foreach ($entry in (Get-CimInstance Win32_Process)) {
|
|
481
|
+
$live[[int]$entry.ProcessId] = $entry
|
|
482
|
+
}
|
|
483
|
+
$results = New-Object System.Collections.ArrayList
|
|
484
|
+
$validated = New-Object System.Collections.ArrayList
|
|
485
|
+
foreach ($target in $targets) {
|
|
486
|
+
$processId = [int]$target.pid
|
|
487
|
+
if ($protectPids -contains $processId) { Fail 'PROTECTED' '包含受保护的进程,整组操作已取消' }
|
|
488
|
+
$liveEntry = $live[$processId]
|
|
489
|
+
if ($liveEntry -eq $null) {
|
|
490
|
+
[void]$results.Add([pscustomobject]@{ pid = $processId; ok = $false; code = 'GONE'; message = '进程已不存在,已跳过' })
|
|
491
|
+
continue
|
|
492
|
+
}
|
|
493
|
+
if (([string]$liveEntry.Name).ToLowerInvariant() -ne ([string]$target.name).ToLowerInvariant()) {
|
|
494
|
+
[void]$results.Add([pscustomobject]@{ pid = $processId; ok = $false; code = 'STALE_PROCESS'; message = '进程名已变化(PID 可能被复用),已跳过' })
|
|
495
|
+
continue
|
|
496
|
+
}
|
|
497
|
+
if (-not [string]::IsNullOrWhiteSpace([string]$target.path) -and -not [string]::IsNullOrWhiteSpace([string]$liveEntry.ExecutablePath)) {
|
|
498
|
+
if (([string]$liveEntry.ExecutablePath).ToLowerInvariant() -ne ([string]$target.path).ToLowerInvariant()) {
|
|
499
|
+
[void]$results.Add([pscustomobject]@{ pid = $processId; ok = $false; code = 'STALE_PROCESS'; message = '进程路径已变化,已跳过' })
|
|
500
|
+
continue
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
if (-not [string]::IsNullOrWhiteSpace([string]$target.started) -and $liveEntry.CreationDate -ne $null) {
|
|
504
|
+
$parsed = [datetime]::MinValue
|
|
505
|
+
if ([datetime]::TryParse([string]$target.started, [ref]$parsed)) {
|
|
506
|
+
$liveStart = [datetime]$liveEntry.CreationDate
|
|
507
|
+
if ([math]::Abs(($liveStart - $parsed).TotalSeconds) -gt 5) {
|
|
508
|
+
[void]$results.Add([pscustomobject]@{ pid = $processId; ok = $false; code = 'STALE_PROCESS'; message = '启动时间不匹配(PID 可能被复用),已跳过' })
|
|
509
|
+
continue
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
if ($protectNames -contains ([string]$liveEntry.Name).ToLowerInvariant()) {
|
|
514
|
+
Fail 'PROTECTED' (([string]$liveEntry.Name) + ' 受保护,面板不会结束它')
|
|
515
|
+
}
|
|
516
|
+
[void]$validated.Add([pscustomobject]@{ pid = $processId; name = [string]$liveEntry.Name })
|
|
517
|
+
}
|
|
518
|
+
foreach ($target in $validated) {
|
|
519
|
+
try {
|
|
520
|
+
if ($mode -eq 'close') {
|
|
521
|
+
$process = Get-Process -Id $target.pid -ErrorAction Stop
|
|
522
|
+
$closed = $process.CloseMainWindow()
|
|
523
|
+
[void]$results.Add([pscustomobject]@{
|
|
524
|
+
pid = $target.pid
|
|
525
|
+
ok = [bool]$closed
|
|
526
|
+
code = if ($closed) { 'OK' } else { 'NO_WINDOW' }
|
|
527
|
+
message = if ($closed) { '已请求正常关闭' } else { '该进程没有可关闭的主窗口,请改用强制结束' }
|
|
528
|
+
})
|
|
529
|
+
} else {
|
|
530
|
+
Stop-Process -Id $target.pid -Force -ErrorAction Stop
|
|
531
|
+
Start-Sleep -Milliseconds 250
|
|
532
|
+
$stillThere = Get-Process -Id $target.pid -ErrorAction SilentlyContinue
|
|
533
|
+
[void]$results.Add([pscustomobject]@{
|
|
534
|
+
pid = $target.pid
|
|
535
|
+
ok = ($stillThere -eq $null)
|
|
536
|
+
code = if ($stillThere -eq $null) { 'OK' } else { 'STILL_RUNNING' }
|
|
537
|
+
message = if ($stillThere -eq $null) { '已结束' } else { '进程仍在运行(可能受保护)' }
|
|
538
|
+
})
|
|
539
|
+
}
|
|
540
|
+
} catch {
|
|
541
|
+
$code = if (Test-AccessDenied $_.Exception) { 'ACCESS_DENIED' } else { 'OP_FAILED' }
|
|
542
|
+
[void]$results.Add([pscustomobject]@{ pid = $target.pid; ok = $false; code = $code; message = $_.Exception.Message })
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
if ($validated.Count -eq 0) {
|
|
546
|
+
$r = [pscustomobject]@{ ok = $false; code = 'STALE_PROCESS'; message = '目标进程已不存在或已变化,请刷新后重试'; results = @($results) }
|
|
547
|
+
} else {
|
|
548
|
+
$failed = @($results | Where-Object { -not $_.ok })
|
|
549
|
+
$r = [pscustomobject]@{
|
|
550
|
+
ok = ($failed.Count -eq 0)
|
|
551
|
+
code = if ($failed.Count -eq 0) { 'OK' } else { 'PARTIAL' }
|
|
552
|
+
message = if ($failed.Count -eq 0) { '操作完成' } else { '部分进程未能处理' }
|
|
553
|
+
results = @($results)
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
} catch {
|
|
557
|
+
$message = $_.Exception.Message
|
|
558
|
+
$code = 'OP_FAILED'
|
|
559
|
+
if ($message -match '^([A-Z_]+)\|(.*)$') {
|
|
560
|
+
$code = $Matches[1]
|
|
561
|
+
$message = $Matches[2]
|
|
562
|
+
} elseif (Test-AccessDenied $_.Exception) {
|
|
563
|
+
$code = 'ACCESS_DENIED'
|
|
564
|
+
}
|
|
565
|
+
$r = [pscustomobject]@{ ok = $false; code = $code; message = $message; results = @() }
|
|
566
|
+
}
|
|
567
|
+
`
|
|
568
|
+
|
|
569
|
+
export async function stopProcesses(payload, { signal, elevate = false } = {}) {
|
|
570
|
+
const body = STOP_BODY_TEMPLATE.replaceAll('__PAYLOAD__', payloadBase64(payload))
|
|
571
|
+
const result = await runScript(body, {
|
|
572
|
+
signal,
|
|
573
|
+
elevate,
|
|
574
|
+
timeoutMs: OPERATION_TIMEOUT_MS,
|
|
575
|
+
prefix: 'stop',
|
|
576
|
+
})
|
|
577
|
+
if (result?.ok === true) return result
|
|
578
|
+
const code = String(result?.code ?? 'OP_FAILED')
|
|
579
|
+
const message = String(result?.message ?? '操作失败')
|
|
580
|
+
if ((code === 'ACCESS_DENIED' || code === 'ELEVATION_REQUIRED') && !elevate) {
|
|
581
|
+
throw failure('ELEVATION_REQUIRED', code === 'ELEVATION_REQUIRED' ? message : '结束该进程需要管理员权限', { results: result?.results })
|
|
582
|
+
}
|
|
583
|
+
throw failure(code, message, { results: result?.results })
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
// ---------------------------------------------------------------------------
|
|
587
|
+
// Toggle one startup entry
|
|
588
|
+
// ---------------------------------------------------------------------------
|
|
589
|
+
|
|
590
|
+
const STARTUP_SET_TEMPLATE = String.raw`
|
|
591
|
+
$ErrorActionPreference = 'Stop'
|
|
592
|
+
function Fail([string]$code, [string]$message) {
|
|
593
|
+
throw [System.InvalidOperationException]::new($code + '|' + $message)
|
|
594
|
+
}
|
|
595
|
+
function Test-AccessDenied($exception) {
|
|
596
|
+
$current = $exception
|
|
597
|
+
$guard = 0
|
|
598
|
+
while ($current -ne $null -and $guard -lt 6) {
|
|
599
|
+
try { if ($current.HResult -eq -2147024891) { return $true } } catch { }
|
|
600
|
+
if ($current -is [System.UnauthorizedAccessException]) { return $true }
|
|
601
|
+
if ($current -is [System.ComponentModel.Win32Exception] -and $current.NativeErrorCode -eq 5) { return $true }
|
|
602
|
+
$current = $current.InnerException
|
|
603
|
+
$guard = $guard + 1
|
|
604
|
+
}
|
|
605
|
+
return $false
|
|
606
|
+
}
|
|
607
|
+
$payloadText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__'))
|
|
608
|
+
$request = $payloadText | ConvertFrom-Json
|
|
609
|
+
$r = [pscustomobject]@{ ok = $false; code = 'OP_FAILED'; message = '操作失败'; enabled = $null }
|
|
610
|
+
try {
|
|
611
|
+
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
|
612
|
+
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
|
|
613
|
+
$isAdmin = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
|
614
|
+
$source = [string]$request.source
|
|
615
|
+
$enabled = [bool]$request.enabled
|
|
616
|
+
$expect = [string]$request.expect
|
|
617
|
+
$runKeyPaths = @{
|
|
618
|
+
'HKCU|Run' = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run'
|
|
619
|
+
'HKLM|Run' = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Run'
|
|
620
|
+
'HKLM|Run32' = 'HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Run'
|
|
621
|
+
}
|
|
622
|
+
$approvalKeyPaths = @{
|
|
623
|
+
'HKCU|Run' = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'
|
|
624
|
+
'HKLM|Run' = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run'
|
|
625
|
+
'HKLM|Run32' = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run32'
|
|
626
|
+
}
|
|
627
|
+
function Read-Approved([string]$approvalPath, [string]$valueName) {
|
|
628
|
+
if (-not (Test-Path -LiteralPath $approvalPath)) { return 'enabled' }
|
|
629
|
+
try {
|
|
630
|
+
$value = (Get-ItemProperty -LiteralPath $approvalPath -Name $valueName -ErrorAction Stop).$valueName
|
|
631
|
+
if ($value -is [byte[]] -and $value.Length -ge 1) {
|
|
632
|
+
if ($value[0] -eq 3) { return 'disabled' }
|
|
633
|
+
if ($value[0] -eq 2 -or $value[0] -eq 6) { return 'enabled' }
|
|
634
|
+
}
|
|
635
|
+
} catch { }
|
|
636
|
+
return 'enabled'
|
|
637
|
+
}
|
|
638
|
+
function Write-Approved([string]$approvalPath, [string]$valueName, [bool]$on) {
|
|
639
|
+
if (-not (Test-Path -LiteralPath $approvalPath)) {
|
|
640
|
+
New-Item -Path $approvalPath -Force | Out-Null
|
|
641
|
+
}
|
|
642
|
+
if ($on) {
|
|
643
|
+
$bytes = [byte[]](2,0,0,0,0,0,0,0,0,0,0,0)
|
|
644
|
+
} else {
|
|
645
|
+
$stamp = [BitConverter]::GetBytes([long]([DateTime]::UtcNow.ToFileTimeUtc()))
|
|
646
|
+
$bytes = [byte[]]@(3,0,0,0) + [byte[]]$stamp
|
|
647
|
+
}
|
|
648
|
+
New-ItemProperty -LiteralPath $approvalPath -Name $valueName -PropertyType Binary -Value ([byte[]]$bytes) -Force | Out-Null
|
|
649
|
+
}
|
|
650
|
+
if ($source -eq 'run') {
|
|
651
|
+
$hive = [string]$request.hive
|
|
652
|
+
$key = [string]$request.key
|
|
653
|
+
$name = [string]$request.name
|
|
654
|
+
if ($hive -notin @('HKCU','HKLM')) { Fail 'BAD_ARGS' '不支持的注册表范围' }
|
|
655
|
+
if ($hive -eq 'HKLM' -and -not $isAdmin) { Fail 'ELEVATION_REQUIRED' '修改系统级启动项需要管理员权限' }
|
|
656
|
+
if ($key -notin @('Run','Run32')) { Fail 'BAD_ARGS' '一次性启动项不支持开关' }
|
|
657
|
+
if ($name -eq '' -or $name.Length -gt 300) { Fail 'BAD_ARGS' '启动项名称非法' }
|
|
658
|
+
$mapKey = $hive + '|' + $key
|
|
659
|
+
$runPath = $runKeyPaths[$mapKey]
|
|
660
|
+
$approvalPath = $approvalKeyPaths[$mapKey]
|
|
661
|
+
if (-not $runPath -or -not $approvalPath) { Fail 'BAD_ARGS' '不支持的启动项位置' }
|
|
662
|
+
if (-not (Test-Path -LiteralPath $runPath)) { Fail 'STALE_ENTRY' '启动项注册表键不存在' }
|
|
663
|
+
$current = $null
|
|
664
|
+
try { $current = [string](Get-ItemProperty -LiteralPath $runPath -Name $name -ErrorAction Stop).$name } catch { Fail 'STALE_ENTRY' '启动项已不存在,请刷新后重试' }
|
|
665
|
+
if ($expect -ne '' -and $current -ne $expect) { Fail 'STALE_ENTRY' '启动项内容已变化,请刷新后重试' }
|
|
666
|
+
Write-Approved $approvalPath $name $enabled
|
|
667
|
+
$state = Read-Approved $approvalPath $name
|
|
668
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = ($state -eq 'enabled'); message = if ($state -eq 'enabled') { '已启用' } else { '已禁用' } }
|
|
669
|
+
} elseif ($source -eq 'folder') {
|
|
670
|
+
$scope = [string]$request.scope
|
|
671
|
+
$file = [string]$request.file
|
|
672
|
+
if ($scope -notin @('user','machine')) { Fail 'BAD_ARGS' '不支持的启动文件夹范围' }
|
|
673
|
+
if ($scope -eq 'machine' -and -not $isAdmin) { Fail 'ELEVATION_REQUIRED' '修改公共启动文件夹需要管理员权限' }
|
|
674
|
+
if ($file -eq '' -or $file.Length -gt 300 -or $file -match '[\\/:]') { Fail 'BAD_ARGS' '启动文件名非法' }
|
|
675
|
+
$folder = if ($scope -eq 'machine') { $env:ProgramData + '\Microsoft\Windows\Start Menu\Programs\Startup' } else { $env:APPDATA + '\Microsoft\Windows\Start Menu\Programs\Startup' }
|
|
676
|
+
$filePath = Join-Path $folder $file
|
|
677
|
+
if (-not (Test-Path -LiteralPath $filePath)) { Fail 'STALE_ENTRY' '启动文件夹中的文件已不存在,请刷新后重试' }
|
|
678
|
+
$approvalPath = if ($scope -eq 'machine') { 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder' } else { 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\StartupFolder' }
|
|
679
|
+
if ($expect -ne '' -and $file -match '\.lnk$') {
|
|
680
|
+
try {
|
|
681
|
+
$actual = [string](New-Object -ComObject WScript.Shell).CreateShortcut($filePath).TargetPath
|
|
682
|
+
if ($actual -ne '' -and $actual -ne $expect) { Fail 'STALE_ENTRY' '启动项目标已变化,请刷新后重试' }
|
|
683
|
+
} catch { }
|
|
684
|
+
}
|
|
685
|
+
Write-Approved $approvalPath $file $enabled
|
|
686
|
+
$state = Read-Approved $approvalPath $file
|
|
687
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = ($state -eq 'enabled'); message = if ($state -eq 'enabled') { '已启用' } else { '已禁用' } }
|
|
688
|
+
} elseif ($source -eq 'task') {
|
|
689
|
+
$taskPath = [string]$request.taskPath
|
|
690
|
+
$taskName = [string]$request.taskName
|
|
691
|
+
if ($taskPath -notmatch '^\\' -or $taskName -eq '') { Fail 'BAD_ARGS' '计划任务参数非法' }
|
|
692
|
+
if ($taskPath -match '^\\Microsoft(\\|$)') { Fail 'PROTECTED' 'Windows 自带任务不在面板修改范围内' }
|
|
693
|
+
if (-not $isAdmin) { Fail 'ELEVATION_REQUIRED' '修改计划任务需要管理员权限' }
|
|
694
|
+
$task = Get-ScheduledTask -TaskPath $taskPath -TaskName $taskName -ErrorAction SilentlyContinue
|
|
695
|
+
if ($task -eq $null) { Fail 'STALE_ENTRY' '计划任务已不存在,请刷新后重试' }
|
|
696
|
+
if ($enabled) { Enable-ScheduledTask -TaskPath $taskPath -TaskName $taskName | Out-Null }
|
|
697
|
+
else { Disable-ScheduledTask -TaskPath $taskPath -TaskName $taskName | Out-Null }
|
|
698
|
+
$after = Get-ScheduledTask -TaskPath $taskPath -TaskName $taskName
|
|
699
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = ([string]$after.State -ne 'Disabled'); message = if ([string]$after.State -ne 'Disabled') { '已启用' } else { '已禁用' } }
|
|
700
|
+
} elseif ($source -eq 'service') {
|
|
701
|
+
$serviceName = [string]$request.serviceName
|
|
702
|
+
if ($serviceName -eq '' -or $serviceName -notmatch '^[A-Za-z0-9_.\-]+$') { Fail 'BAD_ARGS' '服务名非法' }
|
|
703
|
+
if (-not $isAdmin) { Fail 'ELEVATION_REQUIRED' '停止或修改服务需要管理员权限' }
|
|
704
|
+
$service = Get-CimInstance Win32_Service -Filter ("Name='" + $serviceName.Replace("'", "''") + "'") -ErrorAction SilentlyContinue
|
|
705
|
+
if ($service -eq $null) { Fail 'STALE_ENTRY' '服务已不存在,请刷新后重试' }
|
|
706
|
+
$servicePath = [string]$service.PathName
|
|
707
|
+
if ($servicePath -match '^"?[A-Za-z]:\\Windows\\') { Fail 'PROTECTED' 'Windows 系统服务不在面板修改范围内' }
|
|
708
|
+
if (-not $enabled -and [string]$service.StartMode -eq 'Disabled') {
|
|
709
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = $false; message = '该服务已经是禁用状态' }
|
|
710
|
+
} else {
|
|
711
|
+
if ($enabled) {
|
|
712
|
+
Set-Service -Name $serviceName -StartupType Automatic -ErrorAction Stop
|
|
713
|
+
if ([bool]$request.delayed) {
|
|
714
|
+
$keyPath = 'HKLM:\SYSTEM\CurrentControlSet\Services\' + $serviceName
|
|
715
|
+
New-ItemProperty -LiteralPath $keyPath -Name DelayedAutostart -PropertyType DWord -Value 1 -Force | Out-Null
|
|
716
|
+
}
|
|
717
|
+
$after = Get-CimInstance Win32_Service -Filter ("Name='" + $serviceName.Replace("'", "''") + "'")
|
|
718
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = ([string]$after.StartMode -ne 'Disabled'); message = '已启用' }
|
|
719
|
+
} else {
|
|
720
|
+
Set-Service -Name $serviceName -StartupType Disabled -ErrorAction Stop
|
|
721
|
+
$stopNote = ''
|
|
722
|
+
if ([bool]$request.stopRunning -and [string]$service.State -eq 'Running') {
|
|
723
|
+
try {
|
|
724
|
+
Stop-Service -Name $serviceName -Force -ErrorAction Stop
|
|
725
|
+
} catch {
|
|
726
|
+
$stopNote = ';服务未能停止:' + $_.Exception.Message
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
$after = Get-CimInstance Win32_Service -Filter ("Name='" + $serviceName.Replace("'", "''") + "'")
|
|
730
|
+
$r = [pscustomobject]@{ ok = $true; code = 'OK'; enabled = ([string]$after.StartMode -ne 'Disabled'); message = '已禁用' + $stopNote }
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
} else {
|
|
734
|
+
Fail 'BAD_ARGS' '不支持的启动项类型'
|
|
735
|
+
}
|
|
736
|
+
} catch {
|
|
737
|
+
$message = $_.Exception.Message
|
|
738
|
+
$code = 'OP_FAILED'
|
|
739
|
+
if ($message -match '^([A-Z_]+)\|(.*)$') {
|
|
740
|
+
$code = $Matches[1]
|
|
741
|
+
$message = $Matches[2]
|
|
742
|
+
} elseif (Test-AccessDenied $_.Exception) {
|
|
743
|
+
$code = 'ACCESS_DENIED'
|
|
744
|
+
}
|
|
745
|
+
$r = [pscustomobject]@{ ok = $false; code = $code; message = $message; enabled = $null }
|
|
746
|
+
}
|
|
747
|
+
`
|
|
748
|
+
|
|
749
|
+
export async function setStartupEntry(payload, { signal, elevate = false } = {}) {
|
|
750
|
+
const body = STARTUP_SET_TEMPLATE.replaceAll('__PAYLOAD__', payloadBase64(payload))
|
|
751
|
+
const result = await runScript(body, {
|
|
752
|
+
signal,
|
|
753
|
+
elevate,
|
|
754
|
+
timeoutMs: OPERATION_TIMEOUT_MS,
|
|
755
|
+
prefix: 'startup',
|
|
756
|
+
})
|
|
757
|
+
if (result?.ok === true) return result
|
|
758
|
+
const code = String(result?.code ?? 'OP_FAILED')
|
|
759
|
+
const message = String(result?.message ?? '操作失败')
|
|
760
|
+
if ((code === 'ACCESS_DENIED' || code === 'ELEVATION_REQUIRED') && !elevate) {
|
|
761
|
+
throw failure('ELEVATION_REQUIRED', message || '修改该启动项需要管理员权限', {})
|
|
762
|
+
}
|
|
763
|
+
throw failure(code, message)
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// ---------------------------------------------------------------------------
|
|
767
|
+
// Inspect one target
|
|
768
|
+
// ---------------------------------------------------------------------------
|
|
769
|
+
|
|
770
|
+
const INSPECT_TEMPLATE = String.raw`
|
|
771
|
+
$ErrorActionPreference = 'SilentlyContinue'
|
|
772
|
+
$payloadText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PAYLOAD__'))
|
|
773
|
+
$request = $payloadText | ConvertFrom-Json
|
|
774
|
+
$r = [pscustomobject]@{ ok = $false; code = 'OP_FAILED'; message = '检查失败' }
|
|
775
|
+
try {
|
|
776
|
+
$targetPath = [string]$request.path
|
|
777
|
+
$targetPid = [int]$request.pid
|
|
778
|
+
$process = $null
|
|
779
|
+
if ($targetPid -gt 0) { $process = Get-CimInstance Win32_Process -Filter ("ProcessId=" + $targetPid) }
|
|
780
|
+
if ($process -ne $null -and [string]::IsNullOrWhiteSpace($targetPath)) { $targetPath = [string]$process.ExecutablePath }
|
|
781
|
+
if ([string]::IsNullOrWhiteSpace($targetPath)) { throw '找不到目标路径' }
|
|
782
|
+
$fileInfo = $null
|
|
783
|
+
try { $fileInfo = Get-Item -LiteralPath $targetPath -ErrorAction Stop } catch { }
|
|
784
|
+
$version = $null
|
|
785
|
+
try { $version = [Diagnostics.FileVersionInfo]::GetVersionInfo($targetPath) } catch { }
|
|
786
|
+
$signature = $null
|
|
787
|
+
try { $signature = Get-AuthenticodeSignature -LiteralPath $targetPath -ErrorAction Stop } catch { }
|
|
788
|
+
$services = @()
|
|
789
|
+
try {
|
|
790
|
+
$services = @(Get-CimInstance Win32_Service | Where-Object {
|
|
791
|
+
($targetPid -gt 0 -and [int]$_.ProcessId -eq $targetPid) -or
|
|
792
|
+
(-not [string]::IsNullOrWhiteSpace($targetPath) -and $_.PathName -and $_.PathName.ToLowerInvariant().Contains($targetPath.ToLowerInvariant()))
|
|
793
|
+
} | Select-Object Name, DisplayName, Description, State, StartMode, ProcessId)
|
|
794
|
+
} catch { }
|
|
795
|
+
$parents = New-Object System.Collections.ArrayList
|
|
796
|
+
$current = $process
|
|
797
|
+
$guard = 0
|
|
798
|
+
while ($current -ne $null -and $guard -lt 8) {
|
|
799
|
+
$parentId = [int]$current.ParentProcessId
|
|
800
|
+
if ($parentId -le 0) { break }
|
|
801
|
+
$parent = Get-CimInstance Win32_Process -Filter ("ProcessId=" + $parentId)
|
|
802
|
+
if ($parent -eq $null) { break }
|
|
803
|
+
[void]$parents.Add([pscustomobject]@{ pid = [int]$parent.ProcessId; name = [string]$parent.Name; path = [string]$parent.ExecutablePath })
|
|
804
|
+
$current = $parent
|
|
805
|
+
$guard = $guard + 1
|
|
806
|
+
}
|
|
807
|
+
$r = [pscustomobject]@{
|
|
808
|
+
ok = $true
|
|
809
|
+
path = $targetPath
|
|
810
|
+
name = if ($process -ne $null) { [string]$process.Name } else { [string]$fileInfo.Name }
|
|
811
|
+
command_line = if ($process -ne $null) { [string]$process.CommandLine } else { '' }
|
|
812
|
+
started_at = if ($process -ne $null -and $process.CreationDate -ne $null) { ([datetime]$process.CreationDate).ToString('o') } else { '' }
|
|
813
|
+
company = if ($version) { [string]$version.CompanyName } else { '' }
|
|
814
|
+
product = if ($version) { [string]$version.ProductName } else { '' }
|
|
815
|
+
description = if ($version) { [string]$version.FileDescription } else { '' }
|
|
816
|
+
version = if ($version) { [string]$version.FileVersion } else { '' }
|
|
817
|
+
size_bytes = if ($fileInfo) { [long]$fileInfo.Length } else { 0 }
|
|
818
|
+
created_at = if ($fileInfo) { $fileInfo.CreationTime.ToString('o') } else { '' }
|
|
819
|
+
modified_at = if ($fileInfo) { $fileInfo.LastWriteTime.ToString('o') } else { '' }
|
|
820
|
+
signature_status = if ($signature) { [string]$signature.Status } else { 'Unknown' }
|
|
821
|
+
signature_signer = if ($signature -and $signature.SignerCertificate) { [string]$signature.SignerCertificate.Subject } else { '' }
|
|
822
|
+
services = @($services)
|
|
823
|
+
parents = @($parents)
|
|
824
|
+
}
|
|
825
|
+
} catch {
|
|
826
|
+
$r = [pscustomobject]@{ ok = $false; code = 'NOT_FOUND'; message = $_.Exception.Message }
|
|
827
|
+
}
|
|
828
|
+
`
|
|
829
|
+
|
|
830
|
+
export async function inspectTarget(payload, { signal } = {}) {
|
|
831
|
+
const body = INSPECT_TEMPLATE.replaceAll('__PAYLOAD__', payloadBase64(payload))
|
|
832
|
+
const result = await runScript(body, { signal, timeoutMs: READ_TIMEOUT_MS, prefix: 'inspect' })
|
|
833
|
+
if (result?.ok !== true) throw failure(result?.code ?? 'NOT_FOUND', result?.message ?? '检查失败')
|
|
834
|
+
return result
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
// ---------------------------------------------------------------------------
|
|
838
|
+
// Open a Windows tool (no elevation, fire and forget)
|
|
839
|
+
// ---------------------------------------------------------------------------
|
|
840
|
+
|
|
841
|
+
export function openWindowsTool(tool, target) {
|
|
842
|
+
if (!isWindows()) throw failure('UNSUPPORTED_PLATFORM', '该功能仅支持 Windows')
|
|
843
|
+
const map = {
|
|
844
|
+
taskmgr: ['taskmgr.exe', []],
|
|
845
|
+
startupapps: ['explorer.exe', ['ms-settings:startupapps']],
|
|
846
|
+
services: ['mmc.exe', ['services.msc']],
|
|
847
|
+
reveal: ['explorer.exe', ['/select,', String(target ?? '')]],
|
|
848
|
+
}
|
|
849
|
+
const entry = map[tool]
|
|
850
|
+
if (entry === undefined) throw failure('BAD_ARGS', '不支持的系统工具')
|
|
851
|
+
const child = spawn(entry[0], entry[1], { detached: true, stdio: 'ignore', windowsHide: true })
|
|
852
|
+
child.on('error', () => {})
|
|
853
|
+
child.unref()
|
|
854
|
+
return { ok: true }
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** Raw constant scripts, exposed for static tests only. */
|
|
858
|
+
export const SCRIPT_TEMPLATES = {
|
|
859
|
+
collect: COLLECT_BODY,
|
|
860
|
+
stop: STOP_BODY_TEMPLATE,
|
|
861
|
+
startup: STARTUP_SET_TEMPLATE,
|
|
862
|
+
inspect: INSPECT_TEMPLATE,
|
|
863
|
+
}
|