@jiyr0119/dsh-service-console 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,334 @@
1
+ // dsh-service-console · M1 动态原型 Host(v12 = pkg-17 对应代码)
2
+ // 覆盖任务:T1-1 ProcessInspector · T1-2 ServiceRegistry · T1-3 会话台账
3
+ // T1-4 归属评分 · T1-5 脱敏 · T1-6 生命周期 · T1-7 API · T1-8 配置
4
+ // 说明:动态 Cordis 插件 Host 半,纯 JavaScript。通过 ctx.get('shell') 执行平台命令,
5
+ // 不依赖 Node child_process(动态 Host 无 process 全局)。
6
+ // 注意:
7
+ // - 动态 Host/Client 均无 setTimeout/setInterval 全局,定时器用 timer 服务(inject: ['timer'] + ctx.timeout/ctx.interval)
8
+ // - fingerprint 用 FNV-1a(动态环境无 crypto),M2 原生包迁移为 node:crypto sha256
9
+ // - 动态工具结果传递在当前 DSH 会话中受限,开发期验证以面板 host.call + bash 链路复现为准
10
+
11
+ return {
12
+ inject: ['timer'],
13
+ apply(ctx) {
14
+ const shell = ctx.get('shell')
15
+ if (shell === undefined) return
16
+ const workspaceRegistry = ctx.get('workspaceRegistry')
17
+
18
+ const MONTHS = { Jan: 1, Feb: 2, Mar: 3, Apr: 4, May: 5, Jun: 6, Jul: 7, Aug: 8, Sep: 9, Oct: 10, Nov: 11, Dec: 12 }
19
+
20
+ // ---------- T1-8 Config ----------
21
+ const config = { refreshInterval: 5000, defaultScope: 'workspace', gracefulTimeout: 3000, showUnknown: true, forceKill: false, autoCleanup: false }
22
+ const CONFIG_LIMITS = { refreshInterval: [2000, 30000], gracefulTimeout: [1000, 15000] }
23
+ const actionLog = []
24
+ function logAction(serviceId, action, result, code) {
25
+ actionLog.push({ at: Date.now(), serviceId, action, result, code: code || null })
26
+ if (actionLog.length > 200) actionLog.shift()
27
+ }
28
+
29
+ // ---------- 工具函数 ----------
30
+ function fnv1a(str) {
31
+ let h = 0x811c9dc5
32
+ for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = (h * 0x01000193) >>> 0 }
33
+ return h.toString(36)
34
+ }
35
+ function ok(data) { return { ok: true, data } }
36
+ function err(code, message) { return { ok: false, error: { code, message } } }
37
+
38
+ async function runCommand(command, timeoutMs) {
39
+ try {
40
+ const spec = shell.resolve({ command, timeout: timeoutMs || 5000 })
41
+ const res = await shell.run(spec)
42
+ const stdout = typeof res.stdout === 'string' ? res.stdout
43
+ : typeof res.output === 'string' ? res.output
44
+ : typeof res.text === 'string' ? res.text : ''
45
+ const stderr = typeof res.stderr === 'string' ? res.stderr : ''
46
+ const code = res.code !== undefined ? res.code : res.exitCode !== undefined ? res.exitCode : null
47
+ return { stdout, stderr, code }
48
+ } catch (e) { return { stdout: '', stderr: String((e && e.message) || e), code: null } }
49
+ }
50
+
51
+ // ps lstart: "Mon Aug 17 19:32:16 2026" → epoch ms(5 个 token:星期 月 日 时间 年)
52
+ function parseLstart(str) {
53
+ const parts = String(str).trim().split(/\s+/)
54
+ if (parts.length < 5) return null
55
+ const mon = MONTHS[parts[1]]
56
+ const day = parseInt(parts[2], 10)
57
+ const year = parseInt(parts[4], 10)
58
+ if (!mon || !day || !year || !parts[3]) return null
59
+ const iso = year + '-' + String(mon).padStart(2, '0') + '-' + String(day).padStart(2, '0') + 'T' + parts[3]
60
+ const t = Date.parse(iso)
61
+ return Number.isFinite(t) ? t : null
62
+ }
63
+
64
+ function parseListenRows(stdout) {
65
+ const rows = []
66
+ for (const line of String(stdout).split('\n')) {
67
+ const t = line.trim()
68
+ if (!t || t.startsWith('COMMAND')) continue
69
+ const m = t.match(/^(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/)
70
+ if (!m) continue
71
+ const name = m[9].trim()
72
+ if (!/\(LISTEN\)$/.test(name)) continue
73
+ rows.push({ command: m[1], pid: parseInt(m[2], 10), user: m[3], fd: m[4], type: m[5], address: name.replace(/\s*\(LISTEN\)$/, '') })
74
+ }
75
+ return rows
76
+ }
77
+
78
+ function parsePsRows(stdout) {
79
+ const rows = []
80
+ for (const line of String(stdout).split('\n')) {
81
+ const t = line.trim()
82
+ if (!t) continue
83
+ const parts = t.split(/\s+/)
84
+ const pid = parseInt(parts[0], 10)
85
+ const ppid = parseInt(parts[1], 10)
86
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue
87
+ const lstart = parts.slice(2, 7).join(' ')
88
+ rows.push({ pid, ppid, lstart, startedAt: parseLstart(lstart), command: parts.slice(7).join(' ') })
89
+ }
90
+ return rows
91
+ }
92
+
93
+ function parseAddress(addr) {
94
+ let host = null
95
+ let port = null
96
+ let m = String(addr).match(/^\[([^\]]+)\]:(.+)$/)
97
+ if (m) { host = m[1]; port = parseInt(m[2], 10) }
98
+ else { m = String(addr).match(/^(.+):(\d+)$/); if (m) { host = m[1]; port = parseInt(m[2], 10) } }
99
+ return { host, port }
100
+ }
101
+
102
+ function shellQuote(s) { return "'" + String(s).replace(/'/g, "'\\''") + "'" }
103
+
104
+ // ---------- T1-5 Redaction ----------
105
+ const REDACT_RULES = [
106
+ {
107
+ // --token=abc123 / --token abc123 / --token:abc123 → 保留 --token 与分隔符,值脱敏
108
+ re: /(--(?:token|password|passwd|secret|key|api[-_]?key|client[-_]?secret|cookie|session))\s*[=:]\s*(\S+)/gi,
109
+ replace: function (m) { return m.replace(/(?:[=:]\s*|\s+)\S+$/, '=***') },
110
+ },
111
+ {
112
+ // KEY=value / KEY='value' → 保留 KEY=,值脱敏
113
+ re: /((?:token|password|passwd|secret|api[-_]?key|client[-_]?secret|authorization|set-cookie|connection[-_]?string))\s*=\s*(['"]?)([^\s&'"]+)\2/gi,
114
+ replace: function (m, p1, p2) { return (p1 || '') + '=' + (p2 || '') + '***' },
115
+ },
116
+ {
117
+ // scheme://user:pass@ → 保留 scheme://,凭据脱敏
118
+ re: /(postgres(?:ql)?|mysql|redis|mongodb)(\+s?)?:\/\/[^\s@]+@/gi,
119
+ replace: function (m, p1) { return (p1 || '') + '://***@' },
120
+ },
121
+ {
122
+ // JWT
123
+ re: /\b(eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{10,})\b/g,
124
+ replace: function () { return '***' },
125
+ },
126
+ ]
127
+ function redact(command) {
128
+ if (typeof command !== 'string' || !command) return command
129
+ let out = command
130
+ for (const rule of REDACT_RULES) {
131
+ out = out.replace(rule.re, function () { return rule.replace.apply(null, arguments) })
132
+ }
133
+ return out
134
+ }
135
+
136
+ // ---------- T1-3 Session Launch Ledger ----------
137
+ const ledger = []
138
+ const DEV_COMMAND_RE = /(npm (run|start|dev)|pnpm (run|dev|start)|yarn (dev|start)|next dev|vite|uvicorn|gunicorn|flask run|django runserver|cargo run|node (server|app|index)|python3? -m (http.server|uvicorn)|serve|http-server|nodemon|tsx watch|deno run)/
139
+ ctx.on('tools/result', (exec) => {
140
+ try {
141
+ if (!exec || exec.name !== 'bash') return
142
+ const args = exec.args || {}
143
+ const command = String(args.command || '')
144
+ if (!DEV_COMMAND_RE.test(command)) return
145
+ let sessionKey = null
146
+ try { sessionKey = (exec.agent && (exec.agent.id || exec.agent.sessionId)) || null } catch (e) { sessionKey = null }
147
+ ledger.push({ at: Date.now(), command, cwd: args.workdir || null, sessionKey, redacted: redact(command) })
148
+ if (ledger.length > 200) ledger.shift()
149
+ } catch (err) { console.error('ledger error', String((err && err.message) || err)) }
150
+ })
151
+
152
+ // ---------- T1-4 Ownership ----------
153
+ function classifyOwnership(proc, ledgers, workspaces) {
154
+ const cwd = proc.cwd
155
+ const command = proc.command || ''
156
+ const evidence = []
157
+ let ownership = 'unknown'
158
+ let confidence = 'unknown'
159
+ let ledgerEntry = null
160
+ if (cwd && ledgers.length > 0) {
161
+ ledgerEntry = ledgers.find((l) => l.cwd && cwd.indexOf(l.cwd) === 0 && proc.startedAt && Math.abs(proc.startedAt - l.at) < 10 * 60 * 1000)
162
+ }
163
+ if (ledgerEntry) {
164
+ ownership = 'conversation-confirmed'
165
+ confidence = 'confirmed'
166
+ evidence.push('matched session launch ledger: ' + (ledgerEntry.redacted || ledgerEntry.command).slice(0, 60))
167
+ } else if (cwd && workspaces.length > 0) {
168
+ const ws = workspaces.find((w) => w && w.path && cwd.indexOf(w.path) === 0)
169
+ if (ws) { ownership = 'workspace-inferred'; confidence = 'inferred'; evidence.push('cwd under workspace: ' + ws.path) }
170
+ } else if (cwd && !/^(\/usr\/|\/System\/|\/Library\/|\/bin\/|\/sbin\/|\/private\/)/.test(cwd)) {
171
+ ownership = 'other-local'; confidence = 'inferred'; evidence.push('local cwd not in workspace: ' + cwd)
172
+ } else {
173
+ evidence.push('cannot confirm origin (cwd or command unavailable)')
174
+ }
175
+ return { ownership, confidence, evidence, ledgerEntry }
176
+ }
177
+
178
+ // ---------- T1-2 ServiceRegistry ----------
179
+ async function buildSnapshot() {
180
+ const partialWarnings = []
181
+ const tcp = await runCommand('lsof -nP -iTCP -sTCP:LISTEN', 5000)
182
+ if (tcp.code !== 0 && tcp.code !== null && tcp.code !== 1) partialWarnings.push('TCP listener scan exit=' + String(tcp.code))
183
+ const rows = parseListenRows(tcp.stdout)
184
+ const pids = [...new Set(rows.map((r) => r.pid))]
185
+ const pidList = pids.join(',')
186
+
187
+ let procByPid = new Map()
188
+ let extraByPid = new Map()
189
+ if (pids.length > 0) {
190
+ const psRes = await runCommand('ps -o pid=,ppid=,lstart=,command= -p ' + pidList, 5000)
191
+ procByPid = new Map(parsePsRows(psRes.stdout).map((r) => [r.pid, r]))
192
+ if (psRes.code !== 0 && psRes.code !== null) partialWarnings.push('ps detail partial')
193
+ const pgidRes = await runCommand('ps -o pid=,pgid= -p ' + pidList, 5000)
194
+ const pgidMap = new Map()
195
+ for (const line of String(pgidRes.stdout).split('\n')) {
196
+ const parts = line.trim().split(/\s+/)
197
+ if (parts.length >= 2) {
198
+ const p = parseInt(parts[0], 10); const g = parseInt(parts[1], 10)
199
+ if (Number.isFinite(p) && Number.isFinite(g)) pgidMap.set(p, g)
200
+ }
201
+ }
202
+ let cwdByPid = new Map()
203
+ const cwdRes = await runCommand('lsof -a -p ' + pidList + ' -d cwd', 5000)
204
+ for (const line of String(cwdRes.stdout).split('\n')) {
205
+ const t = line.trim()
206
+ if (!t || t.startsWith('COMMAND')) continue
207
+ const m = t.match(/^(\S+)\s+(\d+)\s+(\S+)\s+cwd\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.+)$/)
208
+ if (m) cwdByPid.set(parseInt(m[2], 10), m[8].trim())
209
+ }
210
+ if (cwdRes.code !== 0 && cwdRes.code !== null) partialWarnings.push('cwd scan partial')
211
+ for (const pid of pids) extraByPid.set(pid, { pgid: pgidMap.get(pid) || null, cwd: cwdByPid.get(pid) || null })
212
+ }
213
+
214
+ const byPid = new Map()
215
+ for (const r of rows) {
216
+ const { host, port } = parseAddress(r.address)
217
+ if (!byPid.has(r.pid)) byPid.set(r.pid, [])
218
+ byPid.get(r.pid).push({ host, port, protocol: r.type === 'IPv6' ? 'tcp6' : 'tcp' })
219
+ }
220
+
221
+ let workspaces = []
222
+ try { if (workspaceRegistry && workspaceRegistry.list) workspaces = workspaceRegistry.list() } catch (e) { /* ignore */ }
223
+
224
+ const services = []
225
+ for (const [pid, listeners] of byPid) {
226
+ const proc = procByPid.get(pid)
227
+ const ex = extraByPid.get(pid) || {}
228
+ const command = proc ? proc.command : null
229
+ const cwd = ex.cwd
230
+ const name = proc ? proc.name || (command ? String(command).split(/\s+/)[0] : null) : null
231
+ const startedAt = proc ? proc.startedAt : null
232
+ const fpSource = [pid, startedAt, command || '', cwd || '', listeners.map((l) => l.host + ':' + l.port).sort().join(',')].join('|')
233
+ const serviceId = 'svc_' + fnv1a(fpSource)
234
+ const cls = classifyOwnership({ cwd, command, startedAt, pid }, ledger, workspaces)
235
+ const listenersFinal = listeners.map((l) => {
236
+ const isLocalhost = l.host === '127.0.0.1' || l.host === '::1' || l.host === 'localhost'
237
+ return Object.assign({}, l, { url: isLocalhost ? 'http://localhost:' + l.port : null })
238
+ })
239
+ services.push({
240
+ id: serviceId,
241
+ status: 'running',
242
+ ownership: cls.ownership,
243
+ confidence: cls.confidence,
244
+ name: name || 'unknown',
245
+ pid,
246
+ processGroupId: ex.pgid,
247
+ parentPid: proc ? proc.ppid : null,
248
+ commandSummary: command ? redact(String(command)).slice(0, 200) : null,
249
+ cwd,
250
+ startedAt,
251
+ listeners: listenersFinal,
252
+ restartable: !!cls.ledgerEntry,
253
+ protected: false,
254
+ ownershipEvidence: cls.evidence,
255
+ fingerprint: fpSource,
256
+ })
257
+ }
258
+ services.sort((a, b) => (a.ownership === 'conversation-confirmed' ? -1 : 1) - (b.ownership === 'conversation-confirmed' ? -1 : 1))
259
+ return { scannedAt: Date.now(), count: services.length, services, partialWarnings, ledgerCount: ledger.length }
260
+ }
261
+
262
+ // ---------- T1-6 Lifecycle ----------
263
+ async function stopService(serviceId, mode) {
264
+ const s = await buildSnapshot()
265
+ const svc = s.services.find((x) => x.id === serviceId)
266
+ if (!svc) return err('TARGET_GONE', '该服务已结束,列表已刷新')
267
+ if (svc.protected) return err('PROTECTED_PROCESS', '该进程受保护,不能通过 Service Console 操作')
268
+ if (svc.ownership === 'unknown') return err('UNKNOWN_OWNERSHIP', '无法确认服务来源,默认不允许控制')
269
+ const target = svc.processGroupId ? '-' + svc.processGroupId : String(svc.pid)
270
+ await runCommand('kill -TERM ' + target, 3000)
271
+ const deadline = Date.now() + (config.gracefulTimeout || 3000)
272
+ while (Date.now() < deadline) {
273
+ await ctx.timeout(400)
274
+ const re = await buildSnapshot()
275
+ if (!re.services.some((x) => x.id === serviceId)) {
276
+ logAction(serviceId, 'stop', 'stopped')
277
+ return ok({ result: 'stopped' })
278
+ }
279
+ }
280
+ if (config.forceKill) {
281
+ await runCommand('kill -KILL ' + target, 3000)
282
+ logAction(serviceId, 'stop', 'force-killed')
283
+ return ok({ result: 'force-killed' })
284
+ }
285
+ logAction(serviceId, 'stop', 'timeout', 'GRACEFUL_TIMEOUT')
286
+ return err('GRACEFUL_TIMEOUT', '服务未在等待时间内退出,可重试或在设置允许时强制终止')
287
+ }
288
+
289
+ async function restartService(serviceId) {
290
+ const s = await buildSnapshot()
291
+ const svc = s.services.find((x) => x.id === serviceId)
292
+ if (!svc) return err('TARGET_GONE', '该服务已结束,列表已刷新')
293
+ if (!svc.restartable) return err('RESTART_UNSAFE', '缺少安全复现启动所需的信息,不能重启')
294
+ const entry = ledger.find((l) => svc.cwd && l.cwd && svc.cwd.indexOf(l.cwd) === 0)
295
+ if (!entry) return err('RESTART_UNSAFE', '缺少启动命令记录,不能重启')
296
+ const stopped = await stopService(serviceId, 'graceful')
297
+ if (!stopped.ok && stopped.error.code !== 'TARGET_GONE') return stopped
298
+ const cmd = 'cd ' + shellQuote(entry.cwd || '.') + ' && ' + entry.command
299
+ await runCommand(cmd + ' >/dev/null 2>&1 &', 3000)
300
+ logAction(serviceId, 'restart', 'started')
301
+ return ok({ result: 'started', command: redact(entry.command) })
302
+ }
303
+
304
+ // ---------- T1-7 API 层 ----------
305
+ harness.handle('scan', async () => ok(await buildSnapshot()))
306
+ harness.handle('detail', async (args) => {
307
+ const s = await buildSnapshot()
308
+ const svc = s.services.find((x) => x.id === (args && args.serviceId))
309
+ if (!svc) return err('TARGET_GONE', '服务不存在')
310
+ return ok(Object.assign({}, svc, { recentActions: actionLog.filter((a) => a.serviceId === svc.id).slice(-10) }))
311
+ })
312
+ harness.handle('stop', async (args) => stopService(args && args.serviceId, (args && args.mode) || 'graceful'))
313
+ harness.handle('restart', async (args) => restartService(args && args.serviceId))
314
+ harness.handle('config', async (args) => {
315
+ const a = args || {}
316
+ if (a.action === 'update' && a.patch) {
317
+ const patch = a.patch
318
+ for (const key of Object.keys(patch)) {
319
+ if (!(key in config)) return err('BAD_REQUEST', 'unknown config key: ' + key)
320
+ const v = patch[key]
321
+ if (typeof v === 'boolean') { config[key] = v; continue }
322
+ if (typeof v === 'number' && CONFIG_LIMITS[key]) {
323
+ if (v < CONFIG_LIMITS[key][0] || v > CONFIG_LIMITS[key][1]) return err('BAD_REQUEST', 'config out of range: ' + key)
324
+ config[key] = v; continue
325
+ }
326
+ return err('BAD_REQUEST', 'invalid value for: ' + key)
327
+ }
328
+ return ok({ config })
329
+ }
330
+ return ok({ config })
331
+ })
332
+ harness.handle('actions', async () => ok({ actions: actionLog.slice(-50) }))
333
+ },
334
+ }