@gluztm/dsh-guard 2.4.1 → 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
@@ -3,12 +3,18 @@ import {
3
3
  PACKAGE_VERSION,
4
4
  RELEASE_URL,
5
5
  REPO_URL,
6
+ createSnapshot,
6
7
  formatHealthText,
7
8
  formatSnapshotsText,
8
9
  inspectHealth,
9
10
  inspectSnapshots,
10
11
  locateGuardInstallation,
11
12
  openGuard,
13
+ repairBrokenModuleLinks,
14
+ resolveDshHome,
15
+ restoreSnapshotConfig,
16
+ togglePatchEntry,
17
+ upsertCredentialKey,
12
18
  } from './inspector.mjs'
13
19
 
14
20
  let defineTool = (def) => def
@@ -23,6 +29,7 @@ try {
23
29
 
24
30
  const name = 'dsh-guard'
25
31
  const API_BASE = '/api/dsh-guard'
32
+ const MAX_JSON_BYTES = 32768
26
33
 
27
34
  function sendJson(res, status, value) {
28
35
  const body = JSON.stringify(value)
@@ -51,6 +58,92 @@ function isRequestAllowed(ctx, req, res) {
51
58
  return true
52
59
  }
53
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
+
54
147
  function buildRouteTable(ctx) {
55
148
  return [
56
149
  {
@@ -63,14 +156,15 @@ function buildRouteTable(ctx) {
63
156
  return
64
157
  }
65
158
  try {
66
- // 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.
67
160
  const health = inspectHealth({ target: 'all' })
68
- const snapshots = inspectSnapshots({ target: 'all', limit: 15 })
161
+ const snapshots = inspectSnapshots({ target: 'all', limit: 25 })
69
162
  sendJson(res, 200, {
70
163
  ok: true,
71
164
  version: PACKAGE_VERSION,
72
165
  platform: process.platform,
73
166
  installerUrl: INSTALLER_URL,
167
+ releaseUrl: RELEASE_URL,
74
168
  repoUrl: REPO_URL,
75
169
  health,
76
170
  snapshots,
@@ -84,30 +178,52 @@ function buildRouteTable(ctx) {
84
178
  }
85
179
  },
86
180
  },
87
- {
88
- path: `${API_BASE}/open`,
89
- handler: async (req, res) => {
90
- if (!isRequestAllowed(ctx, req, res)) return
91
- const method = String((req && req.method) || '').toUpperCase()
92
- if (method !== 'POST') {
93
- sendJson(res, 405, { ok: false, error: 'method_not_allowed' })
94
- return
95
- }
96
- try {
97
- const result = openGuard({ launch: true })
98
- sendJson(res, 200, {
99
- ok: true,
100
- platform: process.platform,
101
- ...result,
102
- })
103
- } catch (err) {
104
- sendJson(res, 500, {
105
- ok: false,
106
- error: err && err.message ? String(err.message) : 'internal_error',
107
- })
108
- }
109
- },
110
- },
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
+ }),
111
227
  ]
112
228
  }
113
229
 
@@ -116,9 +232,9 @@ function buildToolDefinitions() {
116
232
  defineTool({
117
233
  name: 'dsh_guard_status',
118
234
  description:
119
- 'Read-only health check for DSH Web and Desktop profiles: checks package.json bundle/dependency drift, '
120
- + 'cordis.patch.yml structural integrity, masked .credentials.yaml key readiness (never reads or exposes secret values), '
121
- + '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.',
122
238
  parameters: {
123
239
  target: {
124
240
  type: 'string',
@@ -155,8 +271,7 @@ function buildToolDefinitions() {
155
271
  defineTool({
156
272
  name: 'dsh_guard_snapshots',
157
273
  description:
158
- 'Read-only list of pre-change DSHGuard configuration and plugin snapshots stored on this Windows machine '
159
- + '(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).',
160
275
  parameters: {
161
276
  target: {
162
277
  type: 'string',
@@ -192,11 +307,50 @@ function buildToolDefinitions() {
192
307
  },
193
308
  }),
194
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
+
195
350
  defineTool({
196
351
  name: 'dsh_guard_open',
197
352
  description:
198
- 'Locate the local Windows out-of-band DSHGuard desktop supervisor executable or return its official release download link. '
199
- + '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.',
200
354
  parameters: {
201
355
  launch: {
202
356
  type: 'boolean',
@@ -217,7 +371,7 @@ function buildToolDefinitions() {
217
371
  },
218
372
  render: (_args, value) => [{
219
373
  type: 'text',
220
- text: value.message + (value.installed ? '' : `\n安装包直链:${value.installerUrl}\n发布页:${value.releaseUrl}`),
374
+ text: value.message + (value.installed ? '' : `\n安装包:${value.installerUrl}\n发布页:${value.releaseUrl}`),
221
375
  }],
222
376
  },
223
377
  async execute(args = {}) {
@@ -248,18 +402,28 @@ export function apply(ctx) {
248
402
  ctx.inject(['commands'], (cmdCtx) => {
249
403
  const dispose = cmdCtx.commands.register({
250
404
  name: 'guard',
251
- description: 'DSH 守护壳伴生命令:/guard [status|snapshots|open]',
252
- input: { hint: '[status|snapshots|open]' },
405
+ description: 'DSH 守护伴生命令:/guard [status|snapshots|backup [web|desktop|all]|open]',
406
+ input: { hint: '[status|snapshots|backup|open]' },
253
407
  async handler(invocation) {
254
- 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] || ''
255
411
  if (sub === 'snapshots' || sub === 'snap') {
256
412
  return { kind: 'success', text: formatSnapshotsText(inspectSnapshots({})) }
257
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
+ }
258
422
  if (sub === 'open') {
259
423
  const res = openGuard({ launch: true })
260
424
  return {
261
425
  kind: 'success',
262
- text: res.message + (res.installed ? '' : `\n安装包直链:${res.installerUrl || INSTALLER_URL}\n发布页:${res.releaseUrl}`),
426
+ text: res.message + (res.installed ? '' : `\n安装包:${res.installerUrl || INSTALLER_URL}\n发布页:${res.releaseUrl}`),
263
427
  }
264
428
  }
265
429
  return { kind: 'success', text: formatHealthText(inspectHealth({})) }
@@ -285,10 +449,15 @@ export function apply(ctx) {
285
449
  export {
286
450
  apply as default,
287
451
  name,
452
+ createSnapshot,
453
+ formatHealthText,
454
+ formatSnapshotsText,
288
455
  inspectHealth,
289
456
  inspectSnapshots,
290
457
  locateGuardInstallation,
291
458
  openGuard,
292
- formatHealthText,
293
- formatSnapshotsText,
459
+ repairBrokenModuleLinks,
460
+ restoreSnapshotConfig,
461
+ togglePatchEntry,
462
+ upsertCredentialKey,
294
463
  }