dsh-vigil 0.0.1

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.
Files changed (56) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +188 -0
  3. package/client.js +4652 -0
  4. package/cordis.patch.yml +7 -0
  5. package/docs/DETAIL.md +66 -0
  6. package/icon.png +0 -0
  7. package/illustrations/notice.png +0 -0
  8. package/illustrations/warning.png +0 -0
  9. package/locale/en.json +7 -0
  10. package/locale/zh.json +7 -0
  11. package/package.json +75 -0
  12. package/rules/audit.yaml +130 -0
  13. package/rules/manifest.json +7 -0
  14. package/rules/sentinel.yaml +289 -0
  15. package/src/alert-route.js +194 -0
  16. package/src/approval.js +398 -0
  17. package/src/artwork-route.js +87 -0
  18. package/src/audit/ast.js +213 -0
  19. package/src/audit/install-scan.js +127 -0
  20. package/src/audit/lexer.js +307 -0
  21. package/src/audit/narrative.js +320 -0
  22. package/src/audit/rules.js +1440 -0
  23. package/src/audit/scan.js +880 -0
  24. package/src/audit-clear-route.js +89 -0
  25. package/src/audit-feed.js +265 -0
  26. package/src/audit-log.js +887 -0
  27. package/src/config-schema.js +194 -0
  28. package/src/config.js +580 -0
  29. package/src/delete/command-kinds.js +46 -0
  30. package/src/delete/lex.js +46 -0
  31. package/src/delete/parser-posix.js +1427 -0
  32. package/src/delete/parser-pwsh.js +1729 -0
  33. package/src/delete/parser.js +2082 -0
  34. package/src/delete/policy.js +680 -0
  35. package/src/delete/quarantine.js +417 -0
  36. package/src/index.js +1134 -0
  37. package/src/install-scan-route.js +58 -0
  38. package/src/install-watch.js +389 -0
  39. package/src/integrity.js +509 -0
  40. package/src/live-config.js +88 -0
  41. package/src/quarantine-route.js +74 -0
  42. package/src/quarantine-view.js +44 -0
  43. package/src/rules/pack.js +423 -0
  44. package/src/rules/update.js +341 -0
  45. package/src/rules/yaml.js +186 -0
  46. package/src/sage-action-route.js +63 -0
  47. package/src/sage-provision.js +716 -0
  48. package/src/sentinel/guard.js +392 -0
  49. package/src/sentinel/hook.js +546 -0
  50. package/src/sentinel/rules.js +488 -0
  51. package/src/sentinel/sage-load.js +79 -0
  52. package/src/sentinel/sage.js +550 -0
  53. package/src/tools.js +727 -0
  54. package/src/update-check.js +339 -0
  55. package/src/util.js +400 -0
  56. package/threats/README.md +25 -0
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Self-protection (FR-5.5).
3
+ *
4
+ * Two layers share one inspection:
5
+ *
6
+ * - `tools/pre-execute` (the sentinel) reports the hit so it can be audited
7
+ * and — when `selfProtection: 'ask'` — parked for an in-conversation
8
+ * approval;
9
+ * - `ctx.tools.guard()` is monotonic and can only deny, so it enforces the
10
+ * shipped default: neither the installed plugin directory nor dsh-vigil's
11
+ * own state (quarantine, audit log, integrity baseline) may be deleted or
12
+ * moved by a tool call, and the agent may not uninstall/replace dsh-vigil
13
+ * through a plugin-manager tool call.
14
+ *
15
+ * `selfProtection: 'ask'` turns the guard into a no-op for these hits and lets
16
+ * the normal decision path ask the user (允许 / 拒绝 in the composer). The
17
+ * explicit opt-out for plugin-manager removal stays `allowSelfUninstall: true`.
18
+ *
19
+ * `selfProtection: 'deny'` (the default) also rejects tool call that write or
20
+ * edit files inside those directories. The guard is monotonic and can only
21
+ * deny, so the plugin's own files cannot be rewritten by the agent; setting it
22
+ * to `ask` parks the call for an in-conversation allow/deny instead. The
23
+ * explicit opt-out for plugin-manager removal stays `allowSelfUninstall: true`.
24
+ *
25
+ * Known limits, kept honest in the README:
26
+ * - delete/move targets are judged by the parsed intent (with `cd` operands
27
+ * ignored); write/edit checks still compare path tokens, so a shell command
28
+ * that writes a relative path after `cd` into the plugin dir is judged by
29
+ * the text mention (and is therefore refused, not missed);
30
+ * - runtime-computed targets such as `(Join-Path ...)` cannot be resolved, so
31
+ * they fall back to the conservative text check;
32
+ * - the checks only see model tool calls, not UI actions that call the plugin
33
+ * manager Remote service directly;
34
+ * - the emergency kill switch (`DSH_VIGIL_DISABLED` / `DISABLED` file) bypasses
35
+ * both layers, because a protection that cannot be turned off is a liability.
36
+ *
37
+ * @module dsh-vigil/guard
38
+ */
39
+
40
+ import { basename, relative, resolve } from 'node:path'
41
+ import { canonicalizePath, getHomeDir, isWithin, pathKey } from '../util.js'
42
+ import { parseDeleteIntent } from '../delete/parser.js'
43
+ import { isMoveCommand } from '../delete/command-kinds.js'
44
+
45
+ const DESTRUCTIVE_VERB = /\b(?:rm|rmdir|del|erase|rd|remove-item|remove|unlink|mv|move|move-item|ren|rename|rename-item|trash|shred|delete|robocopy(?:\s+\S+){2}\s+\/mir|\/mir)\b/i
46
+ const WRITE_VERB = /\b(?:set-content|add-content|out-file|tee-object|tee|new-item|touch|copy-item|move-item|rename-item|mkdir|robocopy|xcopy|clear-content|sed\s+-i|perl\s+-pi|apply_patch|git\s+(?:apply|checkout|reset|clean)|npm\s+(?:install|ci|uninstall|update)|pnpm\s+(?:add|install|remove|update)|yarn\s+(?:add|install|remove))\b/i
47
+ const PATH_TOOL = /^(?:delete_file|remove_file|delete|remove|unlink|move_file|move|rename|trash)$/i
48
+ const WRITE_PATH_TOOL = /^(?:write|write_file|edit|edit_file|patch|apply_patch|applypatch|create_file|multi_edit|update_file|str_replace_editor|insert_text|replace_text)$/i
49
+ const MANAGER_TOOL = /^(?:plugin_manager|plugin-manager|dsh_plugin_manager)$/i
50
+
51
+ /**
52
+ * @param {unknown} value
53
+ * @returns {string}
54
+ */
55
+ function safeStringify(value) {
56
+ try {
57
+ const text = JSON.stringify(value ?? {})
58
+ return typeof text === 'string' ? text.slice(0, 20000) : ''
59
+ } catch {
60
+ return ''
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Inspect one execution for a self-protection hit.
66
+ * @param {{ name: string, arguments?: unknown }} execution
67
+ * @param {{ config: any, pluginDir: string, logger?: { warn?: (message: string) => void } }} options
68
+ * @returns {{ kind: 'deny'|'ask', ruleId: 'VG-GUARD-01', reason: string } | null}
69
+ */
70
+ export function inspectSelfProtection(execution, options) {
71
+ try {
72
+ const config = options.config ?? {}
73
+ const pluginDir = options.pluginDir
74
+ const stateDir = config?.paths?.stateDir ?? ''
75
+ const protectedDirs = [pluginDir, stateDir]
76
+ .filter(value => typeof value === 'string' && value !== '')
77
+ .map(value => canonicalizePath(value))
78
+ .filter(value => value !== '')
79
+ if (protectedDirs.length === 0) return null
80
+ const decision = config?.selfProtection === 'ask' ? 'ask' : 'deny'
81
+ const allowUninstall = config?.allowSelfUninstall === true
82
+ // Alternative spellings of the protected directories (`~/…`, forward
83
+ // slashes). Canonical comparison covers 8.3 names and `\\?\`; these cover
84
+ // the shell forms that never reach the filesystem untouched.
85
+ const homeDir = getHomeDir()
86
+ const protectedSpellings = protectedDirs.flatMap(dir => {
87
+ const spellings = [pathKey(dir).replace(/\\/g, '/')]
88
+ if (homeDir && isWithin(homeDir, dir)) {
89
+ const rel = relative(homeDir, dir).split('\\').join('/')
90
+ spellings.push(pathKey(`~/${rel}`).replace(/\\/g, '/'))
91
+ }
92
+ return spellings
93
+ })
94
+
95
+ /**
96
+ * @param {string} pathValue
97
+ * @returns {string|null}
98
+ */
99
+ function protectedHit(pathValue) {
100
+ if (typeof pathValue !== 'string' || pathValue.trim() === '') return null
101
+ const absoluteLike = pathValue.startsWith('/')
102
+ || /^[A-Za-z]:[\\/]/.test(pathValue)
103
+ || pathValue.startsWith('\\\\')
104
+ || pathValue.startsWith('~')
105
+ || /^\$env:/i.test(pathValue)
106
+ || /^%[A-Za-z_][A-Za-z0-9_]*%/.test(pathValue)
107
+ const expanded = absoluteLike ? pathValue : resolve(process.cwd(), pathValue)
108
+ const candidate = canonicalizePath(expanded)
109
+ if (candidate === '') return null
110
+ const key = pathKey(candidate)
111
+ for (const dir of protectedDirs) {
112
+ const dirKey = pathKey(dir)
113
+ if (key === dirKey || key.startsWith(`${dirKey}\\`) || key.startsWith(`${dirKey}/`)) return dirKey
114
+ }
115
+ return null
116
+ }
117
+
118
+ /**
119
+ * Path-like tokens of a shell command, for canonical comparison.
120
+ * @param {string} text
121
+ * @returns {string[]}
122
+ */
123
+ function commandPathTokens(text) {
124
+ /** @type {string[]} */
125
+ const tokens = []
126
+ const pattern = /(?:'[^']*'|"[^"]*"|[^\s;|&<>()]+)/g
127
+ let match
128
+ while ((match = pattern.exec(text)) !== null) {
129
+ const value = match[0].replace(/^['"]|['"]$/g, '')
130
+ if (value === '') continue
131
+ if (!/[\\/]|^~|^%[A-Za-z_]|^\$env:/i.test(value)) continue
132
+ tokens.push(value)
133
+ }
134
+ return tokens
135
+ }
136
+
137
+ /**
138
+ * @param {string} text
139
+ * @returns {string|null}
140
+ */
141
+ function commandMentionsProtected(text) {
142
+ if (typeof text !== 'string' || text === '') return null
143
+ const normalized = pathKey(text).replace(/\\/g, '/')
144
+ for (const spelling of protectedSpellings) {
145
+ if (normalized.includes(spelling)) return spelling
146
+ }
147
+ for (const token of commandPathTokens(text)) {
148
+ const hit = protectedHit(token)
149
+ if (hit) return hit
150
+ }
151
+ return null
152
+ }
153
+
154
+ /**
155
+ * @param {string} text
156
+ * @returns {string|null}
157
+ */
158
+ function protectedCommandWriteHit(text) {
159
+ if (typeof text !== 'string' || text === '') return null
160
+ if (!WRITE_VERB.test(text)) return null
161
+ return commandMentionsProtected(text)
162
+ }
163
+
164
+ /**
165
+ * Resolve one path-like argument (optionally relative to an explicit cwd)
166
+ * and report the protected directory it points inside.
167
+ * @param {unknown} value
168
+ * @param {string} cwd
169
+ * @returns {string|null}
170
+ */
171
+ function writePathHit(value, cwd) {
172
+ if (typeof value !== 'string' || value.trim() === '') return null
173
+ const absolute = /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('/') || value.startsWith('\\\\')
174
+ const candidate = absolute || cwd === '' ? value : resolve(cwd, value)
175
+ return protectedHit(candidate)
176
+ }
177
+
178
+
179
+ /**
180
+ * @param {string} text
181
+ * @returns {string|null}
182
+ */
183
+ function protectedCommandHit(text) {
184
+ if (typeof text !== 'string' || text === '') return null
185
+ if (!DESTRUCTIVE_VERB.test(text)) return null
186
+ return commandMentionsProtected(text)
187
+ }
188
+
189
+ /**
190
+ * Effective working directory after leading `cd` / `Set-Location` calls.
191
+ * A relative target after `cd <pluginDir>` must be resolved against it,
192
+ * otherwise self-protection would judge the wrong file.
193
+ * @param {string} text
194
+ * @param {string} baseCwd
195
+ * @returns {string}
196
+ */
197
+ function effectiveShellCwd(text, baseCwd) {
198
+ let cwd = baseCwd
199
+ for (const rawSegment of String(text ?? '').split(/[;&|\n]+/)) {
200
+ const segment = rawSegment.trim()
201
+ const match = /^(?:cd|chdir|pushd|set-location|sl)\b\s+(?:'([^']*)'|"([^"]*)"|([^\s]+))/i.exec(segment)
202
+ if (!match) continue
203
+ const value = match[1] ?? match[2] ?? match[3] ?? ''
204
+ // Variables/percent-expansions are not resolved here; keep the base.
205
+ if (value === '' || /^\$/.test(value) || /%[A-Za-z_][A-Za-z0-9_]*%/.test(value)) continue
206
+ try {
207
+ cwd = /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('/') || value.startsWith('\\\\')
208
+ ? resolve(value)
209
+ : resolve(cwd, value)
210
+ } catch {
211
+ // keep the previous cwd
212
+ }
213
+ }
214
+ return cwd
215
+ }
216
+
217
+ /**
218
+ * Drop `cd <dir>` operands: a chdir argument is not a delete target, and
219
+ * treating it as one is what made `cd <pluginDir>; Remove-Item %TEMP%\x`
220
+ * look like self-modification.
221
+ * @param {string} text
222
+ * @returns {string}
223
+ */
224
+ function withoutCwdOperands(text) {
225
+ return String(text ?? '').replace(
226
+ /(^|[;&|]\s*|then\s+)(?:cd|chdir|pushd|set-location|sl)\b\s+(?:'[^']*'|"[^"]*"|[^\s;|&]+)/gi,
227
+ '$1',
228
+ )
229
+ }
230
+
231
+ const toolName = typeof execution?.name === 'string' ? execution.name : ''
232
+ if (toolName === '' || toolName.startsWith('vigil_')) return null
233
+ const args = execution?.arguments && typeof execution.arguments === 'object'
234
+ ? /** @type {Record<string, any>} */ (execution.arguments)
235
+ : {}
236
+ const serialized = safeStringify(args)
237
+
238
+ /**
239
+ * @param {string} verb 删除 or 移动
240
+ * @param {string} where
241
+ * @returns {{ kind: 'deny'|'ask', ruleId: 'VG-GUARD-01', reason: string }}
242
+ */
243
+ const hit = (where, what) => ({
244
+ kind: decision,
245
+ ruleId: 'VG-GUARD-01',
246
+ reason: `守夜人 自保护:${what}(${where})${decision === 'deny' ? ',已拦截(FR-5.5)' : ',需要你确认(FR-5.5)'}`,
247
+ })
248
+
249
+ // Deletion / move of plugin files or plugin state.
250
+ if (PATH_TOOL.test(toolName)) {
251
+ for (const key of ['path', 'file_path', 'target', 'targetPath', 'destination', 'destination_path', 'source']) {
252
+ const pathHit = protectedHit(args[key])
253
+ if (pathHit) return hit(basename(pathHit), '该调用会删除或移动 dsh-vigil 自身目录/状态目录')
254
+ }
255
+ for (const listKey of ['paths', 'files']) {
256
+ if (!Array.isArray(args[listKey])) continue
257
+ for (const item of args[listKey]) {
258
+ const pathHit = protectedHit(item)
259
+ if (pathHit) return hit(basename(pathHit), '该调用会删除或移动 dsh-vigil 自身目录/状态目录')
260
+ }
261
+ }
262
+ }
263
+
264
+ // Writes / edits of plugin files or plugin state.
265
+ if (WRITE_PATH_TOOL.test(toolName)) {
266
+ const cwd = typeof args.cwd === 'string' ? args.cwd : ''
267
+ for (const key of ['path', 'file_path', 'target', 'targetPath', 'file', 'destination', 'destination_path', 'dir', 'directory']) {
268
+ const pathHit = writePathHit(args[key], cwd)
269
+ if (pathHit) return hit(basename(pathHit), '该调用会写入/修改 dsh-vigil 自身目录或状态目录')
270
+ }
271
+ for (const listKey of ['paths', 'files']) {
272
+ if (!Array.isArray(args[listKey])) continue
273
+ for (const item of args[listKey]) {
274
+ const pathHit = writePathHit(item, cwd)
275
+ if (pathHit) return hit(basename(pathHit), '该调用会写入/修改 dsh-vigil 自身目录或状态目录')
276
+ }
277
+ }
278
+ }
279
+
280
+ // Shell command that removes or moves the protected paths. Judge the parsed
281
+ // targets first: a `cd <pluginDir>` operand is not a delete target, so it
282
+ // must not turn an unrelated cleanup into a self-protection hit.
283
+ if (typeof args.command === 'string' || args.cmd === 'string' || typeof args.script === 'string') {
284
+ const command = args.command ?? args.cmd ?? args.script
285
+ const baseCwd = typeof args.workdir === 'string' && args.workdir !== ''
286
+ ? args.workdir
287
+ : typeof args.cwd === 'string' && args.cwd !== ''
288
+ ? args.cwd
289
+ : typeof args.workingDirectory === 'string' && args.workingDirectory !== ''
290
+ ? args.workingDirectory
291
+ : process.cwd()
292
+ const commandCwd = effectiveShellCwd(command, baseCwd)
293
+ /** @type {any} */
294
+ let intent = null
295
+ try {
296
+ intent = parseDeleteIntent(command, {
297
+ cwd: commandCwd,
298
+ homeDir: getHomeDir(),
299
+ env: process.env,
300
+ platform: process.platform,
301
+ })
302
+ } catch {
303
+ intent = null
304
+ }
305
+ const mention = text => protectedCommandHit(withoutCwdOperands(text))
306
+ const moveDelete = (intent?.statements ?? []).filter(statement =>
307
+ statement.isDelete === true
308
+ || statement.deleteKind === 'move'
309
+ || isMoveCommand(statement.command))
310
+ if (moveDelete.length > 0) {
311
+ let where = null
312
+ for (const statement of moveDelete) {
313
+ for (const target of statement.targets ?? []) {
314
+ if (typeof target?.resolvedPath !== 'string') continue
315
+ where = protectedHit(target.resolvedPath)
316
+ if (where) break
317
+ }
318
+ if (where) break
319
+ }
320
+ if (where) return hit(basename(where), '该命令会删除或移动 dsh-vigil 自身目录/状态目录')
321
+ const unresolved = moveDelete.some(statement => statement.unparsed === true)
322
+ const anyResolved = moveDelete.some(statement => (statement.targets ?? []).some(target => typeof target?.resolvedPath === 'string'))
323
+ if (unresolved || !anyResolved) {
324
+ const whereFallback = mention(command)
325
+ if (whereFallback) return hit(basename(whereFallback), '该命令会删除或移动 dsh-vigil 自身目录/状态目录')
326
+ }
327
+ } else if (intent !== null) {
328
+ // No parsed destructive statement. Only a command that actually carries
329
+ // a destructive verb may fall back to the text check; otherwise a plain
330
+ // command running with the plugin dir as cwd would be refused.
331
+ if (DESTRUCTIVE_VERB.test(command)) {
332
+ const whereFallback = mention(command)
333
+ if (whereFallback) return hit(basename(whereFallback), '该命令会删除或移动 dsh-vigil 自身目录/状态目录')
334
+ }
335
+ } else {
336
+ if (DESTRUCTIVE_VERB.test(command)) {
337
+ const whereFallback = mention(command)
338
+ if (whereFallback) return hit(basename(whereFallback), '该命令会删除或移动 dsh-vigil 自身目录/状态目录')
339
+ }
340
+ }
341
+ const writeCommandHit = protectedCommandWriteHit(command)
342
+ if (writeCommandHit) return hit(basename(writeCommandHit), '该命令会写入/修改 dsh-vigil 自身目录或状态目录')
343
+ }
344
+
345
+ // Plugin manager: any mutation of this package (install/update/remove/
346
+ // disable/enable) is self-modification. Read-only listings stay allowed.
347
+ if (MANAGER_TOOL.test(toolName) && !allowUninstall) {
348
+ const action = typeof args.action === 'string' ? args.action.toLowerCase() : ''
349
+ const mentionsSelf = /dsh-vigil/i.test(serialized)
350
+ const readOnly = action === '' || /^(?:list|get|status|info|search|read|inspect|check|versions?)/i.test(action)
351
+ if (mentionsSelf && !readOnly) {
352
+ return hit('plugin_manager', '不允许通过工具卸载、停用、替换或修改 dsh-vigil 自身;若要停用,请设置 config.allowSelfUninstall=true 或使用停机开关')
353
+ }
354
+ }
355
+
356
+ return null
357
+ } catch (error) {
358
+ options.logger?.warn?.(`[dsh-vigil] 自保护检查异常:${error instanceof Error ? error.message : String(error)}`)
359
+ return null
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Build the monotonic guard for the shipped default (`deny`). In `ask` mode it
365
+ * returns `undefined` so the sentinel's normal pipeline can ask the user.
366
+ * @param {object} options
367
+ * @param {any} options.config resolved configuration
368
+ * @param {string} options.pluginDir installed package directory
369
+ * @param {(now?: number) => boolean} [options.isDisabled]
370
+ * @param {{ warn?: (message: string) => void }} [options.logger]
371
+ * @returns {(execution: { name: string, arguments?: unknown }) => string | undefined}
372
+ */
373
+ export function createSelfGuard(options) {
374
+ return execution => {
375
+ try {
376
+ if (options.isDisabled?.()) return undefined
377
+ // Documented invariant (docs/ARCHITECTURE.md): monitor mode records what it
378
+ // would have decided and never blocks. The guard is monotonic, so it has to
379
+ // step aside here explicitly — otherwise `mode: monitor` would still deny
380
+ // self-protection hits even though the sentinel already allowed them.
381
+ if (options.config?.mode === 'monitor') return undefined
382
+ const hit = inspectSelfProtection(execution, options)
383
+ if (!hit || hit.kind !== 'deny') return undefined
384
+ return hit.reason
385
+ } catch (error) {
386
+ // A throwing guard has undefined consequences on the dispatch path; an
387
+ // unreadable argument is not a reason to deny an unrelated call.
388
+ options.logger?.warn?.(`[dsh-vigil] 自保护 guard 异常:${error instanceof Error ? error.message : String(error)}`)
389
+ return undefined
390
+ }
391
+ }
392
+ }