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
package/src/util.js ADDED
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Small dependency-free helpers shared by the dsh-vigil Host plugin.
3
+ *
4
+ * The plugin deliberately ships with zero npm dependencies: it is installed from
5
+ * a local directory into a Harness profile, so every import must resolve from
6
+ * Node builtins or from files inside this package. Keeping the helpers here (and
7
+ * the code plain ES modules) also means the shipped files are the audited files
8
+ * — nothing is generated by a build step.
9
+ *
10
+ * @module dsh-vigil/util
11
+ */
12
+
13
+ import { createHash, randomBytes } from 'node:crypto'
14
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'
17
+
18
+ /** @returns {string} the OS user's home directory. */
19
+ export function getHomeDir() {
20
+ return process.env.HOME || process.env.USERPROFILE || homedir()
21
+ }
22
+
23
+ /**
24
+ * The Harness home directory. `DSH_HOME` is set for profile-launched Harnesses;
25
+ * `~/.dsh` is the documented fallback.
26
+ * @returns {string}
27
+ */
28
+ export function getDshHome() {
29
+ const fromEnv = process.env.DSH_HOME
30
+ if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return resolve(fromEnv)
31
+ return join(getHomeDir(), '.dsh')
32
+ }
33
+
34
+ /**
35
+ * Expand a leading `~` and process environment references in a configured path.
36
+ * @param {string} value
37
+ * @returns {string}
38
+ */
39
+ export function expandPath(value) {
40
+ if (typeof value !== 'string') return ''
41
+ let out = value.trim()
42
+ if (out === '') return ''
43
+ if (out === '~') return getHomeDir()
44
+ if (out.startsWith('~/') || out.startsWith('~\\')) out = join(getHomeDir(), out.slice(2))
45
+ out = out.replace(/%([A-Za-z_][A-Za-z0-9_]*)%/g, (match, name) => process.env[name] ?? match)
46
+ out = out.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name) => process.env[name] ?? match)
47
+ // PowerShell's $env:NAME — agents use it constantly, and a path that only
48
+ // spells the variable this way must still canonicalize to the same location.
49
+ out = out.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (match, name) => process.env[name] ?? match)
50
+ const home = getHomeDir()
51
+ out = out.replace(/^\$HOME(?=$|[\\/])/, home)
52
+ return out
53
+ }
54
+
55
+ /**
56
+ * Resolve a user/config supplied path to an absolute path.
57
+ * @param {string} value
58
+ * @param {string} [base] base directory for relative paths; defaults to process.cwd()
59
+ * @returns {string}
60
+ */
61
+ export function resolvePath(value, base) {
62
+ const expanded = expandPath(value)
63
+ if (expanded === '') return ''
64
+ return resolve(isAbsolute(expanded) ? expanded : join(base || process.cwd(), expanded))
65
+ }
66
+
67
+ /**
68
+ * Case-normalized key for path comparison. Windows paths compare
69
+ * case-insensitively; other platforms compare exactly.
70
+ * @param {string} value
71
+ * @returns {string}
72
+ */
73
+ export function pathKey(value) {
74
+ const normalized = normalize(value)
75
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
76
+ }
77
+
78
+ /**
79
+ * Whether `child` is `parent` itself or a descendant of it.
80
+ * @param {string} parent
81
+ * @param {string} child
82
+ * @returns {boolean}
83
+ */
84
+ export function isWithin(parent, child) {
85
+ if (!parent || !child) return false
86
+ const rel = relative(normalize(parent), normalize(child))
87
+ if (rel === '') return true
88
+ if (isAbsolute(rel)) return false
89
+ return !rel.startsWith(`..${sep}`) && rel !== '..'
90
+ }
91
+
92
+ /**
93
+ * Relative path from `base` with POSIX separators (stable in reports).
94
+ * @param {string} base
95
+ * @param {string} target
96
+ * @returns {string}
97
+ */
98
+ export function toPosixRelative(base, target) {
99
+ return relative(base, target).split(sep).join('/')
100
+ }
101
+
102
+ /** Cache of canonical forms; keyed by the expanded input, bounded. */
103
+ const CANONICAL_CACHE = new Map()
104
+ const CANONICAL_CACHE_MAX = 1024
105
+
106
+ /**
107
+ * Canonical absolute path used for security comparisons.
108
+ *
109
+ * The raw string a shell command carries is not a safe identity for a file:
110
+ * `~`, `%USERPROFILE%`, `$env:USERPROFILE`, 8.3 short names (`PROGRA~1`),
111
+ * junctions and `\\?\` prefixes can all name the same directory. A protected
112
+ * root check that compares strings therefore misses exactly the spellings an
113
+ * agent would use to slip past it. This resolves the nearest existing ancestor
114
+ * with `realpathSync.native` (which expands 8.3 names and strips device
115
+ * prefixes) and reappends the non-existent tail.
116
+ *
117
+ * Non-absolute input is only normalized, never resolved: the caller decides
118
+ * what a relative path means.
119
+ *
120
+ * @param {string} value
121
+ * @returns {string}
122
+ */
123
+ export function canonicalizePath(value) {
124
+ if (typeof value !== 'string' || value.trim() === '') return ''
125
+ const expanded = expandPath(value)
126
+ .replace(/^\\\\\?\\/, '')
127
+ .replace(/^\\\\\.\\/, '')
128
+ if (expanded === '') return ''
129
+ if (!isAbsolute(expanded)) return normalize(expanded)
130
+ const key = process.platform === 'win32' ? expanded.toLowerCase() : expanded
131
+ const cached = CANONICAL_CACHE.get(key)
132
+ if (cached !== undefined) return cached
133
+ const resolved = realpathWithExistingAncestor(expanded)
134
+ if (CANONICAL_CACHE.size >= CANONICAL_CACHE_MAX) CANONICAL_CACHE.clear()
135
+ CANONICAL_CACHE.set(key, resolved)
136
+ return resolved
137
+ }
138
+
139
+ /**
140
+ * @param {string} absolute
141
+ * @returns {string}
142
+ */
143
+ function realpathWithExistingAncestor(absolute) {
144
+ try {
145
+ return normalize(realpathSync.native(absolute))
146
+ } catch {
147
+ // The leaf may not exist yet (a delete target usually does, a write target
148
+ // often does not): canonicalize the nearest existing ancestor instead.
149
+ }
150
+ /** @type {string[]} */
151
+ const tail = []
152
+ let head = absolute
153
+ for (let depth = 0; depth < 16; depth += 1) {
154
+ const parent = dirname(head)
155
+ if (parent === head) break
156
+ tail.unshift(basename(head))
157
+ head = parent
158
+ try {
159
+ return normalize(join(realpathSync.native(head), ...tail))
160
+ } catch {
161
+ // keep walking up
162
+ }
163
+ }
164
+ return normalize(absolute)
165
+ }
166
+
167
+ /**
168
+ * Whether two path spellings name the same location (case-insensitive on
169
+ * Windows, 8.3/junction/`~` aware).
170
+ * @param {string} left
171
+ * @param {string} right
172
+ * @returns {boolean}
173
+ */
174
+ export function samePath(left, right) {
175
+ const a = canonicalizePath(left)
176
+ const b = canonicalizePath(right)
177
+ if (a === '' || b === '') return false
178
+ return pathKey(a) === pathKey(b)
179
+ }
180
+
181
+ /**
182
+ * `isWithin` for path spellings that need canonicalization first.
183
+ * @param {string} parent
184
+ * @param {string} child
185
+ * @returns {boolean}
186
+ */
187
+ export function isWithinCanonical(parent, child) {
188
+ const a = canonicalizePath(parent)
189
+ const b = canonicalizePath(child)
190
+ if (a === '' || b === '') return false
191
+ return isWithin(a, b)
192
+ }
193
+
194
+ /**
195
+ * SHA-256 hex digest of a string or buffer.
196
+ * @param {string|Uint8Array} input
197
+ * @returns {string}
198
+ */
199
+ export function sha256(input) {
200
+ return createHash('sha256').update(input).digest('hex')
201
+ }
202
+
203
+ /**
204
+ * Deterministic JSON for hashing records whose key order must not matter.
205
+ * Only plain objects/arrays/primitives are expected here.
206
+ * @param {unknown} value
207
+ * @returns {string}
208
+ */
209
+ export function stableStringify(value) {
210
+ if (value === null || typeof value !== 'object') return JSON.stringify(value)
211
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
212
+ const entries = Object.keys(/** @type {Record<string, unknown>} */ (value)).sort()
213
+ return `{${entries.map(key => `${JSON.stringify(key)}:${stableStringify(/** @type {Record<string, unknown>} */ (value)[key])}`).join(',')}}`
214
+ }
215
+
216
+ /**
217
+ * Create a directory tree, ignoring races where another writer won.
218
+ * @param {string} dir
219
+ * @returns {boolean} whether the directory exists afterwards
220
+ */
221
+ export function ensureDir(dir) {
222
+ try {
223
+ mkdirSync(dir, { recursive: true })
224
+ return true
225
+ } catch {
226
+ return existsSync(dir)
227
+ }
228
+ }
229
+
230
+ /**
231
+ * Write a file through a sibling temporary file so a crash cannot truncate the
232
+ * previous content.
233
+ * @param {string} file
234
+ * @param {string|Uint8Array} content
235
+ * @returns {boolean} whether the write succeeded
236
+ */
237
+ export function atomicWriteFile(file, content) {
238
+ const tmp = `${file}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
239
+ try {
240
+ ensureDir(join(file, '..'))
241
+ writeFileSync(tmp, content)
242
+ renameSync(tmp, file)
243
+ return true
244
+ } catch {
245
+ try {
246
+ unlinkSync(tmp)
247
+ } catch {
248
+ // best effort
249
+ }
250
+ return false
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Atomically persist a JSON document.
256
+ * @param {string} file
257
+ * @param {unknown} value
258
+ * @returns {boolean}
259
+ */
260
+ export function atomicWriteJson(file, value) {
261
+ return atomicWriteFile(file, `${JSON.stringify(value, null, 2)}\n`)
262
+ }
263
+
264
+ /**
265
+ * Read and parse JSON; returns `undefined` for absent or malformed files.
266
+ * @param {string} file
267
+ * @returns {any}
268
+ */
269
+ export function readJson(file) {
270
+ try {
271
+ return JSON.parse(readFileSync(file, 'utf8'))
272
+ } catch {
273
+ return undefined
274
+ }
275
+ }
276
+
277
+ /**
278
+ * File size in bytes, or `undefined` when the path is not a regular file.
279
+ * @param {string} file
280
+ * @returns {number|undefined}
281
+ */
282
+ export function fileSize(file) {
283
+ try {
284
+ const stat = statSync(file)
285
+ return stat.isFile() ? stat.size : undefined
286
+ } catch {
287
+ return undefined
288
+ }
289
+ }
290
+
291
+ /**
292
+ * Human readable byte size. Uses binary units (KiB/MiB/GiB), matching how
293
+ * deletion thresholds are configured.
294
+ * @param {number} bytes
295
+ * @returns {string}
296
+ */
297
+ export function formatBytes(bytes) {
298
+ if (!Number.isFinite(bytes) || bytes < 0) return '?'
299
+ if (bytes < 1024) return `${bytes} B`
300
+ const units = ['KiB', 'MiB', 'GiB', 'TiB']
301
+ let value = bytes / 1024
302
+ let index = 0
303
+ while (value >= 1024 && index < units.length - 1) {
304
+ value /= 1024
305
+ index += 1
306
+ }
307
+ return `${value >= 100 ? Math.round(value) : value.toFixed(1)} ${units[index]}`
308
+ }
309
+
310
+ /** @returns {string} ISO timestamp of the current instant. */
311
+ export function nowIso() {
312
+ return new Date().toISOString()
313
+ }
314
+
315
+ /**
316
+ * Clamp a string to a maximum length, marking truncation explicitly so a
317
+ * truncated audit record is never mistaken for the full value.
318
+ * @param {unknown} value
319
+ * @param {number} max
320
+ * @returns {string}
321
+ */
322
+ export function truncate(value, max) {
323
+ const text = typeof value === 'string' ? value : value === undefined || value === null ? '' : String(value)
324
+ if (text.length <= max) return text
325
+ return `${text.slice(0, Math.max(0, max - 1))}…`
326
+ }
327
+
328
+ /**
329
+ * Remove the current user's home directory (and the Harness home) from a string
330
+ * so paths in logs and reports do not leak the account name.
331
+ * @param {string} text
332
+ * @returns {string}
333
+ */
334
+ export function scrubHome(text) {
335
+ if (typeof text !== 'string' || text === '') return ''
336
+ const home = getHomeDir()
337
+ if (!home) return text
338
+ const variants = [home, home.replace(/\\/g, '\\\\')]
339
+ let out = text
340
+ for (const variant of variants) {
341
+ if (variant.length > 2) out = out.split(variant).join('~')
342
+ }
343
+ const dshHome = process.env.DSH_HOME
344
+ if (typeof dshHome === 'string' && dshHome.length > 2) {
345
+ out = out.split(dshHome).join('<DSH_HOME>').split(dshHome.replace(/\\/g, '\\\\')).join('<DSH_HOME>')
346
+ }
347
+ return out
348
+ }
349
+
350
+ /**
351
+ * @param {string} [prefix]
352
+ * @returns {string} a short random id safe for file names
353
+ */
354
+ export function randomId(prefix = '') {
355
+ return `${prefix}${Date.now().toString(36)}-${randomBytes(4).toString('hex')}`
356
+ }
357
+
358
+ /**
359
+ * @param {unknown} value
360
+ * @returns {value is Record<string, unknown>}
361
+ */
362
+ export function isPlainObject(value) {
363
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
364
+ }
365
+
366
+ /**
367
+ * Recursively merge `overrides` into `base` without mutating either. Arrays are
368
+ * replaced, not concatenated: a preset's protected-root list is a complete
369
+ * statement of intent.
370
+ * @param {Record<string, unknown>} base
371
+ * @param {Record<string, unknown>} overrides
372
+ * @returns {Record<string, unknown>}
373
+ */
374
+ export function deepMerge(base, overrides) {
375
+ const result = { ...base }
376
+ for (const [key, value] of Object.entries(overrides || {})) {
377
+ if (value === undefined) continue
378
+ const previous = result[key]
379
+ if (isPlainObject(previous) && isPlainObject(value)) {
380
+ result[key] = deepMerge(previous, value)
381
+ } else {
382
+ result[key] = value
383
+ }
384
+ }
385
+ return result
386
+ }
387
+
388
+ /**
389
+ * Run `fn` and capture a thrown error as a value.
390
+ * @template T
391
+ * @param {() => T} fn
392
+ * @returns {{ ok: true, value: T } | { ok: false, error: Error }}
393
+ */
394
+ export function attempt(fn) {
395
+ try {
396
+ return { ok: true, value: fn() }
397
+ } catch (error) {
398
+ return { ok: false, error: error instanceof Error ? error : new Error(String(error)) }
399
+ }
400
+ }
@@ -0,0 +1,25 @@
1
+ # Optional Sage threat rules
2
+
3
+ This directory is intentionally empty in the source package.
4
+
5
+ dsh-vigil does **not** bundle `@gendigital/sage-core` or its YAML rule set. Reasons,
6
+ recorded as a deliberate deviation from the original requirement draft (FR-2.2, §9):
7
+
8
+ 1. **Licensing/attribution**: Sage rules are Apache-2.0 under DRL 1.1 obligations
9
+ (retain author attribution, cite the source, credit the rule when a match is
10
+ reported). Vendoring a drifting rule set into this package would put that
11
+ upkeep on dsh-vigil.
12
+ 2. **Supply-chain surface**: a security plugin whose job is to reduce install-time
13
+ risk should not add native optional dependencies (`koffi`,
14
+ `onnxruntime-node`) to every installation.
15
+ 3. **Offline determinism**: the built-in rule set must work with no extra package
16
+ and no network.
17
+
18
+ When you enable `sage.enabled` and point `sage.threatsDir` at a Sage rules
19
+ directory (or set `SAGE_THREATS_DIR`), the adapter loads the rules through Sage's
20
+ own `loadThreats()` and reports matches with attribution
21
+ ("Sage (@gendigital/sage-core, Apache-2.0)").
22
+
23
+ If a future release vendors rules here, each bundled rule must keep its original
24
+ author attribution, cite its upstream source, and every matching verdict must
25
+ carry the rule id. Do not add rules here without that record.