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,89 @@
1
+ /**
2
+ * Audit-log cleanup route.
3
+ *
4
+ * Two user-requested cleanup operations, both mounted on the authenticated
5
+ * browser Fetch channel:
6
+ *
7
+ * POST /api/dsh-vigil/audit-clear { action: 'all' }
8
+ * POST /api/dsh-vigil/audit-clear { action: 'session', sessionId: '…' }
9
+ *
10
+ * The log is a single hash chain shared by every session, so cleanup cannot
11
+ * delete a middle chunk without breaking verification. Instead the Host
12
+ * rewrites a fresh valid chain (dropping the requested records) and writes one
13
+ * `audit-clear` event into it, keeping `vigil_audit action=verify` useful.
14
+ *
15
+ * Never mount this on the raw web server: it destroys records.
16
+ *
17
+ * @module dsh-vigil/audit-clear-route
18
+ */
19
+
20
+ /** Authenticated browser fetch path for audit-log cleanup. */
21
+ export const AUDIT_CLEAR_PATH = '/api/dsh-vigil/audit-clear'
22
+
23
+ /** @param {unknown} body @returns {{ ok: boolean, error?: string, status: number }} */
24
+ function readAction(body) {
25
+ const action = body && typeof body === 'object' ? /** @type {any} */ (body).action : null
26
+ if (action === 'all') return { ok: true, status: 200 }
27
+ if (action === 'session') {
28
+ const sessionId = /** @type {any} */ (body).sessionId
29
+ if (typeof sessionId !== 'string' || sessionId === '') return { ok: false, error: '缺少会话 ID', status: 400 }
30
+ return { ok: true, status: 200 }
31
+ }
32
+ return { ok: false, error: '未知操作', status: 400 }
33
+ }
34
+
35
+ /**
36
+ * @param {{ getRuntime: () => any }} deps
37
+ * @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
38
+ */
39
+ export function createAuditClearRoute(deps) {
40
+ return {
41
+ path: AUDIT_CLEAR_PATH,
42
+ methods: ['POST'],
43
+ requestBody: 'buffered',
44
+ fetch: async request => {
45
+ /** @type {{ ok: boolean, [key: string]: unknown }} */
46
+ let payload
47
+ let status = 200
48
+ try {
49
+ const body = typeof request.json === 'function'
50
+ ? await request.json().catch(() => null)
51
+ : null
52
+ const action = readAction(body)
53
+ if (!action.ok) {
54
+ payload = { ok: false, error: action.error }
55
+ status = action.status
56
+ } else {
57
+ const log = deps.getRuntime()?.audit
58
+ if (!log) {
59
+ payload = { ok: false, error: '审计日志不可用' }
60
+ status = 503
61
+ } else if (/** @type {any} */ (body).action === 'all') {
62
+ const result = typeof log.clearAll === 'function' ? log.clearAll() : null
63
+ payload = result
64
+ ? { ok: true, action: 'all', ...result, describe: log.describe?.() ?? '' }
65
+ : { ok: false, error: '当前审计日志不支持清理' }
66
+ if (!result) status = 503
67
+ } else {
68
+ const result = typeof log.clearSession === 'function'
69
+ ? log.clearSession(/** @type {any} */ (body).sessionId)
70
+ : null
71
+ payload = result
72
+ ? { ok: true, action: 'session', ...result, describe: log.describe?.() ?? '' }
73
+ : { ok: false, error: '当前审计日志不支持清理' }
74
+ if (!result) status = 503
75
+ }
76
+ }
77
+ } catch (error) {
78
+ payload = { ok: false, error: error instanceof Error ? error.message : String(error) }
79
+ status = 500
80
+ }
81
+ const headers = {
82
+ 'content-type': 'application/json; charset=utf-8',
83
+ 'cache-control': 'no-store',
84
+ 'x-content-type-options': 'nosniff',
85
+ }
86
+ return new Response(`${JSON.stringify(payload)}\n`, { status, headers })
87
+ },
88
+ }
89
+ }
@@ -0,0 +1,265 @@
1
+ /**
2
+ * Conversation-facing audit feed.
3
+ *
4
+ * The Chat audit drawer reads the Host's hash-chained log through the Harness
5
+ * browser-native Fetch channel:
6
+ *
7
+ * GET /api/dsh-vigil/audit?limit=40
8
+ *
9
+ * `ctx.connection.fetch.register()` routes are mounted inside the authenticated
10
+ * `/api` channel, so the browser's same-origin `fetch` carries the normal signed
11
+ * credential and the carrier rejects unauthenticated peers before this handler
12
+ * runs. The route is therefore read-only and does not implement its own trust
13
+ * fence; it must never be mounted on the raw Web server instead.
14
+ *
15
+ * The payload contains only the already-scrubbed audit summary (tool name,
16
+ * decision, reason, rule ids, Sage attribution). Raw tool arguments never leave
17
+ * the Host through this route.
18
+ *
19
+ * @module dsh-vigil/audit-feed
20
+ */
21
+
22
+ import { nowIso, sha256 } from './util.js'
23
+ import { quarantineView } from './quarantine-view.js'
24
+ import { probeAlertWindow } from './alert-route.js'
25
+
26
+ /** Authenticated browser fetch path for the audit drawer. */
27
+ export const AUDIT_FEED_PATH = '/api/dsh-vigil/audit'
28
+
29
+ /** `installed()` walks every profile; cache it until the watcher checks again. */
30
+ const installedCache = new WeakMap()
31
+ /** Stable `generatedAt` while the feed content is unchanged (enables 204s). */
32
+ const feedCache = new WeakMap()
33
+
34
+ /**
35
+ * @param {any} watcher
36
+ * @returns {Array<object>}
37
+ */
38
+ function installedFor(watcher) {
39
+ if (!watcher || typeof watcher.installed !== 'function') return []
40
+ const key = `${watcher.lastCheckAt ?? ''}\u0000${watcher.lastError ?? ''}`
41
+ const cached = installedCache.get(watcher)
42
+ if (cached && cached.key === key) return cached.value
43
+ const value = watcher.installed()
44
+ const list = Array.isArray(value) ? value : []
45
+ installedCache.set(watcher, { key, value: list })
46
+ return list
47
+ }
48
+
49
+ /**
50
+ * Project the current runtime's audit entries into the feed payload.
51
+ * @param {any} runtime current runtime generation
52
+ * @param {{ isDisabled?: () => boolean }} deps
53
+ * @param {{ limit?: number }} [options]
54
+ * @returns {object}
55
+ */
56
+ export function buildAuditFeed(runtime, deps, options = {}) {
57
+ // The client projects this feed to one session. A window that is too small
58
+ // lets other sessions (or a busy subagent tree) push the current session's
59
+ // own blocks out, which read as "本会话还没有拦截记录". Keep a much wider
60
+ // window and let the per-session projection do the trimming.
61
+ const limit = Math.max(1, Math.min(Number(options.limit ?? 300) || 300, 500))
62
+ const windowSize = Math.max(limit * 2, 600)
63
+ const rawRecords = typeof runtime?.audit?.read === 'function'
64
+ ? runtime.audit.read({ limit: windowSize })
65
+ : []
66
+ const records = Array.isArray(rawRecords) ? rawRecords : []
67
+ /** @type {Array<{ ts: string, tool: string|null, decision: string, wouldBe: string|null, ruleIds: string[], reason: string, sage: object|null, session: string|null }>} */
68
+ const decisions = []
69
+ for (const record of records) {
70
+ if (record?.kind !== 'decision') continue
71
+ if (record.event !== 'pre-execute' && record.event !== 'pre-execute-error') continue
72
+ decisions.push({
73
+ ts: typeof record.ts === 'string' ? record.ts : '',
74
+ tool: typeof record.tool === 'string' ? record.tool : null,
75
+ decision: typeof record.decision === 'string' ? record.decision : 'none',
76
+ wouldBe: typeof record.wouldBe === 'string' ? record.wouldBe : null,
77
+ ruleIds: Array.isArray(record.ruleIds) ? record.ruleIds.filter(item => typeof item === 'string') : [],
78
+ reason: typeof record.reason === 'string' ? record.reason : '',
79
+ sage: record.sage && typeof record.sage === 'object'
80
+ ? {
81
+ threatId: typeof record.sage.threatId === 'string' ? record.sage.threatId : null,
82
+ category: typeof record.sage.category === 'string' ? record.sage.category : null,
83
+ severity: typeof record.sage.severity === 'string' ? record.sage.severity : null,
84
+ attribution: typeof record.sage.attribution === 'string' ? record.sage.attribution : 'Sage (@gendigital/sage-core, Apache-2.0)',
85
+ }
86
+ : null,
87
+ session: typeof record.session === 'string' ? record.session : null,
88
+ approval: record.approval && typeof record.approval === 'object'
89
+ ? {
90
+ action: typeof record.approval.action === 'string' ? record.approval.action : null,
91
+ scope: typeof record.approval.scope === 'string' ? record.approval.scope : null,
92
+ remembered: record.approval.remembered === true,
93
+ }
94
+ : null,
95
+ })
96
+ }
97
+ const recent = decisions.slice(-limit)
98
+ const counts = { allow: 0, ask: 0, deny: 0 }
99
+ for (const decision of recent) {
100
+ if (decision.decision === 'allow') counts.allow += 1
101
+ else if (decision.decision === 'ask') counts.ask += 1
102
+ else if (decision.decision === 'deny') counts.deny += 1
103
+ }
104
+ const sage = runtime?.sage?.status ?? {}
105
+ const feed = {
106
+ schema: 1,
107
+ generatedAt: nowIso(),
108
+ mode: runtime?.config?.mode ?? 'enforce',
109
+ /** Host locale hint for reasons that are still generated in Chinese. */
110
+ locale: typeof runtime?.config?.locale === 'string' ? runtime.config.locale : 'auto',
111
+ killSwitch: deps?.isDisabled?.() === true,
112
+ killSwitchPath: typeof runtime?.config?.killSwitch?.path === 'string' ? runtime.config.killSwitch.path : '',
113
+ killSwitchEnvVar: typeof runtime?.config?.killSwitch?.envVar === 'string' && runtime.config.killSwitch.envVar !== ''
114
+ ? runtime.config.killSwitch.envVar
115
+ : 'DSH_VIGIL_DISABLED',
116
+ notify: {
117
+ enabled: runtime?.config?.notify?.enabled !== false,
118
+ includeAsk: runtime?.config?.notify?.includeAsk !== false,
119
+ },
120
+ approval: {
121
+ /** The page can answer `ask` decisions itself instead of waiting on the host dialog. */
122
+ enabled: runtime?.config?.notify?.inlineApproval !== false,
123
+ timeoutMs: Number(runtime?.config?.notify?.approvalTimeoutMs) || 120000,
124
+ /** Per-session remembered allow state (blanket + per-finding). */
125
+ sessions: (() => {
126
+ try {
127
+ return Array.isArray(options.approval?.sessions?.()) ? options.approval.sessions() : []
128
+ } catch {
129
+ return []
130
+ }
131
+ })(),
132
+ },
133
+ /** Calls currently parked waiting for the page's 允许 / 拒绝 answer. */
134
+ pending: (() => {
135
+ try {
136
+ return Array.isArray(options.approval?.list?.()) ? options.approval.list() : []
137
+ } catch {
138
+ return []
139
+ }
140
+ })(),
141
+ decisions: recent,
142
+ counts,
143
+ /** Read-only status lines for the Settings page card. */
144
+ integrity: {
145
+ describe: typeof runtime?.integrity?.describe === 'function' ? runtime.integrity.describe() : '',
146
+ baseline: runtime?.integrity?.state?.baseline?.state ?? null,
147
+ },
148
+ rules: {
149
+ sources: Array.isArray(runtime?.rulePack?.sources) ? runtime.rulePack.sources.length : 0,
150
+ warnings: Array.isArray(runtime?.rulePack?.warnings) ? runtime.rulePack.warnings : [],
151
+ },
152
+ sage: {
153
+ state: typeof sage.state === 'string' ? sage.state : 'unknown',
154
+ version: typeof sage.version === 'string' ? sage.version : null,
155
+ rules: Number(sage.rules) || 0,
156
+ describe: typeof runtime?.sage?.describe === 'function' ? runtime.sage.describe() : '',
157
+ },
158
+ quarantine: quarantineView(runtime?.quarantine),
159
+ installAudits: (() => {
160
+ try {
161
+ const list = options.installWatcher?.list?.()
162
+ return Array.isArray(list) ? list : []
163
+ } catch {
164
+ return []
165
+ }
166
+ })(),
167
+ installScan: (() => {
168
+ try {
169
+ const watcher = options.installWatcher
170
+ return {
171
+ lastCheckAt: typeof watcher?.lastCheckAt === 'string' ? watcher.lastCheckAt : null,
172
+ lastError: typeof watcher?.lastError === 'string' ? watcher.lastError : null,
173
+ description: typeof watcher?.describe === 'function' ? watcher.describe() : '安装审计:未启用',
174
+ state: watcher?.state && typeof watcher.state === 'object' ? watcher.state : null,
175
+ installed: installedFor(watcher),
176
+ }
177
+ } catch {
178
+ return { lastCheckAt: null, lastError: null, description: '安装审计:不可用' }
179
+ }
180
+ })(),
181
+ audit: {
182
+ count: Number(runtime?.audit?.stats?.()?.total) || 0,
183
+ dir: typeof runtime?.audit?.dir === 'string' ? runtime.audit.dir : '',
184
+ },
185
+ alert: (() => {
186
+ const alert = runtime?.config?.notify?.alert
187
+ if (!alert || typeof alert !== 'object') {
188
+ return { enabled: false, sound: false, windowsNotification: false, raiseWindow: false }
189
+ }
190
+ return {
191
+ enabled: alert.enabled !== false,
192
+ sound: alert.sound !== false,
193
+ windowsNotification: alert.windowsNotification !== false,
194
+ raiseWindow: alert.raiseWindow !== false,
195
+ }
196
+ })(),
197
+ alertWindow: probeAlertWindow(),
198
+ }
199
+ // Keep `generatedAt` stable while the observable content is unchanged: the
200
+ // route hashes the body and can answer 204 instead of resending it on every
201
+ // 2.5s poll. Only a real change refreshes the timestamp.
202
+ const signature = JSON.stringify({ ...feed, generatedAt: null })
203
+ const cached = feedCache.get(runtime)
204
+ if (cached && cached.signature === signature) {
205
+ feed.generatedAt = cached.generatedAt
206
+ } else {
207
+ feed.generatedAt = nowIso()
208
+ feedCache.set(runtime, { signature, generatedAt: feed.generatedAt })
209
+ }
210
+ return feed
211
+ }
212
+
213
+ /**
214
+ * Build one `connection.fetch` route definition for the drawer.
215
+ * @param {{ getRuntime: () => any, isDisabled?: () => boolean, limit?: number, approval?: { list?: () => any[] }, installWatcher?: { list?: () => any[], lastCheckAt?: string|null, lastError?: string|null, describe?: () => string } }} deps
216
+ * @returns {{ path: string, methods: Array<'GET'|'HEAD'>, requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
217
+ */
218
+ export function createAuditFeedRoute(deps) {
219
+ return {
220
+ path: AUDIT_FEED_PATH,
221
+ methods: ['GET', 'HEAD'],
222
+ requestBody: 'buffered',
223
+ fetch: async request => {
224
+ let limit = deps.limit
225
+ try {
226
+ const requested = Number(new URL(request.url).searchParams.get('limit'))
227
+ if (Number.isInteger(requested) && requested > 0) limit = requested
228
+ } catch {
229
+ // malformed URL keeps the route default
230
+ }
231
+ let payload
232
+ try {
233
+ payload = {
234
+ ok: true,
235
+ ...buildAuditFeed(deps.getRuntime(), { isDisabled: deps.isDisabled }, {
236
+ limit,
237
+ approval: deps.approval,
238
+ installWatcher: deps.installWatcher,
239
+ }),
240
+ }
241
+ } catch (error) {
242
+ payload = { ok: false, error: error instanceof Error ? error.message : String(error) }
243
+ }
244
+ const body = `${JSON.stringify(payload)}\n`
245
+ const hash = sha256(body)
246
+ const etag = `"${hash}"`
247
+ const headers = {
248
+ 'content-type': 'application/json; charset=utf-8',
249
+ 'cache-control': 'no-store',
250
+ 'x-content-type-options': 'nosniff',
251
+ etag,
252
+ 'x-dsh-vigil-feed-hash': hash,
253
+ }
254
+ const method = String(request?.method ?? 'GET').toUpperCase()
255
+ if (method === 'HEAD') return new Response(null, { status: 200, headers })
256
+ const known = request.headers?.get?.('x-dsh-vigil-feed-hash') ?? request.headers?.get?.('if-none-match')
257
+ // Unchanged feed: answer 204 and let the page keep its current state
258
+ // instead of re-downloading and re-rendering the same 100+ KB payload.
259
+ if (typeof known === 'string' && (known === hash || known === etag)) {
260
+ return new Response(null, { status: 204, headers })
261
+ }
262
+ return new Response(body, { status: 200, headers })
263
+ },
264
+ }
265
+ }