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,194 @@
1
+ /**
2
+ * Approval window-alert route.
3
+ *
4
+ * POST /api/dsh-vigil/alert-window { action: 'raise' | 'clear' | 'focus' }
5
+ *
6
+ * Capability chain (best-effort, never throws):
7
+ * 1. Electron window control (Host runs in a desktop window process):
8
+ * raise = restore/show/focus + temporary always-on-top;
9
+ * focus = restore previous top state and bring the window forward;
10
+ * clear = restore the previous always-on-top state.
11
+ * 2. Fallback on Windows: `FlashWindowEx`. `raise` flashes the taskbar button
12
+ * until it is cleared (or the window is focused); `focus` restores and
13
+ * foregrounds the DSH window with `ShowWindow` + `SetForegroundWindow`.
14
+ * 3. Otherwise report `unavailable`; the client falls back to window.focus()
15
+ * and the notification click.
16
+ *
17
+ * @module dsh-vigil/alert-route
18
+ */
19
+
20
+ import { createRequire } from 'node:module'
21
+ import { execFile } from 'node:child_process'
22
+
23
+ /** Authenticated browser fetch path for the approval alert window action. */
24
+ export const ALERT_WINDOW_PATH = '/api/dsh-vigil/alert-window'
25
+
26
+ /** Load Electron from the Host process; null outside the Desktop main process. */
27
+ function defaultLoadElectron() {
28
+ try {
29
+ return createRequire(import.meta.url)('electron')
30
+ } catch {
31
+ return null
32
+ }
33
+ }
34
+
35
+ /**
36
+ * PowerShell script that flashes/stops/foregrounds the DSH taskbar button.
37
+ * The script is fixed text: no user input is ever interpolated into it.
38
+ */
39
+ function buildWindowScript(action) {
40
+ // FLASHW_CAPTION 1, FLASHW_TRAY 2, FLASHW_TIMER 4, FLASHW_TIMERNOFG 8.
41
+ // raise: keep flashing until the window is foreground. clear: stop.
42
+ const flags = action === 'raise' ? '(0x1 -bor 0x2 -bor 0xC)' : '0x0'
43
+ return [
44
+ "$ErrorActionPreference = 'SilentlyContinue'",
45
+ 'Add-Type @"',
46
+ 'using System;',
47
+ 'using System.Runtime.InteropServices;',
48
+ 'public class VigilWin32 {',
49
+ ' [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public uint cbSize; public IntPtr hwnd; public uint dwFlags; public uint uCount; public uint dwTimeout; }',
50
+ ' [DllImport("user32.dll")] public static extern bool FlashWindowEx(ref FLASHWINFO pwfi);',
51
+ ' [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);',
52
+ ' [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr hWnd);',
53
+ '}',
54
+ '"@',
55
+ `$flags = ${flags}`,
56
+ "$wins = Get-Process | Where-Object { $_.MainWindowHandle -ne 0 -and ($_.MainWindowTitle -match 'DeepSeek|Harness' -or $_.ProcessName -match 'DeepSeek|Harness') }",
57
+ 'foreach ($w in $wins) {',
58
+ ' $info = New-Object VigilWin32+FLASHWINFO',
59
+ ' $info.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($info)',
60
+ ' $info.hwnd = $w.MainWindowHandle',
61
+ ' $info.dwFlags = $flags',
62
+ ' $info.uCount = 0',
63
+ ' $info.dwTimeout = 0',
64
+ ' [void][VigilWin32]::FlashWindowEx([ref]$info)',
65
+ '}',
66
+ action === 'focus'
67
+ ? 'foreach ($w in $wins) { [void][VigilWin32]::ShowWindow($w.MainWindowHandle, 9); [void][VigilWin32]::SetForegroundWindow($w.MainWindowHandle) }'
68
+ : '',
69
+ ].filter(Boolean).join('\n')
70
+ }
71
+
72
+ /** @returns {Promise<boolean>} whether the window script ran successfully */
73
+ function defaultWindowAction(action) {
74
+ return new Promise(resolve => {
75
+ try {
76
+ execFile(
77
+ 'powershell.exe',
78
+ ['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-Command', buildWindowScript(action)],
79
+ { timeout: 8000, windowsHide: true },
80
+ error => resolve(!error),
81
+ )
82
+ } catch {
83
+ resolve(false)
84
+ }
85
+ })
86
+ }
87
+
88
+ /**
89
+ * Report how the Host can draw attention to the window right now.
90
+ * @param {() => any} [loadElectron]
91
+ * @param {NodeJS.Platform} [platform]
92
+ * @returns {{ mode: 'electron'|'flash'|'unavailable', windows: number }}
93
+ */
94
+ export function probeAlertWindow(loadElectron = defaultLoadElectron, platform = process.platform) {
95
+ try {
96
+ const electron = loadElectron()
97
+ const browserWindow = electron?.BrowserWindow
98
+ const windows = typeof browserWindow?.getAllWindows === 'function'
99
+ ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
100
+ : []
101
+ if (windows.length > 0) return { mode: 'electron', windows: windows.length }
102
+ } catch {
103
+ // fall through to the platform fallback
104
+ }
105
+ return platform === 'win32' ? { mode: 'flash', windows: 0 } : { mode: 'unavailable', windows: 0 }
106
+ }
107
+
108
+ /**
109
+ * @param {{ loadElectron?: () => any, platform?: NodeJS.Platform, windowAction?: (action: 'raise'|'clear'|'focus') => Promise<boolean> }} [deps]
110
+ * @returns {{ path: string, methods: string[], requestBody: 'buffered', fetch: (request: Request) => Promise<Response> }}
111
+ */
112
+ export function createAlertWindowRoute(deps = {}) {
113
+ const loadElectron = deps.loadElectron ?? defaultLoadElectron
114
+ const platform = deps.platform ?? process.platform
115
+ const windowAction = deps.windowAction ?? defaultWindowAction
116
+ /** Windows whose always-on-top state we changed, with the previous value. */
117
+ const raised = new Map()
118
+
119
+ const json = (payload, status = 200) => new Response(`${JSON.stringify(payload)}\n`, {
120
+ status,
121
+ headers: {
122
+ 'content-type': 'application/json; charset=utf-8',
123
+ 'cache-control': 'no-store',
124
+ 'x-content-type-options': 'nosniff',
125
+ },
126
+ })
127
+
128
+ const restoreTop = () => {
129
+ for (const [win, previous] of raised) {
130
+ try {
131
+ win.setAlwaysOnTop(previous)
132
+ } catch {
133
+ // window already gone
134
+ }
135
+ }
136
+ raised.clear()
137
+ }
138
+
139
+ return {
140
+ path: ALERT_WINDOW_PATH,
141
+ methods: ['POST'],
142
+ requestBody: 'buffered',
143
+ fetch: async request => {
144
+ let body = null
145
+ try {
146
+ body = typeof request?.json === 'function' ? await request.json().catch(() => null) : null
147
+ } catch {
148
+ body = null
149
+ }
150
+ const action = body?.action === 'clear' ? 'clear' : body?.action === 'focus' ? 'focus' : 'raise'
151
+
152
+ let windows = []
153
+ try {
154
+ const electron = loadElectron()
155
+ const browserWindow = electron?.BrowserWindow
156
+ windows = typeof browserWindow?.getAllWindows === 'function'
157
+ ? browserWindow.getAllWindows().filter(win => win && (typeof win.isDestroyed !== 'function' || !win.isDestroyed()))
158
+ : []
159
+ } catch {
160
+ windows = []
161
+ }
162
+
163
+ if (windows.length > 0) {
164
+ if (action === 'clear') {
165
+ restoreTop()
166
+ return json({ ok: true, mode: 'electron', action, windows: windows.length })
167
+ }
168
+ if (action === 'focus') restoreTop()
169
+ for (const win of windows) {
170
+ try {
171
+ if (typeof win.isMinimized === 'function' && win.isMinimized()) win.restore()
172
+ if (typeof win.show === 'function') win.show()
173
+ if (typeof win.focus === 'function') win.focus()
174
+ if (action === 'raise' && typeof win.setAlwaysOnTop === 'function' && !raised.has(win)) {
175
+ const previous = typeof win.isAlwaysOnTop === 'function' ? Boolean(win.isAlwaysOnTop()) : false
176
+ raised.set(win, previous)
177
+ if (!previous) win.setAlwaysOnTop(true, 'floating')
178
+ }
179
+ } catch {
180
+ // best-effort per window
181
+ }
182
+ }
183
+ return json({ ok: true, mode: 'electron', action, windows: windows.length })
184
+ }
185
+
186
+ if (platform === 'win32') {
187
+ const ok = await windowAction(action)
188
+ return json({ ok, mode: 'flash', action })
189
+ }
190
+
191
+ return json({ ok: false, mode: 'unavailable', action })
192
+ },
193
+ }
194
+ }
@@ -0,0 +1,398 @@
1
+ /**
2
+ * In-conversation approvals for `ask` decisions.
3
+ *
4
+ * Harness approval prompts can be unavailable (approval policy "never", headless
5
+ * sessions, or a host that never renders a dialog). For the Verdicts this plugin
6
+ * raises as `ask`, the sentinel instead parks the call in this queue and waits
7
+ * for the page's own buttons:
8
+ *
9
+ * - 拒绝 → deny this call
10
+ * - 允许一次 → allow this call only
11
+ * - 允许 → allow this call and remember `<tool>|<ruleIds>` for the
12
+ * Session, so the same finding is not asked again
13
+ *
14
+ * The page answers over the authenticated browser Fetch channel:
15
+ * POST /api/dsh-vigil/approval { id, action }
16
+ *
17
+ * A request that nobody answers expires into a deny (fail closed) and is
18
+ * audited. Aborting the tool call resolves it immediately as deny. When the
19
+ * queue is full or unavailable the sentinel falls back to the host's own `ask`
20
+ * path, so no call is silently allowed.
21
+ *
22
+ * @module dsh-vigil/approval
23
+ */
24
+
25
+ import { nowIso } from './util.js'
26
+
27
+ /** Authenticated browser Fetch path for approval answers. */
28
+ export const APPROVAL_ROUTE_PATH = '/api/dsh-vigil/approval'
29
+
30
+ const DEFAULT_TIMEOUT_MS = 120_000
31
+ const MAX_PENDING = 8
32
+
33
+ /**
34
+ * @param {string|null|undefined} tool
35
+ * @param {string[]} [ruleIds]
36
+ * @returns {string}
37
+ */
38
+ function signatureOf(tool, ruleIds = []) {
39
+ return `${tool ?? ''}|${[...new Set(ruleIds)].sort().join(',')}`
40
+ }
41
+
42
+ /**
43
+ * Create the per-plugin approval queue. One instance lives for the plugin
44
+ * lifetime so pending approvals survive volatile-config rebuilds.
45
+ * @param {{ getTimeoutMs?: () => number, maxPending?: number, audit?: any, logger?: { warn?: (message: string) => void } }} [options]
46
+ */
47
+ export function createApprovalQueue(options = {}) {
48
+ const getTimeoutMs = typeof options.getTimeoutMs === 'function'
49
+ ? options.getTimeoutMs
50
+ : () => Number(options.timeoutMs) || DEFAULT_TIMEOUT_MS
51
+ const maxPending = Math.max(1, Number(options.maxPending) || MAX_PENDING)
52
+ const audit = options.audit
53
+ /** @type {Map<string, any>} */
54
+ const pending = new Map()
55
+ /** @type {Map<string, Set<string>>} */
56
+ const sessionAllow = new Map()
57
+ /** Sessions where the user pressed "always allow high-risk" in the dock. */
58
+ const sessionAlwaysAllow = new Set()
59
+ /** Number of in-flight pre-execute evaluations; lets the page show a checking hint. */
60
+ let evaluating = 0
61
+ let sequence = 0
62
+ let disposed = false
63
+
64
+ /**
65
+ * @param {{ tool: string, command?: string|null, reason?: string, ruleIds?: string[], sage?: any, sessionId?: string|null }} input
66
+ * @returns {{ id: string, tool: string, command: string|null, reason: string, ruleIds: string[], sage: any, sessionId: string|null, createdAt: string, expiresAt: string }}
67
+ */
68
+ function prepare(input) {
69
+ const id = `ap_${Date.now().toString(36)}_${(sequence += 1).toString(36)}`
70
+ return {
71
+ id,
72
+ tool: String(input.tool ?? ''),
73
+ command: typeof input.command === 'string' && input.command.trim() !== '' ? input.command : null,
74
+ reason: typeof input.reason === 'string' ? input.reason : '',
75
+ ruleIds: Array.isArray(input.ruleIds) ? [...new Set(input.ruleIds)] : [],
76
+ sage: input.sage ?? null,
77
+ sessionId: input.sessionId ?? null,
78
+ createdAt: nowIso(),
79
+ expiresAt: new Date(Date.now() + Math.max(5_000, Number(getTimeoutMs()) || DEFAULT_TIMEOUT_MS)).toISOString(),
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Park one decision and wait for the page's answer.
85
+ * @param {{ tool: string, command?: string|null, reason?: string, ruleIds?: string[], sage?: any, sessionId?: string|null, signal?: AbortSignal }} input
86
+ * @returns {Promise<{ action: 'allow'|'deny', scope: string, id: string, tool: string, ruleIds: string[] }>}
87
+ */
88
+ function request(input) {
89
+ if (disposed) return Promise.resolve({ action: 'deny', scope: 'disposed', id: '', tool: String(input.tool ?? ''), ruleIds: input.ruleIds ?? [] })
90
+ if (pending.size >= maxPending) {
91
+ return Promise.resolve({ action: 'deny', scope: 'queue-full', id: '', tool: String(input.tool ?? ''), ruleIds: input.ruleIds ?? [] })
92
+ }
93
+ const base = prepare(input)
94
+ const timeoutMs = Math.max(5_000, Number(getTimeoutMs()) || DEFAULT_TIMEOUT_MS)
95
+ return new Promise(resolve => {
96
+ /** @param {'allow'|'deny'} action @param {string} scope */
97
+ const finish = (action, scope) => {
98
+ const entry = pending.get(base.id)
99
+ if (!entry) return
100
+ pending.delete(base.id)
101
+ clearTimeout(entry.timer)
102
+ try {
103
+ entry.cleanup?.()
104
+ } catch {
105
+ // listener already detached
106
+ }
107
+ resolve({ action, scope, id: base.id, tool: entry.tool, ruleIds: entry.ruleIds })
108
+ }
109
+ const timer = setTimeout(() => {
110
+ try {
111
+ audit?.record({
112
+ kind: 'decision',
113
+ event: 'approval',
114
+ tool: base.tool,
115
+ session: base.sessionId,
116
+ decision: 'deny',
117
+ ruleIds: base.ruleIds,
118
+ reason: '等待对话内确认超时,已按拒绝处理(fail-closed)',
119
+ })
120
+ } catch {
121
+ // audit failures never change the decision
122
+ }
123
+ finish('deny', 'timeout')
124
+ }, timeoutMs)
125
+ const entry = { ...base, timer, cleanup: null, finish }
126
+ pending.set(base.id, entry)
127
+ if (input.signal) {
128
+ const onAbort = () => {
129
+ try {
130
+ audit?.record({
131
+ kind: 'decision',
132
+ event: 'approval',
133
+ tool: base.tool,
134
+ session: base.sessionId,
135
+ decision: 'deny',
136
+ ruleIds: base.ruleIds,
137
+ reason: '调用被取消,待确认请求已撤销',
138
+ })
139
+ } catch {
140
+ // ignore
141
+ }
142
+ finish('deny', 'aborted')
143
+ }
144
+ if (input.signal.aborted) onAbort()
145
+ else {
146
+ input.signal.addEventListener('abort', onAbort, { once: true })
147
+ entry.cleanup = () => input.signal.removeEventListener('abort', onAbort)
148
+ }
149
+ }
150
+ })
151
+ }
152
+
153
+ /**
154
+ * Apply one page answer.
155
+ * @param {string} id
156
+ * @param {string} action `allow-once` | `allow` | `deny`
157
+ * @returns {{ ok: boolean, error?: string }}
158
+ */
159
+ function resolve(id, action) {
160
+ const entry = pending.get(id)
161
+ if (!entry) return { ok: false, error: 'unknown-or-expired' }
162
+ if (action === 'allow-once') {
163
+ entry.finish('allow', 'once')
164
+ return { ok: true }
165
+ }
166
+ if (action === 'allow') {
167
+ if (entry.sessionId) {
168
+ let allowed = sessionAllow.get(entry.sessionId)
169
+ if (!allowed) {
170
+ allowed = new Set()
171
+ sessionAllow.set(entry.sessionId, allowed)
172
+ }
173
+ allowed.add(signatureOf(entry.tool, entry.ruleIds))
174
+ // "允许(本会话)" and the dock's "始终允许高危" are the same state:
175
+ // approving in the dialog also flips the dock switch on.
176
+ sessionAlwaysAllow.add(entry.sessionId)
177
+ }
178
+ entry.finish('allow', 'session')
179
+ return { ok: true }
180
+ }
181
+ if (action === 'deny') {
182
+ entry.finish('deny', 'user')
183
+ return { ok: true }
184
+ }
185
+ return { ok: false, error: 'invalid-action' }
186
+ }
187
+
188
+ /**
189
+ * Whether this exact finding already has a Session-scoped allow.
190
+ * @param {{ sessionId?: string|null, tool: string, ruleIds?: string[] }} input
191
+ */
192
+ function isSessionAllowed(input) {
193
+ if (!input.sessionId) return false
194
+ const allowed = sessionAllow.get(input.sessionId)
195
+ return Boolean(allowed && allowed.has(signatureOf(input.tool, input.ruleIds)))
196
+ }
197
+
198
+ /**
199
+ * Toggle the session-wide "always allow" switch. Turning it off also forgets
200
+ * every per-finding session allow, so the next matching call asks again.
201
+ * @param {string} sessionId
202
+ * @param {boolean} enabled
203
+ * @returns {{ ok: boolean, error?: string, sessionId?: string, alwaysAllow?: boolean, remembered?: number }}
204
+ */
205
+ function setSessionAlwaysAllow(sessionId, enabled) {
206
+ const id = typeof sessionId === 'string' ? sessionId : ''
207
+ if (id === '') return { ok: false, error: 'missing-session' }
208
+ if (enabled) sessionAlwaysAllow.add(id)
209
+ else {
210
+ sessionAlwaysAllow.delete(id)
211
+ sessionAllow.delete(id)
212
+ }
213
+ try {
214
+ audit?.record({
215
+ kind: 'event',
216
+ event: 'approval-always-allow',
217
+ session: id,
218
+ reason: enabled
219
+ ? '本会话已开启“始终允许高危”,后续询问将自动放行'
220
+ : '本会话已取消“始终允许高危”,后续询问恢复确认',
221
+ extra: { enabled },
222
+ })
223
+ } catch {
224
+ // audit failures never change the answer
225
+ }
226
+ return { ok: true, sessionId: id, alwaysAllow: enabled, remembered: sessionAllow.get(id)?.size ?? 0 }
227
+ }
228
+
229
+ /** @param {string|null|undefined} sessionId */
230
+ function isSessionAlwaysAllowed(sessionId) {
231
+ return Boolean(sessionId && sessionAlwaysAllow.has(sessionId))
232
+ }
233
+
234
+ /** Per-session allow state for the dock switch and tests. @param {string} sessionId */
235
+ function sessionState(sessionId) {
236
+ const id = typeof sessionId === 'string' ? sessionId : ''
237
+ return { sessionId: id, alwaysAllow: isSessionAlwaysAllowed(id), remembered: sessionAllow.get(id)?.size ?? 0 }
238
+ }
239
+
240
+ /** Every session that has at least one remembered allow or the blanket flag. */
241
+ function sessions() {
242
+ const ids = new Set([...sessionAlwaysAllow, ...sessionAllow.keys()])
243
+ return [...ids].map(id => sessionState(id))
244
+ }
245
+
246
+ /** Pending approvals as plain JSON for the audit feed. */
247
+ function list() {
248
+ return [...pending.values()].map(entry => ({
249
+ id: entry.id,
250
+ tool: entry.tool,
251
+ command: entry.command,
252
+ reason: entry.reason,
253
+ ruleIds: entry.ruleIds,
254
+ sage: entry.sage,
255
+ session: entry.sessionId,
256
+ createdAt: entry.createdAt,
257
+ expiresAt: entry.expiresAt,
258
+ }))
259
+ }
260
+
261
+ /**
262
+ * Mark the beginning of one pre-execute evaluation. The returned function
263
+ * ends it; it is idempotent so callers can use it in a finally block.
264
+ * @returns {() => void}
265
+ */
266
+ function beginEvaluation() {
267
+ evaluating += 1
268
+ let ended = false
269
+ return () => {
270
+ if (ended) return
271
+ ended = true
272
+ evaluating = Math.max(0, evaluating - 1)
273
+ }
274
+ }
275
+
276
+ /** @returns {boolean} whether at least one evaluation is in flight. */
277
+ function isEvaluating() {
278
+ return evaluating > 0
279
+ }
280
+
281
+ function dispose() {
282
+ disposed = true
283
+ for (const entry of [...pending.values()]) {
284
+ try {
285
+ entry.finish('deny', 'disposed')
286
+ } catch {
287
+ // ignore
288
+ }
289
+ }
290
+ pending.clear()
291
+ sessionAllow.clear()
292
+ sessionAlwaysAllow.clear()
293
+ }
294
+
295
+ return {
296
+ request,
297
+ resolve,
298
+ list,
299
+ isSessionAllowed,
300
+ isSessionAlwaysAllowed,
301
+ setSessionAlwaysAllow,
302
+ sessionState,
303
+ sessions,
304
+ list,
305
+ beginEvaluation,
306
+ isEvaluating,
307
+ dispose,
308
+ get size() {
309
+ return pending.size
310
+ },
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Build the `connection.fetch` route that accepts the page's answers.
316
+ * @param {{ getQueue: () => { resolve: (id: string, action: string) => { ok: boolean, error?: string }, size: number } | null | undefined }} deps
317
+ */
318
+ export function createApprovalRoute(deps) {
319
+ const headers = {
320
+ 'content-type': 'application/json; charset=utf-8',
321
+ 'cache-control': 'no-store',
322
+ 'x-content-type-options': 'nosniff',
323
+ }
324
+ return {
325
+ path: APPROVAL_ROUTE_PATH,
326
+ methods: ['GET', 'POST'],
327
+ requestBody: 'buffered',
328
+ fetch: async request => {
329
+ const method = typeof request?.method === 'string' ? request.method.toUpperCase() : 'POST'
330
+ if (method === 'GET') {
331
+ const queue = deps.getQueue?.()
332
+ if (!queue) {
333
+ return new Response(JSON.stringify({ ok: false, error: 'unavailable' }), { status: 503, headers })
334
+ }
335
+ let waitMs = 0
336
+ try {
337
+ waitMs = Number(new URL(request.url).searchParams.get('wait')) || 0
338
+ } catch {
339
+ waitMs = 0
340
+ }
341
+ waitMs = Math.min(20_000, Math.max(0, waitMs))
342
+ const startedAt = Date.now()
343
+ const snapshot = () => {
344
+ const watcher = deps.getWatcher?.()
345
+ const scanState = watcher && typeof watcher.state === 'object' ? watcher.state : null
346
+ return {
347
+ ok: true,
348
+ evaluating: typeof queue.isEvaluating === 'function' ? queue.isEvaluating() === true : false,
349
+ pending: typeof queue.list === 'function' ? queue.list() : [],
350
+ scanning: scanState && typeof scanState.analyzing === 'string' ? scanState.analyzing : null,
351
+ }
352
+ }
353
+ let payload = snapshot()
354
+ // Long-poll: return as soon as an evaluation starts, a request parks, or
355
+ // an install scan begins, so the page can show its hint without waiting
356
+ // for the regular audit-feed cadence.
357
+ while (
358
+ !payload.evaluating
359
+ && payload.pending.length === 0
360
+ && payload.scanning === null
361
+ && Date.now() - startedAt < waitMs
362
+ ) {
363
+ if (request.signal?.aborted) break
364
+ await new Promise(resolve => setTimeout(resolve, 100))
365
+ payload = snapshot()
366
+ }
367
+ return new Response(JSON.stringify(payload), { headers })
368
+ }
369
+ let body
370
+ try {
371
+ body = await request.json()
372
+ } catch {
373
+ return new Response(JSON.stringify({ ok: false, error: 'invalid-json' }), { status: 400, headers })
374
+ }
375
+ const id = typeof body?.id === 'string' ? body.id : ''
376
+ const action = typeof body?.action === 'string' ? body.action : ''
377
+ const queue = deps.getQueue?.()
378
+ if (!queue) {
379
+ return new Response(JSON.stringify({ ok: false, error: 'unavailable' }), { status: 503, headers })
380
+ }
381
+ if (action === 'always-allow') {
382
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''
383
+ const result = typeof queue.setSessionAlwaysAllow === 'function'
384
+ ? queue.setSessionAlwaysAllow(sessionId, body?.enabled === true)
385
+ : { ok: false, error: 'unsupported' }
386
+ return new Response(JSON.stringify({ ok: result.ok, ...result }), {
387
+ status: result.ok ? 200 : 400,
388
+ headers,
389
+ })
390
+ }
391
+ const result = queue.resolve(id, action)
392
+ return new Response(JSON.stringify({ ok: result.ok, ...result, pending: queue.size }), {
393
+ status: result.ok ? 200 : 409,
394
+ headers,
395
+ })
396
+ },
397
+ }
398
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Dialog artwork route.
3
+ *
4
+ * The Web client runs from a single `client.js`; it cannot read files from the
5
+ * package directory. The two dialog illustrations are therefore served by the
6
+ * Host over the authenticated browser Fetch channel:
7
+ *
8
+ * GET /api/dsh-vigil/artwork?name=warning|notice
9
+ *
10
+ * Only the two whitelisted names are readable, and the bytes are cached in
11
+ * memory after the first read. Unknown names return 404 (no path traversal:
12
+ * the request never becomes a filesystem path).
13
+ *
14
+ * @module dsh-vigil/artwork-route
15
+ */
16
+
17
+ import { readFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /** Authenticated browser fetch path for the dialog illustrations. */
21
+ export const ARTWORK_PATH = '/api/dsh-vigil/artwork'
22
+
23
+ /** Whitelisted illustration names and their package-relative files. */
24
+ const ARTWORK_FILES = new Map([
25
+ ['warning', 'illustrations/warning.png'],
26
+ ['notice', 'illustrations/notice.png'],
27
+ ])
28
+
29
+ /**
30
+ * @param {{ pluginDir: string }} deps
31
+ * @returns {{ path: string, methods: string[], fetch: (request: Request) => Promise<Response> }}
32
+ */
33
+ export function createArtworkRoute(deps) {
34
+ /** @type {Map<string, Buffer|null>} */
35
+ const cache = new Map()
36
+
37
+ /** @param {string} name @returns {Buffer|null} */
38
+ const read = name => {
39
+ if (cache.has(name)) return cache.get(name) ?? null
40
+ const relative = ARTWORK_FILES.get(name)
41
+ if (!relative) return null
42
+ try {
43
+ const bytes = readFileSync(join(deps.pluginDir, relative))
44
+ cache.set(name, bytes)
45
+ return bytes
46
+ } catch {
47
+ // Missing artwork must not break the dialog: the client falls back to
48
+ // hiding the image on a 404.
49
+ cache.set(name, null)
50
+ return null
51
+ }
52
+ }
53
+
54
+ return {
55
+ path: ARTWORK_PATH,
56
+ methods: ['GET'],
57
+ fetch: async request => {
58
+ let name = ''
59
+ try {
60
+ name = new URL(String(request.url ?? ''), 'http://127.0.0.1').searchParams.get('name') ?? ''
61
+ } catch {
62
+ name = ''
63
+ }
64
+ const bytes = read(name)
65
+ if (!bytes) {
66
+ return new Response('not found\n', {
67
+ status: 404,
68
+ headers: {
69
+ 'content-type': 'text/plain; charset=utf-8',
70
+ 'cache-control': 'no-store',
71
+ 'x-content-type-options': 'nosniff',
72
+ },
73
+ })
74
+ }
75
+ return new Response(bytes, {
76
+ status: 200,
77
+ headers: {
78
+ 'content-type': 'image/png',
79
+ // The file is bundled with the plugin version, so a short public
80
+ // cache is safe and avoids re-sending it for every dialog open.
81
+ 'cache-control': 'public, max-age=3600',
82
+ 'x-content-type-options': 'nosniff',
83
+ },
84
+ })
85
+ },
86
+ }
87
+ }