dsh-ops-kit 0.4.1 → 0.4.3
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 +2660 -2403
- package/index.js +429 -125
- package/package.json +4 -1
package/index.js
CHANGED
|
@@ -27,10 +27,20 @@ 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
|
|
33
35
|
|
|
36
|
+
|
|
37
|
+
/** Best-effort loads: surface the reason instead of swallowing it silently. */
|
|
38
|
+
function softFail(where, error) {
|
|
39
|
+
const message = error && error.message ? error.message : String(error || '')
|
|
40
|
+
if (!message || /ENOENT|no such file/i.test(message)) return
|
|
41
|
+
console.warn('[dsh-ops-kit]', where + ':', message)
|
|
42
|
+
}
|
|
43
|
+
|
|
34
44
|
function kitDir() {
|
|
35
45
|
return join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'ops-kit')
|
|
36
46
|
}
|
|
@@ -47,20 +57,91 @@ function secretsFile() {
|
|
|
47
57
|
return join(kitDir(), 'secrets.json')
|
|
48
58
|
}
|
|
49
59
|
|
|
50
|
-
/**
|
|
60
|
+
/**
|
|
61
|
+
* SSH passwords live in the system keychain (macOS `security`, Linux
|
|
62
|
+
* `secret-tool`). Only when neither exists do we fall back to a 0600 file —
|
|
63
|
+
* and that file is base64, i.e. obfuscation, not encryption. The panel says so.
|
|
64
|
+
*/
|
|
65
|
+
const KEYCHAIN_SERVICE = 'dsh-ops-kit'
|
|
66
|
+
|
|
67
|
+
async function keychainGet(name) {
|
|
68
|
+
if (process.platform === 'darwin') {
|
|
69
|
+
const { stdout } = await run('security', ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', String(name), '-w'], { timeout: 10_000 })
|
|
70
|
+
return String(stdout).replace(/\n$/, '')
|
|
71
|
+
}
|
|
72
|
+
if (process.platform === 'linux') {
|
|
73
|
+
const { stdout } = await run('secret-tool', ['lookup', 'service', KEYCHAIN_SERVICE, 'account', String(name)], { timeout: 10_000 })
|
|
74
|
+
return String(stdout).replace(/\n$/, '')
|
|
75
|
+
}
|
|
76
|
+
throw new Error('no system keychain on this platform')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function keychainSet(name, password) {
|
|
80
|
+
if (process.platform === 'darwin') {
|
|
81
|
+
await run('security', ['add-generic-password', '-U', '-s', KEYCHAIN_SERVICE, '-a', String(name), '-w', String(password)], { timeout: 10_000 })
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
if (process.platform === 'linux') {
|
|
85
|
+
await new Promise((resolve, reject) => {
|
|
86
|
+
const child = spawn('secret-tool', ['store', '--label', 'dsh-ops-kit ' + name, 'service', KEYCHAIN_SERVICE, 'account', String(name)])
|
|
87
|
+
child.on('error', reject)
|
|
88
|
+
child.on('close', (code) => { if (code === 0) resolve(); else reject(new Error('secret-tool exit ' + code)) })
|
|
89
|
+
child.stdin.end(String(password))
|
|
90
|
+
})
|
|
91
|
+
return
|
|
92
|
+
}
|
|
93
|
+
throw new Error('no system keychain on this platform')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function keychainDelete(name) {
|
|
97
|
+
if (process.platform === 'darwin') {
|
|
98
|
+
await run('security', ['delete-generic-password', '-s', KEYCHAIN_SERVICE, '-a', String(name)], { timeout: 10_000 })
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
if (process.platform === 'linux') {
|
|
102
|
+
await run('secret-tool', ['clear', 'service', KEYCHAIN_SERVICE, 'account', String(name)], { timeout: 10_000 })
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Legacy 0600 file; only consulted when the keychain has nothing. */
|
|
51
108
|
async function loadSecrets() {
|
|
52
109
|
try {
|
|
53
110
|
const data = JSON.parse(await readFile(secretsFile(), 'utf8'))
|
|
54
111
|
return data && typeof data === 'object' ? data : {}
|
|
55
|
-
} catch {
|
|
112
|
+
} catch (error) {
|
|
113
|
+
softFail('loadSecrets', error)
|
|
56
114
|
return {}
|
|
57
115
|
}
|
|
58
116
|
}
|
|
59
117
|
|
|
118
|
+
/** Password for one host: keychain first, 0600 file as the fallback. */
|
|
119
|
+
async function readPassword(name) {
|
|
120
|
+
try {
|
|
121
|
+
const value = await keychainGet(name)
|
|
122
|
+
if (value) return value
|
|
123
|
+
} catch { /* no keychain entry or no keychain tool */ }
|
|
124
|
+
const all = await loadSecrets()
|
|
125
|
+
const secret = all[name]
|
|
126
|
+
return secret && secret.password ? Buffer.from(secret.password, 'base64').toString('utf8') : ''
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function hasPassword(name) {
|
|
130
|
+
return Boolean(await readPassword(name))
|
|
131
|
+
}
|
|
132
|
+
|
|
60
133
|
async function saveSecret(name, password) {
|
|
61
134
|
const all = await loadSecrets()
|
|
62
|
-
|
|
63
|
-
|
|
135
|
+
const label = String(name)
|
|
136
|
+
if (password) {
|
|
137
|
+
let inKeychain = false
|
|
138
|
+
try { await keychainSet(label, String(password)); inKeychain = true } catch { inKeychain = false }
|
|
139
|
+
if (inKeychain) delete all[label]
|
|
140
|
+
else all[label] = { password: Buffer.from(String(password), 'utf8').toString('base64'), enc: 'base64', at: new Date().toISOString() }
|
|
141
|
+
} else {
|
|
142
|
+
delete all[label]
|
|
143
|
+
try { await keychainDelete(label) } catch { /* nothing stored */ }
|
|
144
|
+
}
|
|
64
145
|
await mkdir(kitDir(), { recursive: true })
|
|
65
146
|
await writeFile(secretsFile(), JSON.stringify(all, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 })
|
|
66
147
|
try { await chmod(secretsFile(), 0o600) } catch { /* best effort */ }
|
|
@@ -74,7 +155,8 @@ async function loadHistory() {
|
|
|
74
155
|
const raw = await readFile(historyFile(), 'utf8')
|
|
75
156
|
const data = JSON.parse(raw)
|
|
76
157
|
return Array.isArray(data.entries) ? data.entries : []
|
|
77
|
-
} catch {
|
|
158
|
+
} catch (error) {
|
|
159
|
+
softFail('loadHistory', error)
|
|
78
160
|
return []
|
|
79
161
|
}
|
|
80
162
|
}
|
|
@@ -91,7 +173,8 @@ async function loadHosts() {
|
|
|
91
173
|
const raw = await readFile(hostsFile(), 'utf8')
|
|
92
174
|
const data = JSON.parse(raw)
|
|
93
175
|
return { hosts: Array.isArray(data.hosts) ? data.hosts : [], defaultHost: data.defaultHost }
|
|
94
|
-
} catch {
|
|
176
|
+
} catch (error) {
|
|
177
|
+
softFail('loadHosts', error)
|
|
95
178
|
return { hosts: [], defaultHost: undefined }
|
|
96
179
|
}
|
|
97
180
|
}
|
|
@@ -167,8 +250,8 @@ function sshPassword(cfg, password, command, timeoutMs = 20_000) {
|
|
|
167
250
|
conn.on('ready', () => {
|
|
168
251
|
conn.exec(command, (error, stream) => {
|
|
169
252
|
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') })
|
|
253
|
+
stream.on('data', (chunk) => { if (stdout.length < PASSWORD_OUTPUT_LIMIT) stdout += chunk.toString('utf8') })
|
|
254
|
+
stream.stderr.on('data', (chunk) => { if (stderr.length < PASSWORD_OUTPUT_LIMIT) stderr += chunk.toString('utf8') })
|
|
172
255
|
stream.on('close', (code) => done({ ok: code === 0, code: code ?? 1, stdout, stderr }))
|
|
173
256
|
})
|
|
174
257
|
})
|
|
@@ -191,12 +274,8 @@ function sshPassword(cfg, password, command, timeoutMs = 20_000) {
|
|
|
191
274
|
}
|
|
192
275
|
|
|
193
276
|
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
|
-
}
|
|
277
|
+
const password = await readPassword(cfg.name)
|
|
278
|
+
if (password) return sshPassword(cfg, password, command, timeoutMs)
|
|
200
279
|
const args = [
|
|
201
280
|
'-o', 'BatchMode=yes',
|
|
202
281
|
'-o', 'ConnectTimeout=8',
|
|
@@ -225,7 +304,7 @@ async function ssh(cfg, command, timeoutMs = 20_000) {
|
|
|
225
304
|
|
|
226
305
|
function clip(text, limit = MAX_OUTPUT) {
|
|
227
306
|
const value = String(text ?? '')
|
|
228
|
-
return value.length > limit ? `${value.slice(0, limit)}\n… (${value.length - limit}
|
|
307
|
+
return value.length > limit ? `${value.slice(0, limit)}\n… (${value.length - limit} 字符已省略)` : value
|
|
229
308
|
}
|
|
230
309
|
|
|
231
310
|
function cleanStderr(text) {
|
|
@@ -281,6 +360,10 @@ function firstLines(text, count = 2) {
|
|
|
281
360
|
|
|
282
361
|
/** Check every configured host in parallel and record one history entry per host. */
|
|
283
362
|
async function statusAll() {
|
|
363
|
+
if (!(await acquireLock('.status-pass.lock', 3 * 60_000))) {
|
|
364
|
+
return { at: new Date().toISOString(), skipped: true, elapsedMs: 0, results: [] }
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
284
367
|
const data = await loadHosts()
|
|
285
368
|
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
369
|
const started = Date.now()
|
|
@@ -308,18 +391,58 @@ async function statusAll() {
|
|
|
308
391
|
summary: row.ok ? firstLines(row.output) : clip(row.error, 200),
|
|
309
392
|
})))
|
|
310
393
|
return { at, elapsedMs: Date.now() - started, results }
|
|
394
|
+
} finally {
|
|
395
|
+
await releaseLock('.status-pass.lock')
|
|
396
|
+
}
|
|
311
397
|
}
|
|
312
398
|
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
399
|
+
/**
|
|
400
|
+
* Commands that can destroy data or take the server down. Every one of these
|
|
401
|
+
* needs an explicit `confirm: true` — the panel shows the reasons first, the
|
|
402
|
+
* tools tell the model to re-run with confirm.
|
|
403
|
+
*/
|
|
404
|
+
const RISK_RULES = [
|
|
405
|
+
{ id: 'rm-recursive', rx: /(^|[\s;|&])rm\s+(-[a-zA-Z]*[rR][a-zA-Z]*|--recursive)\b/, why: '递归删除(rm -r / rm -rf),会连同目录内容一起删掉' },
|
|
406
|
+
{ id: 'rm-root', rx: /(^|[\s;|&])rm\s+[^;|&]*\s(\/+|\/\*|~|\$HOME)(\s|;|$)/, why: '删除根目录、通配符或家目录' },
|
|
407
|
+
{ id: 'dd-device', rx: /(^|[\s;|&])dd\b[^;|&]*\bof=\/dev\//, why: 'dd 直接写块设备,会覆盖磁盘数据' },
|
|
408
|
+
{ id: 'mkfs', rx: /(^|[\s;|&])(mkfs(\.[a-z0-9]+)?|wipefs|fdisk|parted|sfdisk)\b/, why: '格式化、分区或擦除磁盘' },
|
|
409
|
+
{ id: 'shutdown', rx: /(^|[\s;|&])(shutdown|reboot|halt|poweroff)\b/, why: '关机或重启服务器' },
|
|
410
|
+
{ id: 'systemctl-power', rx: /systemctl\s+(poweroff|reboot|halt|kexec)\b/, why: 'systemctl 关机或重启' },
|
|
411
|
+
{ id: 'init0', rx: /(^|[\s;|&])init\s+0(\s|$)/, why: 'init 0 会让服务器关机' },
|
|
412
|
+
{ id: 'fork-bomb', rx: /:\(\)\s*\{\s*:\|:&\s*\}\s*;\s*:/, why: 'fork 炸弹,会耗尽系统进程' },
|
|
413
|
+
{ id: 'crontab-flush', rx: /crontab\s+-r\b/, why: '清空当前用户的全部定时任务' },
|
|
414
|
+
{ id: 'chmod-zero', rx: /chmod\s+(-R\s+)?(0{3,4}|a=)(\s|\/)/, why: '把文件权限改成 000,可能锁死服务' },
|
|
415
|
+
{ id: 'find-delete', rx: /find\s+\/[^;|&]*\s-delete\b/, why: '从根目录 find 并删除文件' },
|
|
416
|
+
{ id: 'overwrite-system', rx: /(^|[\s;|&])>\s*\/(etc|boot|dev|var\/lib)\//, why: '用重定向覆盖系统目录里的文件' },
|
|
417
|
+
{ id: 'truncate-zero', rx: /truncate\s+-s\s*0\b/, why: '把文件截断成 0 字节' },
|
|
418
|
+
{ id: 'drop-db', rx: /(drop\s+database|drop\s+table|truncate\s+table)/i, why: '删除数据库或表' },
|
|
419
|
+
{ id: 'docker-prune', rx: /docker\s+(system|volume|image|container)\s+prune/, why: '批量清理 Docker 数据(镜像、卷、容器)' },
|
|
420
|
+
{ id: 'kill-init', rx: /kill\s+-9\s+1(\s|$)/, why: '杀 init 进程,等于停机' },
|
|
421
|
+
{ id: 'git-clean', rx: /git\s+clean\s+-[a-z]*f/, why: 'git clean 会删掉未跟踪文件' },
|
|
319
422
|
]
|
|
320
423
|
|
|
424
|
+
/** @returns {{dangerous: boolean, reasons: string[]}} */
|
|
425
|
+
function classifyCommand(command) {
|
|
426
|
+
const text = String(command ?? '')
|
|
427
|
+
const reasons = []
|
|
428
|
+
for (const rule of RISK_RULES) {
|
|
429
|
+
if (rule.rx.test(text)) reasons.push(rule.why)
|
|
430
|
+
}
|
|
431
|
+
return { dangerous: reasons.length > 0, reasons: [...new Set(reasons)] }
|
|
432
|
+
}
|
|
433
|
+
|
|
321
434
|
function looksDangerous(command) {
|
|
322
|
-
return
|
|
435
|
+
return classifyCommand(command).dangerous
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Unit names are user input; keep them to what systemd actually accepts. */
|
|
439
|
+
const UNIT_NAME = /^[A-Za-z0-9@._:-]{1,120}$/
|
|
440
|
+
|
|
441
|
+
function safeUnit(name) {
|
|
442
|
+
const value = String(name ?? '').trim()
|
|
443
|
+
if (!value) throw new Error('service is required')
|
|
444
|
+
if (!UNIT_NAME.test(value)) throw new Error('service 名称不合法:只允许字母、数字和 @ . _ : -')
|
|
445
|
+
return value
|
|
323
446
|
}
|
|
324
447
|
|
|
325
448
|
function asTool(def) {
|
|
@@ -368,6 +491,63 @@ function readBody(req, limit = 64 * 1024) {
|
|
|
368
491
|
})
|
|
369
492
|
}
|
|
370
493
|
|
|
494
|
+
/* ---------- background jobs: backup / restore / cleanup / deploy ---------- */
|
|
495
|
+
|
|
496
|
+
const jobs = new Map()
|
|
497
|
+
const JOB_TTL = 60 * 60_000
|
|
498
|
+
let jobSeq = 0
|
|
499
|
+
|
|
500
|
+
function jobSnapshot(job) {
|
|
501
|
+
return {
|
|
502
|
+
id: job.id,
|
|
503
|
+
kind: job.kind,
|
|
504
|
+
label: job.label,
|
|
505
|
+
host: job.host,
|
|
506
|
+
status: job.status,
|
|
507
|
+
startedAt: job.startedAt,
|
|
508
|
+
finishedAt: job.finishedAt ?? null,
|
|
509
|
+
error: job.error,
|
|
510
|
+
output: clip(job.output || '', 2_000),
|
|
511
|
+
...(job.status === 'done' ? { result: job.result } : {}),
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Run fn in the background; the panel polls GET /ops-kit/api/job?id=… */
|
|
516
|
+
function startJob(meta, fn) {
|
|
517
|
+
const id = `j${++jobSeq}-${Date.now().toString(36)}`
|
|
518
|
+
const job = {
|
|
519
|
+
id,
|
|
520
|
+
kind: meta.kind || 'task',
|
|
521
|
+
label: meta.label || '',
|
|
522
|
+
host: meta.host || '',
|
|
523
|
+
status: 'running',
|
|
524
|
+
startedAt: new Date().toISOString(),
|
|
525
|
+
output: '',
|
|
526
|
+
error: '',
|
|
527
|
+
result: null,
|
|
528
|
+
}
|
|
529
|
+
jobs.set(id, job)
|
|
530
|
+
Promise.resolve()
|
|
531
|
+
.then(fn)
|
|
532
|
+
.then((result) => {
|
|
533
|
+
job.status = 'done'
|
|
534
|
+
job.result = result
|
|
535
|
+
job.output = typeof result === 'string' ? result : JSON.stringify(result ?? {}, null, 2)
|
|
536
|
+
})
|
|
537
|
+
.catch((error) => {
|
|
538
|
+
job.status = 'failed'
|
|
539
|
+
job.error = String(error?.message || error)
|
|
540
|
+
})
|
|
541
|
+
.finally(() => {
|
|
542
|
+
job.finishedAt = new Date().toISOString()
|
|
543
|
+
const cutoff = Date.now() - JOB_TTL
|
|
544
|
+
for (const [key, value] of jobs) {
|
|
545
|
+
if (Date.parse(value.startedAt) < cutoff) jobs.delete(key)
|
|
546
|
+
}
|
|
547
|
+
})
|
|
548
|
+
return job
|
|
549
|
+
}
|
|
550
|
+
|
|
371
551
|
/**
|
|
372
552
|
* The panel's JSON API: Node request/response handlers registered on the web
|
|
373
553
|
* server. Authentication reuses the same trust gate as DSH's own routes.
|
|
@@ -388,6 +568,29 @@ function createApiHandler({ connection } = {}) {
|
|
|
388
568
|
const url = new URL(String(req.url || '/'), 'http://127.0.0.1')
|
|
389
569
|
const route = url.pathname.replace(/^\/ops-kit\/api\/?/, '').replace(/\/$/, '')
|
|
390
570
|
|
|
571
|
+
// This API can run commands on your servers, so reject anything that did not
|
|
572
|
+
// come from the panel itself: foreign Origin, cross-site fetch, or a body
|
|
573
|
+
// that is not JSON (a text/plain POST is a classic CSRF bypass because it
|
|
574
|
+
// skips the browser preflight).
|
|
575
|
+
const selfHost = String(req.headers.host || '')
|
|
576
|
+
const origin = String(req.headers.origin || '')
|
|
577
|
+
if (origin) {
|
|
578
|
+
let sameOrigin = false
|
|
579
|
+
try { sameOrigin = new URL(origin).host === selfHost } catch { sameOrigin = false }
|
|
580
|
+
if (!sameOrigin) { sendJson(res, 403, { error: 'cross-origin request rejected' }); return }
|
|
581
|
+
}
|
|
582
|
+
if (String(req.headers['sec-fetch-site'] || '') === 'cross-site') {
|
|
583
|
+
sendJson(res, 403, { error: 'cross-site request rejected' })
|
|
584
|
+
return
|
|
585
|
+
}
|
|
586
|
+
if (method !== 'GET') {
|
|
587
|
+
const contentType = String(req.headers['content-type'] || '').toLowerCase()
|
|
588
|
+
if (!contentType.startsWith('application/json')) {
|
|
589
|
+
sendJson(res, 415, { error: 'content-type must be application/json' })
|
|
590
|
+
return
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
391
594
|
try {
|
|
392
595
|
if (route === 'hosts' && method === 'GET') {
|
|
393
596
|
const data = await loadHosts()
|
|
@@ -530,10 +733,14 @@ function createApiHandler({ connection } = {}) {
|
|
|
530
733
|
const body = (await readBody(req)) || {}
|
|
531
734
|
const command = String(body.command ?? '').trim()
|
|
532
735
|
if (!command) { sendJson(res, 400, { error: 'command is required' }); return }
|
|
533
|
-
|
|
534
|
-
|
|
736
|
+
const risk = classifyCommand(command)
|
|
737
|
+
if (risk.dangerous && body.confirm !== true) {
|
|
738
|
+
sendJson(res, 200, { needsConfirm: true, command, reasons: risk.reasons })
|
|
535
739
|
return
|
|
536
740
|
}
|
|
741
|
+
if (risk.dangerous) {
|
|
742
|
+
await appendAudit({ host: Array.isArray(body.hosts) ? body.hosts.join(',') : 'all', action: '执行命令', detail: command.slice(0, 200) })
|
|
743
|
+
}
|
|
537
744
|
sendJson(res, 200, await batchRun(command, Array.isArray(body.hosts) ? body.hosts : undefined))
|
|
538
745
|
return
|
|
539
746
|
}
|
|
@@ -622,7 +829,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
622
829
|
const detail = Array.isArray(body.paths) && body.paths.length
|
|
623
830
|
? `${body.paths.length} 个选中文件${body.includeJournal === false ? '' : ' + journal'}`
|
|
624
831
|
: 'journal 保留 200MB;删除 7 天前的轮转日志'
|
|
625
|
-
|
|
832
|
+
const job = startJob({ kind: 'cleanup', label: '清理旧日志', host: cfg.name }, () =>
|
|
833
|
+
audited(cfg, '清理旧日志', detail, () => cleanupDisk(cfg, body)))
|
|
834
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
626
835
|
return
|
|
627
836
|
}
|
|
628
837
|
|
|
@@ -895,7 +1104,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
895
1104
|
const body = (await readBody(req)) || {}
|
|
896
1105
|
const cfg = pickHost(await loadHosts(), body.host)
|
|
897
1106
|
if (body.action === 'restore') {
|
|
898
|
-
|
|
1107
|
+
const job = startJob({ kind: 'restore', label: `恢复 ${body.id}`, host: cfg.name }, () =>
|
|
1108
|
+
audited(cfg, '恢复备份', String(body.id ?? ''), () => restoreBackup(cfg, body.id, { user: body.user, password: body.password })))
|
|
1109
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
899
1110
|
return
|
|
900
1111
|
}
|
|
901
1112
|
if (body.action === 'remove') {
|
|
@@ -909,7 +1120,16 @@ function createApiHandler({ connection } = {}) {
|
|
|
909
1120
|
sendJson(res, 200, { host: cfg.name, backups: all[cfg.name] })
|
|
910
1121
|
return
|
|
911
1122
|
}
|
|
912
|
-
|
|
1123
|
+
const job = startJob({ kind: 'backup', label: `备份${body.type === 'mysql' ? '数据库 ' + (body.database || '全部') : '目录 ' + (body.path || '/')}`, host: cfg.name }, () =>
|
|
1124
|
+
audited(cfg, '执行备份', `${body.type === 'mysql' ? (body.database || '全部数据库') : body.path || '/'}`, () => runBackup(cfg, body)))
|
|
1125
|
+
sendJson(res, 200, { job: jobSnapshot(job) })
|
|
1126
|
+
return
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
if (route === 'job' && method === 'GET') {
|
|
1130
|
+
const job = jobs.get(String(url.searchParams.get('id') || ''))
|
|
1131
|
+
if (!job) { sendJson(res, 404, { error: 'job not found' }); return }
|
|
1132
|
+
sendJson(res, 200, jobSnapshot(job))
|
|
913
1133
|
return
|
|
914
1134
|
}
|
|
915
1135
|
|
|
@@ -987,7 +1207,9 @@ function createApiHandler({ connection } = {}) {
|
|
|
987
1207
|
}
|
|
988
1208
|
const job = list.find(item => item.id === body.id) || body.job
|
|
989
1209
|
if (!job) { sendJson(res, 404, { error: '发布任务不存在' }); return }
|
|
990
|
-
|
|
1210
|
+
const started = startJob({ kind: 'deploy', label: `发布 ${job.name || job.dir}`, host: cfg.name }, () =>
|
|
1211
|
+
audited(cfg, '执行发布', job.name || job.dir, () => runDeploy(cfg, job)))
|
|
1212
|
+
sendJson(res, 200, { job: jobSnapshot(started) })
|
|
991
1213
|
return
|
|
992
1214
|
}
|
|
993
1215
|
|
|
@@ -1256,7 +1478,8 @@ async function loadConfig() {
|
|
|
1256
1478
|
try {
|
|
1257
1479
|
const data = JSON.parse(await readFile(configFile(), 'utf8'))
|
|
1258
1480
|
return { ...DEFAULT_CONFIG, ...data }
|
|
1259
|
-
} catch {
|
|
1481
|
+
} catch (error) {
|
|
1482
|
+
softFail('loadConfig', error)
|
|
1260
1483
|
return { ...DEFAULT_CONFIG }
|
|
1261
1484
|
}
|
|
1262
1485
|
}
|
|
@@ -1272,7 +1495,8 @@ async function loadState() {
|
|
|
1272
1495
|
try {
|
|
1273
1496
|
const data = JSON.parse(await readFile(stateFile(), 'utf8'))
|
|
1274
1497
|
return { hosts: data.hosts ?? {}, lastRunAt: data.lastRunAt ?? 0 }
|
|
1275
|
-
} catch {
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
softFail('loadState', error)
|
|
1276
1500
|
return { hosts: {}, lastRunAt: 0 }
|
|
1277
1501
|
}
|
|
1278
1502
|
}
|
|
@@ -1290,7 +1514,8 @@ async function loadAlerts() {
|
|
|
1290
1514
|
try {
|
|
1291
1515
|
const data = JSON.parse(await readFile(alertsFile(), 'utf8'))
|
|
1292
1516
|
return Array.isArray(data.entries) ? data.entries : []
|
|
1293
|
-
} catch {
|
|
1517
|
+
} catch (error) {
|
|
1518
|
+
softFail('loadAlerts', error)
|
|
1294
1519
|
return []
|
|
1295
1520
|
}
|
|
1296
1521
|
}
|
|
@@ -1439,9 +1664,10 @@ async function hostAction(kind, cfg, target, action) {
|
|
|
1439
1664
|
const prefix = cfg.sudo ? 'sudo -n ' : ''
|
|
1440
1665
|
let command
|
|
1441
1666
|
if (kind === 'service') {
|
|
1667
|
+
const unit = safeUnit(target)
|
|
1442
1668
|
command = action === 'logs'
|
|
1443
|
-
? `${prefix}journalctl -u ${
|
|
1444
|
-
: `${prefix}systemctl ${action} ${
|
|
1669
|
+
? `${prefix}journalctl -u ${unit} -n 60 --no-pager`
|
|
1670
|
+
: `${prefix}systemctl ${action} ${unit}`
|
|
1445
1671
|
} else {
|
|
1446
1672
|
const safe = String(target).replace(/[^A-Za-z0-9_.-]/g, '')
|
|
1447
1673
|
command = action === 'logs'
|
|
@@ -1458,10 +1684,21 @@ const METRICS_LIMIT = 20000
|
|
|
1458
1684
|
function metricsFile() { return join(kitDir(), 'metrics.jsonl') }
|
|
1459
1685
|
function inventoryFile() { return join(kitDir(), 'inventory.json') }
|
|
1460
1686
|
|
|
1687
|
+
const METRICS_MAX_BYTES = 8 * 1024 * 1024
|
|
1688
|
+
const METRICS_KEEP_LINES = 15_000
|
|
1689
|
+
|
|
1461
1690
|
async function appendMetrics(samples) {
|
|
1462
1691
|
await mkdir(kitDir(), { recursive: true })
|
|
1463
1692
|
const lines = samples.map(sample => JSON.stringify(sample)).join('\n') + '\n'
|
|
1464
1693
|
await writeFile(metricsFile(), lines, { flag: 'a' })
|
|
1694
|
+
try {
|
|
1695
|
+
const info = await stat(metricsFile())
|
|
1696
|
+
if (info.size > METRICS_MAX_BYTES) {
|
|
1697
|
+
const raw = await readFile(metricsFile(), 'utf8')
|
|
1698
|
+
const kept = raw.split('\n').filter(Boolean).slice(-METRICS_KEEP_LINES)
|
|
1699
|
+
await writeFile(metricsFile(), kept.join('\n') + '\n', 'utf8')
|
|
1700
|
+
}
|
|
1701
|
+
} catch { /* 裁剪失败不影响采样 */ }
|
|
1465
1702
|
}
|
|
1466
1703
|
|
|
1467
1704
|
async function loadMetrics(host, sinceMs = 0) {
|
|
@@ -1477,7 +1714,8 @@ async function loadMetrics(host, sinceMs = 0) {
|
|
|
1477
1714
|
rows.push(row)
|
|
1478
1715
|
}
|
|
1479
1716
|
return rows.slice(-METRICS_LIMIT)
|
|
1480
|
-
} catch {
|
|
1717
|
+
} catch (error) {
|
|
1718
|
+
softFail('loadMetrics', error)
|
|
1481
1719
|
return []
|
|
1482
1720
|
}
|
|
1483
1721
|
}
|
|
@@ -1672,7 +1910,7 @@ async function cleanupDisk(cfg, options = {}) {
|
|
|
1672
1910
|
options.includeJournal === false ? 'true' : `journalctl --vacuum-size=${journalMb}M >/dev/null 2>&1 || true`,
|
|
1673
1911
|
// Only rotated files older than a week; never truncate a live or recent log.
|
|
1674
1912
|
Array.isArray(options.paths) && options.paths.length
|
|
1675
|
-
? options.paths.filter(item => logSafePath(item)).map(item => `rm -f ${
|
|
1913
|
+
? options.paths.filter(item => logSafePath(item)).map(item => `rm -f ${q(item)}`).join('; ') || true
|
|
1676
1914
|
: `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
1915
|
'after=$(df -P / | awk \'NR==2{gsub("%","",$5);print $5}\')',
|
|
1678
1916
|
'used_after=$(df -P / | awk \'NR==2{print $3}\')',
|
|
@@ -1711,10 +1949,10 @@ function fileAllowed(path) {
|
|
|
1711
1949
|
|
|
1712
1950
|
async function readRemoteFile(cfg, path) {
|
|
1713
1951
|
if (!fileAllowed(path)) throw new Error('path is outside the editable configuration area')
|
|
1714
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
1952
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(path)} 2>/dev/null || echo 0`, 10_000)
|
|
1715
1953
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
1716
1954
|
if (size > 512 * 1024) throw new Error(`文件太大(${Math.round(size / 1024)} KB),面板只编辑 512 KB 以内的配置`)
|
|
1717
|
-
const result = await ssh(cfg, `test -f ${
|
|
1955
|
+
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
1956
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
1719
1957
|
const content = Buffer.from(result.stdout.replace(/\s+/g, ''), 'base64').toString('utf8')
|
|
1720
1958
|
return { host: cfg.name, path, content: content.slice(0, 200_000), truncated: content.length > 200_000 }
|
|
@@ -1726,10 +1964,10 @@ async function writeRemoteFile(cfg, path, content) {
|
|
|
1726
1964
|
const backup = `${path}.bak.${stamp}`
|
|
1727
1965
|
const encoded = Buffer.from(String(content), 'utf8').toString('base64')
|
|
1728
1966
|
const command = [
|
|
1729
|
-
`cp -a ${
|
|
1730
|
-
`printf %s ${
|
|
1967
|
+
`cp -a ${q(path)} ${q(backup)}`,
|
|
1968
|
+
`printf %s ${q(encoded)} | base64 -d > ${q(path)}`,
|
|
1731
1969
|
`echo "BACKUP ${backup}"`,
|
|
1732
|
-
'wc -c < ' +
|
|
1970
|
+
'wc -c < ' + q(path),
|
|
1733
1971
|
].join(' && ')
|
|
1734
1972
|
const result = await ssh(cfg, command, 30_000)
|
|
1735
1973
|
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 +2130,7 @@ async function diagnose(cfg, question = '') {
|
|
|
1892
2130
|
/** Directory sizes one level below `path`, largest last. */
|
|
1893
2131
|
async function diskUsage(cfg, path = '/') {
|
|
1894
2132
|
const safe = String(path || '/').replace(/[;&|`$><\n]/g, '')
|
|
1895
|
-
const result = await ssh(cfg, `du -xh --max-depth=1 ${
|
|
2133
|
+
const result = await ssh(cfg, `du -xh --max-depth=1 ${q(safe)} 2>/dev/null | sort -h | tail -25`, 45_000)
|
|
1896
2134
|
const rows = String(result.stdout || '')
|
|
1897
2135
|
.split('\n')
|
|
1898
2136
|
.map(line => line.trim())
|
|
@@ -1934,7 +2172,7 @@ async function tailLog(cfg, source, lines = 200, filters = {}) {
|
|
|
1934
2172
|
const grep = String(filters.grep || '').trim().slice(0, 120).replace(/[^\p{L}\p{N} ._@:/=#-]/gu, '')
|
|
1935
2173
|
const level = ['error', 'warn'].includes(filters.level) ? filters.level : ''
|
|
1936
2174
|
const filters_chain = []
|
|
1937
|
-
if (grep) filters_chain.push(`grep -i -- ${
|
|
2175
|
+
if (grep) filters_chain.push(`grep -i -- ${q(grep)}`)
|
|
1938
2176
|
if (level === 'error') filters_chain.push(`grep -iE 'ERROR|CRITICAL|FATAL|Exception|Traceback'`)
|
|
1939
2177
|
if (level === 'warn') filters_chain.push(`grep -iE 'WARN|WARNING'`)
|
|
1940
2178
|
const pipeline = filters_chain.length ? ` | ${filters_chain.join(' | ')}` : ''
|
|
@@ -1958,7 +2196,7 @@ async function tailLog(cfg, source, lines = 200, filters = {}) {
|
|
|
1958
2196
|
if (raw.startsWith('file:')) {
|
|
1959
2197
|
const path = raw.slice(5)
|
|
1960
2198
|
if (!/^\/[A-Za-z0-9._\/-]+$/.test(path)) throw new Error('bad log path')
|
|
1961
|
-
command = `tail -n ${n} ${
|
|
2199
|
+
command = `tail -n ${n} ${q(path)} 2>&1${pipeline} | tail -n ${n}`
|
|
1962
2200
|
} else {
|
|
1963
2201
|
const unit = raw.replace(/[^A-Za-z0-9@._:-]/g, '')
|
|
1964
2202
|
const sinceArg = since > 0 ? ` --since "-${since} min"` : ''
|
|
@@ -2008,7 +2246,7 @@ async function tailProcessLog(cfg, source, lines = 200) {
|
|
|
2008
2246
|
if (raw.startsWith('jar:')) {
|
|
2009
2247
|
const jar = raw.slice(4).trim()
|
|
2010
2248
|
if (!/^[A-Za-z0-9._@/-]+$/.test(jar)) throw new Error('bad jar name')
|
|
2011
|
-
const found = await ssh(cfg, `for p in $(pgrep -f -- ${
|
|
2249
|
+
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
2250
|
pid = Number(String(found.stdout || '').trim())
|
|
2013
2251
|
if (!pid) {
|
|
2014
2252
|
return {
|
|
@@ -2053,10 +2291,10 @@ async function tailProcessLog(cfg, source, lines = 200) {
|
|
|
2053
2291
|
}
|
|
2054
2292
|
}
|
|
2055
2293
|
|
|
2056
|
-
const quoted = files.map(f =>
|
|
2294
|
+
const quoted = files.map(f => q(f)).join(' ')
|
|
2057
2295
|
const newest = await ssh(cfg, `ls -1t ${quoted} 2>/dev/null | head -1`, 20_000)
|
|
2058
2296
|
const picked = String(newest.stdout || '').split('\n')[0].trim() || files[0]
|
|
2059
|
-
const res = await ssh(cfg, `tail -n ${n} ${
|
|
2297
|
+
const res = await ssh(cfg, `tail -n ${n} ${q(picked)} 2>&1`, 25_000)
|
|
2060
2298
|
return {
|
|
2061
2299
|
host: cfg.name, source: raw, resolved: picked, via: 'file',
|
|
2062
2300
|
ok: res.ok, lines: String(res.stdout || '').slice(0, 60_000),
|
|
@@ -2099,7 +2337,7 @@ function fsSafePath(path) {
|
|
|
2099
2337
|
/** Directory listing with size and mtime. */
|
|
2100
2338
|
async function listDir(cfg, path) {
|
|
2101
2339
|
const dir = String(path || '/').trim() || '/'
|
|
2102
|
-
const result = await ssh(cfg, `ls -la --time-style=+%Y-%m-%dT%H:%M ${
|
|
2340
|
+
const result = await ssh(cfg, `ls -la --time-style=+%Y-%m-%dT%H:%M ${q(dir)} 2>/dev/null`, 20_000)
|
|
2103
2341
|
if (!result.ok) {
|
|
2104
2342
|
return { host: cfg.name, path: dir, ok: false, entries: [], error: cleanStderr(result.stderr) || 'cannot list directory' }
|
|
2105
2343
|
}
|
|
@@ -2127,10 +2365,10 @@ async function listDir(cfg, path) {
|
|
|
2127
2365
|
/** Read a file as base64 (bounded). */
|
|
2128
2366
|
async function downloadFile(cfg, path, limitMb = 8) {
|
|
2129
2367
|
const target = fsSafePath(path)
|
|
2130
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2368
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2131
2369
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2132
2370
|
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 ${
|
|
2371
|
+
const result = await ssh(cfg, `base64 -w0 ${q(target)} 2>/dev/null || base64 ${q(target)}`, 60_000)
|
|
2134
2372
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
2135
2373
|
return { host: cfg.name, path: target, size, base64: String(result.stdout).replace(/\s+/g, '') }
|
|
2136
2374
|
}
|
|
@@ -2142,10 +2380,10 @@ async function uploadFile(cfg, path, base64, limitMb = 8) {
|
|
|
2142
2380
|
if (size > limitMb * 1024 * 1024) throw new Error(`payload is ${Math.round(size / 1048576)} MB; the panel uploads at most ${limitMb} MB`)
|
|
2143
2381
|
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2144
2382
|
const command = [
|
|
2145
|
-
`if [ -f ${
|
|
2146
|
-
`mkdir -p $(dirname ${
|
|
2147
|
-
`printf %s ${
|
|
2148
|
-
`echo "SIZE $(stat -c%s ${
|
|
2383
|
+
`if [ -f ${q(target)} ]; then cp -a ${q(target)} ${q(target + '.bak.' + stamp)}; fi`,
|
|
2384
|
+
`mkdir -p $(dirname ${q(target)})`,
|
|
2385
|
+
`printf %s ${q(String(base64))} | base64 -d > ${q(target)}`,
|
|
2386
|
+
`echo "SIZE $(stat -c%s ${q(target)})"`,
|
|
2149
2387
|
].join(' && ')
|
|
2150
2388
|
const result = await ssh(cfg, command, 90_000)
|
|
2151
2389
|
const sizeLine = String(result.stdout || '').match(/SIZE (\d+)/)
|
|
@@ -2157,10 +2395,10 @@ async function uploadFile(cfg, path, base64, limitMb = 8) {
|
|
|
2157
2395
|
/** Read a text file for the editor (bounded, binary-safe). */
|
|
2158
2396
|
async function readTextFile(cfg, path) {
|
|
2159
2397
|
const target = fsSafePath(path)
|
|
2160
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2398
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2161
2399
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2162
2400
|
if (size > 512 * 1024) throw new Error(`文件有 ${Math.round(size / 1024)} KB,超过 512 KB,面板不展开编辑`)
|
|
2163
|
-
const result = await ssh(cfg, `base64 -w0 ${
|
|
2401
|
+
const result = await ssh(cfg, `base64 -w0 ${q(target)} 2>/dev/null || base64 ${q(target)} 2>/dev/null`, 25_000)
|
|
2164
2402
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || '无法读取文件')
|
|
2165
2403
|
const buffer = Buffer.from(String(result.stdout).replace(/\s+/g, ''), 'base64')
|
|
2166
2404
|
if (buffer.includes(0)) return { host: cfg.name, path: target, size, binary: true, content: '' }
|
|
@@ -2174,10 +2412,10 @@ async function writeTextFile(cfg, path, content) {
|
|
|
2174
2412
|
const backup = `${target}.bak.${stamp}`
|
|
2175
2413
|
const encoded = Buffer.from(String(content ?? ''), 'utf8').toString('base64')
|
|
2176
2414
|
const command = [
|
|
2177
|
-
`cp -a ${
|
|
2178
|
-
`printf %s ${
|
|
2415
|
+
`cp -a ${q(target)} ${q(backup)} 2>/dev/null || true`,
|
|
2416
|
+
`printf %s ${q(encoded)} | base64 -d > ${q(target)}`,
|
|
2179
2417
|
`echo BACKUP ${backup}`,
|
|
2180
|
-
`wc -c < ${
|
|
2418
|
+
`wc -c < ${q(target)}`,
|
|
2181
2419
|
].join('\n')
|
|
2182
2420
|
const result = await ssh(cfg, command, 60_000)
|
|
2183
2421
|
return {
|
|
@@ -2194,7 +2432,7 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2194
2432
|
const primary = (Array.isArray(extra.paths) && extra.paths.length ? extra.paths[0] : path) || ''
|
|
2195
2433
|
const target = primary ? fsSafePath(primary) : ''
|
|
2196
2434
|
if (action === 'mkdir') {
|
|
2197
|
-
const result = await ssh(cfg, `mkdir -p ${
|
|
2435
|
+
const result = await ssh(cfg, `mkdir -p ${q(target)} && echo OK`, 20_000)
|
|
2198
2436
|
return { host: cfg.name, action, path: target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2199
2437
|
}
|
|
2200
2438
|
if (action === 'chmod') {
|
|
@@ -2203,7 +2441,7 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2203
2441
|
throw new Error('权限格式应为 644 这样的数字,或 u+x 这样的符号')
|
|
2204
2442
|
}
|
|
2205
2443
|
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} ${
|
|
2444
|
+
const result = await ssh(cfg, targets.map(item => `chmod ${mode} ${q(item)}`).join(' && ') + ' && echo OK', 30_000)
|
|
2207
2445
|
return { host: cfg.name, action, paths: targets, mode, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2208
2446
|
}
|
|
2209
2447
|
if (action === 'compress') {
|
|
@@ -2212,10 +2450,10 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2212
2450
|
const format = extra.format === 'zip' ? 'zip' : 'tar.gz'
|
|
2213
2451
|
const archive = fsSafePath(extra.archive || `${paths[0]}.tar.gz`)
|
|
2214
2452
|
const base = archive.replace(/\/[^/]+$/, '') || '/'
|
|
2215
|
-
const names = paths.map(item =>
|
|
2453
|
+
const names = paths.map(item => q(item.slice(item.lastIndexOf('/') + 1))).join(' ')
|
|
2216
2454
|
const command = format === 'zip'
|
|
2217
|
-
? `cd ${
|
|
2218
|
-
: `tar -czf ${
|
|
2455
|
+
? `cd ${q(base)} && zip -qr ${q(archive.slice(archive.lastIndexOf('/') + 1))} ${names} && echo OK`
|
|
2456
|
+
: `tar -czf ${q(archive)} -C ${q(paths[0].replace(/\/[^/]+$/, '') || '/')} ${names} && echo OK`
|
|
2219
2457
|
const result = await ssh(cfg, command, 300_000)
|
|
2220
2458
|
return { host: cfg.name, action, archive, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2221
2459
|
}
|
|
@@ -2224,20 +2462,20 @@ async function fsAction(cfg, action, path, confirm, extra = {}) {
|
|
|
2224
2462
|
const target = fsSafePath(extra.target || archive.replace(/\/[^/]+$/, '') || '/')
|
|
2225
2463
|
const isZip = /\.zip$/i.test(archive)
|
|
2226
2464
|
const command = isZip
|
|
2227
|
-
? `mkdir -p ${
|
|
2228
|
-
: `mkdir -p ${
|
|
2465
|
+
? `mkdir -p ${q(target)} && unzip -o ${q(archive)} -d ${q(target)} 2>&1 | tail -3`
|
|
2466
|
+
: `mkdir -p ${q(target)} && tar -xzf ${q(archive)} -C ${q(target)} 2>&1 | tail -3 && echo OK`
|
|
2229
2467
|
const result = await ssh(cfg, command, 300_000)
|
|
2230
2468
|
return { host: cfg.name, action, archive, target, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2231
2469
|
}
|
|
2232
2470
|
if (action === 'rename') {
|
|
2233
2471
|
const to = fsSafePath(path)
|
|
2234
|
-
const result = await ssh(cfg, `mv ${
|
|
2472
|
+
const result = await ssh(cfg, `mv ${q(target)} ${q(to)} && echo OK`, 20_000)
|
|
2235
2473
|
return { host: cfg.name, action, path: to, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2236
2474
|
}
|
|
2237
2475
|
if (action === 'delete') {
|
|
2238
2476
|
if (confirm !== true) throw new Error('deleting needs confirm=true')
|
|
2239
2477
|
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 ${
|
|
2478
|
+
const result = await ssh(cfg, targets.map(item => `rm -rf ${q(item)}`).join(' && ') + ' && echo OK', 120_000)
|
|
2241
2479
|
return { host: cfg.name, action, paths: targets, ok: result.ok, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
2242
2480
|
}
|
|
2243
2481
|
throw new Error(`unknown action ${action}`)
|
|
@@ -2290,8 +2528,7 @@ async function testConnection(cfg) {
|
|
|
2290
2528
|
}
|
|
2291
2529
|
|
|
2292
2530
|
async function authKind(cfg) {
|
|
2293
|
-
|
|
2294
|
-
return secrets[cfg.name]?.password ? 'password' : 'key'
|
|
2531
|
+
return (await hasPassword(cfg.name)) ? 'password' : 'key'
|
|
2295
2532
|
}
|
|
2296
2533
|
|
|
2297
2534
|
/** Append this machine's public key to the host's authorized_keys. */
|
|
@@ -2306,7 +2543,7 @@ async function installKey(cfg) {
|
|
|
2306
2543
|
if (!pub.startsWith('ssh-')) throw new Error('public key file does not look like an SSH key')
|
|
2307
2544
|
const command = [
|
|
2308
2545
|
'mkdir -p ~/.ssh && chmod 700 ~/.ssh',
|
|
2309
|
-
`grep -qxF ${
|
|
2546
|
+
`grep -qxF ${q(pub)} ~/.ssh/authorized_keys 2>/dev/null || echo ${q(pub)} >> ~/.ssh/authorized_keys`,
|
|
2310
2547
|
'chmod 600 ~/.ssh/authorized_keys',
|
|
2311
2548
|
'grep -c . ~/.ssh/authorized_keys',
|
|
2312
2549
|
].join(' && ')
|
|
@@ -2327,8 +2564,7 @@ function termSsh2() {
|
|
|
2327
2564
|
}
|
|
2328
2565
|
|
|
2329
2566
|
async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
2330
|
-
const
|
|
2331
|
-
const secret = secrets[cfg.name]
|
|
2567
|
+
const password = await readPassword(cfg.name)
|
|
2332
2568
|
const id = `t${++termSeq}-${Date.now()}`
|
|
2333
2569
|
const session = { id, host: cfg.name, buffer: '', seq: 0, closed: false, conn: null, stream: null, child: null, args: [] }
|
|
2334
2570
|
const size = { cols: Math.max(40, Number(cols) || 120), rows: Math.max(10, Number(rows) || 30) }
|
|
@@ -2351,7 +2587,7 @@ async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
|
2351
2587
|
if (cfg.key) args.push('-i', cfg.key)
|
|
2352
2588
|
args.push(`${cfg.user ? cfg.user + '@' : ''}${cfg.host}`)
|
|
2353
2589
|
|
|
2354
|
-
if (!
|
|
2590
|
+
if (!password) {
|
|
2355
2591
|
// Key / agent authentication: a real PTY comes from ssh -tt through pipes.
|
|
2356
2592
|
const child = spawn('ssh', args, { env: { ...process.env, TERM: 'xterm-256color' } })
|
|
2357
2593
|
session.child = child
|
|
@@ -2392,7 +2628,7 @@ async function openTerminal(cfg, cols = 120, rows = 30) {
|
|
|
2392
2628
|
host: cfg.host,
|
|
2393
2629
|
port: Number(cfg.port || 22),
|
|
2394
2630
|
username: cfg.user || process.env.USER,
|
|
2395
|
-
password
|
|
2631
|
+
password,
|
|
2396
2632
|
readyTimeout: 15_000,
|
|
2397
2633
|
keepaliveInterval: 15_000,
|
|
2398
2634
|
})
|
|
@@ -2445,13 +2681,11 @@ function terminalClose(id) {
|
|
|
2445
2681
|
|
|
2446
2682
|
/** Run a remote command with a binary stdin payload (large data never goes in argv). */
|
|
2447
2683
|
async function sshStdin(cfg, command, buffer, timeoutMs = 180_000) {
|
|
2448
|
-
const
|
|
2449
|
-
|
|
2450
|
-
if (secret?.password) {
|
|
2684
|
+
const password = await readPassword(cfg.name)
|
|
2685
|
+
if (password) {
|
|
2451
2686
|
const ssh2 = loadSsh2()
|
|
2452
2687
|
if (!ssh2) throw new Error('ssh2 is not available in this profile')
|
|
2453
2688
|
const conn = new ssh2.Client()
|
|
2454
|
-
const password = Buffer.from(secret.password, 'base64').toString('utf8')
|
|
2455
2689
|
return await new Promise((resolve, reject) => {
|
|
2456
2690
|
const timer = setTimeout(() => { try { conn.end() } catch {} ; reject(new Error('command timeout')) }, timeoutMs)
|
|
2457
2691
|
conn.on('ready', () => {
|
|
@@ -2511,7 +2745,7 @@ const CHUNK_MAX = 8 * 1024 * 1024
|
|
|
2511
2745
|
/** Bytes already written to <path>.part, for resumable uploads. */
|
|
2512
2746
|
async function uploadStatus(cfg, path) {
|
|
2513
2747
|
const target = fsSafePath(path)
|
|
2514
|
-
const result = await ssh(cfg, `stat -c%s ${
|
|
2748
|
+
const result = await ssh(cfg, `stat -c%s ${q(target + '.part')} 2>/dev/null || echo 0`, 10_000)
|
|
2515
2749
|
return { host: cfg.name, path: target, bytes: Number(String(result.stdout || '0').trim()) || 0 }
|
|
2516
2750
|
}
|
|
2517
2751
|
|
|
@@ -2524,10 +2758,10 @@ async function uploadChunk(cfg, path, offset, base64) {
|
|
|
2524
2758
|
if (buffer.length === 0) return { host: cfg.name, ok: true, bytes: expected }
|
|
2525
2759
|
if (buffer.length > CHUNK_MAX) throw new Error('chunk too large')
|
|
2526
2760
|
const command = [
|
|
2527
|
-
`size=$(stat -c%s ${
|
|
2761
|
+
`size=$(stat -c%s ${q(part)} 2>/dev/null || echo 0)`,
|
|
2528
2762
|
`if [ "$size" -ne ${expected} ]; then echo "OFFSET_MISMATCH $size"; exit 3; fi`,
|
|
2529
|
-
`cat >> ${
|
|
2530
|
-
`stat -c%s ${
|
|
2763
|
+
`cat >> ${q(part)}`,
|
|
2764
|
+
`stat -c%s ${q(part)}`,
|
|
2531
2765
|
].join('\n')
|
|
2532
2766
|
const result = await sshStdin(cfg, command, buffer, 180_000)
|
|
2533
2767
|
if (result.code === 3) {
|
|
@@ -2547,10 +2781,10 @@ async function uploadFinish(cfg, path) {
|
|
|
2547
2781
|
const part = `${target}.part`
|
|
2548
2782
|
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
2549
2783
|
const command = [
|
|
2550
|
-
`test -f ${
|
|
2551
|
-
`cp -a ${
|
|
2552
|
-
`mv -f ${
|
|
2553
|
-
`stat -c%s ${
|
|
2784
|
+
`test -f ${q(part)} || { echo MISSING_PART; exit 4; }`,
|
|
2785
|
+
`cp -a ${q(target)} ${q(`${target}.bak.${stamp}`)} 2>/dev/null || true`,
|
|
2786
|
+
`mv -f ${q(part)} ${q(target)} && echo OK`,
|
|
2787
|
+
`stat -c%s ${q(target)}`,
|
|
2554
2788
|
].join('\n')
|
|
2555
2789
|
const result = await ssh(cfg, command, 60_000)
|
|
2556
2790
|
return {
|
|
@@ -2566,9 +2800,9 @@ async function downloadChunk(cfg, path, offset, length) {
|
|
|
2566
2800
|
const target = fsSafePath(path)
|
|
2567
2801
|
const start = Math.max(0, Number(offset) || 0)
|
|
2568
2802
|
const count = Math.min(CHUNK_MAX, Math.max(1, Number(length) || CHUNK_MAX))
|
|
2569
|
-
const sizeResult = await ssh(cfg, `stat -c%s ${
|
|
2803
|
+
const sizeResult = await ssh(cfg, `stat -c%s ${q(target)} 2>/dev/null || echo 0`, 10_000)
|
|
2570
2804
|
const size = Number(String(sizeResult.stdout || '0').trim()) || 0
|
|
2571
|
-
const result = await ssh(cfg, `dd if=${
|
|
2805
|
+
const result = await ssh(cfg, `dd if=${q(target)} bs=1 skip=${start} count=${count} 2>/dev/null | base64 -w0`, 180_000)
|
|
2572
2806
|
if (!result.ok) throw new Error(cleanStderr(result.stderr) || 'cannot read file')
|
|
2573
2807
|
return { host: cfg.name, path: target, size, offset: start, base64: String(result.stdout || '').replace(/\s+/g, '') }
|
|
2574
2808
|
}
|
|
@@ -2754,7 +2988,7 @@ async function logUsage(cfg) {
|
|
|
2754
2988
|
.map(match => ({ bytes: Number(match[1]), at: new Date(Number(match[2]) * 1000).toISOString(), path: match[3], source: '系统日志' }))
|
|
2755
2989
|
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2756
2990
|
try {
|
|
2757
|
-
const found = await ssh(cfg, `find ${
|
|
2991
|
+
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
2992
|
for (const line of String(found.stdout || '').split('\n')) {
|
|
2759
2993
|
const match = line.match(/^(\d{4,}) ([\d.]+) (.+)$/)
|
|
2760
2994
|
if (!match) continue
|
|
@@ -2812,7 +3046,7 @@ async function cleanupPreview(cfg) {
|
|
|
2812
3046
|
]
|
|
2813
3047
|
for (const dir of await discoverLogDirs(cfg).catch(() => [])) {
|
|
2814
3048
|
try {
|
|
2815
|
-
const found = await ssh(cfg, `find ${
|
|
3049
|
+
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
3050
|
for (const line of String(found.stdout || '').split('\n')) {
|
|
2817
3051
|
const match = line.match(/^(\d+) ([\d.]+) (\S+) (.+)$/)
|
|
2818
3052
|
if (!match) continue
|
|
@@ -2968,8 +3202,8 @@ async function backupLogs(cfg, paths) {
|
|
|
2968
3202
|
const dest = `/var/backups/dsh-ops-kit/logs-${stamp}.tar.gz`
|
|
2969
3203
|
const command = [
|
|
2970
3204
|
`mkdir -p /var/backups/dsh-ops-kit`,
|
|
2971
|
-
`tar -czf ${
|
|
2972
|
-
`stat -c%s ${
|
|
3205
|
+
`tar -czf ${q(dest)} ${list.map(item => q(item)).join(' ')} 2>/dev/null && echo OK`,
|
|
3206
|
+
`stat -c%s ${q(dest)}`,
|
|
2973
3207
|
].join('\\n')
|
|
2974
3208
|
const result = await ssh(cfg, command, 300_000)
|
|
2975
3209
|
const size = Number(String(result.stdout || '').trim().split('\\n').pop()) || 0
|
|
@@ -3191,20 +3425,20 @@ async function runMonitor(cfg, monitor) {
|
|
|
3191
3425
|
const target = String(monitor.target || '').trim()
|
|
3192
3426
|
let command
|
|
3193
3427
|
if (type === 'http') {
|
|
3194
|
-
command = `curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 8 ${
|
|
3428
|
+
command = `curl -s -o /dev/null -w '%{http_code} %{time_total}' --max-time 8 ${q(target)} 2>/dev/null || echo "000 0"`
|
|
3195
3429
|
} else if (type === 'port') {
|
|
3196
3430
|
const [host, port] = target.split(':')
|
|
3197
3431
|
if (!host || !port) throw new Error('port monitor needs host:port')
|
|
3198
3432
|
command = `timeout 4 bash -c '</dev/tcp/${host.replace(/[^A-Za-z0-9.-]/g, '')}/${Number(port)}' 2>/dev/null && echo OPEN || echo CLOSED`
|
|
3199
3433
|
} else if (type === 'process') {
|
|
3200
|
-
command = `pgrep -f ${
|
|
3434
|
+
command = `pgrep -f ${q(target)} >/dev/null 2>&1 && echo RUNNING || echo STOPPED`
|
|
3201
3435
|
} else if (type === 'service') {
|
|
3202
3436
|
command = `systemctl is-active ${target.replace(/[^A-Za-z0-9@._-]/g, '')} 2>/dev/null || true`
|
|
3203
3437
|
} else if (type === 'script') {
|
|
3204
3438
|
const language = ['shell', 'python', 'js'].includes(monitor.language) ? monitor.language : 'shell'
|
|
3205
3439
|
const interpreter = language === 'python' ? 'python3' : language === 'js' ? 'node' : 'bash'
|
|
3206
3440
|
const encoded = Buffer.from(String(monitor.script || ''), 'utf8').toString('base64')
|
|
3207
|
-
command = `f=$(mktemp); printf %s ${
|
|
3441
|
+
command = `f=$(mktemp); printf %s ${q(encoded)} | base64 -d > "$f"; ${interpreter} "$f"; rc=$?; rm -f "$f"; exit $rc`
|
|
3208
3442
|
} else {
|
|
3209
3443
|
throw new Error(`unknown monitor type ${type}`)
|
|
3210
3444
|
}
|
|
@@ -3389,13 +3623,19 @@ async function runMonitorPass(force = false) {
|
|
|
3389
3623
|
|
|
3390
3624
|
/* ---------- backups, health, certificates, cron, file history, deploy ---------- */
|
|
3391
3625
|
|
|
3392
|
-
|
|
3626
|
+
/**
|
|
3627
|
+
* Shell quote for the remote sh: wrap in single quotes and escape embedded
|
|
3628
|
+
* ones. JSON.stringify() is NOT safe here — a double-quoted string still lets
|
|
3629
|
+
* the remote shell expand $(...) and backticks.
|
|
3630
|
+
*/
|
|
3631
|
+
const q = (value) => "'" + String(value ?? '').replace(/'/g, "'\\''") + "'"
|
|
3393
3632
|
|
|
3394
3633
|
async function loadJsonFile(name, fallback) {
|
|
3395
3634
|
try {
|
|
3396
3635
|
const data = JSON.parse(await readFile(join(kitDir(), name), 'utf8'))
|
|
3397
3636
|
return data && typeof data === 'object' ? data : fallback
|
|
3398
|
-
} catch {
|
|
3637
|
+
} catch (error) {
|
|
3638
|
+
softFail('loadJsonFile', error)
|
|
3399
3639
|
return fallback
|
|
3400
3640
|
}
|
|
3401
3641
|
}
|
|
@@ -3414,6 +3654,9 @@ async function runBackup(cfg, job) {
|
|
|
3414
3654
|
const started = Date.now()
|
|
3415
3655
|
let file
|
|
3416
3656
|
let command
|
|
3657
|
+
let stdinScript = null
|
|
3658
|
+
let parent = ''
|
|
3659
|
+
let target
|
|
3417
3660
|
|
|
3418
3661
|
if (job.type === 'mysql') {
|
|
3419
3662
|
const database = String(job.database || '').trim()
|
|
@@ -3421,33 +3664,43 @@ async function runBackup(cfg, job) {
|
|
|
3421
3664
|
const password = String(job.password || '')
|
|
3422
3665
|
const scope = database ? `--databases ${q(database)}` : '--all-databases'
|
|
3423
3666
|
file = `${dir}/mysql-${database || 'all'}-${stamp}.sql.gz`
|
|
3424
|
-
|
|
3667
|
+
target = database || 'all'
|
|
3668
|
+
// The password stays out of argv on both ends: the script goes over stdin.
|
|
3669
|
+
stdinScript = [
|
|
3425
3670
|
`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
|
-
|
|
3671
|
+
`MYSQL_PWD=${q(password)} mysqldump -u${q(user)} ${scope} --single-transaction --quick --routines > /tmp/.ops-bk.sql 2>/tmp/.ops-bk.err`,
|
|
3672
|
+
'rc=$?',
|
|
3673
|
+
'if [ "$rc" -ne 0 ]; then cat /tmp/.ops-bk.err; exit $rc; fi',
|
|
3674
|
+
`gzip -c /tmp/.ops-bk.sql > ${q(file)} && rm -f /tmp/.ops-bk.sql`,
|
|
3429
3675
|
`stat -c %s ${q(file)} 2>/dev/null || wc -c < ${q(file)}`,
|
|
3430
3676
|
].join('\n')
|
|
3431
3677
|
} else {
|
|
3432
3678
|
const raw = String(job.path || '').replace(/\/+$/, '')
|
|
3433
3679
|
if (!raw || raw === '/') {
|
|
3434
3680
|
file = `${dir}/rootfs-${stamp}.tar.gz`
|
|
3681
|
+
target = '/'
|
|
3682
|
+
parent = '/'
|
|
3435
3683
|
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
3684
|
} else {
|
|
3437
3685
|
const base = raw.split('/').pop()
|
|
3438
|
-
|
|
3686
|
+
parent = raw.split('/').slice(0, -1).join('/') || '/'
|
|
3687
|
+
target = raw
|
|
3439
3688
|
file = `${dir}/dir-${base}-${stamp}.tar.gz`
|
|
3440
3689
|
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
3690
|
}
|
|
3442
3691
|
}
|
|
3443
3692
|
|
|
3444
|
-
const result =
|
|
3693
|
+
const result = stdinScript
|
|
3694
|
+
? await sshStdin(cfg, 'sh -s', Buffer.from(stdinScript, 'utf8'), 20 * 60_000)
|
|
3695
|
+
: await ssh(cfg, command, 20 * 60_000)
|
|
3445
3696
|
const size = Number(String(result.stdout || '').trim().split('\n').pop()) || 0
|
|
3446
3697
|
const record = {
|
|
3447
3698
|
id: `b${Date.now().toString(36)}`,
|
|
3448
3699
|
host: cfg.name,
|
|
3449
3700
|
type: job.type === 'mysql' ? 'mysql' : 'dir',
|
|
3450
|
-
target
|
|
3701
|
+
target,
|
|
3702
|
+
parent,
|
|
3703
|
+
user: job.type === 'mysql' ? String(job.user || 'root').trim() : '',
|
|
3451
3704
|
file,
|
|
3452
3705
|
size,
|
|
3453
3706
|
keep,
|
|
@@ -3474,24 +3727,49 @@ async function runBackup(cfg, job) {
|
|
|
3474
3727
|
return record
|
|
3475
3728
|
}
|
|
3476
3729
|
|
|
3477
|
-
async function restoreBackup(cfg, id) {
|
|
3730
|
+
async function restoreBackup(cfg, id, options = {}) {
|
|
3478
3731
|
const all = await loadJsonFile('backups.json', {})
|
|
3479
3732
|
const record = (all[cfg.name] || []).find(item => item.id === id)
|
|
3480
3733
|
if (!record) throw new Error('备份记录不存在')
|
|
3481
3734
|
if (!record.ok) throw new Error('这条备份本身失败了,不能恢复')
|
|
3482
|
-
|
|
3735
|
+
const backupDir = String(record.file || '').replace(/\/[^/]+$/, '')
|
|
3736
|
+
const stamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 14)
|
|
3737
|
+
let script
|
|
3738
|
+
let preRestore = ''
|
|
3739
|
+
|
|
3483
3740
|
if (record.type === 'mysql') {
|
|
3484
|
-
const
|
|
3485
|
-
|
|
3741
|
+
const user = String(options.user || record.user || 'root').trim()
|
|
3742
|
+
const password = String(options.password || '')
|
|
3743
|
+
preRestore = `${backupDir}/pre-restore-${record.target || 'all'}-${stamp}.sql.gz`
|
|
3744
|
+
script = [
|
|
3745
|
+
// 恢复前先给当前库拍一份快照,恢复失败还能退回去
|
|
3746
|
+
`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`,
|
|
3747
|
+
`gunzip -c ${q(record.file)} | MYSQL_PWD=${q(password)} mysql -u${q(user)} 2>&1 | tail -5`,
|
|
3748
|
+
].join('\n')
|
|
3486
3749
|
} else {
|
|
3487
|
-
const parent = record.
|
|
3488
|
-
|
|
3750
|
+
const parent = String(record.parent || (record.target && record.target !== '/' ? String(record.target).replace(/\/[^/]+$/, '') : '/') || '/')
|
|
3751
|
+
const base = String(record.target || '/').split('/').filter(Boolean).pop() || ''
|
|
3752
|
+
if (base && parent !== '/') {
|
|
3753
|
+
preRestore = `${backupDir}/pre-restore-${stamp}.tar.gz`
|
|
3754
|
+
script = [
|
|
3755
|
+
`tar -czf ${q(preRestore)} -C ${q(parent)} ${q(base)} 2>/dev/null || true`,
|
|
3756
|
+
`tar -tzf ${q(record.file)} >/dev/null 2>&1 || { echo '备份文件损坏'; exit 1; }`,
|
|
3757
|
+
`tar -xzf ${q(record.file)} -C ${q(parent)} 2>&1 | tail -3`,
|
|
3758
|
+
].join('\n')
|
|
3759
|
+
} else {
|
|
3760
|
+
script = [
|
|
3761
|
+
`tar -tzf ${q(record.file)} >/dev/null 2>&1 || { echo '备份文件损坏'; exit 1; }`,
|
|
3762
|
+
`tar -xzf ${q(record.file)} -C ${q(parent)} 2>&1 | tail -3`,
|
|
3763
|
+
].join('\n')
|
|
3764
|
+
}
|
|
3489
3765
|
}
|
|
3490
|
-
|
|
3766
|
+
|
|
3767
|
+
const result = await sshStdin(cfg, 'sh -s', Buffer.from(script, 'utf8'), 20 * 60_000)
|
|
3491
3768
|
record.restoredAt = new Date().toISOString()
|
|
3492
3769
|
record.restoreOk = result.ok
|
|
3770
|
+
if (result.ok && preRestore) record.preRestore = preRestore
|
|
3493
3771
|
await saveJsonFile('backups.json', all)
|
|
3494
|
-
return { id, ok: result.ok, output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 800) }
|
|
3772
|
+
return { id, ok: result.ok, preRestore: result.ok ? preRestore : '', output: clip(`${result.stdout || ''}${cleanStderr(result.stderr)}`, 800) }
|
|
3495
3773
|
}
|
|
3496
3774
|
|
|
3497
3775
|
/* ---- health score ---- */
|
|
@@ -3629,12 +3907,22 @@ async function writeCron(cfg, lines) {
|
|
|
3629
3907
|
return { ok: result.ok, count: Number(String(result.stdout || '').trim()) || 0, error: result.ok ? '' : cleanStderr(result.stderr) }
|
|
3630
3908
|
}
|
|
3631
3909
|
|
|
3910
|
+
const CRON_FIELD = /^[0-9*/,\-]+$/
|
|
3911
|
+
|
|
3632
3912
|
async function addCron(cfg, job) {
|
|
3633
3913
|
const current = await ssh(cfg, 'crontab -l 2>/dev/null || true', 20_000)
|
|
3634
3914
|
const lines = String(current.stdout || '').split('\n').filter(line => line.trim())
|
|
3635
|
-
const
|
|
3636
|
-
|
|
3637
|
-
|
|
3915
|
+
const command = String(job.command || '').trim()
|
|
3916
|
+
if (!command) throw new Error('command is required')
|
|
3917
|
+
// A newline would append extra crontab lines; % is cron's own newline marker.
|
|
3918
|
+
if (/[\r\n]/.test(command)) throw new Error('命令里不能有换行')
|
|
3919
|
+
const field = (value, fallback) => {
|
|
3920
|
+
const text = String(value ?? fallback).trim()
|
|
3921
|
+
if (text !== '*' && !CRON_FIELD.test(text)) throw new Error('计划时间格式不合法:只允许数字、* / , -')
|
|
3922
|
+
return text
|
|
3923
|
+
}
|
|
3924
|
+
const schedule = [field(job.minute, '0'), field(job.hour, '3'), field(job.day, '*'), field(job.month, '*'), field(job.weekday, '*')].join(' ')
|
|
3925
|
+
const line = `${schedule} ${command}`
|
|
3638
3926
|
return writeCron(cfg, [...lines, line])
|
|
3639
3927
|
}
|
|
3640
3928
|
|
|
@@ -4743,8 +5031,9 @@ export function apply(ctx) {
|
|
|
4743
5031
|
async execute(args = {}) {
|
|
4744
5032
|
const command = String(args.command ?? '').trim()
|
|
4745
5033
|
if (!command) throw new Error('command is required')
|
|
4746
|
-
|
|
4747
|
-
|
|
5034
|
+
const risk = classifyCommand(command)
|
|
5035
|
+
if (risk.dangerous && args.confirm !== true) {
|
|
5036
|
+
throw new Error(`这条命令可能造成不可逆的破坏:${risk.reasons.join(';')}。确认要执行就带 confirm=true 重来一次。`)
|
|
4748
5037
|
}
|
|
4749
5038
|
return batchRun(command, Array.isArray(args.hosts) ? args.hosts : undefined)
|
|
4750
5039
|
},
|
|
@@ -4764,8 +5053,9 @@ export function apply(ctx) {
|
|
|
4764
5053
|
async execute(args = {}) {
|
|
4765
5054
|
const command = String(args.command ?? '').trim()
|
|
4766
5055
|
if (!command) throw new Error('command is required')
|
|
4767
|
-
|
|
4768
|
-
|
|
5056
|
+
const risk = classifyCommand(command)
|
|
5057
|
+
if (risk.dangerous && args.confirm !== true) {
|
|
5058
|
+
throw new Error(`这条命令可能造成不可逆的破坏:${risk.reasons.join(';')}。确认要执行就带 confirm=true 重来一次。`)
|
|
4769
5059
|
}
|
|
4770
5060
|
const cfg = pickHost(await loadHosts(), args.host)
|
|
4771
5061
|
const result = await ssh(cfg, command, Number(args.timeoutMs ?? 20_000))
|
|
@@ -4854,12 +5144,12 @@ export function apply(ctx) {
|
|
|
4854
5144
|
|
|
4855
5145
|
ctx.effect(() => {
|
|
4856
5146
|
const tick = () => {
|
|
4857
|
-
void runScheduledPass().catch(
|
|
4858
|
-
void runMetricsPass().catch(
|
|
4859
|
-
void runMonitorPass().catch(
|
|
4860
|
-
void checkCertAlerts().catch(
|
|
4861
|
-
void logGrowthPass().catch(
|
|
4862
|
-
void logAutoCleanPass().catch(
|
|
5147
|
+
void runScheduledPass().catch(error => softFail('scheduled pass', error))
|
|
5148
|
+
void runMetricsPass().catch(error => softFail('metrics pass', error))
|
|
5149
|
+
void runMonitorPass().catch(error => softFail('monitor pass', error))
|
|
5150
|
+
void checkCertAlerts().catch(error => softFail('cert alerts', error))
|
|
5151
|
+
void logGrowthPass().catch(error => softFail('log growth', error))
|
|
5152
|
+
void logAutoCleanPass().catch(error => softFail('log auto clean', error))
|
|
4863
5153
|
}
|
|
4864
5154
|
const previous = globalThis.__opsKitScheduler
|
|
4865
5155
|
if (previous) { clearInterval(previous.handle); clearTimeout(previous.first) }
|
|
@@ -4875,3 +5165,17 @@ export function apply(ctx) {
|
|
|
4875
5165
|
}
|
|
4876
5166
|
})
|
|
4877
5167
|
}
|
|
5168
|
+
|
|
5169
|
+
/** Internals for the test suite; not part of the plugin API. */
|
|
5170
|
+
export const __test = {
|
|
5171
|
+
q,
|
|
5172
|
+
clip,
|
|
5173
|
+
pickHost,
|
|
5174
|
+
safeUnit,
|
|
5175
|
+
classifyCommand,
|
|
5176
|
+
looksDangerous,
|
|
5177
|
+
fileAllowed,
|
|
5178
|
+
fsSafePath,
|
|
5179
|
+
logSafePath,
|
|
5180
|
+
jobSnapshot,
|
|
5181
|
+
}
|