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,550 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Optional Sage engine adapter (FR-2.2 / FR-2.5).
|
|
3
|
+
*
|
|
4
|
+
* `@gendigital/sage-core` is a real, Apache-2.0, platform-agnostic detection
|
|
5
|
+
* engine. It is **not bundled** and not a hard dependency of dsh-vigil:
|
|
6
|
+
*
|
|
7
|
+
* - bundling its YAML rule set would put the DRL 1.1 attribution/licensing
|
|
8
|
+
* obligations into this package, and the rule set drifts independently;
|
|
9
|
+
* - its optional native dependencies (koffi / onnxruntime-node) must not
|
|
10
|
+
* become install-time requirements of a security plugin whose whole point is
|
|
11
|
+
* to reduce supply-chain risk;
|
|
12
|
+
* - an unavailable engine must still leave a working, deterministic rule set.
|
|
13
|
+
*
|
|
14
|
+
* So the adapter is lazy: it imports Sage only when `sage.enabled` is true, and
|
|
15
|
+
* the built-in rules keep working when it is absent. When enabled-but-missing,
|
|
16
|
+
* `sage.required` decides between "report and use built-ins" (default) and
|
|
17
|
+
* "deny every relevant call" (strict fail-closed).
|
|
18
|
+
*
|
|
19
|
+
* Network reputation checks (URL/file/package) are disabled by default: dsh-vigil
|
|
20
|
+
* does not send your commands or file contents to a cloud service unless the
|
|
21
|
+
* operator opts in.
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-vigil/sage
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
27
|
+
import { extname, join } from 'node:path'
|
|
28
|
+
import { pathToFileURL } from 'node:url'
|
|
29
|
+
import { importSageModule } from './sage-load.js'
|
|
30
|
+
import { locateSage, sageInstallDir } from '../sage-provision.js'
|
|
31
|
+
import { resolvePath, truncate } from '../util.js'
|
|
32
|
+
|
|
33
|
+
/** @typedef {'disabled'|'unavailable'|'ready'|'error'} SageState */
|
|
34
|
+
|
|
35
|
+
/** dsh tool name → Sage canonical tool vocabulary. */
|
|
36
|
+
const TOOL_MAP = Object.freeze({
|
|
37
|
+
pwsh: 'Bash',
|
|
38
|
+
powershell: 'Bash',
|
|
39
|
+
bash: 'Bash',
|
|
40
|
+
sh: 'Bash',
|
|
41
|
+
shell: 'Bash',
|
|
42
|
+
exec: 'Bash',
|
|
43
|
+
terminal: 'Bash',
|
|
44
|
+
run_command: 'Bash',
|
|
45
|
+
read: 'Read',
|
|
46
|
+
write: 'Write',
|
|
47
|
+
edit: 'Edit',
|
|
48
|
+
write_file: 'Write',
|
|
49
|
+
edit_file: 'Edit',
|
|
50
|
+
patch: 'ApplyPatch',
|
|
51
|
+
apply_patch: 'ApplyPatch',
|
|
52
|
+
delete_file: 'Delete',
|
|
53
|
+
remove_file: 'Delete',
|
|
54
|
+
unlink: 'Delete',
|
|
55
|
+
glob: 'Glob',
|
|
56
|
+
grep: 'Grep',
|
|
57
|
+
web_fetch: 'WebFetch',
|
|
58
|
+
web_search: 'WebSearch',
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @typedef {object} SageEvaluation
|
|
63
|
+
* @property {'allow'|'ask'|'deny'} kind
|
|
64
|
+
* @property {string} reason
|
|
65
|
+
* @property {string[]} ruleIds
|
|
66
|
+
* @property {object} sage
|
|
67
|
+
*/
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Create the Sage adapter. Never throws: a missing module or rule set is a
|
|
71
|
+
* reported state, not an activation failure. When the feature is enabled but
|
|
72
|
+
* nothing is installed yet, the status asks the caller to provision (see
|
|
73
|
+
* `sage-provision.js`) and the built-in rules keep enforcing meanwhile.
|
|
74
|
+
*
|
|
75
|
+
* @param {any} config resolved configuration
|
|
76
|
+
* @param {{ warn?: (message: string) => void }} [logger]
|
|
77
|
+
* @returns {Promise<SageEngine>}
|
|
78
|
+
*/
|
|
79
|
+
export async function createSageEngine(config, logger) {
|
|
80
|
+
/** @type {any} */
|
|
81
|
+
const installDir = (() => {
|
|
82
|
+
try {
|
|
83
|
+
return sageInstallDir(config)
|
|
84
|
+
} catch {
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
})()
|
|
88
|
+
const provisioned = installDir ? locateSage(installDir) : null
|
|
89
|
+
const explicitModule = config?.sage?.modulePath
|
|
90
|
+
|
|
91
|
+
/** @type {{ state: SageState, reason: string|null, modulePath: string|null, threatsDir: string|null, rules: number, version: string|null, source: string|null, installDir: string|null, needsProvision: boolean }} */
|
|
92
|
+
const status = {
|
|
93
|
+
state: config?.sage?.enabled ? 'unavailable' : 'disabled',
|
|
94
|
+
reason: config?.sage?.enabled ? '尚未初始化' : '配置未启用(默认离线运行内置规则)',
|
|
95
|
+
modulePath: null,
|
|
96
|
+
threatsDir: null,
|
|
97
|
+
rules: 0,
|
|
98
|
+
version: null,
|
|
99
|
+
source: null,
|
|
100
|
+
installDir,
|
|
101
|
+
needsProvision: false,
|
|
102
|
+
}
|
|
103
|
+
if (!config?.sage?.enabled) return createDisabledEngine(status)
|
|
104
|
+
|
|
105
|
+
let sage
|
|
106
|
+
try {
|
|
107
|
+
sage = await importSage(config, provisioned, logger)
|
|
108
|
+
status.modulePath = sage.specifier
|
|
109
|
+
status.source = sage.source
|
|
110
|
+
status.version = provisioned?.version ?? (typeof sage.module?.version === 'string' ? sage.module.version : null)
|
|
111
|
+
} catch (error) {
|
|
112
|
+
status.state = 'unavailable'
|
|
113
|
+
status.reason = `无法加载 @gendigital/sage-core:${error instanceof Error ? error.message : String(error)}`
|
|
114
|
+
status.needsProvision = !explicitModule
|
|
115
|
+
if (status.needsProvision) status.reason = '尚未安装 Sage 引擎,等待自动下载'
|
|
116
|
+
else logger?.warn?.(`[dsh-vigil] ${status.reason}`)
|
|
117
|
+
return createUnavailableEngine(status, config)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const { module } = sage
|
|
121
|
+
const threatsDir = resolveThreatsDir(config, provisioned)
|
|
122
|
+
status.threatsDir = threatsDir || null
|
|
123
|
+
if (!threatsDir) {
|
|
124
|
+
status.state = 'unavailable'
|
|
125
|
+
status.reason = '未找到 Sage 规则目录(sage.threatsDir / SAGE_THREATS_DIR / ~/.sage/threats)'
|
|
126
|
+
status.needsProvision = !explicitModule && !config?.sage?.threatsDir
|
|
127
|
+
if (status.needsProvision) status.reason = '尚未下载 Sage 规则,等待自动下载'
|
|
128
|
+
else logger?.warn?.(`[dsh-vigil] ${status.reason}`)
|
|
129
|
+
return createUnavailableEngine(status, config)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
let threats
|
|
133
|
+
try {
|
|
134
|
+
threats = await module.loadThreats(threatsDir)
|
|
135
|
+
status.rules = Array.isArray(threats) ? threats.length : 0
|
|
136
|
+
} catch (error) {
|
|
137
|
+
status.state = 'error'
|
|
138
|
+
status.reason = `加载 Sage 规则失败:${error instanceof Error ? error.message : String(error)}`
|
|
139
|
+
logger?.warn?.(`[dsh-vigil] ${status.reason}`)
|
|
140
|
+
return createUnavailableEngine(status, config)
|
|
141
|
+
}
|
|
142
|
+
if (!Array.isArray(threats) || threats.length === 0) {
|
|
143
|
+
status.state = 'unavailable'
|
|
144
|
+
status.reason = `Sage 规则目录为空:${threatsDir}`
|
|
145
|
+
logger?.warn?.(`[dsh-vigil] ${status.reason}`)
|
|
146
|
+
return createUnavailableEngine(status, config)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
let sageConfig
|
|
150
|
+
try {
|
|
151
|
+
sageConfig = buildOfflineConfig(module, config)
|
|
152
|
+
} catch (error) {
|
|
153
|
+
status.state = 'error'
|
|
154
|
+
status.reason = `构建 Sage 配置失败:${error instanceof Error ? error.message : String(error)}`
|
|
155
|
+
return createUnavailableEngine(status, config)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const trustedDomainsDir = config?.sage?.trustedDomainsDir
|
|
159
|
+
? resolvePath(config.sage.trustedDomainsDir)
|
|
160
|
+
: join(threatsDir, '..', 'trusted-domains')
|
|
161
|
+
const sageDirPath = resolvePath('~/.sage')
|
|
162
|
+
|
|
163
|
+
const nullLogger = module.nullLogger ?? {
|
|
164
|
+
debug() {},
|
|
165
|
+
info() {},
|
|
166
|
+
warn() {},
|
|
167
|
+
error() {},
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// Evaluations share one engine instance. Serialize them so two concurrent
|
|
171
|
+
// tool calls cannot pile up inside the engine and push a warm call past the
|
|
172
|
+
// timeout; the cold-start cost (~0.4 s on this machine) is paid once in the
|
|
173
|
+
// warm-up below instead of inside the first real decision.
|
|
174
|
+
let evaluationChain = Promise.resolve()
|
|
175
|
+
let lastLatencyMs = null
|
|
176
|
+
let timeoutCount = 0
|
|
177
|
+
|
|
178
|
+
const warmUp = async () => {
|
|
179
|
+
try {
|
|
180
|
+
const command = 'echo vigil-warmup'
|
|
181
|
+
const artifacts = typeof module.extractFromBash === 'function' ? module.extractFromBash(command) : []
|
|
182
|
+
const request = {
|
|
183
|
+
sessionId: 'dsh-vigil-warmup',
|
|
184
|
+
hookType: 'PreToolUse',
|
|
185
|
+
toolName: 'Bash',
|
|
186
|
+
toolInput: { command },
|
|
187
|
+
artifacts,
|
|
188
|
+
}
|
|
189
|
+
let timer
|
|
190
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
191
|
+
timer = setTimeout(() => reject(new Error('warmup-timeout')), 4000)
|
|
192
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
193
|
+
})
|
|
194
|
+
try {
|
|
195
|
+
await Promise.race([
|
|
196
|
+
module.evaluateToolCall(request, { threatsDir, trustedDomainsDir, sageDirPath, config: sageConfig, logger: nullLogger, sessionId: request.sessionId }),
|
|
197
|
+
timeout,
|
|
198
|
+
])
|
|
199
|
+
} finally {
|
|
200
|
+
clearTimeout(timer)
|
|
201
|
+
}
|
|
202
|
+
} catch (error) {
|
|
203
|
+
logger?.warn?.(`[dsh-vigil] Sage 预热未完成:${error instanceof Error ? error.message : String(error)}`)
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
const warmupPromise = warmUp()
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* @param {{ name: string, arguments?: unknown, agent?: { id?: string } }} exec
|
|
210
|
+
* @returns {Promise<SageEvaluation|null>}
|
|
211
|
+
*/
|
|
212
|
+
async function evaluateNow(exec) {
|
|
213
|
+
if (status.state !== 'ready' && status.state !== 'error') return null
|
|
214
|
+
const toolName = canonicalToolName(module, exec?.name)
|
|
215
|
+
const args = exec?.arguments && typeof exec.arguments === 'object' ? /** @type {Record<string, unknown>} */ (exec.arguments) : {}
|
|
216
|
+
const artifacts = buildSageArtifacts(module, toolName, args)
|
|
217
|
+
if (artifacts.length === 0) return null
|
|
218
|
+
const timeoutMs = Math.max(10, Number(config?.sage?.timeoutMs) || 2000)
|
|
219
|
+
const request = {
|
|
220
|
+
sessionId: exec?.agent?.id ? String(exec.agent.id) : 'dsh-vigil',
|
|
221
|
+
hookType: 'PreToolUse',
|
|
222
|
+
toolName,
|
|
223
|
+
toolInput: args,
|
|
224
|
+
artifacts,
|
|
225
|
+
}
|
|
226
|
+
const evaluation = module.evaluateToolCall(request, {
|
|
227
|
+
threatsDir,
|
|
228
|
+
trustedDomainsDir,
|
|
229
|
+
sageDirPath,
|
|
230
|
+
config: sageConfig,
|
|
231
|
+
logger: nullLogger,
|
|
232
|
+
sessionId: request.sessionId,
|
|
233
|
+
})
|
|
234
|
+
let timer
|
|
235
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
236
|
+
timer = setTimeout(() => reject(new Error(`Sage 评估超时(>${timeoutMs} ms)`)), timeoutMs)
|
|
237
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
238
|
+
})
|
|
239
|
+
try {
|
|
240
|
+
const verdict = await Promise.race([evaluation, timeout])
|
|
241
|
+
return mapVerdict(verdict)
|
|
242
|
+
} catch (error) {
|
|
243
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
244
|
+
const required = config?.sage?.required === true
|
|
245
|
+
if (message.includes('超时') || message.includes('timeout')) {
|
|
246
|
+
timeoutCount += 1
|
|
247
|
+
status.timeouts = timeoutCount
|
|
248
|
+
}
|
|
249
|
+
status.lastError = message
|
|
250
|
+
if (required) {
|
|
251
|
+
status.state = 'error'
|
|
252
|
+
status.reason = `Sage 评估异常:${message}`
|
|
253
|
+
logger?.warn?.(`[dsh-vigil] ${status.reason}`)
|
|
254
|
+
return {
|
|
255
|
+
kind: 'deny',
|
|
256
|
+
reason: `Sage 引擎不可用(required=true,fail-closed):${status.reason}`,
|
|
257
|
+
ruleIds: ['VG-SAGE-ERR'],
|
|
258
|
+
sage: { source: 'sage', state: status.state, error: true, attribution: 'Sage (@gendigital/sage-core, Apache-2.0)' },
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
// An optional engine hiccup (usually a cold-start timeout) must not turn
|
|
262
|
+
// every call into an approval request: degrade to the built-in rules and
|
|
263
|
+
// leave an audit mark instead.
|
|
264
|
+
logger?.warn?.(`[dsh-vigil] Sage 本次评估失败,继续使用内置规则:${message}`)
|
|
265
|
+
return {
|
|
266
|
+
kind: 'allow',
|
|
267
|
+
reason: `Sage 本次评估失败(已降级为仅内置规则):${message}`,
|
|
268
|
+
ruleIds: ['VG-SAGE-ERR'],
|
|
269
|
+
sage: { source: 'sage', state: status.state, error: true, transient: true, attribution: 'Sage (@gendigital/sage-core, Apache-2.0)' },
|
|
270
|
+
}
|
|
271
|
+
} finally {
|
|
272
|
+
clearTimeout(timer)
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Serialized, latency-instrumented entry point. `lastLatencyMs` records what
|
|
278
|
+
* the decision path actually waited (queue + evaluation).
|
|
279
|
+
* @param {{ name: string, arguments?: unknown, agent?: { id?: string } }} exec
|
|
280
|
+
* @returns {Promise<SageEvaluation|null>}
|
|
281
|
+
*/
|
|
282
|
+
async function evaluate(exec) {
|
|
283
|
+
const started = performance.now()
|
|
284
|
+
const run = evaluationChain.then(() => evaluateNow(exec))
|
|
285
|
+
evaluationChain = run.then(() => undefined, () => undefined)
|
|
286
|
+
try {
|
|
287
|
+
return await run
|
|
288
|
+
} finally {
|
|
289
|
+
lastLatencyMs = Math.round(performance.now() - started)
|
|
290
|
+
status.lastLatencyMs = lastLatencyMs
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
await warmupPromise
|
|
295
|
+
status.state = 'ready'
|
|
296
|
+
status.reason = null
|
|
297
|
+
status.needsProvision = false
|
|
298
|
+
return {
|
|
299
|
+
status,
|
|
300
|
+
evaluate,
|
|
301
|
+
/** @returns {boolean} */
|
|
302
|
+
get ready() {
|
|
303
|
+
return status.state === 'ready'
|
|
304
|
+
},
|
|
305
|
+
/**
|
|
306
|
+
* @param {string} canonical
|
|
307
|
+
* @returns {string[]} dsh tool names that would be evaluated
|
|
308
|
+
*/
|
|
309
|
+
supports(canonical) {
|
|
310
|
+
return Object.entries(TOOL_MAP).filter(([, value]) => value === canonical).map(([key]) => key)
|
|
311
|
+
},
|
|
312
|
+
describe() {
|
|
313
|
+
if (status.state === 'disabled') return 'Sage:未启用(使用内置规则)'
|
|
314
|
+
if (status.state === 'ready') {
|
|
315
|
+
const source = status.source === 'provisioned' ? '自动下载' : status.source === 'configured' ? '配置路径' : '模块解析'
|
|
316
|
+
const latency = Number.isFinite(status.lastLatencyMs) ? `,最近一次评估 ${status.lastLatencyMs} ms` : ''
|
|
317
|
+
const timeouts = Number(status.timeouts) > 0 ? `,超时/异常 ${status.timeouts} 次` : ''
|
|
318
|
+
return `Sage:已就绪,${status.rules} 条规则(${source})${latency}${timeouts},规则目录 ${status.threatsDir}`
|
|
319
|
+
}
|
|
320
|
+
return `Sage:${status.state} — ${status.reason ?? '未知原因'}`
|
|
321
|
+
},
|
|
322
|
+
/** @returns {string} attribution line required when a Sage rule matched */
|
|
323
|
+
attribution(threatId) {
|
|
324
|
+
return `规则 ${threatId} 来自 Sage(@gendigital/sage-core, Apache-2.0)`
|
|
325
|
+
},
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** @typedef {Awaited<ReturnType<typeof createSageEngine>>} SageEngine */
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* @param {{ state: SageState, reason: string|null }} status
|
|
333
|
+
* @returns {SageEngine}
|
|
334
|
+
*/
|
|
335
|
+
function createDisabledEngine(status) {
|
|
336
|
+
return {
|
|
337
|
+
status,
|
|
338
|
+
evaluate: async () => null,
|
|
339
|
+
ready: false,
|
|
340
|
+
supports: () => [],
|
|
341
|
+
describe: () => 'Sage:未启用(使用内置规则)',
|
|
342
|
+
attribution: threatId => `规则 ${threatId} 来自 Sage(@gendigital/sage-core, Apache-2.0)`,
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* @param {{ state: SageState, reason: string|null }} status
|
|
348
|
+
* @param {any} config
|
|
349
|
+
* @returns {SageEngine}
|
|
350
|
+
*/
|
|
351
|
+
function createUnavailableEngine(status, config) {
|
|
352
|
+
return {
|
|
353
|
+
status,
|
|
354
|
+
evaluate: async exec => {
|
|
355
|
+
if (config?.sage?.required !== true) return null
|
|
356
|
+
return {
|
|
357
|
+
kind: 'deny',
|
|
358
|
+
reason: `Sage 已启用但不可用(required=true,fail-closed):${status.reason ?? '未知原因'}`,
|
|
359
|
+
ruleIds: ['VG-SAGE-UNAVAILABLE'],
|
|
360
|
+
sage: { source: 'sage', state: status.state, error: true, attribution: 'Sage (@gendigital/sage-core, Apache-2.0)' },
|
|
361
|
+
}
|
|
362
|
+
},
|
|
363
|
+
ready: false,
|
|
364
|
+
supports: () => [],
|
|
365
|
+
describe: () => `Sage:${status.state} — ${status.reason ?? '未知原因'}`,
|
|
366
|
+
attribution: threatId => `规则 ${threatId} 来自 Sage(@gendigital/sage-core, Apache-2.0)`,
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Import the configured module. Resolution order:
|
|
372
|
+
* 1. `sage.modulePath` — an explicit operator choice;
|
|
373
|
+
* 2. the plugin-provisioned install (`<stateDir>/sage/node_modules/...`);
|
|
374
|
+
* 3. a bare `@gendigital/sage-core` import, resolved from the Host's paths.
|
|
375
|
+
* @param {any} config
|
|
376
|
+
* @param {any} provisioned result of `locateSage`
|
|
377
|
+
* @param {{ warn?: (message: string) => void }} [logger]
|
|
378
|
+
* @returns {Promise<{ module: any, specifier: string, source: string }>}
|
|
379
|
+
*/
|
|
380
|
+
async function importSage(config, provisioned, logger) {
|
|
381
|
+
const configuredPath = config?.sage?.modulePath
|
|
382
|
+
if (typeof configuredPath === 'string' && configuredPath.trim() !== '') {
|
|
383
|
+
const absolute = resolvePath(configuredPath)
|
|
384
|
+
if (!existsSync(absolute)) throw new Error(`sage.modulePath 不存在:${absolute}`)
|
|
385
|
+
const target = absolute.endsWith('/')
|
|
386
|
+
? pathToFileURL(join(absolute, 'dist', 'index.js')).href
|
|
387
|
+
: pathToFileURL(absolute).href
|
|
388
|
+
const module = await importSageModule(target)
|
|
389
|
+
return { module, specifier: absolute, source: 'configured' }
|
|
390
|
+
}
|
|
391
|
+
if (provisioned?.available && provisioned.modulePath) {
|
|
392
|
+
const module = await importSageModule(pathToFileURL(provisioned.modulePath).href)
|
|
393
|
+
return { module, specifier: provisioned.modulePath, source: 'provisioned' }
|
|
394
|
+
}
|
|
395
|
+
try {
|
|
396
|
+
const module = await importSageModule('@gendigital/sage-core')
|
|
397
|
+
return { module, specifier: '@gendigital/sage-core', source: 'modules' }
|
|
398
|
+
} catch (error) {
|
|
399
|
+
logger?.warn?.(`[dsh-vigil] 无法从模块解析路径加载 @gendigital/sage-core:${String(error)}`)
|
|
400
|
+
throw error
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* Resolve a Sage rules directory: explicit config, the provisioned rule set, the
|
|
406
|
+
* environment, then the conventional `~/.sage` locations.
|
|
407
|
+
* @param {any} config
|
|
408
|
+
* @param {any} provisioned
|
|
409
|
+
* @returns {string|null}
|
|
410
|
+
*/
|
|
411
|
+
function resolveThreatsDir(config, provisioned) {
|
|
412
|
+
const candidates = []
|
|
413
|
+
if (typeof config?.sage?.threatsDir === 'string' && config.sage.threatsDir.trim() !== '') {
|
|
414
|
+
candidates.push(resolvePath(config.sage.threatsDir))
|
|
415
|
+
}
|
|
416
|
+
if (provisioned?.threatsDir) candidates.push(provisioned.threatsDir)
|
|
417
|
+
if (typeof process.env.SAGE_THREATS_DIR === 'string' && process.env.SAGE_THREATS_DIR.trim() !== '') {
|
|
418
|
+
candidates.push(resolvePath(process.env.SAGE_THREATS_DIR))
|
|
419
|
+
}
|
|
420
|
+
candidates.push(resolvePath('~/.sage/threats'))
|
|
421
|
+
candidates.push(resolvePath('~/.sage/rules'))
|
|
422
|
+
for (const candidate of candidates) {
|
|
423
|
+
try {
|
|
424
|
+
if (!existsSync(candidate)) continue
|
|
425
|
+
const files = readdirSync(candidate)
|
|
426
|
+
if (files.some(file => ['.yaml', '.yml'].includes(extname(file).toLowerCase()))) return candidate
|
|
427
|
+
} catch {
|
|
428
|
+
// unreadable candidate: try the next one
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return null
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/**
|
|
435
|
+
* Build a Sage configuration that performs no network egress unless the operator
|
|
436
|
+
* explicitly turns reputation checks on.
|
|
437
|
+
* @param {any} module
|
|
438
|
+
* @param {any} config
|
|
439
|
+
* @returns {any}
|
|
440
|
+
*/
|
|
441
|
+
function buildOfflineConfig(module, config) {
|
|
442
|
+
const offline = {
|
|
443
|
+
sensitivity: config?.sage?.sensitivity ?? 'balanced',
|
|
444
|
+
heuristics_enabled: true,
|
|
445
|
+
url_check: { enabled: config?.sage?.disableNetworkChecks === false },
|
|
446
|
+
file_check: { enabled: false },
|
|
447
|
+
package_check: { enabled: false },
|
|
448
|
+
amsi_check: { enabled: false },
|
|
449
|
+
pi_check: { enabled: false },
|
|
450
|
+
skill_check: { enabled: false, upload_enabled: false },
|
|
451
|
+
cache: { enabled: false },
|
|
452
|
+
logging: { enabled: false },
|
|
453
|
+
operational_logging: { enabled: false },
|
|
454
|
+
community_iq: false,
|
|
455
|
+
manage_status_line: false,
|
|
456
|
+
announce_clean_scans: false,
|
|
457
|
+
}
|
|
458
|
+
if (typeof module.ConfigSchema?.parse === 'function') {
|
|
459
|
+
return module.ConfigSchema.parse(offline)
|
|
460
|
+
}
|
|
461
|
+
return offline
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* @param {any} module
|
|
466
|
+
* @param {string} toolName
|
|
467
|
+
* @returns {string}
|
|
468
|
+
*/
|
|
469
|
+
function canonicalToolName(module, toolName) {
|
|
470
|
+
if (typeof module?.canonicalizeToolName === 'function') {
|
|
471
|
+
try {
|
|
472
|
+
return module.canonicalizeToolName(TOOL_MAP, toolName)
|
|
473
|
+
} catch {
|
|
474
|
+
// fall through to the local map
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
return TOOL_MAP[toolName] ?? 'Unknown'
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* Build Sage artifacts for one tool call.
|
|
482
|
+
*
|
|
483
|
+
* Only execution/network/URL surfaces are sent. Write/Edit/ApplyPatch payloads
|
|
484
|
+
* are deliberately skipped: their (often large, often non-English) file content
|
|
485
|
+
* makes the engine slow and triggers prompt-injection-style rules on innocuous
|
|
486
|
+
* UI strings such as Chinese labels — the static audit already covers code, and
|
|
487
|
+
* dsh-vigil's own config/persistence rules cover the write itself.
|
|
488
|
+
*
|
|
489
|
+
* @param {any} module
|
|
490
|
+
* @param {string} canonical
|
|
491
|
+
* @param {Record<string, unknown>} args
|
|
492
|
+
* @returns {Array<{ type: string, value: string, context?: string }>}
|
|
493
|
+
*/
|
|
494
|
+
export function buildSageArtifacts(module, canonical, args) {
|
|
495
|
+
try {
|
|
496
|
+
let artifacts
|
|
497
|
+
switch (canonical) {
|
|
498
|
+
case 'Bash': {
|
|
499
|
+
const command = typeof args.command === 'string' ? args.command : typeof args.cmd === 'string' ? args.cmd : ''
|
|
500
|
+
artifacts = command ? module.extractFromBash(command) : []
|
|
501
|
+
break
|
|
502
|
+
}
|
|
503
|
+
case 'Read':
|
|
504
|
+
artifacts = module.extractFromRead(args)
|
|
505
|
+
break
|
|
506
|
+
case 'Delete':
|
|
507
|
+
artifacts = module.extractFromDelete(args)
|
|
508
|
+
break
|
|
509
|
+
case 'WebFetch':
|
|
510
|
+
artifacts = module.extractFromWebFetch(args)
|
|
511
|
+
break
|
|
512
|
+
default:
|
|
513
|
+
artifacts = []
|
|
514
|
+
}
|
|
515
|
+
if (!Array.isArray(artifacts)) return []
|
|
516
|
+
return artifacts.slice(0, 20).map(artifact => ({
|
|
517
|
+
...artifact,
|
|
518
|
+
value: typeof artifact?.value === 'string' ? artifact.value.slice(0, 4000) : artifact?.value,
|
|
519
|
+
}))
|
|
520
|
+
} catch {
|
|
521
|
+
return []
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* @param {any} verdict
|
|
527
|
+
* @returns {SageEvaluation}
|
|
528
|
+
*/
|
|
529
|
+
function mapVerdict(verdict) {
|
|
530
|
+
const decision = verdict?.decision
|
|
531
|
+
const kind = decision === 'deny' ? 'deny' : decision === 'ask' ? 'ask' : 'allow'
|
|
532
|
+
const reasons = Array.isArray(verdict?.reasons) ? verdict.reasons : []
|
|
533
|
+
const artifacts = Array.isArray(verdict?.artifacts) ? verdict.artifacts : []
|
|
534
|
+
const text = reasons.length > 0 ? reasons.join(';') : `Sage 判定 ${String(verdict?.source ?? '')}`.trim()
|
|
535
|
+
return {
|
|
536
|
+
kind,
|
|
537
|
+
reason: truncate(text, 500),
|
|
538
|
+
ruleIds: verdict?.matchedThreatId ? [String(verdict.matchedThreatId)] : [],
|
|
539
|
+
sage: {
|
|
540
|
+
source: 'sage',
|
|
541
|
+
threatId: verdict?.matchedThreatId ?? null,
|
|
542
|
+
category: verdict?.category ?? null,
|
|
543
|
+
severity: verdict?.severity ?? null,
|
|
544
|
+
confidence: verdict?.confidence ?? null,
|
|
545
|
+
customThreat: Boolean(verdict?.customThreat),
|
|
546
|
+
artifacts: artifacts.slice(0, 3),
|
|
547
|
+
attribution: 'Sage (@gendigital/sage-core, Apache-2.0)',
|
|
548
|
+
},
|
|
549
|
+
}
|
|
550
|
+
}
|