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.
- package/LICENSE +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,546 @@
|
|
|
1
|
+
const MANAGER_TOOL = /^(?:plugin_manager|plugin-manager|dsh_plugin_manager)$/i
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The `tools/pre-execute` waterfall listener: dsh-vigil's main runtime channel.
|
|
5
|
+
*
|
|
6
|
+
* Order of evaluation (see the requirements' decision flow):
|
|
7
|
+
* command text → parse delete intent → dsh-specific rules → Sage (optional)
|
|
8
|
+
* → deletion policy (protected roots, call/session scale) → strictest verdict
|
|
9
|
+
* → audit record → `PreToolDecision`.
|
|
10
|
+
*
|
|
11
|
+
* Fail-closed rules for this module:
|
|
12
|
+
* - the listener always returns a decision; it never relies on the Host's
|
|
13
|
+
* throw-to-deny fallback;
|
|
14
|
+
* - an internal exception during evaluation of a *relevant* call becomes a
|
|
15
|
+
* denial with an explicit reason, and is itself audited;
|
|
16
|
+
* - an internal exception outside evaluation (audit log, status bookkeeping)
|
|
17
|
+
* is audited as a failure but does not deny unrelated calls, because a
|
|
18
|
+
* broken guard that blocks everything is not protection.
|
|
19
|
+
*
|
|
20
|
+
* The waterfall is not monotonic, so the "never delete dsh-vigil itself"
|
|
21
|
+
* invariant does not live here: it is registered as a `ctx.tools.guard()` in
|
|
22
|
+
* `index.js`.
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-vigil/hook
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync } from 'node:fs'
|
|
28
|
+
import { resolve } from 'node:path'
|
|
29
|
+
import { parseDeleteIntent } from '../delete/parser.js'
|
|
30
|
+
import { strictestDecision } from '../config.js'
|
|
31
|
+
import { summarizeArguments, redactSecrets } from '../audit-log.js'
|
|
32
|
+
import { scanPluginDirectory } from '../audit/scan.js'
|
|
33
|
+
import { resolveLocalInstallTarget, summarizeInstallScan } from '../audit/install-scan.js'
|
|
34
|
+
import { getHomeDir, resolvePath, truncate } from '../util.js'
|
|
35
|
+
import { inspectSelfProtection } from './guard.js'
|
|
36
|
+
import {
|
|
37
|
+
commandTextOf,
|
|
38
|
+
inspectToolCall,
|
|
39
|
+
isDeleteTool,
|
|
40
|
+
isRelevantTool,
|
|
41
|
+
isShellTool,
|
|
42
|
+
pathsOf,
|
|
43
|
+
} from './rules.js'
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* @typedef {object} InterceptorOptions
|
|
47
|
+
* @property {any} config resolved configuration
|
|
48
|
+
* @property {any} audit audit log facade
|
|
49
|
+
* @property {any} policy deletion policy facade
|
|
50
|
+
* @property {any} sage Sage engine adapter
|
|
51
|
+
* @property {{ request: (input: any) => Promise<{ action: 'allow'|'deny', scope: string }>, isSessionAllowed: (input: any) => boolean } | null} [approval] in-conversation approval queue (null/absent keeps the host ask path)
|
|
52
|
+
* @property {Function} [scanPlugin] injectable static scanner (tests use a stub)
|
|
53
|
+
* @property {any} [integrity] integrity monitor (for periodic checks)
|
|
54
|
+
* @property {{ warn?: (message: string) => void }} [logger]
|
|
55
|
+
* @property {(now?: number) => boolean} [isDisabled] kill-switch probe
|
|
56
|
+
* @property {string} [cwd]
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {InterceptorOptions} options
|
|
61
|
+
* @returns {Interceptor}
|
|
62
|
+
*/
|
|
63
|
+
export function createInterceptor(options) {
|
|
64
|
+
const { config, audit, policy, sage } = options
|
|
65
|
+
const logger = options.logger
|
|
66
|
+
// An empty string means "the effective working directory is unknown" (the host
|
|
67
|
+
// process runs inside the Harness home). Relative delete targets then stay
|
|
68
|
+
// unresolved and are treated as untrusted instead of being guessed.
|
|
69
|
+
const cwd = typeof options.cwd === 'string' && options.cwd === ''
|
|
70
|
+
? ''
|
|
71
|
+
: resolve(options.cwd ?? process.cwd())
|
|
72
|
+
const homeDir = getHomeDir()
|
|
73
|
+
const enabled = config?.sentinel?.enabled !== false || config?.deleteGuard?.enabled !== false
|
|
74
|
+
const monitor = config?.mode === 'monitor'
|
|
75
|
+
const allowTools = new Set(config?.sentinel?.allowTools ?? [])
|
|
76
|
+
/** @type {Map<string, number>} */
|
|
77
|
+
const counters = new Map()
|
|
78
|
+
/** @type {Array<object>} */
|
|
79
|
+
const recent = []
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Effective working directory for one call: an explicit workdir argument wins,
|
|
83
|
+
* then the configured project root, then the host cwd when it is a real
|
|
84
|
+
* workspace. Never falls back to a path inside the Harness home.
|
|
85
|
+
* @param {Record<string, any>} args
|
|
86
|
+
* @returns {string}
|
|
87
|
+
*/
|
|
88
|
+
function cwdFor(args) {
|
|
89
|
+
for (const key of ['workdir', 'workingDirectory', 'work_dir', 'cwd']) {
|
|
90
|
+
const value = args?.[key]
|
|
91
|
+
if (typeof value === 'string' && value.trim() !== '') return resolvePath(value, cwd || process.cwd())
|
|
92
|
+
}
|
|
93
|
+
return cwd
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* @param {string} key
|
|
98
|
+
*/
|
|
99
|
+
function count(key) {
|
|
100
|
+
counters.set(key, (counters.get(key) ?? 0) + 1)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {object} record
|
|
105
|
+
*/
|
|
106
|
+
function remember(record) {
|
|
107
|
+
recent.push(record)
|
|
108
|
+
if (recent.length > 20) recent.shift()
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* @param {{ name: string, arguments?: unknown, agent?: { id?: string } }} exec
|
|
113
|
+
* @param {string} baseCwd effective working directory for this call
|
|
114
|
+
* @returns {any} a synthetic delete intent for fs-level delete/move tools
|
|
115
|
+
*/
|
|
116
|
+
function intentFromTool(exec, baseCwd) {
|
|
117
|
+
const args = exec?.arguments && typeof exec.arguments === 'object' ? /** @type {Record<string, any>} */ (exec.arguments) : {}
|
|
118
|
+
const paths = args ? pathsOf(args) : []
|
|
119
|
+
/** @type {Array<Record<string, unknown>>} */
|
|
120
|
+
const targets = []
|
|
121
|
+
let unresolved = false
|
|
122
|
+
for (const raw of paths) {
|
|
123
|
+
const absolute = raw.startsWith('/') || /^[A-Za-z]:[\\/]/.test(raw) || raw.startsWith('\\\\') || raw.startsWith('~')
|
|
124
|
+
let resolvedPath = null
|
|
125
|
+
if (absolute) resolvedPath = resolve(resolvePath(raw, baseCwd || process.cwd()))
|
|
126
|
+
else if (baseCwd) resolvedPath = resolve(baseCwd, raw)
|
|
127
|
+
else unresolved = true
|
|
128
|
+
targets.push({
|
|
129
|
+
raw,
|
|
130
|
+
resolvedPath,
|
|
131
|
+
hasGlob: /[*?[{]/.test(raw),
|
|
132
|
+
rootLike: false,
|
|
133
|
+
scope: 'literal',
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
if (targets.length === 0 || unresolved) {
|
|
137
|
+
return {
|
|
138
|
+
isDelete: true,
|
|
139
|
+
dryRun: false,
|
|
140
|
+
recursive: false,
|
|
141
|
+
wildcard: false,
|
|
142
|
+
targets,
|
|
143
|
+
unparsed: true,
|
|
144
|
+
riskSignals: ['unknown-construct'],
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
isDelete: true,
|
|
149
|
+
dryRun: false,
|
|
150
|
+
recursive: false,
|
|
151
|
+
wildcard: targets.some(target => target.hasGlob),
|
|
152
|
+
targets,
|
|
153
|
+
unparsed: false,
|
|
154
|
+
riskSignals: [],
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Evaluate one call and build the pre-execute decision.
|
|
160
|
+
* @param {{ name: string, arguments?: unknown, agent?: { id?: string }, signal?: AbortSignal }} exec
|
|
161
|
+
* @param {() => Promise<any>} next
|
|
162
|
+
* @returns {Promise<any>}
|
|
163
|
+
*/
|
|
164
|
+
async function handlePreExecute(exec, next) {
|
|
165
|
+
const toolName = typeof exec?.name === 'string' ? exec.name : ''
|
|
166
|
+
try {
|
|
167
|
+
if (!enabled || allowTools.has(toolName) || toolName.startsWith('vigil_')) return await next()
|
|
168
|
+
if (!isRelevantTool(toolName)) return await next()
|
|
169
|
+
if (options.isDisabled?.()) {
|
|
170
|
+
count('bypassed')
|
|
171
|
+
try {
|
|
172
|
+
audit?.record({
|
|
173
|
+
kind: 'decision',
|
|
174
|
+
event: 'pre-execute-bypass',
|
|
175
|
+
tool: toolName,
|
|
176
|
+
session: exec?.agent?.id ? String(exec.agent.id) : null,
|
|
177
|
+
decision: 'allow',
|
|
178
|
+
ruleIds: ['VG-KILL-SWITCH'],
|
|
179
|
+
reason: '停机开关已启用:跳过拦截(仍记录本次调用)',
|
|
180
|
+
})
|
|
181
|
+
} catch {
|
|
182
|
+
// bypass auditing must not block the call it is describing
|
|
183
|
+
}
|
|
184
|
+
return await next()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
options.integrity?.check?.()
|
|
188
|
+
|
|
189
|
+
const sessionId = exec?.agent?.id ? String(exec.agent.id) : null
|
|
190
|
+
const args = exec?.arguments && typeof exec.arguments === 'object' ? exec.arguments : {}
|
|
191
|
+
const command = commandTextOf(toolName, args)
|
|
192
|
+
const callCwd = cwdFor(args)
|
|
193
|
+
|
|
194
|
+
/** @type {any[]} */
|
|
195
|
+
const findings = []
|
|
196
|
+
/** @type {string[]} */
|
|
197
|
+
const reasons = []
|
|
198
|
+
/** @type {string[]} */
|
|
199
|
+
const ruleIds = []
|
|
200
|
+
|
|
201
|
+
// 1. Deletion intent (shell text or a delete/move tool).
|
|
202
|
+
let assessment = null
|
|
203
|
+
const shellDeleteIntent = command !== null && isShellTool(toolName)
|
|
204
|
+
? parseDeleteIntent(command, { cwd: callCwd, homeDir, platform: process.platform })
|
|
205
|
+
: null
|
|
206
|
+
if (shellDeleteIntent?.isDelete) {
|
|
207
|
+
assessment = policy.assess(shellDeleteIntent, { sessionId, tool: toolName })
|
|
208
|
+
} else if (isDeleteTool(toolName)) {
|
|
209
|
+
assessment = policy.assess(intentFromTool(exec, callCwd), { sessionId, tool: toolName })
|
|
210
|
+
}
|
|
211
|
+
if (assessment) {
|
|
212
|
+
findings.push(...(assessment.kind === 'allow' ? [] : [{
|
|
213
|
+
ruleId: 'VG-DEL',
|
|
214
|
+
kind: assessment.kind,
|
|
215
|
+
reason: assessment.reason ?? '删除防护',
|
|
216
|
+
}]))
|
|
217
|
+
ruleIds.push(...assessment.ruleIds)
|
|
218
|
+
if (assessment.reason) reasons.push(assessment.reason)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// 2. dsh-specific runtime rules.
|
|
222
|
+
const ruleResult = inspectToolCall(exec, config, { cwd: callCwd || process.cwd(), pluginDir: options.pluginDir })
|
|
223
|
+
findings.push(...ruleResult.findings)
|
|
224
|
+
ruleIds.push(...ruleResult.ruleIds)
|
|
225
|
+
reasons.push(...ruleResult.reasons)
|
|
226
|
+
|
|
227
|
+
// 2b. Self-protection (delete/move of the plugin or its state, or
|
|
228
|
+
// removal/replacement through a tool). `deny` is the shipped default; in
|
|
229
|
+
// `ask` mode this becomes a normal question so the composer can answer it.
|
|
230
|
+
const selfHit = inspectSelfProtection(exec, { config, pluginDir: options.pluginDir, logger })
|
|
231
|
+
if (selfHit) {
|
|
232
|
+
findings.push({ ruleId: selfHit.ruleId, kind: selfHit.kind, reason: selfHit.reason })
|
|
233
|
+
ruleIds.push(selfHit.ruleId)
|
|
234
|
+
reasons.push(selfHit.reason)
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// 2c. Install-time static audit for tool-mediated plugin installs. A local
|
|
238
|
+
// path can be audited before the package manager touches it; registry/git
|
|
239
|
+
// specs are audited after install by the install watcher.
|
|
240
|
+
if (MANAGER_TOOL.test(toolName)) {
|
|
241
|
+
const action = String(args.action ?? '').toLowerCase()
|
|
242
|
+
if (/install|update|upgrade/.test(action)) {
|
|
243
|
+
const target = resolveLocalInstallTarget(args, { cwd })
|
|
244
|
+
if (target) {
|
|
245
|
+
try {
|
|
246
|
+
// The gate must stay synchronous, so it gets a strict budget: a big
|
|
247
|
+
// package is scanned cooperatively up to the deadline, and an
|
|
248
|
+
// unfinished scan becomes a question instead of a stall.
|
|
249
|
+
const deadlineAt = Date.now() + 1500
|
|
250
|
+
const scanPromise = (options.scanPlugin ?? scanPluginDirectory)(target.dir, {
|
|
251
|
+
includeInfo: false,
|
|
252
|
+
maxFiles: 200,
|
|
253
|
+
deadlineAt,
|
|
254
|
+
ast: config.scan?.ast,
|
|
255
|
+
})
|
|
256
|
+
const report = await Promise.race([
|
|
257
|
+
scanPromise,
|
|
258
|
+
new Promise(resolve => {
|
|
259
|
+
const timer = setTimeout(() => resolve(null), 2500)
|
|
260
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
261
|
+
}),
|
|
262
|
+
])
|
|
263
|
+
if (!report) {
|
|
264
|
+
const timeoutPrompt = '本地插件静态审计超时(超过 1.5 秒),未能给出结论。是否仍要继续安装?'
|
|
265
|
+
findings.push({ ruleId: 'VG-AUDIT-02', kind: 'ask', reason: timeoutPrompt })
|
|
266
|
+
reasons.push(timeoutPrompt)
|
|
267
|
+
ruleIds.push('VG-AUDIT-02')
|
|
268
|
+
} else {
|
|
269
|
+
const scanSummary = summarizeInstallScan(report, { target: target.spec, dir: target.dir })
|
|
270
|
+
ruleIds.push('VG-AUDIT-01')
|
|
271
|
+
reasons.push(scanSummary.text)
|
|
272
|
+
if (scanSummary.blockers > 0) {
|
|
273
|
+
// High-risk findings are a question, not a veto: the page shows
|
|
274
|
+
// what is dangerous and lets the user continue or block.
|
|
275
|
+
const riskList = scanSummary.blockerReasons.length > 0 ? scanSummary.blockerReasons : scanSummary.reasons
|
|
276
|
+
const risk = riskList.length > 0 ? riskList.slice(0, 3).join(';') : '存在高风险代码'
|
|
277
|
+
const riskPrompt = `该插件有 ${scanSummary.blockers} 个高危命中:${risk}。是否继续安装?`
|
|
278
|
+
findings.push({ ruleId: 'VG-AUDIT-01', kind: 'ask', reason: riskPrompt })
|
|
279
|
+
reasons.push(riskPrompt)
|
|
280
|
+
} else if (scanSummary.incomplete) {
|
|
281
|
+
// "No blockers" is only meaningful when the scanner read the
|
|
282
|
+
// package; a padded/oversized/truncated scan is a question.
|
|
283
|
+
const coveragePrompt = `静态审计未能覆盖该插件的全部文件:${scanSummary.coverageNote}。是否仍要继续安装?`
|
|
284
|
+
findings.push({ ruleId: 'VG-AUDIT-02', kind: 'ask', reason: coveragePrompt })
|
|
285
|
+
reasons.push(coveragePrompt)
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
audit?.record({
|
|
289
|
+
kind: 'event',
|
|
290
|
+
event: 'install-scan',
|
|
291
|
+
tool: toolName,
|
|
292
|
+
session: sessionId,
|
|
293
|
+
decision: scanSummary.blockers > 0 ? 'ask' : 'none',
|
|
294
|
+
ruleIds: scanSummary.ruleIds.slice(0, 10),
|
|
295
|
+
reason: `${target.spec} ${scanSummary.text}`,
|
|
296
|
+
extra: {
|
|
297
|
+
target: target.spec,
|
|
298
|
+
dir: target.dir,
|
|
299
|
+
blockers: scanSummary.blockers,
|
|
300
|
+
review: scanSummary.review,
|
|
301
|
+
notices: scanSummary.notice,
|
|
302
|
+
filesSkipped: scanSummary.filesSkipped,
|
|
303
|
+
scanTruncated: scanSummary.scanTruncated,
|
|
304
|
+
findings: scanSummary.top,
|
|
305
|
+
},
|
|
306
|
+
})
|
|
307
|
+
} catch {
|
|
308
|
+
// auditing is best-effort; the decision stands on its own
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} catch (error) {
|
|
312
|
+
logger?.warn?.(`[dsh-vigil] 安装前静态审计失败:${error instanceof Error ? error.message : String(error)}`)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// 3. Optional Sage evaluation.
|
|
319
|
+
let sageMetadata = null
|
|
320
|
+
if (sage?.ready || sage?.status?.state === 'error') {
|
|
321
|
+
const verdict = await sage.evaluate(exec)
|
|
322
|
+
if (verdict) {
|
|
323
|
+
findings.push({ ruleId: 'VG-SAGE', kind: verdict.kind, reason: verdict.reason })
|
|
324
|
+
ruleIds.push(...verdict.ruleIds)
|
|
325
|
+
if (verdict.kind !== 'allow') reasons.push(verdict.reason)
|
|
326
|
+
sageMetadata = verdict.sage
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
let kind = /** @type {'allow'|'ask'|'deny'} */ ('allow')
|
|
331
|
+
for (const finding of findings) {
|
|
332
|
+
if (finding.kind === 'ask' || finding.kind === 'deny') kind = strictestDecision(kind, finding.kind)
|
|
333
|
+
}
|
|
334
|
+
const wouldBe = kind
|
|
335
|
+
if (monitor && kind !== 'allow') {
|
|
336
|
+
count(`monitor-${kind}`)
|
|
337
|
+
kind = 'allow'
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
const dedupedRuleIds = [...new Set(ruleIds)]
|
|
341
|
+
let reasonText = buildReason(kind, reasons, assessment, sage)
|
|
342
|
+
let finalKind = kind
|
|
343
|
+
/** @type {Record<string, unknown>|null} */
|
|
344
|
+
let approvalMeta = null
|
|
345
|
+
|
|
346
|
+
// 4. `ask` can be answered in the conversation itself. The call parks here
|
|
347
|
+
// until the page sends 允许 / 拒绝 (or the request expires), so a host
|
|
348
|
+
// without an approval dialog does not silently reject it.
|
|
349
|
+
if (kind === 'ask') {
|
|
350
|
+
const approval = options.approval
|
|
351
|
+
if (approval && config?.notify?.inlineApproval !== false) {
|
|
352
|
+
const alwaysAllowed = approval.isSessionAlwaysAllowed?.(sessionId) === true
|
|
353
|
+
const alreadyAllowed = !alwaysAllowed
|
|
354
|
+
&& approval.isSessionAllowed({ sessionId, tool: toolName, ruleIds: dedupedRuleIds })
|
|
355
|
+
if (alwaysAllowed) {
|
|
356
|
+
finalKind = 'allow'
|
|
357
|
+
approvalMeta = { action: 'allow', scope: 'session-always', remembered: true }
|
|
358
|
+
reasonText = `${reasonText ?? ''}(本会话已开启“始终允许高危”,已自动放行)`.trim()
|
|
359
|
+
} else if (alreadyAllowed) {
|
|
360
|
+
finalKind = 'allow'
|
|
361
|
+
approvalMeta = { action: 'allow', scope: 'session', remembered: true }
|
|
362
|
+
reasonText = `${reasonText ?? ''}(本会话已允许该类调用)`.trim()
|
|
363
|
+
} else {
|
|
364
|
+
const approvalDetail = (() => {
|
|
365
|
+
try {
|
|
366
|
+
if (typeof command === 'string' && command.trim() !== '') return truncate(redactSecrets(command), 600)
|
|
367
|
+
const summary = summarizeArgsSafe(args, config).summary
|
|
368
|
+
return summary ? truncate(summary, 600) : null
|
|
369
|
+
} catch {
|
|
370
|
+
return null
|
|
371
|
+
}
|
|
372
|
+
})()
|
|
373
|
+
const outcome = await approval.request({
|
|
374
|
+
tool: toolName,
|
|
375
|
+
command: approvalDetail,
|
|
376
|
+
reason: reasonText ?? '',
|
|
377
|
+
ruleIds: dedupedRuleIds,
|
|
378
|
+
sage: sageMetadata,
|
|
379
|
+
sessionId,
|
|
380
|
+
signal: exec?.signal,
|
|
381
|
+
})
|
|
382
|
+
if (outcome.action === 'allow') {
|
|
383
|
+
finalKind = 'allow'
|
|
384
|
+
approvalMeta = { action: 'allow', scope: outcome.scope }
|
|
385
|
+
reasonText = `${reasonText ?? ''}(已由你在对话内允许:${outcome.scope === 'session' ? '本会话记住' : '仅本次'})`.trim()
|
|
386
|
+
} else {
|
|
387
|
+
finalKind = 'deny'
|
|
388
|
+
approvalMeta = { action: 'deny', scope: outcome.scope }
|
|
389
|
+
// Drop the host-side "需要你确认" prefix: the denial already says
|
|
390
|
+
// the user answered, so repeating "needs confirmation" reads wrong.
|
|
391
|
+
const detail = String(reasonText ?? '')
|
|
392
|
+
.replace(/^(?:dsh-vigil|守夜人)\s*(?:需要你确认|请求人工确认)[::]?\s*/, '')
|
|
393
|
+
.trim()
|
|
394
|
+
|| (dedupedRuleIds.length > 0 ? `命中规则:${dedupedRuleIds.join('、')}` : '运行时检查')
|
|
395
|
+
reasonText = outcome.scope === 'timeout'
|
|
396
|
+
? `守夜人 等待确认超时,已按拒绝处理:${detail}`
|
|
397
|
+
: outcome.scope === 'queue-full' || outcome.scope === 'disposed'
|
|
398
|
+
? `守夜人 待确认队列不可用,已按拒绝处理:${detail}`
|
|
399
|
+
: outcome.scope === 'aborted'
|
|
400
|
+
? `调用已取消,待确认请求随之撤销:${detail}`
|
|
401
|
+
: `你在对话内拒绝了这次调用:${detail}`
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
if (finalKind === 'allow') count('allow')
|
|
408
|
+
else count(finalKind)
|
|
409
|
+
|
|
410
|
+
const auditRecord = {
|
|
411
|
+
kind: 'decision',
|
|
412
|
+
event: 'pre-execute',
|
|
413
|
+
tool: toolName,
|
|
414
|
+
session: sessionId,
|
|
415
|
+
decision: finalKind,
|
|
416
|
+
...(monitor && wouldBe !== finalKind ? { wouldBe } : {}),
|
|
417
|
+
ruleIds: dedupedRuleIds,
|
|
418
|
+
reason: reasonText ?? '',
|
|
419
|
+
args: audit ? summarizeArgsSafe(args, config) : undefined,
|
|
420
|
+
...(approvalMeta ? { approval: approvalMeta } : {}),
|
|
421
|
+
...(sageMetadata ? { sage: sageMetadata } : {}),
|
|
422
|
+
...(assessment?.scale ? { extra: { scale: assessment.scale } } : {}),
|
|
423
|
+
}
|
|
424
|
+
audit?.record(auditRecord)
|
|
425
|
+
/** @type {Record<string, unknown>} */
|
|
426
|
+
const recentEntry = {
|
|
427
|
+
ts: new Date().toISOString(),
|
|
428
|
+
tool: toolName,
|
|
429
|
+
decision: finalKind,
|
|
430
|
+
ruleIds: dedupedRuleIds,
|
|
431
|
+
}
|
|
432
|
+
if (monitor && wouldBe !== finalKind) recentEntry.wouldBe = wouldBe
|
|
433
|
+
if (approvalMeta) recentEntry.approval = approvalMeta
|
|
434
|
+
remember(recentEntry)
|
|
435
|
+
|
|
436
|
+
if (finalKind === 'allow') return await next()
|
|
437
|
+
if (finalKind === 'ask') {
|
|
438
|
+
return {
|
|
439
|
+
kind: 'ask',
|
|
440
|
+
reason: reasonText ?? '守夜人 请求人工确认',
|
|
441
|
+
displayReason: {
|
|
442
|
+
en: `Vigil needs your confirmation before this call. Rules: ${dedupedRuleIds.join(', ') || 'sentinel'}.`,
|
|
443
|
+
zh: `守夜人 在执行前需要你确认。命中规则:${dedupedRuleIds.join('、') || '运行时检查'}。`,
|
|
444
|
+
},
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
return { kind: 'deny', reason: reasonText ?? '守夜人 拒绝了该调用' }
|
|
448
|
+
} catch (error) {
|
|
449
|
+
// The listener itself failed: fail closed, and say exactly why.
|
|
450
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
451
|
+
count('internal-error')
|
|
452
|
+
try {
|
|
453
|
+
audit?.record({
|
|
454
|
+
kind: 'decision',
|
|
455
|
+
event: 'pre-execute-error',
|
|
456
|
+
tool: toolName,
|
|
457
|
+
session: exec?.agent?.id ? String(exec.agent.id) : null,
|
|
458
|
+
decision: 'deny',
|
|
459
|
+
ruleIds: ['VG-INT-10'],
|
|
460
|
+
reason: `内部异常,按 fail-closed 拒绝:${message}`,
|
|
461
|
+
})
|
|
462
|
+
} catch {
|
|
463
|
+
// audit failures are already swallowed by the audit facade
|
|
464
|
+
}
|
|
465
|
+
logger?.warn?.(`[dsh-vigil] pre-execute 内部异常:${message}`)
|
|
466
|
+
return {
|
|
467
|
+
kind: 'deny',
|
|
468
|
+
reason: `守夜人 内部异常,已按 fail-closed 拒绝本次调用:${truncate(message, 300)}(可用 DSH_VIGIL_DISABLED=1 或创建 DISABLED 文件临时停用)`,
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
enabled,
|
|
475
|
+
monitor,
|
|
476
|
+
handlePreExecute,
|
|
477
|
+
/** @returns {{ counts: Record<string, number>, recent: object[] }} */
|
|
478
|
+
stats() {
|
|
479
|
+
return { counts: Object.fromEntries(counters), recent: [...recent] }
|
|
480
|
+
},
|
|
481
|
+
/** @returns {string} */
|
|
482
|
+
describe() {
|
|
483
|
+
const parts = [`pre-execute:${enabled ? '已挂载' : '未启用'}${monitor ? '(monitor:只记录不拦截)' : ''}`]
|
|
484
|
+
const counts = Object.fromEntries(counters)
|
|
485
|
+
const total = Object.values(counts).reduce((sum, value) => sum + value, 0)
|
|
486
|
+
if (total > 0) parts.push(`已评估 ${total} 次`)
|
|
487
|
+
if (counts.deny) parts.push(`拒绝 ${counts.deny}`)
|
|
488
|
+
if (counts.ask) parts.push(`询问 ${counts.ask}`)
|
|
489
|
+
if (counts['internal-error']) parts.push(`内部异常 ${counts['internal-error']}`)
|
|
490
|
+
return parts.join(',')
|
|
491
|
+
},
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** @typedef {ReturnType<typeof createInterceptor>} Interceptor */
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* Compose the user-facing reason. Deliberately explicit about what was blocked,
|
|
499
|
+
* what was moved to quarantine, and which rule fired (FR-2.4).
|
|
500
|
+
* @param {'allow'|'ask'|'deny'} kind
|
|
501
|
+
* @param {string[]} reasons
|
|
502
|
+
* @param {any} assessment
|
|
503
|
+
* @param {any} sage
|
|
504
|
+
* @returns {string|null}
|
|
505
|
+
*/
|
|
506
|
+
function buildReason(kind, reasons, assessment, sage) {
|
|
507
|
+
if (kind === 'allow') return null
|
|
508
|
+
const unique = [...new Set(reasons.filter(reason => typeof reason === 'string' && reason.trim() !== ''))]
|
|
509
|
+
const lines = unique.slice(0, 6)
|
|
510
|
+
if (sage?.status?.state === 'ready' && unique.some(line => line.includes('Sage'))) {
|
|
511
|
+
// Attribution is preserved when a Sage rule contributed (DRL 1.1).
|
|
512
|
+
lines.push('Sage 规则结果由 @gendigital/sage-core 提供')
|
|
513
|
+
}
|
|
514
|
+
if (assessment?.quarantine?.quarantined?.length) {
|
|
515
|
+
const ids = assessment.quarantine.quarantined.map(entry => entry.id)
|
|
516
|
+
lines.push(`可恢复:vigil_quarantine action=restore id=${ids[0]}`)
|
|
517
|
+
}
|
|
518
|
+
if (assessment?.quarantine?.skipped?.length) {
|
|
519
|
+
const skipped = assessment.quarantine.skipped[0]
|
|
520
|
+
if (skipped) lines.push(`有 ${assessment.quarantine.skipped.length} 项未进入隔离区:${skipped.error}`)
|
|
521
|
+
}
|
|
522
|
+
const prefix = kind === 'deny' ? '守夜人 已拦截' : '守夜人 需要你确认'
|
|
523
|
+
return `${prefix}:${lines.join(';')}`
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* @param {unknown} args
|
|
528
|
+
* @param {any} config
|
|
529
|
+
* @returns {{ digest: string, length: number, summary: string|null }}
|
|
530
|
+
*/
|
|
531
|
+
function summarizeArgsSafe(args, config) {
|
|
532
|
+
try {
|
|
533
|
+
return summarizeArguments(/** @type {Record<string, unknown>} */ (args), config)
|
|
534
|
+
} catch {
|
|
535
|
+
return { digest: '', length: 0, summary: null }
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Whether the kill switch file exists (probe used by the caller each call). */
|
|
540
|
+
export function killSwitchFileExists(pathValue) {
|
|
541
|
+
try {
|
|
542
|
+
return typeof pathValue === 'string' && pathValue !== '' && existsSync(pathValue)
|
|
543
|
+
} catch {
|
|
544
|
+
return false
|
|
545
|
+
}
|
|
546
|
+
}
|