@gluztm/dsh-guard 2.4.0 → 2.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/lib/index.mjs CHANGED
@@ -1,11 +1,20 @@
1
1
  import {
2
+ INSTALLER_URL,
3
+ PACKAGE_VERSION,
2
4
  RELEASE_URL,
5
+ REPO_URL,
6
+ createSnapshot,
3
7
  formatHealthText,
4
8
  formatSnapshotsText,
5
9
  inspectHealth,
6
10
  inspectSnapshots,
7
11
  locateGuardInstallation,
8
12
  openGuard,
13
+ repairBrokenModuleLinks,
14
+ resolveDshHome,
15
+ restoreSnapshotConfig,
16
+ togglePatchEntry,
17
+ upsertCredentialKey,
9
18
  } from './inspector.mjs'
10
19
 
11
20
  let defineTool = (def) => def
@@ -20,6 +29,7 @@ try {
20
29
 
21
30
  const name = 'dsh-guard'
22
31
  const API_BASE = '/api/dsh-guard'
32
+ const MAX_JSON_BYTES = 32768
23
33
 
24
34
  function sendJson(res, status, value) {
25
35
  const body = JSON.stringify(value)
@@ -48,6 +58,92 @@ function isRequestAllowed(ctx, req, res) {
48
58
  return true
49
59
  }
50
60
 
61
+ async function readJsonBody(req, maxBytes = MAX_JSON_BYTES) {
62
+ if (req && req.body && typeof req.body === 'object' && !Buffer.isBuffer(req.body)) {
63
+ return req.body
64
+ }
65
+ if (!req || typeof req.on !== 'function') {
66
+ return {}
67
+ }
68
+ return await new Promise((resolve, reject) => {
69
+ const chunks = []
70
+ let total = 0
71
+ let finished = false
72
+ req.on('data', (chunk) => {
73
+ if (finished) return
74
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')
75
+ total += buf.length
76
+ if (total > maxBytes) {
77
+ finished = true
78
+ reject(Object.assign(new Error('payload_too_large'), { status: 413 }))
79
+ return
80
+ }
81
+ chunks.push(buf)
82
+ })
83
+ req.on('end', () => {
84
+ if (finished) return
85
+ finished = true
86
+ const raw = Buffer.concat(chunks).toString('utf8').trim()
87
+ if (!raw) {
88
+ resolve({})
89
+ return
90
+ }
91
+ try {
92
+ const parsed = JSON.parse(raw)
93
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
94
+ reject(Object.assign(new Error('invalid_json_object'), { status: 400 }))
95
+ return
96
+ }
97
+ resolve(parsed)
98
+ } catch {
99
+ reject(Object.assign(new Error('invalid_json'), { status: 400 }))
100
+ }
101
+ })
102
+ req.on('error', (err) => {
103
+ if (finished) return
104
+ finished = true
105
+ reject(err)
106
+ })
107
+ })
108
+ }
109
+
110
+ function makePostRoute(ctx, routePath, handler) {
111
+ return {
112
+ path: `${API_BASE}${routePath}`,
113
+ handler: async (req, res) => {
114
+ if (!isRequestAllowed(ctx, req, res)) return
115
+ const method = String((req && req.method) || '').toUpperCase()
116
+ if (method !== 'POST') {
117
+ sendJson(res, 405, { ok: false, error: 'method_not_allowed' })
118
+ return
119
+ }
120
+ let body
121
+ try {
122
+ body = await readJsonBody(req)
123
+ } catch (err) {
124
+ sendJson(res, err && err.status ? err.status : 400, {
125
+ ok: false,
126
+ error: err && err.message ? String(err.message) : 'invalid_request_body',
127
+ })
128
+ return
129
+ }
130
+ try {
131
+ const result = await handler(body)
132
+ if (result && result.ok === false) {
133
+ sendJson(res, 400, result)
134
+ return
135
+ }
136
+ sendJson(res, 200, { ok: true, ...(result || {}) })
137
+ } catch (err) {
138
+ sendJson(res, 500, {
139
+ ok: false,
140
+ error: err && err.message ? String(err.message) : 'internal_error',
141
+ })
142
+ }
143
+ },
144
+ }
145
+ }
146
+
51
147
  function buildRouteTable(ctx) {
52
148
  return [
53
149
  {
@@ -60,12 +156,16 @@ function buildRouteTable(ctx) {
60
156
  return
61
157
  }
62
158
  try {
63
- // Server-side env vars only (DSH_HOME / DSHGUARD_HOME); never accept path traversal params from HTTP requests.
159
+ // Server-side env vars only (DSH_HOME / DSHGUARD_HOME); never accept path params from HTTP requests.
64
160
  const health = inspectHealth({ target: 'all' })
65
- const snapshots = inspectSnapshots({ target: 'all', limit: 15 })
161
+ const snapshots = inspectSnapshots({ target: 'all', limit: 25 })
66
162
  sendJson(res, 200, {
67
163
  ok: true,
164
+ version: PACKAGE_VERSION,
68
165
  platform: process.platform,
166
+ installerUrl: INSTALLER_URL,
167
+ releaseUrl: RELEASE_URL,
168
+ repoUrl: REPO_URL,
69
169
  health,
70
170
  snapshots,
71
171
  checkedAt: Date.now(),
@@ -78,30 +178,52 @@ function buildRouteTable(ctx) {
78
178
  }
79
179
  },
80
180
  },
81
- {
82
- path: `${API_BASE}/open`,
83
- handler: async (req, res) => {
84
- if (!isRequestAllowed(ctx, req, res)) return
85
- const method = String((req && req.method) || '').toUpperCase()
86
- if (method !== 'POST') {
87
- sendJson(res, 405, { ok: false, error: 'method_not_allowed' })
88
- return
89
- }
90
- try {
91
- const result = openGuard({ launch: true })
92
- sendJson(res, 200, {
93
- ok: true,
94
- platform: process.platform,
95
- ...result,
96
- })
97
- } catch (err) {
98
- sendJson(res, 500, {
99
- ok: false,
100
- error: err && err.message ? String(err.message) : 'internal_error',
101
- })
102
- }
103
- },
104
- },
181
+
182
+ makePostRoute(ctx, '/open', async () => {
183
+ const res = openGuard({ launch: true })
184
+ return {
185
+ ok: true,
186
+ platform: process.platform,
187
+ ...res,
188
+ }
189
+ }),
190
+
191
+ makePostRoute(ctx, '/snapshots/create', async (body) => {
192
+ const target = body.target === 'desktop' || body.target === 'all' ? body.target : 'web'
193
+ const reason = typeof body.reason === 'string' ? body.reason.slice(0, 120) : ''
194
+ return createSnapshot(resolveDshHome(), target, 'manual', reason)
195
+ }),
196
+
197
+ makePostRoute(ctx, '/snapshots/restore-config', async (body) => {
198
+ const snapshotId = typeof body.snapshotId === 'string' ? body.snapshotId.trim() : ''
199
+ return restoreSnapshotConfig(resolveDshHome(), locateGuardInstallation(), snapshotId)
200
+ }),
201
+
202
+ makePostRoute(ctx, '/toggle-entry', async (body) => {
203
+ const target = body.target === 'desktop' ? 'desktop' : 'web'
204
+ const id = typeof body.id === 'string' ? body.id.trim() : ''
205
+ const disabled = Boolean(body.disabled)
206
+ return togglePatchEntry(resolveDshHome(), target, id, disabled, locateGuardInstallation())
207
+ }),
208
+
209
+ makePostRoute(ctx, '/repair-links', async (body) => {
210
+ const target = body.target === 'desktop' ? 'desktop' : 'web'
211
+ return repairBrokenModuleLinks(resolveDshHome(), target)
212
+ }),
213
+
214
+ makePostRoute(ctx, '/credential-key', async (body) => {
215
+ const key = typeof body.key === 'string' ? body.key : ''
216
+ const value = typeof body.value === 'string' ? body.value : ''
217
+ const res = upsertCredentialKey(resolveDshHome(), key, value)
218
+ if (!res.ok) return res
219
+ // Strict one-way write: never echo secret value or partial characters back over HTTP.
220
+ return {
221
+ ok: true,
222
+ key: res.key,
223
+ path: res.path,
224
+ created: Boolean(res.created),
225
+ }
226
+ }),
105
227
  ]
106
228
  }
107
229
 
@@ -110,9 +232,9 @@ function buildToolDefinitions() {
110
232
  defineTool({
111
233
  name: 'dsh_guard_status',
112
234
  description:
113
- 'Read-only health check for DSH Web and Desktop profiles: checks package.json bundle/dependency drift, '
114
- + 'cordis.patch.yml structural integrity, masked .credentials.yaml key readiness (never reads or exposes secret values), '
115
- + 'and local Windows DSHGuard supervisor installation status.',
235
+ 'Check DSH Web and Desktop profiles in-process: checks package.json dependency drift, broken module links, '
236
+ + 'cordis.patch.yml plugins/MCP/llm-pi-ai readiness, masked .credentials.yaml key readiness (never exposes secret values), '
237
+ + 'and local snapshot availability.',
116
238
  parameters: {
117
239
  target: {
118
240
  type: 'string',
@@ -149,8 +271,7 @@ function buildToolDefinitions() {
149
271
  defineTool({
150
272
  name: 'dsh_guard_snapshots',
151
273
  description:
152
- 'Read-only list of pre-change DSHGuard configuration and plugin snapshots stored on this Windows machine '
153
- + '(separated by Web and Desktop tracks).',
274
+ 'List plugin and desktop DSH configuration snapshots stored locally (separated by Web and Desktop tracks, with live file diff status).',
154
275
  parameters: {
155
276
  target: {
156
277
  type: 'string',
@@ -186,11 +307,50 @@ function buildToolDefinitions() {
186
307
  },
187
308
  }),
188
309
 
310
+ defineTool({
311
+ name: 'dsh_guard_backup',
312
+ description:
313
+ 'Create a safe configuration snapshot (cordis.patch.yml, cordis.yml, package.json, settings.yaml; never copies .credentials.yaml) directly inside the companion plugin.',
314
+ parameters: {
315
+ target: {
316
+ type: 'string',
317
+ enum: ['web', 'desktop', 'all'],
318
+ description: 'Which profile config files to back up (default: web).',
319
+ },
320
+ reason: {
321
+ type: 'string',
322
+ description: 'Short label for this manual backup snapshot.',
323
+ },
324
+ },
325
+ output: {
326
+ schema: {
327
+ type: 'object',
328
+ additionalProperties: false,
329
+ properties: {
330
+ ok: { type: 'boolean', required: true },
331
+ snapshotId: { type: 'string', required: true },
332
+ itemCount: { type: 'integer', required: true },
333
+ summary: { type: 'string', required: true },
334
+ },
335
+ },
336
+ render: (_args, value) => [{ type: 'text', text: value.summary }],
337
+ },
338
+ async execute(args = {}) {
339
+ const target = args.target === 'desktop' || args.target === 'all' ? args.target : 'web'
340
+ const res = createSnapshot(resolveDshHome(), target, 'manual', args.reason || 'Agent 手动配置备份')
341
+ return {
342
+ ok: Boolean(res.ok),
343
+ snapshotId: res.snapshot.id,
344
+ itemCount: res.snapshot.itemCount,
345
+ summary: `已生成配置快照 ${res.snapshot.id}(包含 ${res.snapshot.itemCount} 个配置文件,已自动排除 .credentials.yaml)。`,
346
+ }
347
+ },
348
+ }),
349
+
189
350
  defineTool({
190
351
  name: 'dsh_guard_open',
191
352
  description:
192
- 'Locate the local Windows out-of-band DSHGuard desktop supervisor executable or return its official release download link. '
193
- + 'Pass launch=true only when the user asks to open the DSHGuard GUI window for snapshot rollback, credential vault, or CC Switch import.',
353
+ 'Locate or launch the optional Windows out-of-band DSHGuard desktop supervisor when process isolation, Windows DPAPI vault, or running-bundle rollback is needed.',
194
354
  parameters: {
195
355
  launch: {
196
356
  type: 'boolean',
@@ -206,9 +366,13 @@ function buildToolDefinitions() {
206
366
  launched: { type: 'boolean', required: true },
207
367
  message: { type: 'string', required: true },
208
368
  releaseUrl: { type: 'string', required: true },
369
+ installerUrl: { type: 'string', required: true },
209
370
  },
210
371
  },
211
- render: (_args, value) => [{ type: 'text', text: value.message + (value.installed ? '' : `\n下载链接:${value.releaseUrl}`) }],
372
+ render: (_args, value) => [{
373
+ type: 'text',
374
+ text: value.message + (value.installed ? '' : `\n安装包:${value.installerUrl}\n发布页:${value.releaseUrl}`),
375
+ }],
212
376
  },
213
377
  async execute(args = {}) {
214
378
  const res = openGuard({ launch: Boolean(args.launch) })
@@ -217,6 +381,7 @@ function buildToolDefinitions() {
217
381
  launched: res.launched,
218
382
  message: res.message,
219
383
  releaseUrl: res.releaseUrl,
384
+ installerUrl: res.installerUrl || INSTALLER_URL,
220
385
  }
221
386
  },
222
387
  }),
@@ -237,18 +402,28 @@ export function apply(ctx) {
237
402
  ctx.inject(['commands'], (cmdCtx) => {
238
403
  const dispose = cmdCtx.commands.register({
239
404
  name: 'guard',
240
- description: 'DSH 守护壳伴生命令:/guard [status|snapshots|open]',
241
- input: { hint: '[status|snapshots|open]' },
405
+ description: 'DSH 守护伴生命令:/guard [status|snapshots|backup [web|desktop|all]|open]',
406
+ input: { hint: '[status|snapshots|backup|open]' },
242
407
  async handler(invocation) {
243
- const sub = String((invocation && invocation.rawInput) || '').trim().toLowerCase()
408
+ const raw = String((invocation && invocation.rawInput) || '').trim()
409
+ const parts = raw ? raw.toLowerCase().split(/\s+/) : []
410
+ const sub = parts[0] || ''
244
411
  if (sub === 'snapshots' || sub === 'snap') {
245
412
  return { kind: 'success', text: formatSnapshotsText(inspectSnapshots({})) }
246
413
  }
414
+ if (sub === 'backup') {
415
+ const t = parts[1] === 'desktop' || parts[1] === 'all' ? parts[1] : 'web'
416
+ const res = createSnapshot(resolveDshHome(), t, 'manual', '命令 /guard backup 创建')
417
+ return {
418
+ kind: 'success',
419
+ text: `已创建配置快照 ${res.snapshot.id}(${res.snapshot.target} · ${res.snapshot.itemCount} 个文件,已自动跳过 .credentials.yaml)`,
420
+ }
421
+ }
247
422
  if (sub === 'open') {
248
423
  const res = openGuard({ launch: true })
249
424
  return {
250
425
  kind: 'success',
251
- text: res.message + (res.installed ? '' : `\n下载地址:${res.releaseUrl}`),
426
+ text: res.message + (res.installed ? '' : `\n安装包:${res.installerUrl || INSTALLER_URL}\n发布页:${res.releaseUrl}`),
252
427
  }
253
428
  }
254
429
  return { kind: 'success', text: formatHealthText(inspectHealth({})) }
@@ -274,10 +449,15 @@ export function apply(ctx) {
274
449
  export {
275
450
  apply as default,
276
451
  name,
452
+ createSnapshot,
453
+ formatHealthText,
454
+ formatSnapshotsText,
277
455
  inspectHealth,
278
456
  inspectSnapshots,
279
457
  locateGuardInstallation,
280
458
  openGuard,
281
- formatHealthText,
282
- formatSnapshotsText,
459
+ repairBrokenModuleLinks,
460
+ restoreSnapshotConfig,
461
+ togglePatchEntry,
462
+ upsertCredentialKey,
283
463
  }