dsh-ops-kit 0.4.1 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -4
- package/README.zh-CN.md +3 -1
- package/client.js +282 -73
- package/index.js +399 -111
- package/package.json +4 -1
package/index.js
CHANGED
|
@@ -27,6 +27,8 @@ export const name = 'dsh-ops-kit'
|
|
|
27
27
|
export const inject = ['tools', 'webServer']
|
|
28
28
|
|
|
29
29
|
const MAX_OUTPUT = 8_000
|
|
30
|
+
/** Password-auth sessions have no ssh maxBuffer; cap what we keep. */
|
|
31
|
+
const PASSWORD_OUTPUT_LIMIT = 2 * 1024 * 1024
|
|
30
32
|
|
|
31
33
|
/** Host context, set in apply; used for the optional AI diagnosis. */
|
|
32
34
|
let hostCtx = null
|
|
@@ -47,7 +49,54 @@ function secretsFile() {
|
|
|
47
49
|
return join(kitDir(), 'secrets.json')
|
|
48
50
|
}
|
|
49
51
|
|
|
50
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* SSH passwords live in the system keychain (macOS `security`, Linux
|
|
54
|
+
* `secret-tool`). Only when neither exists do we fall back to a 0600 file —
|
|
55
|
+
* and that file is base64, i.e. obfuscation, not encryption. The panel says so.
|
|
56
|
+
*/
|
|
57
|
+
const KEYCHAIN_SERVICE = 'dsh-ops-kit'
|
|
58
|
+
|
|
59
|
+
async function keychainGet(name) {
|
|
60
|
+
if (process.platform === 'darwin') {
|
|
61
|
+
const { stdout } = await run('security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', String(name), '-w'], { timeout: 10_000 })
|
|
62
|
+
return String(stdout).replace(/\n$/, '')
|
|
63
|
+
}
|
|
64
|
+
if (process.platform === 'linux') {
|
|
65
|
+
const { stdout } = await run('secret-tool', ['lookup', 'service', KEYCHAIN_SERVICE, 'account', String(name)], { timeout: 10_000 })
|
|
66
|
+
return String(stdout).replace(/\n$/, '')
|
|
67
|
+
}
|
|
68
|
+
throw new Error('no system keychain on this platform')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function keychainSet(name, password) {
|
|
72
|
+
if (process.platform === 'darwin') {
|
|
73
|
+
await run('security', ['add-generic-password', '-U', '-s', KEYCHAIN_SERVICE, '-a', String(name), '-w', String(password)], { timeout: 10_000 })
|
|
74
|
+
return
|
|
75
|
+
}
|
|
76
|
+
if (process.platform === 'linux') {
|
|
77
|
+
await new Promise((resolve, reject) => {
|
|
78
|
+
const child = spawn('secret-tool', ['store', '--label', 'dsh-ops-kit ' + name, 'service', KEYCHAIN_SERVICE, 'account', String(name)])
|
|
79
|
+
child.on('error', reject)
|
|
80
|
+
child.on('close', (code) => { if (code === 0) resolve(); else reject(new Error('secret-tool exit ' + code)) })
|
|
81
|
+
child.stdin.end(String(password))
|
|
82
|
+
})
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
throw new Error('no system keychain on this platform')
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function keychainDelete(name) {
|
|
89
|
+
if (process.platform === 'darwin') {
|
|
90
|
+
await run('security', ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', String(name)], { timeout: 10_000 })
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
if (process.platform === 'linux') {
|
|
94
|
+
await run('secret-tool', ['clear', 'service', KEYCHAIN_SERVICE, 'account', String(name)], { timeout: 10_000 })
|
|
95
|
+
return
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Legacy 0600 file; only consulted when the keychain has nothing. */
|
|
51
100
|
async function loadSecrets() {
|
|
52
101
|
try {
|
|
53
102
|
const data = JSON.parse(await readFile(secretsFile(), 'utf8'))
|
|
@@ -57,10 +106,33 @@ async function loadSecrets() {
|
|
|
57
106
|
}
|
|
58
107
|
}
|
|
59
108
|
|
|
109
|
+
/** Password for one host: keychain first, 0600 file as the fallback. */
|
|
110
|
+
async function readPassword(name) {
|
|
111
|
+
try {
|
|
112
|
+
const value = await keychainGet(name)
|
|
113
|
+
if (value) return value
|
|
114
|
+
} catch { /* no keychain entry or no keychain tool */ }
|
|
115
|
+
const all = await loadSecrets()
|
|
116
|
+
const secret = all[name]
|
|
117
|
+
return secret && secret.password ? Buffer.from(secret.password, 'base64').toString('utf8') : ''
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function hasPassword(name) {
|
|
121
|
+
return Boolean(await readPassword(name))
|
|
122
|
+
}
|
|
123
|
+
|
|
60
124
|
async function saveSecret(name, password) {
|
|
61
125
|
const all = await loadSecrets()
|
|
62
|
-
|
|
63
|
-
|
|
126
|
+
const label = String(name)
|
|
127
|
+
if (password) {
|
|
128
|
+
let inKeychain = false
|
|
129
|
+
try { await keychainSet(label, String(password)); inKeychain = true } catch { inKeychain = false }
|
|
130
|
+
if (inKeychain) delete all[label]
|
|
131
|
+
else all[label] = { password: Buffer.from(String(password), 'utf8').toString('base64'), enc: 'base64', at: new Date().toISOString() }
|
|
132
|
+
} else {
|
|
133
|
+
delete all[label]
|
|
134
|
+
try { await keychainDelete(label) } catch { /* nothing stored */ }
|
|
135
|
+
}
|
|
64
136
|
await mkdir(kitDir(), { recursive: true })
|
|
65
137
|
await writeFile(secretsFile(), JSON.stringify(all, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
66
138
|
try { await chmod(secretsFile(), 0o600) } catch { /* best effort */ }
|
|
@@ -167,8 +239,8 @@ function sshPassword(cfg, password, command, timeoutMs = 20_000) {
|
|
|
167
239
|
conn.on('ready', () => {
|
|
168
240
|
conn.exec(command, (error, stream) => {
|
|
169
241
|
if (error) return done({ ok: false, code: 1, stdout, stderr: String(error.message || error) })
|
|
170
|
-
stream.on('data', (chunk) => { stdout += chunk.toString('utf8') })
|
|
171
|
-
stream.stderr.on('data', (chunk) => { stderr += chunk.toString('utf8') })
|
|
242
|
+
stream.on('data', (chunk) => { if (stdout.length < PASSWORD_OUTPUT_LIMIT) stdout += chunk.toString('utf8') })
|
|
243
|
+
stream.stderr.on('data', (chunk) => { if (stderr.length < PASSWORD_OUTPUT_LIMIT) stderr += chunk.toString('utf8') })
|
|
172
244
|
stream.on('close', (code) => done({ ok: code === 0, code: code ?? 1, stdout, stderr }))
|
|
173
245
|
})
|
|
174
246
|
})
|
|
@@ -191,12 +263,8 @@ function sshPassword(cfg, password, command, timeoutMs = 20_000) {
|
|
|
191
263
|
}
|
|
192
264
|
|
|
193
265
|
async function ssh(cfg, command, timeoutMs = 20_000) {
|
|
194
|
-
const
|
|
195
|
-
|
|
196
|
-
if (secret && secret.password) {
|
|
197
|
-
const password = Buffer.from(secret.password, 'base64').toString('utf8')
|
|
198
|
-
return sshPassword(cfg, password, command, timeoutMs)
|
|
199
|
-
}
|
|
266
|
+
const password = await readPassword(cfg.name)
|
|
267
|
+
if (password) return sshPassword(cfg, password, command, timeoutMs)
|
|
200
268
|
const args = [
|
|
201
269
|
'-o', 'BatchMode=yes',
|
|
202
270
|
'-o', 'ConnectTimeout=8',
|
|
@@ -225,7 +293,7 @@ async function ssh(cfg, command, timeoutMs = 20_000) {
|
|
|
225
293
|
|
|
226
294
|
function clip(text, limit = MAX_OUTPUT) {
|
|
227
295
|
const value = String(text ?? '')
|
|
228
|
-
return value.length > limit ? `${value.slice(0, limit)}\n… (${value.length - limit}
|
|
296
|
+
return value.length > limit ? `${value.slice(0, limit)}\n… (${value.length - limit} 字符已省略)` : value
|
|
229
297
|
}
|
|
230
298
|
|
|
231
299
|
function cleanStderr(text) {
|
|
@@ -281,6 +349,10 @@ function firstLines(text, count = 2) {
|
|
|
281
349
|
|
|
282
350
|
/** Check every configured host in parallel and record one history entry per host. */
|
|
283
351
|
async function statusAll() {
|
|
352
|
+
if (!(await acquireLock('.status-pass.lock', 3 * 60_000))) {
|
|
353
|
+
return { at: new Date().toISOString(), skipped: true, elapsedMs: 0, results: [] }
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
284
356
|
const data = await loadHosts()
|
|
285
357
|
if (data.hosts.length === 0) throw new Error('no hosts configured: ask the agent to call ops_hosts with action="add", or add one in the panel')
|
|
286
358
|
const started = Date.now()
|
|
@@ -308,18 +380,58 @@ async function statusAll() {
|
|
|
308
380
|
summary: row.ok ? firstLines(row.output) : clip(row.error, 200),
|
|
309
381
|
})))
|
|
310
382
|
return { at, elapsedMs: Date.now() - started, results }
|
|
383
|
+
} finally {
|
|
384
|
+
await releaseLock('.status-pass.lock')
|
|
385
|
+
}
|
|
311
386
|
}
|
|
312
387
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
388
|
+
/**
|
|
389
|
+
* Commands that can destroy data or take the server down. Every one of these
|
|
390
|
+
* needs an explicit `confirm: true` — the panel shows the reasons first, the
|
|
391
|
+
* tools tell the model to re-run with confirm.
|
|
392
|
+
*/
|
|
393
|
+
const RISK_RULES = [
|
|
394
|
+
{ id: 'rm-recursive', rx: /(^|[\s;|&])rm\s+(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/, why: '递归删除(rm -r / rm -rf),会连同目录内容一起删掉' },
|
|
395
|
+
{ id: 'rm-root', rx: /(^|[\s;|&])rm\s+[^;|&]*\s(\/+|\/\*|~|\$HOME)(\s|;|$)/, why: '删除根目录、通配符或家目录' },
|
|
396
|
+
{ id: 'dd-device', rx: /(^|[\s;|&])dd\b[^;|&]*\bof=\/dev\//, why: 'dd 直接写块设备,会覆盖磁盘数据' },
|
|
397
|
+
{ id: 'mkfs', rx: /(^|[\s;|&])(mkfs(\.[a-z0-9]+)?|wipefs|fdisk|parted|sfdisk)\b/, why: '格式化、分区或擦除磁盘' },
|
|
398
|
+
{ id: 'shutdown', rx: /(^|[\s;|&])(shutdown|reboot|halt|poweroff)\b/, why: '关机或重启服务器' },
|
|
399
|
+
{ id: 'systemctl-power', rx: /systemctl\s+(poweroff|reboot|halt|kexec)\b/, why: 'systemctl 关机或重启' },
|
|
400
|
+
{ id: 'init0', rx: /(^|[\s;|&])init\s+0(\s|$)/, why: 'init 0 会让服务器关机' },
|
|
401
|
+
{ id: 'fork-bomb', rx: /:\(\)\s*\{\s*:\|:&\s*\}\s*;\s*:/, why: 'fork 炸弹,会耗尽系统进程' },
|
|
402
|
+
{ id: 'crontab-flush', rx: /crontab\s+-r\b/, why: '清空当前用户的全部定时任务' },
|
|
403
|
+
{ id: 'chmod-zero', rx: /chmod\s+(-R\s+)?(0{3,4}|a=)(\s|\/)/, why: '把文件权限改成 000,可能锁死服务' },
|
|
404
|
+
{ id: 'find-delete', rx: /find\s+\/[^;|&]*\s-delete\b/, why: '从根目录 find 并删除文件' },
|
|
405
|
+
{ id: 'overwrite-system', rx: /(^|[\s;|&])>\s*\/(etc|boot|dev|var\/lib)\//, why: '用重定向覆盖系统目录里的文件' },
|
|
406
|
+
{ id: 'truncate-zero', rx: /truncate\s+-s\s*0\b/, why: '把文件截断成 0 字节' },
|
|
407
|
+
{ id: 'drop-db', rx: /(drop\s+database|drop\s+table|truncate\s+table)/i, why: '删除数据库或表' },
|
|
408
|
+
{ id: 'docker-prune', rx: /docker\s+(system|volume|image|container)\s+prune/, why: '批量清理 Docker 数据(镜像、卷、容器)' },
|
|
409
|
+
{ id: 'kill-init', rx: /kill\s+-9\s+1(\s|$)/, why: '杀 init 进程,等于停机' },
|
|
410
|
+
{ id: 'git-clean', rx: /git\s+clean\s+-[a-z]*f/, why: 'git clean 会删掉未跟踪文件' },
|
|
319
411
|
]
|
|
320
412
|
|
|
413
|
+
/** @returns {{dangerous: boolean, reasons: string[]}} */
|
|
414
|
+
function classifyCommand(command) {
|
|
415
|
+
const text = String(command ?? '')
|
|
416
|
+
const reasons = []
|
|
417
|
+
for (const rule of RISK_RULES) {
|
|
418
|
+
if (rule.rx.test(text)) reasons.push(rule.why)
|
|
419
|
+
}
|
|
420
|
+
return { dangerous: reasons.length > 0, reasons: [...new Set(reasons)] }
|
|
421
|
+
}
|
|
422
|
+
|
|
321
423
|
function looksDangerous(command) {
|
|
322
|
-
return
|
|
424
|
+
return classifyCommand(command).dangerous
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Unit names are user input; keep them to what systemd actually accepts. */
|
|
428
|
+
const UNIT_NAME = /^[A-Za-z0-9@._:-]{1,120}$/
|
|
429
|
+
|
|
430
|
+
function safeUnit(name) {
|
|
431
|
+
const value = String(name ?? '').trim()
|
|
432
|
+
if (!value) throw new Error('service is required')
|
|
433
|
+
if (!UNIT_NAME.test(value)) throw new Error('service 名称不合法:只允许字母、数字和 @ . _ : -')
|
|
434
|
+
return value
|
|
323
435
|
}
|
|
324
436
|
|
|
325
437
|
function asTool(def) {
|
|
@@ -368,6 +480,63 @@ function readBody(req, limit = 64 * 1024) {
|
|
|
368
480
|
})
|
|
369
481
|
}
|
|
370
482
|
|
|
483
|
+
/* ---------- background jobs: backup / restore / cleanup / deploy ---------- */
|
|
484
|
+
|
|
485
|
+
const jobs = new Map()
|
|
486
|
+
const JOB_TTL = 60 * 60_000
|
|
487
|
+
let jobSeq = 0
|
|
488
|
+
|
|
489
|
+
function jobSnapshot(job) {
|
|
490
|
+
return {
|
|
491
|
+
id: job.id,
|
|
492
|
+
kind: job.kind,
|
|
493
|
+
label: job.label,
|
|
494
|
+
host: job.host,
|
|
495
|
+
status: job.status,
|
|
496
|
+
startedAt: job.startedAt,
|
|
497
|
+
finishedAt: job.finishedAt ?? null,
|
|
498
|
+
error: job.error,
|
|
499
|
+
output: clip(job.output || '', 2_000),
|
|
500
|
+
...(job.status === 'done' ? { result: job.result } : {}),
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Run fn in the background; the panel polls GET /ops-kit/api/job?id=… */
|
|
505
|
+
function startJob(meta, fn) {
|
|
506
|
+
const id = `j${++jobSeq}-${Date.now().toString(36)}`
|
|
507
|
+
const job = {
|
|
508
|
+
id,
|
|
509
|
+
kind: meta.kind || 'task',
|
|
510
|
+
label: meta.label || '',
|
|
511
|
+
host: meta.host || '',
|
|
512
|
+
status: 'running',
|
|
513
|
+
startedAt: new Date().toISOString(),
|
|
514
|
+
output: '',
|
|
515
|
+
error: '',
|
|
516
|
+
result: null,
|
|
517
|
+
}
|
|
518
|
+
jobs.set(id, job)
|
|
519
|
+
Promise.resolve()
|
|
520
|
+
.then(fn)
|
|
521
|
+
.then((result) => {
|
|
522
|
+
job.status = 'done'
|
|
523
|
+
job.result = result
|
|
524
|
+
job.output = typeof result === 'string' ? result : JSON.stringify(result ?? {}, null, 2)
|
|
525
|
+
})
|
|
526
|
+
.catch((error) => {
|
|
527
|
+
job.status = 'failed'
|
|
528
|
+
job.error = String(error?.message || error)
|
|
529
|
+
})
|
|
530
|
+
.finally(() => {
|
|
531
|
+
job.finishedAt = new Date().toISOString()
|
|
532
|
+
const cutoff = Date.now() - JOB_TTL
|
|
533
|
+
for (const [key, value] of jobs) {
|
|
534
|
+
if (Date.parse(value.startedAt) < cutoff) jobs.delete(key)
|
|
535
|
+
}
|
|
536
|
+
})
|
|
537
|
+
return job
|
|
538
|
+
}
|
|
539
|
+
|
|
371
540
|
/**
|
|
372
541
|
* The panel's JSON API: Node request/response handlers registered on the web
|
|
373
542
|
* server. Authentication reuses the same trust gate as DSH's own routes.
|
|
@@ -388,6 +557,29 @@ function createApiHandler({ connection } = {}) {
|
|
|
388
557
|
const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
|
|
389
558
|
const route = url.pathname.replace(/^\/ops-kit\/api\/?/, '').replace(/\/$/, '')
|
|
390
559
|
|
|
560
|
+
// This API can run commands on your servers, so reject anything that did not
|
|
561
|
+
// come from the panel itself: foreign Origin, cross-site fetch, or a body
|
|
562
|
+
// that is not JSON (a text/plain POST is a classic CSRF bypass because it
|
|
563
|
+
// skips the browser preflight).
|
|
564
|
+
const selfHost = String(req.headers.host || '')
|
|
565
|
+
const origin = String(req.headers.origin || '')
|
|
566
|
+
if (origin) {
|
|
567
|
+
let sameOrigin = false
|
|
568
|
+
try { sameOrigin = new URL(origin).host === selfHost } catch { sameOrigin = false }
|
|
569
|
+
if (!sameOrigin) { sendJson(res, 403, { error: 'cross-origin request rejected' }); return }
|
|
570
|
+
}
|
|
571
|
+
if (String(req.headers['sec-fetch-site'] || '') === 'cross-site') {
|
|
572
|
+
sendJson(res, 403, { error: 'cross-site request rejected' })
|
|
573
|
+
return
|
|
574
|
+
}
|
|
575
|
+
if (method !== 'GET') {
|
|
576
|
+
const contentType = String(req.headers['content-type'] || '').toLowerCase()
|
|
577
|
+
if (!contentType.startsWith('application/json')) {
|
|
578
|
+
sendJson(res, 415, { error: 'content-type must be application/json' })
|
|
579
|
+
return
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
391
583
|
try {
|
|
392
584
|
if (route === 'hosts' && method === 'GET') {
|
|
393
585
|
const data = await loadHosts()
|
|
@@ -530,10 +722,14 @@ function createApiHandler({ connection } = {}) {
|
|
|
530
722
|
const body = (await readBody(req)) || {}
|
|
531
723
|
const command = String(body.command ?? '').trim()
|
|
532
724
|
if (!command) { sendJson(res, 400, { error: 'command is required' }); return }
|
|
533
|
-
|
|
534
|
-
|
|
725
|
+
const risk = classifyCommand(command)
|
|
726
|
+
if (risk.dangerous && body.confirm !== true) {
|
|
727
|
+
sendJson(res, 200, { needsConfirm: true, command, reasons: risk.reasons })
|
|
535
728
|
return
|
|
536
729
|
}
|
|
730
|
+
if (risk.dangerous) {
|
|
731
|
+
await appendAudit({ host: Array.isArray(body.hosts) ? body.hosts.join(',') : 'all', action: '执行命令', detail: command.slice(0, 200) })
|
|
732
|
+
}
|
|
537
733
|
sendJson(res, 200, await batchRun(command, Array.isArray(body.hosts) ? body.hosts : undefined))
|
|
538
734
|
return
|
|
539
735
|
}
|
|
@@ -622,7 +818,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
622
818
|
const detail = Array.isArray(body.paths) && body.paths.length
|
|
623
819
|
? `${body.paths.length} 个选中文件${body.includeJournal === false ? '' : ' + journal'}`
|
|
624
820
|
: 'journal 保留 200MB;删除 7 天前的轮转日志'
|
|
625
|
-
|
|
821
|
+
const job = startJob({ kind: 'cleanup', label: '清理旧日志', host: cfg.name }, () =>
|
|
822
|
+
audited(cfg, '清理旧日志', detail, () => cleanupDisk(cfg, body)))
|
|
823
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
626
824
|
return
|
|
627
825
|
}
|
|
628
826
|
|
|
@@ -895,7 +1093,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
895
1093
|
const body = (await readBody(req)) || {}
|
|
896
1094
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
897
1095
|
if (body.action === 'restore') {
|
|
898
|
-
|
|
1096
|
+
const job = startJob({ kind: 'restore', label: `恢复 ${body.id}`, host: cfg.name }, () =>
|
|
1097
|
+
audited(cfg, '恢复备份', String(body.id ?? ''), () => restoreBackup(cfg, body.id, { user: body.user, password: body.password })))
|
|
1098
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
899
1099
|
return
|
|
900
1100
|
}
|
|
901
1101
|
if (body.action === 'remove') {
|
|
@@ -909,7 +1109,16 @@ function createApiHandler({ connection } = {}) {
|
|
|
909
1109
|
sendJson(res, 200, { host: cfg.name, backups: all[cfg.name] })
|
|
910
1110
|
return
|
|
911
1111
|
}
|
|
912
|
-
|
|
1112
|
+
const job = startJob({ kind: 'backup', label: `备份${body.type === 'mysql' ? '数据库 ' + (body.database || '全部') : '目录 ' + (body.path || '/')}`, host: cfg.name }, () =>
|
|
1113
|
+
audited(cfg, '执行备份', `${body.type === 'mysql' ? (body.database || '全部数据库') : body.path || '/'}`, () => runBackup(cfg, body)))
|
|
1114
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
1115
|
+
return
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
if (route === 'job' && method === 'GET') {
|
|
1119
|
+
const job = jobs.get(String(url.searchParams.get('id') || ''))
|
|
1120
|
+
if (!job) { sendJson(res, 404, { error: 'job not found' }); return }
|
|
1121
|
+
sendJson(res, 200, jobSnapshot(job))
|
|
913
1122
|
return
|
|
914
1123
|
}
|
|
915
1124
|
|
|
@@ -987,7 +1196,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
987
1196
|
}
|
|
988
1197
|
const job = list.find(item => item.id === body.id) || body.job
|
|
989
1198
|
if (!job) { sendJson(res, 404, { error: '发布任务不存在' }); return }
|
|
990
|
-
|
|
1199
|
+
const started = startJob({ kind: 'deploy', label: `发布 ${job.name || job.dir}`, host: cfg.name }, () =>
|
|
1200
|
+
audited(cfg, '执行发布', job.name || job.dir, () => runDeploy(cfg, job)))
|
|
1201
|
+
sendJson(res, 200, { job: jobSnapshot(started) })
|
|
991
1202
|
return
|
|
992
1203
|
}
|
|
993
1204
|
|
|
@@ -1439,9 +1650,10 @@ async function hostAction(kind, cfg, target, action) {
|
|
|
1439
1650
|
const prefix = cfg.sudo ? 'sudo -n ' : ''
|
|
1440
1651
|
let command
|
|
1441
1652
|
if (kind === 'service') {
|
|
1653
|
+
const unit = safeUnit(target)
|
|
1442
1654
|
command = action === 'logs'
|
|
1443
|
-
? `${prefix}journalctl -u ${
|
|
1444
|
-
: `${prefix}systemctl ${action} ${
|
|
1655
|
+
? `${prefix}journalctl -u ${unit} -n 60 --no-pager`
|
|
1656
|
+
: `${prefix}systemctl ${action} ${unit}`
|
|
1445
1657
|
} else {
|
|
1446
1658
|
const safe = String(target).replace(/[^A-Za-z0-9_.-]/g, '')
|
|
1447
1659
|
command = action === 'logs'
|
|
@@ -1458,10 +1670,21 @@ const METRICS_LIMIT = 20000
|
|
|
1458
1670
|
function metricsFile() { return join(kitDir(), 'metrics.jsonl') }
|
|
1459
1671
|
function inventoryFile() { return join(kitDir(), 'inventory.json') }
|
|
1460
1672
|
|
|
1673
|
+
const METRICS_MAX_BYTES = 8 * 1024 * 1024
|
|
1674
|
+
const METRICS_KEEP_LINES = 15_000
|
|
1675
|
+
|
|
1461
1676
|
async function appendMetrics(samples) {
|
|
1462
1677
|
await mkdir(kitDir(), { recursive: true })
|
|
1463
1678
|
const lines = samples.map(sample => JSON.stringify(sample)).join('\n') + '\n'
|
|
1464
1679
|
await writeFile(metricsFile(), lines, { flag: 'a' })
|
|
1680
|
+
try {
|
|
1681
|
+
const info = await stat(metricsFile())
|
|
1682
|
+
if (info.size > METRICS_MAX_BYTES) {
|
|
1683
|
+
const raw = await readFile(metricsFile(), 'utf8')
|
|
1684
|
+
const kept = raw.split('\n').filter(Boolean).slice(-METRICS_KEEP_LINES)
|
|
1685
|
+
await writeFile(metricsFile(), kept.join('\n') + '\n', 'utf8')
|
|
1686
|
+
}
|
|
1687
|
+
} catch { /* 裁剪失败不影响采样 */ }
|
|
1465
1688
|
}
|
|
1466
1689
|
|
|
1467
1690
|
async function loadMetrics(host, sinceMs = 0) {
|
|
@@ -1672,7 +1895,7 @@ async function cleanupDisk(cfg, options = {}) {
|
|
|
1672
1895
|
options.includeJournal === false ? 'true' : `journalctl --vacuum-size=${journalMb}M >/dev/null 2>&1 || true`,
|
|
1673
1896
|
// Only rotated files older than a week; never truncate a live or recent log.
|
|
1674
1897
|
Array.isArray(options.paths) && options.paths.length
|
|
1675
|
-
? options.paths.filter(item => logSafePath(item)).map(item => `rm -f ${
|
|
1898
|
+
? options.paths.filter(item => logSafePath(item)).map(item => `rm -f ${q(item)}`).join('; ') || true
|
|
1676
1899
|
: `find /var/log -maxdepth 1 -type f \\( -name "*.gz" -o -name "*.old" -o -name "*.1" -o -name "messages-*" -o -name "secure-*" -o -name "maillog-*" -o -name "cron-*" \\) -mtime +${keepDays} -delete 2>/dev/null || true`,
|
|
1677
1900
|
'after=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
|
|
1678
1901
|
'used_after=$(df -P / | awk \'NR==2{print $3}\')',
|
|
@@ -1711,10 +1934,10 @@ function fileAllowed(path) {
|
|
|
1711
1934
|
|
|
1712
1935
|
async function readRemoteFile(cfg, path) {
|
|
1713
1936
|
if (!fileAllowed(path)) throw new Error('path is outside the editable configuration area')
|
|
1714
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
1937
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(path)} 2>/dev/null || echo 0`, 10_000)
|
|
1715
1938
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
1716
1939
|
if (size > 512 * 1024) throw new Error(`文件太大(${Math.round(size / 1024)} KB),面板只编辑 512 KB 以内的配置`)
|
|
1717
|
-
const result = await ssh(cfg, `test -f ${
|
|
1940
|
+
const result = await ssh(cfg, `test -f ${q(path)} && base64 -w0 ${q(path)} 2>/dev/null || base64 ${q(path)} 2>/dev/null`, 25_000)
|
|
1718
1941
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
1719
1942
|
const content = Buffer.from(result.stdout.replace(/\s+/g, ''), 'base64').toString('utf8')
|
|
1720
1943
|
return { host: cfg.name, path, content: content.slice(0, 200_000), truncated: content.length > 200_000 }
|
|
@@ -1726,10 +1949,10 @@ async function writeRemoteFile(cfg, path, content) {
|
|
|
1726
1949
|
const backup = `${path}.bak.${stamp}`
|
|
1727
1950
|
const encoded = Buffer.from(String(content), 'utf8').toString('base64')
|
|
1728
1951
|
const command = [
|
|
1729
|
-
`cp -a ${
|
|
1730
|
-
`printf %s ${
|
|
1952
|
+
`cp -a ${q(path)} ${q(backup)}`,
|
|
1953
|
+
`printf %s ${q(encoded)} | base64 -d > ${q(path)}`,
|
|
1731
1954
|
`echo "BACKUP ${backup}"`,
|
|
1732
|
-
'wc -c < ' +
|
|
1955
|
+
'wc -c < ' + q(path),
|
|
1733
1956
|
].join(' && ')
|
|
1734
1957
|
const result = await ssh(cfg, command, 30_000)
|
|
1735
1958
|
return { host: cfg.name, path, ok: result.ok, backup, bytes: Number(result.stdout.trim().split('\n').pop()) || null, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
@@ -1892,7 +2115,7 @@ async function diagnose(cfg, question = '') {
|
|
|
1892
2115
|
/** Directory sizes one level below `path`, largest last. */
|
|
1893
2116
|
async function diskUsage(cfg, path = '/') {
|
|
1894
2117
|
const safe = String(path || '/').replace(/[;&|`$><\n]/g, '')
|
|
1895
|
-
const result = await ssh(cfg, `du -xh --max-depth=1 ${
|
|
2118
|
+
const result = await ssh(cfg, `du -xh --max-depth=1 ${q(safe)} 2>/dev/null | sort -h | tail -25`, 45_000)
|
|
1896
2119
|
const rows = String(result.stdout || '')
|
|
1897
2120
|
.split('\n')
|
|
1898
2121
|
.map(line => line.trim())
|
|
@@ -1934,7 +2157,7 @@ async function tailLog(cfg, source, lines = 200, filters = {}) {
|
|
|
1934
2157
|
const grep = String(filters.grep || '').trim().slice(0, 120).replace(/[^\p{L}\p{N} ._@:/=#-]/gu, '')
|
|
1935
2158
|
const level = ['error', 'warn'].includes(filters.level) ? filters.level : ''
|
|
1936
2159
|
const filters_chain = []
|
|
1937
|
-
if (grep) filters_chain.push(`grep -i -- ${
|
|
2160
|
+
if (grep) filters_chain.push(`grep -i -- ${q(grep)}`)
|
|
1938
2161
|
if (level === 'error') filters_chain.push(`grep -iE 'ERROR|CRITICAL|FATAL|Exception|Traceback'`)
|
|
1939
2162
|
if (level === 'warn') filters_chain.push(`grep -iE 'WARN|WARNING'`)
|
|
1940
2163
|
const pipeline = filters_chain.length ? ` | ${filters_chain.join(' | ')}` : ''
|
|
@@ -1958,7 +2181,7 @@ async function tailLog(cfg, source, lines = 200, filters = {}) {
|
|
|
1958
2181
|
if (raw.startsWith('file:')) {
|
|
1959
2182
|
const path = raw.slice(5)
|
|
1960
2183
|
if (!/^\/[A-Za-z0-9._\/-]+$/.test(path)) throw new Error('bad log path')
|
|
1961
|
-
command = `tail -n ${n} ${
|
|
2184
|
+
command = `tail -n ${n} ${q(path)} 2>&1${pipeline} | tail -n ${n}`
|
|
1962
2185
|
} else {
|
|
1963
2186
|
const unit = raw.replace(/[^A-Za-z0-9@._:-]/g, '')
|
|
1964
2187
|
const sinceArg = since > 0 ? ` --since "-${since} min"` : ''
|
|
@@ -2008,7 +2231,7 @@ async function tailProcessLog(cfg, source, lines = 200) {
|
|
|
2008
2231
|
if (raw.startsWith('jar:')) {
|
|
2009
2232
|
const jar = raw.slice(4).trim()
|
|
2010
2233
|
if (!/^[A-Za-z0-9._@/-]+$/.test(jar)) throw new Error('bad jar name')
|
|
2011
|
-
const found = await ssh(cfg, `for p in $(pgrep -f -- ${
|
|
2234
|
+
const found = await ssh(cfg, `for p in $(pgrep -f -- ${q(jar)} 2>/dev/null); do c=$(tr '\\0' ' ' < /proc/$p/cmdline 2>/dev/null); case "$c" in *java*) echo "$p"; break;; esac; done`, 20_000)
|
|
2012
2235
|
pid = Number(String(found.stdout || '').trim())
|
|
2013
2236
|
if (!pid) {
|
|
2014
2237
|
return {
|
|
@@ -2053,10 +2276,10 @@ async function tailProcessLog(cfg, source, lines = 200) {
|
|
|
2053
2276
|
}
|
|
2054
2277
|
}
|
|
2055
2278
|
|
|
2056
|
-
const quoted = files.map(f =>
|
|
2279
|
+
const quoted = files.map(f => q(f)).join(' ')
|
|
2057
2280
|
const newest = await ssh(cfg, `ls -1t ${quoted} 2>/dev/null | head -1`, 20_000)
|
|
2058
2281
|
const picked = String(newest.stdout || '').split('\n')[0].trim() || files[0]
|
|
2059
|
-
const res = await ssh(cfg, `tail -n ${n} ${
|
|
2282
|
+
const res = await ssh(cfg, `tail -n ${n} ${q(picked)} 2>&1`, 25_000)
|
|
2060
2283
|
return {
|
|
2061
2284
|
host: cfg.name, source: raw, resolved: picked, via: 'file',
|
|
2062
2285
|
ok: res.ok, lines: String(res.stdout || '').slice(0, 60_000),
|
|
@@ -2099,7 +2322,7 @@ function fsSafePath(path) {
|
|
|
2099
2322
|
/** Directory listing with size and mtime. */
|
|
2100
2323
|
async function listDir(cfg, path) {
|
|
2101
2324
|
const dir = String(path || '/').trim() || '/'
|
|
2102
|
-
const result = await ssh(cfg, `ls -la --time-style=+%Y-%m-%dT%H:%M ${
|
|
2325
|
+
const result = await ssh(cfg, `ls -la --time-style=+%Y-%m-%dT%H:%M ${q(dir)} 2>/dev/null`, 20_000)
|
|
2103
2326
|
if (!result.ok) {
|
|
2104
2327
|
return { host: cfg.name, path: dir, ok: false, entries: [], error: cleanStderr(result.stderr) || 'cannot list directory' }
|
|
2105
2328
|
}
|
|
@@ -2127,10 +2350,10 @@ async function listDir(cfg, path) {
|
|
|
2127
2350
|
/** Read a file as base64 (bounded). */
|
|
2128
2351
|
async function downloadFile(cfg, path, limitMb = 8) {
|
|
2129
2352
|
const target = fsSafePath(path)
|
|
2130
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2353
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2131
2354
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2132
2355
|
if (size > limitMb * 1024 * 1024) throw new Error(`file is ${Math.round(size / 1048576)} MB; the panel downloads at most ${limitMb} MB`)
|
|
2133
|
-
const result = await ssh(cfg, `base64 -w0 ${
|
|
2356
|
+
const result = await ssh(cfg, `base64 -w0 ${q(target)} 2>/dev/null || base64 ${q(target)}`, 60_000)
|
|
2134
2357
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
2135
2358
|
return { host: cfg.name, path: target, size, base64: String(result.stdout).replace(/\s+/g, '') }
|
|
2136
2359
|
}
|
|
@@ -2142,10 +2365,10 @@ async function uploadFile(cfg, path, base64, limitMb = 8) {
|
|
|
2142
2365
|
if (size > limitMb * 1024 * 1024) throw new Error(`payload is ${Math.round(size / 1048576)} MB; the panel uploads at most ${limitMb} MB`)
|
|
2143
2366
|
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2144
2367
|
const command = [
|
|
2145
|
-
`if [ -f ${
|
|
2146
|
-
`mkdir -p $(dirname ${
|
|
2147
|
-
`printf %s ${
|
|
2148
|
-
`echo "SIZE $(stat -c%s ${
|
|
2368
|
+
`if [ -f ${q(target)} ]; then cp -a ${q(target)} ${q(target + '.bak.' + stamp)}; fi`,
|
|
2369
|
+
`mkdir -p $(dirname ${q(target)})`,
|
|
2370
|
+
`printf %s ${q(String(base64))} | base64 -d > ${q(target)}`,
|
|
2371
|
+
`echo "SIZE $(stat -c%s ${q(target)})"`,
|
|
2149
2372
|
].join(' && ')
|
|
2150
2373
|
const result = await ssh(cfg, command, 90_000)
|
|
2151
2374
|
const sizeLine = String(result.stdout || '').match(/SIZE (\d+)/)
|
|
@@ -2157,10 +2380,10 @@ async function uploadFile(cfg, path, base64, limitMb = 8) {
|
|
|
2157
2380
|
/** Read a text file for the editor (bounded, binary-safe). */
|
|
2158
2381
|
async function readTextFile(cfg, path) {
|
|
2159
2382
|
const target = fsSafePath(path)
|
|
2160
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2383
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2161
2384
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2162
2385
|
if (size > 512 * 1024) throw new Error(`文件有 ${Math.round(size / 1024)} KB,超过 512 KB,面板不展开编辑`)
|
|
2163
|
-
const result = await ssh(cfg, `base64 -w0 ${
|
|
2386
|
+
const result = await ssh(cfg, `base64 -w0 ${q(target)} 2>/dev/null || base64 ${q(target)} 2>/dev/null`, 25_000)
|
|
2164
2387
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || '无法读取文件')
|
|
2165
2388
|
const buffer = Buffer.from(String(result.stdout).replace(/\s+/g, ''), 'base64')
|
|
2166
2389
|
if (buffer.includes(0)) return { host: cfg.name, path: target, size, binary: true, content: '' }
|
|
@@ -2174,10 +2397,10 @@ async function writeTextFile(cfg, path, content) {
|
|
|
2174
2397
|
const backup = `${target}.bak.${stamp}`
|
|
2175
2398
|
const encoded = Buffer.from(String(content ?? ''), 'utf8').toString('base64')
|
|
2176
2399
|
const command = [
|
|
2177
|
-
`cp -a ${
|
|
2178
|
-
`printf %s ${
|
|
2400
|
+
`cp -a ${q(target)} ${q(backup)} 2>/dev/null || true`,
|
|
2401
|
+
`printf %s ${q(encoded)} | base64 -d > ${q(target)}`,
|
|
2179
2402
|
`echo BACKUP ${backup}`,
|
|
2180
|
-
`wc -c < ${
|
|
2403
|
+
`wc -c < ${q(target)}`,
|
|
2181
2404
|
].join('\n')
|
|
2182
2405
|
const result = await ssh(cfg, command, 60_000)
|
|
2183
2406
|
return {
|
|
@@ -2194,7 +2417,7 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2194
2417
|
const primary = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths[0] : path) || ''
|
|
2195
2418
|
const target = primary ? fsSafePath(primary) : ''
|
|
2196
2419
|
if (action === 'mkdir') {
|
|
2197
|
-
const result = await ssh(cfg, `mkdir -p ${
|
|
2420
|
+
const result = await ssh(cfg, `mkdir -p ${q(target)} && echo OK`, 20_000)
|
|
2198
2421
|
return { host: cfg.name, action, path: target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2199
2422
|
}
|
|
2200
2423
|
if (action === 'chmod') {
|
|
@@ -2203,7 +2426,7 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2203
2426
|
throw new Error('权限格式应为 644 这样的数字,或 u+x 这样的符号')
|
|
2204
2427
|
}
|
|
2205
2428
|
const targets = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths : [path]).map(item => fsSafePath(item))
|
|
2206
|
-
const result = await ssh(cfg, targets.map(item => `chmod ${mode} ${
|
|
2429
|
+
const result = await ssh(cfg, targets.map(item => `chmod ${mode} ${q(item)}`).join(' && ') + ' && echo OK', 30_000)
|
|
2207
2430
|
return { host: cfg.name, action, paths: targets, mode, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2208
2431
|
}
|
|
2209
2432
|
if (action === 'compress') {
|
|
@@ -2212,10 +2435,10 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2212
2435
|
const format = extra.format === 'zip' ? 'zip' : 'tar.gz'
|
|
2213
2436
|
const archive = fsSafePath(extra.archive || `${paths[0]}.tar.gz`)
|
|
2214
2437
|
const base = archive.replace(/\/[^/]+$/, '') || '/'
|
|
2215
|
-
const names = paths.map(item =>
|
|
2438
|
+
const names = paths.map(item => q(item.slice(item.lastIndexOf('/') + 1))).join(' ')
|
|
2216
2439
|
const command = format === 'zip'
|
|
2217
|
-
? `cd ${
|
|
2218
|
-
: `tar -czf ${
|
|
2440
|
+
? `cd ${q(base)} && zip -qr ${q(archive.slice(archive.lastIndexOf('/') + 1))} ${names} && echo OK`
|
|
2441
|
+
: `tar -czf ${q(archive)} -C ${q(paths[0].replace(/\/[^/]+$/, '') || '/')} ${names} && echo OK`
|
|
2219
2442
|
const result = await ssh(cfg, command, 300_000)
|
|
2220
2443
|
return { host: cfg.name, action, archive, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2221
2444
|
}
|
|
@@ -2224,20 +2447,20 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2224
2447
|
const target = fsSafePath(extra.target || archive.replace(/\/[^/]+$/, '') || '/')
|
|
2225
2448
|
const isZip = /\.zip$/i.test(archive)
|
|
2226
2449
|
const command = isZip
|
|
2227
|
-
? `mkdir -p ${
|
|
2228
|
-
: `mkdir -p ${
|
|
2450
|
+
? `mkdir -p ${q(target)} && unzip -o ${q(archive)} -d ${q(target)} 2>&1 | tail -3`
|
|
2451
|
+
: `mkdir -p ${q(target)} && tar -xzf ${q(archive)} -C ${q(target)} 2>&1 | tail -3 && echo OK`
|
|
2229
2452
|
const result = await ssh(cfg, command, 300_000)
|
|
2230
2453
|
return { host: cfg.name, action, archive, target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2231
2454
|
}
|
|
2232
2455
|
if (action === 'rename') {
|
|
2233
2456
|
const to = fsSafePath(path)
|
|
2234
|
-
const result = await ssh(cfg, `mv ${
|
|
2457
|
+
const result = await ssh(cfg, `mv ${q(target)} ${q(to)} && echo OK`, 20_000)
|
|
2235
2458
|
return { host: cfg.name, action, path: to, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2236
2459
|
}
|
|
2237
2460
|
if (action === 'delete') {
|
|
2238
2461
|
if (confirm !== true) throw new Error('deleting needs confirm=true')
|
|
2239
2462
|
const targets = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths : [path]).map(item => fsSafePath(item))
|
|
2240
|
-
const result = await ssh(cfg, targets.map(item => `rm -rf ${
|
|
2463
|
+
const result = await ssh(cfg, targets.map(item => `rm -rf ${q(item)}`).join(' && ') + ' && echo OK', 120_000)
|
|
2241
2464
|
return { host: cfg.name, action, paths: targets, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2242
2465
|
}
|
|
2243
2466
|
throw new Error(`unknown action ${action}`)
|
|
@@ -2290,8 +2513,7 @@ async function testConnection(cfg) {
|
|
|
2290
2513
|
}
|
|
2291
2514
|
|
|
2292
2515
|
async function authKind(cfg) {
|
|
2293
|
-
|
|
2294
|
-
return secrets[cfg.name]?.password ? 'password' : 'key'
|
|
2516
|
+
return (await hasPassword(cfg.name)) ? 'password' : 'key'
|
|
2295
2517
|
}
|
|
2296
2518
|
|
|
2297
2519
|
/** Append this machine's public key to the host's authorized_keys. */
|
|
@@ -2306,7 +2528,7 @@ async function installKey(cfg) {
|
|
|
2306
2528
|
if (!pub.startsWith('ssh-')) throw new Error('public key file does not look like an SSH key')
|
|
2307
2529
|
const command = [
|
|
2308
2530
|
'mkdir -p ~/.ssh && chmod 700 ~/.ssh',
|
|
2309
|
-
`grep -qxF ${
|
|
2531
|
+
`grep -qxF ${q(pub)} ~/.ssh/authorized_keys 2>/dev/null || echo ${q(pub)} >> ~/.ssh/authorized_keys`,
|
|
2310
2532
|
'chmod 600 ~/.ssh/authorized_keys',
|
|
2311
2533
|
'grep -c . ~/.ssh/authorized_keys',
|
|
2312
2534
|
].join(' && ')
|
|
@@ -2327,8 +2549,7 @@ function termSsh2() {
|
|
|
2327
2549
|
}
|
|
2328
2550
|
|
|
2329
2551
|
async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
2330
|
-
const
|
|
2331
|
-
const secret = secrets[cfg.name]
|
|
2552
|
+
const password = await readPassword(cfg.name)
|
|
2332
2553
|
const id = `t${++termSeq}-${Date.now()}`
|
|
2333
2554
|
const session = { id, host: cfg.name, buffer: '', seq: 0, closed: false, conn: null, stream: null, child: null, args: [] }
|
|
2334
2555
|
const size = { cols: Math.max(40, Number(cols) || 120), rows: Math.max(10, Number(rows) || 30) }
|
|
@@ -2351,7 +2572,7 @@ async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
|
2351
2572
|
if (cfg.key) args.push('-i', cfg.key)
|
|
2352
2573
|
args.push(`${cfg.user ? cfg.user + '@' : ''}${cfg.host}`)
|
|
2353
2574
|
|
|
2354
|
-
if (!
|
|
2575
|
+
if (!password) {
|
|
2355
2576
|
// Key / agent authentication: a real PTY comes from ssh -tt through pipes.
|
|
2356
2577
|
const child = spawn('ssh', args, { env: { ...process.env, TERM: 'xterm-256color' } })
|
|
2357
2578
|
session.child = child
|
|
@@ -2392,7 +2613,7 @@ async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
|
2392
2613
|
host: cfg.host,
|
|
2393
2614
|
port: Number(cfg.port || 22),
|
|
2394
2615
|
username: cfg.user || process.env.USER,
|
|
2395
|
-
password
|
|
2616
|
+
password,
|
|
2396
2617
|
readyTimeout: 15_000,
|
|
2397
2618
|
keepaliveInterval: 15_000,
|
|
2398
2619
|
})
|
|
@@ -2445,13 +2666,11 @@ function terminalClose(id) {
|
|
|
2445
2666
|
|
|
2446
2667
|
/** Run a remote command with a binary stdin payload (large data never goes in argv). */
|
|
2447
2668
|
async function sshStdin(cfg, command, buffer, timeoutMs = 180_000) {
|
|
2448
|
-
const
|
|
2449
|
-
|
|
2450
|
-
if (secret?.password) {
|
|
2669
|
+
const password = await readPassword(cfg.name)
|
|
2670
|
+
if (password) {
|
|
2451
2671
|
const ssh2 = loadSsh2()
|
|
2452
2672
|
if (!ssh2) throw new Error('ssh2 is not available in this profile')
|
|
2453
2673
|
const conn = new ssh2.Client()
|
|
2454
|
-
const password = Buffer.from(secret.password, 'base64').toString('utf8')
|
|
2455
2674
|
return await new Promise((resolve, reject) => {
|
|
2456
2675
|
const timer = setTimeout(() => { try { conn.end() } catch {} ; reject(new Error('command timeout')) }, timeoutMs)
|
|
2457
2676
|
conn.on('ready', () => {
|
|
@@ -2511,7 +2730,7 @@ const CHUNK_MAX = 8 * 1024 * 1024
|
|
|
2511
2730
|
/** Bytes already written to <path>.part, for resumable uploads. */
|
|
2512
2731
|
async function uploadStatus(cfg, path) {
|
|
2513
2732
|
const target = fsSafePath(path)
|
|
2514
|
-
const result = await ssh(cfg, `stat -c%s ${
|
|
2733
|
+
const result = await ssh(cfg, `stat -c%s ${q(target + '.part')} 2>/dev/null || echo 0`, 10_000)
|
|
2515
2734
|
return { host: cfg.name, path: target, bytes: Number(String(result.stdout || '0').trim()) || 0 }
|
|
2516
2735
|
}
|
|
2517
2736
|
|
|
@@ -2524,10 +2743,10 @@ async function uploadChunk(cfg, path, offset, base64) {
|
|
|
2524
2743
|
if (buffer.length === 0) return { host: cfg.name, ok: true, bytes: expected }
|
|
2525
2744
|
if (buffer.length > CHUNK_MAX) throw new Error('chunk too large')
|
|
2526
2745
|
const command = [
|
|
2527
|
-
`size=$(stat -c%s ${
|
|
2746
|
+
`size=$(stat -c%s ${q(part)} 2>/dev/null || echo 0)`,
|
|
2528
2747
|
`if [ "$size" -ne ${expected} ]; then echo "OFFSET_MISMATCH $size"; exit 3; fi`,
|
|
2529
|
-
`cat >> ${
|
|
2530
|
-
`stat -c%s ${
|
|
2748
|
+
`cat >> ${q(part)}`,
|
|
2749
|
+
`stat -c%s ${q(part)}`,
|
|
2531
2750
|
].join('\n')
|
|
2532
2751
|
const result = await sshStdin(cfg, command, buffer, 180_000)
|
|
2533
2752
|
if (result.code === 3) {
|
|
@@ -2547,10 +2766,10 @@ async function uploadFinish(cfg, path) {
|
|
|
2547
2766
|
const part = `${target}.part`
|
|
2548
2767
|
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2549
2768
|
const command = [
|
|
2550
|
-
`test -f ${
|
|
2551
|
-
`cp -a ${
|
|
2552
|
-
`mv -f ${
|
|
2553
|
-
`stat -c%s ${
|
|
2769
|
+
`test -f ${q(part)} || { echo MISSING_PART; exit 4; }`,
|
|
2770
|
+
`cp -a ${q(target)} ${q(`${target}.bak.${stamp}`)} 2>/dev/null || true`,
|
|
2771
|
+
`mv -f ${q(part)} ${q(target)} && echo OK`,
|
|
2772
|
+
`stat -c%s ${q(target)}`,
|
|
2554
2773
|
].join('\n')
|
|
2555
2774
|
const result = await ssh(cfg, command, 60_000)
|
|
2556
2775
|
return {
|
|
@@ -2566,9 +2785,9 @@ async function downloadChunk(cfg, path, offset, length) {
|
|
|
2566
2785
|
const target = fsSafePath(path)
|
|
2567
2786
|
const start = Math.max(0, Number(offset) || 0)
|
|
2568
2787
|
const count = Math.min(CHUNK_MAX, Math.max(1, Number(length) || CHUNK_MAX))
|
|
2569
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2788
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2570
2789
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2571
|
-
const result = await ssh(cfg, `dd if=${
|
|
2790
|
+
const result = await ssh(cfg, `dd if=${q(target)} bs=1 skip=${start} count=${count} 2>/dev/null | base64 -w0`, 180_000)
|
|
2572
2791
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
2573
2792
|
return { host: cfg.name, path: target, size, offset: start, base64: String(result.stdout || '').replace(/\s+/g, '') }
|
|
2574
2793
|
}
|
|
@@ -2754,7 +2973,7 @@ async function logUsage(cfg) {
|
|
|
2754
2973
|
.map(match => ({ bytes: Number(match[1]), at: new Date(Number(match[2]) * 1000).toISOString(), path: match[3], source: '系统日志' }))
|
|
2755
2974
|
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2756
2975
|
try {
|
|
2757
|
-
const found = await ssh(cfg, `find ${
|
|
2976
|
+
const found = await ssh(cfg, `find ${q(dir.path)} -maxdepth 2 -type f \\( -name "*.log*" -o -name "*.out" \\) -size +200k -printf "%s %T@ %p\\n" 2>/dev/null | head -8`, 20_000)
|
|
2758
2977
|
for (const line of String(found.stdout || '').split('\n')) {
|
|
2759
2978
|
const match = line.match(/^(\d{4,}) ([\d.]+) (.+)$/)
|
|
2760
2979
|
if (!match) continue
|
|
@@ -2812,7 +3031,7 @@ async function cleanupPreview(cfg) {
|
|
|
2812
3031
|
]
|
|
2813
3032
|
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2814
3033
|
try {
|
|
2815
|
-
const found = await ssh(cfg, `find ${
|
|
3034
|
+
const found = await ssh(cfg, `find ${q(dir.path)} -maxdepth 2 -type f \\( -name "*.log" -o -name "*.out" -o -name "*.gz" -o -name "*.old" -o -name "*.log.*" \\) -mtime +${keepDays} -printf "%s %T@ %u %p\\n" 2>/dev/null | sort -rn | head -40`, 25_000)
|
|
2816
3035
|
for (const line of String(found.stdout || '').split('\n')) {
|
|
2817
3036
|
const match = line.match(/^(\d+) ([\d.]+) (\S+) (.+)$/)
|
|
2818
3037
|
if (!match) continue
|
|
@@ -2968,8 +3187,8 @@ async function backupLogs(cfg, paths) {
|
|
|
2968
3187
|
const dest = `/var/backups/dsh-ops-kit/logs-${stamp}.tar.gz`
|
|
2969
3188
|
const command = [
|
|
2970
3189
|
`mkdir -p /var/backups/dsh-ops-kit`,
|
|
2971
|
-
`tar -czf ${
|
|
2972
|
-
`stat -c%s ${
|
|
3190
|
+
`tar -czf ${q(dest)} ${list.map(item => q(item)).join(' ')} 2>/dev/null && echo OK`,
|
|
3191
|
+
`stat -c%s ${q(dest)}`,
|
|
2973
3192
|
].join('\\n')
|
|
2974
3193
|
const result = await ssh(cfg, command, 300_000)
|
|
2975
3194
|
const size = Number(String(result.stdout || '').trim().split('\\n').pop()) || 0
|
|
@@ -3191,20 +3410,20 @@ async function runMonitor(cfg, monitor) {
|
|
|
3191
3410
|
const target = String(monitor.target || '').trim()
|
|
3192
3411
|
let command
|
|
3193
3412
|
if (type === 'http') {
|
|
3194
|
-
command = `curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 8 ${
|
|
3413
|
+
command = `curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 8 ${q(target)} 2>/dev/null || echo "000 0"`
|
|
3195
3414
|
} else if (type === 'port') {
|
|
3196
3415
|
const [host, port] = target.split(':')
|
|
3197
3416
|
if (!host || !port) throw new Error('port monitor needs host:port')
|
|
3198
3417
|
command = `timeout 4 bash -c '</dev/tcp/${host.replace(/[^A-Za-z0-9.-]/g, '')}/${Number(port)}' 2>/dev/null && echo OPEN || echo CLOSED`
|
|
3199
3418
|
} else if (type === 'process') {
|
|
3200
|
-
command = `pgrep -f ${
|
|
3419
|
+
command = `pgrep -f ${q(target)} >/dev/null 2>&1 && echo RUNNING || echo STOPPED`
|
|
3201
3420
|
} else if (type === 'service') {
|
|
3202
3421
|
command = `systemctl is-active ${target.replace(/[^A-Za-z0-9@._-]/g, '')} 2>/dev/null || true`
|
|
3203
3422
|
} else if (type === 'script') {
|
|
3204
3423
|
const language = ['shell', 'python', 'js'].includes(monitor.language) ? monitor.language : 'shell'
|
|
3205
3424
|
const interpreter = language === 'python' ? 'python3' : language === 'js' ? 'node' : 'bash'
|
|
3206
3425
|
const encoded = Buffer.from(String(monitor.script || ''), 'utf8').toString('base64')
|
|
3207
|
-
command = `f=$(mktemp); printf %s ${
|
|
3426
|
+
command = `f=$(mktemp); printf %s ${q(encoded)} | base64 -d > "$f"; ${interpreter} "$f"; rc=$?; rm -f "$f"; exit $rc`
|
|
3208
3427
|
} else {
|
|
3209
3428
|
throw new Error(`unknown monitor type ${type}`)
|
|
3210
3429
|
}
|
|
@@ -3389,7 +3608,12 @@ async function runMonitorPass(force = false) {
|
|
|
3389
3608
|
|
|
3390
3609
|
/* ---------- backups, health, certificates, cron, file history, deploy ---------- */
|
|
3391
3610
|
|
|
3392
|
-
|
|
3611
|
+
/**
|
|
3612
|
+
* Shell quote for the remote sh: wrap in single quotes and escape embedded
|
|
3613
|
+
* ones. JSON.stringify() is NOT safe here — a double-quoted string still lets
|
|
3614
|
+
* the remote shell expand $(...) and backticks.
|
|
3615
|
+
*/
|
|
3616
|
+
const q = (value) => "'" + String(value ?? '').replace(/'/g, "'\\''") + "'"
|
|
3393
3617
|
|
|
3394
3618
|
async function loadJsonFile(name, fallback) {
|
|
3395
3619
|
try {
|
|
@@ -3414,6 +3638,9 @@ async function runBackup(cfg, job) {
|
|
|
3414
3638
|
const started = Date.now()
|
|
3415
3639
|
let file
|
|
3416
3640
|
let command
|
|
3641
|
+
let stdinScript = null
|
|
3642
|
+
let parent = ''
|
|
3643
|
+
let target
|
|
3417
3644
|
|
|
3418
3645
|
if (job.type === 'mysql') {
|
|
3419
3646
|
const database = String(job.database || '').trim()
|
|
@@ -3421,33 +3648,43 @@ async function runBackup(cfg, job) {
|
|
|
3421
3648
|
const password = String(job.password || '')
|
|
3422
3649
|
const scope = database ? `--databases ${q(database)}` : '--all-databases'
|
|
3423
3650
|
file = `${dir}/mysql-${database || 'all'}-${stamp}.sql.gz`
|
|
3424
|
-
|
|
3651
|
+
target = database || 'all'
|
|
3652
|
+
// The password stays out of argv on both ends: the script goes over stdin.
|
|
3653
|
+
stdinScript = [
|
|
3425
3654
|
`mkdir -p ${q(dir)}`,
|
|
3426
|
-
`MYSQL_PWD=${q(password)} mysqldump -u${q(user)} ${scope} --single-transaction --quick --routines 2>/tmp/.ops-bk.err
|
|
3427
|
-
|
|
3428
|
-
|
|
3655
|
+
`MYSQL_PWD=${q(password)} mysqldump -u${q(user)} ${scope} --single-transaction --quick --routines > /tmp/.ops-bk.sql 2>/tmp/.ops-bk.err`,
|
|
3656
|
+
'rc=$?',
|
|
3657
|
+
'if [ "$rc" -ne 0 ]; then cat /tmp/.ops-bk.err; exit $rc; fi',
|
|
3658
|
+
`gzip -c /tmp/.ops-bk.sql > ${q(file)} && rm -f /tmp/.ops-bk.sql`,
|
|
3429
3659
|
`stat -c %s ${q(file)} 2>/dev/null || wc -c < ${q(file)}`,
|
|
3430
3660
|
].join('\n')
|
|
3431
3661
|
} else {
|
|
3432
3662
|
const raw = String(job.path || '').replace(/\/+$/, '')
|
|
3433
3663
|
if (!raw || raw === '/') {
|
|
3434
3664
|
file = `${dir}/rootfs-${stamp}.tar.gz`
|
|
3665
|
+
target = '/'
|
|
3666
|
+
parent = '/'
|
|
3435
3667
|
command = `mkdir -p ${q(dir)} && tar --exclude=proc --exclude=sys --exclude=dev --exclude=run --exclude=tmp -czf ${q(file)} / 2>/dev/null; stat -c %s ${q(file)}`
|
|
3436
3668
|
} else {
|
|
3437
3669
|
const base = raw.split('/').pop()
|
|
3438
|
-
|
|
3670
|
+
parent = raw.split('/').slice(0, -1).join('/') || '/'
|
|
3671
|
+
target = raw
|
|
3439
3672
|
file = `${dir}/dir-${base}-${stamp}.tar.gz`
|
|
3440
3673
|
command = `mkdir -p ${q(dir)} && tar --exclude='*.log' --exclude='logs' --exclude='*.tmp' -czf ${q(file)} -C ${q(parent)} ${q(base)} 2>/dev/null; stat -c %s ${q(file)}`
|
|
3441
3674
|
}
|
|
3442
3675
|
}
|
|
3443
3676
|
|
|
3444
|
-
const result =
|
|
3677
|
+
const result = stdinScript
|
|
3678
|
+
? await sshStdin(cfg, 'sh -s', Buffer.from(stdinScript, 'utf8'), 20 * 60_000)
|
|
3679
|
+
: await ssh(cfg, command, 20 * 60_000)
|
|
3445
3680
|
const size = Number(String(result.stdout || '').trim().split('\n').pop()) || 0
|
|
3446
3681
|
const record = {
|
|
3447
3682
|
id: `b${Date.now().toString(36)}`,
|
|
3448
3683
|
host: cfg.name,
|
|
3449
3684
|
type: job.type === 'mysql' ? 'mysql' : 'dir',
|
|
3450
|
-
target
|
|
3685
|
+
target,
|
|
3686
|
+
parent,
|
|
3687
|
+
user: job.type === 'mysql' ? String(job.user || 'root').trim() : '',
|
|
3451
3688
|
file,
|
|
3452
3689
|
size,
|
|
3453
3690
|
keep,
|
|
@@ -3474,24 +3711,49 @@ async function runBackup(cfg, job) {
|
|
|
3474
3711
|
return record
|
|
3475
3712
|
}
|
|
3476
3713
|
|
|
3477
|
-
async function restoreBackup(cfg, id) {
|
|
3714
|
+
async function restoreBackup(cfg, id, options = {}) {
|
|
3478
3715
|
const all = await loadJsonFile('backups.json', {})
|
|
3479
3716
|
const record = (all[cfg.name] || []).find(item => item.id === id)
|
|
3480
3717
|
if (!record) throw new Error('备份记录不存在')
|
|
3481
3718
|
if (!record.ok) throw new Error('这条备份本身失败了,不能恢复')
|
|
3482
|
-
|
|
3719
|
+
const backupDir = String(record.file || '').replace(/\/[^/]+$/, '')
|
|
3720
|
+
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
3721
|
+
let script
|
|
3722
|
+
let preRestore = ''
|
|
3723
|
+
|
|
3483
3724
|
if (record.type === 'mysql') {
|
|
3484
|
-
const
|
|
3485
|
-
|
|
3725
|
+
const user = String(options.user || record.user || 'root').trim()
|
|
3726
|
+
const password = String(options.password || '')
|
|
3727
|
+
preRestore = `${backupDir}/pre-restore-${record.target || 'all'}-${stamp}.sql.gz`
|
|
3728
|
+
script = [
|
|
3729
|
+
// 恢复前先给当前库拍一份快照,恢复失败还能退回去
|
|
3730
|
+
`command -v mysqldump >/dev/null 2>&1 && MYSQL_PWD=${q(password)} mysqldump -u${q(user)} ${record.target && record.target !== 'all' ? '--databases ' + q(record.target) : '--all-databases'} --single-transaction --quick --routines 2>/dev/null | gzip > ${q(preRestore)} || true`,
|
|
3731
|
+
`gunzip -c ${q(record.file)} | MYSQL_PWD=${q(password)} mysql -u${q(user)} 2>&1 | tail -5`,
|
|
3732
|
+
].join('\n')
|
|
3486
3733
|
} else {
|
|
3487
|
-
const parent = record.
|
|
3488
|
-
|
|
3734
|
+
const parent = String(record.parent || (record.target && record.target !== '/' ? String(record.target).replace(/\/[^/]+$/, '') : '/') || '/')
|
|
3735
|
+
const base = String(record.target || '/').split('/').filter(Boolean).pop() || ''
|
|
3736
|
+
if (base && parent !== '/') {
|
|
3737
|
+
preRestore = `${backupDir}/pre-restore-${stamp}.tar.gz`
|
|
3738
|
+
script = [
|
|
3739
|
+
`tar -czf ${q(preRestore)} -C ${q(parent)} ${q(base)} 2>/dev/null || true`,
|
|
3740
|
+
`tar -tzf ${q(record.file)} >/dev/null 2>&1 || { echo '备份文件损坏'; exit 1; }`,
|
|
3741
|
+
`tar -xzf ${q(record.file)} -C ${q(parent)} 2>&1 | tail -3`,
|
|
3742
|
+
].join('\n')
|
|
3743
|
+
} else {
|
|
3744
|
+
script = [
|
|
3745
|
+
`tar -tzf ${q(record.file)} >/dev/null 2>&1 || { echo '备份文件损坏'; exit 1; }`,
|
|
3746
|
+
`tar -xzf ${q(record.file)} -C ${q(parent)} 2>&1 | tail -3`,
|
|
3747
|
+
].join('\n')
|
|
3748
|
+
}
|
|
3489
3749
|
}
|
|
3490
|
-
|
|
3750
|
+
|
|
3751
|
+
const result = await sshStdin(cfg, 'sh -s', Buffer.from(script, 'utf8'), 20 * 60_000)
|
|
3491
3752
|
record.restoredAt = new Date().toISOString()
|
|
3492
3753
|
record.restoreOk = result.ok
|
|
3754
|
+
if (result.ok && preRestore) record.preRestore = preRestore
|
|
3493
3755
|
await saveJsonFile('backups.json', all)
|
|
3494
|
-
return { id, ok: result.ok, output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 800) }
|
|
3756
|
+
return { id, ok: result.ok, preRestore: result.ok ? preRestore : '', output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 800) }
|
|
3495
3757
|
}
|
|
3496
3758
|
|
|
3497
3759
|
/* ---- health score ---- */
|
|
@@ -3629,12 +3891,22 @@ async function writeCron(cfg, lines) {
|
|
|
3629
3891
|
return { ok: result.ok, count: Number(String(result.stdout || '').trim()) || 0, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
3630
3892
|
}
|
|
3631
3893
|
|
|
3894
|
+
const CRON_FIELD = /^[0-9*/,\-]+$/
|
|
3895
|
+
|
|
3632
3896
|
async function addCron(cfg, job) {
|
|
3633
3897
|
const current = await ssh(cfg, 'crontab -l 2>/dev/null || true', 20_000)
|
|
3634
3898
|
const lines = String(current.stdout || '').split('\n').filter(line => line.trim())
|
|
3635
|
-
const
|
|
3636
|
-
|
|
3637
|
-
|
|
3899
|
+
const command = String(job.command || '').trim()
|
|
3900
|
+
if (!command) throw new Error('command is required')
|
|
3901
|
+
// A newline would append extra crontab lines; % is cron's own newline marker.
|
|
3902
|
+
if (/[\r\n]/.test(command)) throw new Error('命令里不能有换行')
|
|
3903
|
+
const field = (value, fallback) => {
|
|
3904
|
+
const text = String(value ?? fallback).trim()
|
|
3905
|
+
if (text !== '*' && !CRON_FIELD.test(text)) throw new Error('计划时间格式不合法:只允许数字、* / , -')
|
|
3906
|
+
return text
|
|
3907
|
+
}
|
|
3908
|
+
const schedule = [field(job.minute, '0'), field(job.hour, '3'), field(job.day, '*'), field(job.month, '*'), field(job.weekday, '*')].join(' ')
|
|
3909
|
+
const line = `${schedule} ${command}`
|
|
3638
3910
|
return writeCron(cfg, [...lines, line])
|
|
3639
3911
|
}
|
|
3640
3912
|
|
|
@@ -4743,8 +5015,9 @@ export function apply(ctx) {
|
|
|
4743
5015
|
async execute(args = {}) {
|
|
4744
5016
|
const command = String(args.command ?? '').trim()
|
|
4745
5017
|
if (!command) throw new Error('command is required')
|
|
4746
|
-
|
|
4747
|
-
|
|
5018
|
+
const risk = classifyCommand(command)
|
|
5019
|
+
if (risk.dangerous && args.confirm !== true) {
|
|
5020
|
+
throw new Error(`这条命令可能造成不可逆的破坏:${risk.reasons.join(';')}。确认要执行就带 confirm=true 重来一次。`)
|
|
4748
5021
|
}
|
|
4749
5022
|
return batchRun(command, Array.isArray(args.hosts) ? args.hosts : undefined)
|
|
4750
5023
|
},
|
|
@@ -4764,8 +5037,9 @@ export function apply(ctx) {
|
|
|
4764
5037
|
async execute(args = {}) {
|
|
4765
5038
|
const command = String(args.command ?? '').trim()
|
|
4766
5039
|
if (!command) throw new Error('command is required')
|
|
4767
|
-
|
|
4768
|
-
|
|
5040
|
+
const risk = classifyCommand(command)
|
|
5041
|
+
if (risk.dangerous && args.confirm !== true) {
|
|
5042
|
+
throw new Error(`这条命令可能造成不可逆的破坏:${risk.reasons.join(';')}。确认要执行就带 confirm=true 重来一次。`)
|
|
4769
5043
|
}
|
|
4770
5044
|
const cfg = pickHost(await loadHosts(), args.host)
|
|
4771
5045
|
const result = await ssh(cfg, command, Number(args.timeoutMs ?? 20_000))
|
|
@@ -4875,3 +5149,17 @@ export function apply(ctx) {
|
|
|
4875
5149
|
}
|
|
4876
5150
|
})
|
|
4877
5151
|
}
|
|
5152
|
+
|
|
5153
|
+
/** Internals for the test suite; not part of the plugin API. */
|
|
5154
|
+
export const __test = {
|
|
5155
|
+
q,
|
|
5156
|
+
clip,
|
|
5157
|
+
pickHost,
|
|
5158
|
+
safeUnit,
|
|
5159
|
+
classifyCommand,
|
|
5160
|
+
looksDangerous,
|
|
5161
|
+
fileAllowed,
|
|
5162
|
+
fsSafePath,
|
|
5163
|
+
logSafePath,
|
|
5164
|
+
jobSnapshot,
|
|
5165
|
+
}
|