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/config.js ADDED
@@ -0,0 +1,580 @@
1
+ /**
2
+ * Configuration model for dsh-vigil.
3
+ *
4
+ * Configuration reaches the Host plugin as live `Config` references (see
5
+ * `config-schema.js`). `live-config.js` snapshots them into a plain object, and
6
+ * `resolveConfig` validates that snapshot against the built-in defaults, merging
7
+ * deep sections and reporting warnings instead of throwing. A plugin that throws
8
+ * during activation would fail the whole bundle, so malformed config must degrade
9
+ * to a documented default rather than break the Harness.
10
+ *
11
+ * Decisions use three kinds, matching `PreToolDecision`:
12
+ * - `allow` — let the call proceed (still audited).
13
+ * - `ask` — rely on the Harness approval channel. The Host turns `ask` into
14
+ * a denial when no approval answerer is available, which is the
15
+ * fail-closed behaviour dsh-vigil wants.
16
+ * - `deny` — refuse outright.
17
+ *
18
+ * @module dsh-vigil/config
19
+ */
20
+
21
+ import { join } from 'node:path'
22
+ import { isPlainObject, deepMerge, resolvePath, getDshHome } from './util.js'
23
+
24
+ /** @typedef {'allow'|'ask'|'deny'} DecisionKind */
25
+
26
+ /** Suspicious egress destinations: file-sharing, tunnelling and paste endpoints. */
27
+ const SUSPICIOUS_HOSTS = Object.freeze([
28
+ 'pastebin.com',
29
+ 'paste.ee',
30
+ 'transfer.sh',
31
+ 'file.io',
32
+ '0x0.st',
33
+ 'webhook.site',
34
+ 'requestbin.',
35
+ 'pipedream.net',
36
+ 'ngrok.io',
37
+ 'ngrok-free.app',
38
+ 'serveo.net',
39
+ 'localtunnel.me',
40
+ 'trycloudflare.com',
41
+ ])
42
+
43
+ /** Built-in defaults: the effective values a fresh installation runs with. */
44
+ export const DEFAULT_CONFIG = Object.freeze({
45
+ /** `enforce` applies decisions; `monitor` only records what it would decide. */
46
+ mode: 'enforce',
47
+ /** Narrative language for cards: `auto`, `en`, or `zh`. */
48
+ locale: 'auto',
49
+ killSwitch: {
50
+ enabled: true,
51
+ /** Empty means `<DSH_HOME>/vigil/DISABLED`. */
52
+ path: '',
53
+ envVar: 'DSH_VIGIL_DISABLED',
54
+ },
55
+ sentinel: {
56
+ enabled: true,
57
+ credentialReads: 'ask',
58
+ credentialExfil: 'deny',
59
+ suspiciousHosts: [...SUSPICIOUS_HOSTS],
60
+ postToUnknownHost: 'ask',
61
+ downloadToUnknownHost: 'allow',
62
+ allowedHosts: [],
63
+ /**
64
+ * Download-and-execute (`curl … | sh`, `iwr … | iex`, Invoke-Expression)
65
+ * decision: deny (default) / ask / allow. The old boolean
66
+ * `denyDynamicRemoteCode` is migrated to this field.
67
+ */
68
+ dynamicRemoteCode: 'deny',
69
+ encodedCommand: 'ask',
70
+ configTamper: 'deny',
71
+ persistenceWrites: 'ask',
72
+ dshPluginInstall: 'ask',
73
+ /**
74
+ * Irreversible system destruction (disk/partition/boot, registry, shadow
75
+ * copies, event logs, security controls, trust store, system accounts):
76
+ * deny (default) / ask / allow.
77
+ */
78
+ destructiveSystem: 'deny',
79
+ /**
80
+ * Large-scale data destruction (databases, containers, cloud resources, git
81
+ * history, availability actions): ask (default) / deny / allow.
82
+ */
83
+ destructiveData: 'ask',
84
+ /** Extra tool names that are audited but never blocked. */
85
+ allowTools: [],
86
+ },
87
+ deleteGuard: {
88
+ enabled: true,
89
+ recursive: 'ask',
90
+ wildcard: 'ask',
91
+ unknownTarget: 'ask',
92
+ critical: 'deny',
93
+ high: 'ask',
94
+ medium: 'allow',
95
+ thresholds: {
96
+ maxFiles: 1000,
97
+ maxBytes: 314572800,
98
+ /** Bound on how many entries one intent may enumerate. */
99
+ perCallMaxFiles: 20000,
100
+ },
101
+ extraCriticalRoots: [],
102
+ extraHighRoots: [],
103
+ includeProjectRootAsHigh: true,
104
+ /**
105
+ * Base directory for relative delete targets and the high project root.
106
+ * Empty means "process.cwd() when it is not inside the Harness home"; the
107
+ * Desktop app's host process runs from the profile directory, where relative
108
+ * paths would otherwise be classified as critical Harness state.
109
+ */
110
+ projectRoot: '',
111
+ observeScale: true,
112
+ },
113
+ sage: {
114
+ enabled: false,
115
+ /** When true, a newer stable engine/rule pair is installed automatically. */
116
+ autoUpdate: true,
117
+ /** Minimum time between registry checks (default: one day). */
118
+ updateIntervalMs: 86400000,
119
+ /** When true, an enabled-but-unavailable Sage engine denies tool calls. */
120
+ required: false,
121
+ modulePath: '',
122
+ threatsDir: '',
123
+ trustedDomainsDir: '',
124
+ sensitivity: 'balanced',
125
+ timeoutMs: 2000,
126
+ /** Keep Sage's network checks (URL/file/package reputation) off by default. */
127
+ disableNetworkChecks: true,
128
+ },
129
+ quarantine: {
130
+ enabled: true,
131
+ dir: '',
132
+ ttlDays: 7,
133
+ maxEntries: 5000,
134
+ /** Copy the entry metadata next to the payload for manual recovery. */
135
+ metadataFile: 'manifest.json',
136
+ },
137
+ integrity: {
138
+ enabled: true,
139
+ baseline: true,
140
+ canary: true,
141
+ intervalMs: 1800000,
142
+ signatureEnabled: false,
143
+ publicKeyPem: '',
144
+ signatureFile: '',
145
+ },
146
+ auditLog: {
147
+ enabled: true,
148
+ dir: '',
149
+ maxBytes: 8388608,
150
+ maxFiles: 5,
151
+ /** Log a scrubbed argument summary; false logs lengths and hashes only. */
152
+ logArguments: true,
153
+ argumentChars: 300,
154
+ /**
155
+ * Optional external anchor: an HMAC over the chain head, written every
156
+ * `everyN` records, so a full rewrite of the local chain can be detected.
157
+ * The key is read from the environment (`keyEnv`), never from the log dir.
158
+ */
159
+ anchor: {
160
+ enabled: false,
161
+ keyEnv: 'DSH_VIGIL_ANCHOR_KEY',
162
+ everyN: 100,
163
+ },
164
+ },
165
+ tools: {
166
+ enabled: true,
167
+ },
168
+ /**
169
+ * Static audit tuning (install-time gate and `vigil_scan`).
170
+ *
171
+ * `ast.level` maps an AST-derived capability hit to a severity:
172
+ * low -> notice (report only)
173
+ * medium -> review (default; shows up in the report, no install question)
174
+ * high -> blocker (the install gate asks before continuing)
175
+ */
176
+ scan: {
177
+ ast: {
178
+ enabled: true,
179
+ level: 'medium',
180
+ },
181
+ },
182
+ /**
183
+ * External rule packs (YAML). Empty means `<DSH_HOME>/vigil/rules`; files there
184
+ * are applied on top of the shipped pack, so threat data can be updated
185
+ * without a plugin release.
186
+ */
187
+ rules: {
188
+ dir: '',
189
+ /**
190
+ * Optional HTTPS manifest for remote rule-pack updates:
191
+ * `{ "version": "...", "files": { "sentinel.yaml": "https://…" } }`.
192
+ * Defaults to the GitHub raw manifest (fresh every request). The settings
193
+ * page also offers a jsDelivr preset for networks where raw.githubusercontent
194
+ * is unreachable; that CDN caches branch refs for a while, so new rules may
195
+ * lag behind. Set it to '' to disable remote checks entirely.
196
+ */
197
+ source: 'https://raw.githubusercontent.com/DusklitSakura/dsh-vigil/main/rules/manifest.json',
198
+ autoUpdate: false,
199
+ updateIntervalMs: 21600000,
200
+ },
201
+ /** Decision for calls that would delete/move the plugin or its state. */
202
+ selfProtection: 'deny',
203
+ /** Conversation-facing notices shown inside the Chat composer area. */
204
+ notify: {
205
+ /** Show a banner when the sentinel blocks or questions a call. */
206
+ enabled: true,
207
+ /** Include `ask` decisions in the banner (deny always when enabled). */
208
+ includeAsk: true,
209
+ /** Answer `ask` decisions in the conversation instead of the host dialog. */
210
+ inlineApproval: true,
211
+ /** How long an inline approval may wait before failing closed. */
212
+ approvalTimeoutMs: 120000,
213
+ /**
214
+ * Approval alerts shown while the page/window is not focused, so an
215
+ * approval is not missed while working in another application.
216
+ */
217
+ alert: {
218
+ enabled: true,
219
+ /** Short chime via Web Audio. */
220
+ sound: true,
221
+ /** Windows notification-center toast via the browser Notification API. */
222
+ windowsNotification: true,
223
+ /** Raise the DSH window (Host-side Electron: show/focus and temporary top). */
224
+ raiseWindow: true,
225
+ },
226
+ },
227
+ /** Guard-level: allow the agent to uninstall dsh-vigil itself. */
228
+ allowSelfUninstall: false,
229
+ })
230
+
231
+ /**
232
+ * Normalize an aliased decision word to a {@link DecisionKind}, or `undefined`.
233
+ * @param {unknown} value
234
+ * @returns {DecisionKind|undefined}
235
+ */
236
+ export function normalizeDecisionWord(value) {
237
+ if (typeof value !== 'string') return undefined
238
+ const word = value.trim().toLowerCase()
239
+ if (word === 'allow' || word === 'permit' || word === 'pass') return 'allow'
240
+ if (word === 'ask' || word === 'confirm' || word === 'prompt') return 'ask'
241
+ if (word === 'deny' || word === 'block' || word === 'refuse') return 'deny'
242
+ return undefined
243
+ }
244
+
245
+ /**
246
+ * Severity ordering for merging decisions: deny beats ask beats allow.
247
+ * @param {DecisionKind} kind
248
+ * @returns {number}
249
+ */
250
+ export function decisionRank(kind) {
251
+ return kind === 'deny' ? 3 : kind === 'ask' ? 2 : 1
252
+ }
253
+
254
+ /**
255
+ * Merge two decisions, keeping the strictest.
256
+ * @param {DecisionKind} left
257
+ * @param {DecisionKind} right
258
+ * @returns {DecisionKind}
259
+ */
260
+ export function strictestDecision(left, right) {
261
+ return decisionRank(left) >= decisionRank(right) ? left : right
262
+ }
263
+
264
+ /**
265
+ * Resolve the effective configuration from a live-config snapshot.
266
+ *
267
+ * @param {unknown} raw plain configuration object (see `snapshotConfig`)
268
+ * @returns {{ config: any, warnings: string[] }}
269
+ */
270
+ export function resolveConfig(raw) {
271
+ /** @type {string[]} */
272
+ const warnings = []
273
+ const input = isPlainObject(raw) ? raw : {}
274
+ if (raw !== undefined && raw !== null && !isPlainObject(raw)) {
275
+ warnings.push('配置不是对象;已忽略并使用内置默认值')
276
+ }
277
+
278
+ const config = deepMerge(DEFAULT_CONFIG, input)
279
+
280
+ // A section supplied as a non-object (string, array, number) would make every
281
+ // later field write throw in module strict mode. Replace it with the defaults
282
+ // and report it, so one typo cannot fail the whole bundle activation.
283
+ for (const section of Object.keys(DEFAULT_CONFIG)) {
284
+ if (section === 'mode' || section === 'locale' || section === 'allowSelfUninstall' || section === 'selfProtection') continue
285
+ if (!isPlainObject(config[section])) {
286
+ warnings.push(`${section} 必须是对象;已回退到默认值`)
287
+ config[section] = cloneDefault(DEFAULT_CONFIG[section])
288
+ continue
289
+ }
290
+ }
291
+ if (!isPlainObject(config.deleteGuard.thresholds)) {
292
+ warnings.push('deleteGuard.thresholds 必须是对象;已回退到默认值')
293
+ config.deleteGuard.thresholds = cloneDefault(DEFAULT_CONFIG.deleteGuard.thresholds)
294
+ }
295
+ if (!isPlainObject(config.auditLog.anchor)) {
296
+ warnings.push('auditLog.anchor 必须是对象;已回退到默认值')
297
+ config.auditLog.anchor = cloneDefault(DEFAULT_CONFIG.auditLog.anchor)
298
+ }
299
+ if (!isPlainObject(config.scan.ast)) {
300
+ warnings.push('scan.ast 必须是对象;已回退到默认值')
301
+ config.scan.ast = cloneDefault(DEFAULT_CONFIG.scan.ast)
302
+ }
303
+ if (!isPlainObject(config.notify.alert)) {
304
+ warnings.push('notify.alert 必须是对象;已回退到默认值')
305
+ config.notify.alert = cloneDefault(DEFAULT_CONFIG.notify.alert)
306
+ }
307
+ // Deprecated boolean -> tri-state decision. A profile that still carries
308
+ // `denyDynamicRemoteCode` keeps its intent (false meant allow).
309
+ if (Object.prototype.hasOwnProperty.call(config.sentinel, 'denyDynamicRemoteCode')) {
310
+ const legacy = config.sentinel.denyDynamicRemoteCode
311
+ delete config.sentinel.denyDynamicRemoteCode
312
+ const inputSentinel = isPlainObject(input.sentinel) ? input.sentinel : {}
313
+ if (!Object.prototype.hasOwnProperty.call(inputSentinel, 'dynamicRemoteCode')) {
314
+ config.sentinel.dynamicRemoteCode = legacy === false ? 'allow' : 'deny'
315
+ }
316
+ }
317
+
318
+ // Deprecated default -> GitHub raw. Older profiles persisted the old jsDelivr
319
+ // default; keeping it would leave users on a cached source they never chose.
320
+ // The settings page dropdown can switch back to jsDelivr explicitly.
321
+ const legacyJsdelivrSource = 'https://cdn.jsdelivr.net/gh/DusklitSakura/dsh-vigil@main/rules/manifest.json'
322
+ if (config.rules && config.rules.source === legacyJsdelivrSource) {
323
+ // Silent migration: the new default is GitHub raw. A warning here would make
324
+ // every doctor run report a config failure until the user re-saves settings.
325
+ config.rules.source = DEFAULT_CONFIG.rules.source
326
+ }
327
+
328
+ if (config.mode !== 'enforce' && config.mode !== 'monitor') {
329
+ warnings.push('mode 必须是 enforce 或 monitor;回退到 enforce')
330
+ config.mode = 'enforce'
331
+ }
332
+ if (!['auto', 'en', 'zh'].includes(config.locale)) {
333
+ warnings.push('locale 必须是 auto/en/zh;回退到 auto')
334
+ config.locale = 'auto'
335
+ }
336
+ if (!['low', 'medium', 'high'].includes(config.scan.ast.level)) {
337
+ warnings.push('scan.ast.level 必须是 low/medium/high;回退到 medium')
338
+ config.scan.ast.level = 'medium'
339
+ }
340
+
341
+ validateDecisionFields(config, warnings)
342
+ validateIntegers(config, warnings)
343
+ validateStringArrays(config, warnings)
344
+
345
+ config.paths = derivePaths(config)
346
+ return { config, warnings }
347
+ }
348
+
349
+ /**
350
+ * Deep-copy a default section so a validation fallback cannot mutate
351
+ * {@link DEFAULT_CONFIG}.
352
+ * @param {unknown} value
353
+ * @returns {any}
354
+ */
355
+ function cloneDefault(value) {
356
+ try {
357
+ return JSON.parse(JSON.stringify(value))
358
+ } catch {
359
+ return value
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Validate every decision-kind field. Invalid values fall back to the same
365
+ * field of the built-in defaults, never to a weaker value.
366
+ * @param {any} config
367
+ * @param {string[]} warnings
368
+ */
369
+ function validateDecisionFields(config, warnings) {
370
+ /** @type {Array<[any, string, string, any]>} */
371
+ const fields = [
372
+ [config.sentinel, 'credentialReads', 'sentinel.credentialReads', DEFAULT_CONFIG.sentinel.credentialReads],
373
+ [config.sentinel, 'credentialExfil', 'sentinel.credentialExfil', DEFAULT_CONFIG.sentinel.credentialExfil],
374
+ [config.sentinel, 'postToUnknownHost', 'sentinel.postToUnknownHost', DEFAULT_CONFIG.sentinel.postToUnknownHost],
375
+ [config.sentinel, 'downloadToUnknownHost', 'sentinel.downloadToUnknownHost', DEFAULT_CONFIG.sentinel.downloadToUnknownHost],
376
+ [config.sentinel, 'dynamicRemoteCode', 'sentinel.dynamicRemoteCode', DEFAULT_CONFIG.sentinel.dynamicRemoteCode],
377
+ [config.sentinel, 'encodedCommand', 'sentinel.encodedCommand', DEFAULT_CONFIG.sentinel.encodedCommand],
378
+ [config.sentinel, 'configTamper', 'sentinel.configTamper', DEFAULT_CONFIG.sentinel.configTamper],
379
+ [config.sentinel, 'persistenceWrites', 'sentinel.persistenceWrites', DEFAULT_CONFIG.sentinel.persistenceWrites],
380
+ [config.sentinel, 'dshPluginInstall', 'sentinel.dshPluginInstall', DEFAULT_CONFIG.sentinel.dshPluginInstall],
381
+ [config.deleteGuard, 'recursive', 'deleteGuard.recursive', DEFAULT_CONFIG.deleteGuard.recursive],
382
+ [config.deleteGuard, 'wildcard', 'deleteGuard.wildcard', DEFAULT_CONFIG.deleteGuard.wildcard],
383
+ [config.deleteGuard, 'unknownTarget', 'deleteGuard.unknownTarget', DEFAULT_CONFIG.deleteGuard.unknownTarget],
384
+ [config.deleteGuard, 'critical', 'deleteGuard.critical', DEFAULT_CONFIG.deleteGuard.critical],
385
+ [config.deleteGuard, 'high', 'deleteGuard.high', DEFAULT_CONFIG.deleteGuard.high],
386
+ [config.deleteGuard, 'medium', 'deleteGuard.medium', DEFAULT_CONFIG.deleteGuard.medium],
387
+ ]
388
+ for (const [holder, field, label, fallback] of fields) {
389
+ const normalized = normalizeDecisionWord(holder[field])
390
+ if (normalized === undefined) {
391
+ warnings.push(`${label} 取值无效;已回退为 ${fallback}`)
392
+ holder[field] = fallback
393
+ } else {
394
+ holder[field] = normalized
395
+ }
396
+ }
397
+ if (config.deleteGuard.critical === 'allow') {
398
+ warnings.push('deleteGuard.critical 不允许为 allow;已回退到 deny')
399
+ config.deleteGuard.critical = 'deny'
400
+ }
401
+ const selfProtection = normalizeDecisionWord(config.selfProtection)
402
+ if (selfProtection === undefined || selfProtection === 'allow') {
403
+ warnings.push(`selfProtection 取值无效;已回退为 ${DEFAULT_CONFIG.selfProtection}`)
404
+ config.selfProtection = DEFAULT_CONFIG.selfProtection
405
+ } else {
406
+ config.selfProtection = selfProtection
407
+ }
408
+ if (config.deleteGuard.critical === 'deny' && config.mode === 'monitor') {
409
+ warnings.push('mode=monitor:critical 命中只记录,不拦断')
410
+ }
411
+ }
412
+
413
+ /**
414
+ * @param {any} config
415
+ * @param {string[]} warnings
416
+ */
417
+ function validateIntegers(config, warnings) {
418
+ /** @type {Array<[any, string, number, number]>} */
419
+ const fields = [
420
+ [config.deleteGuard.thresholds, 'maxFiles', 1, DEFAULT_CONFIG.deleteGuard.thresholds.maxFiles],
421
+ [config.deleteGuard.thresholds, 'maxBytes', 1, DEFAULT_CONFIG.deleteGuard.thresholds.maxBytes],
422
+ [config.deleteGuard.thresholds, 'perCallMaxFiles', 1, DEFAULT_CONFIG.deleteGuard.thresholds.perCallMaxFiles],
423
+ [config.quarantine, 'ttlDays', 1, DEFAULT_CONFIG.quarantine.ttlDays],
424
+ [config.quarantine, 'maxEntries', 1, DEFAULT_CONFIG.quarantine.maxEntries],
425
+ [config.integrity, 'intervalMs', 1000, DEFAULT_CONFIG.integrity.intervalMs],
426
+ [config.auditLog, 'maxBytes', 4096, DEFAULT_CONFIG.auditLog.maxBytes],
427
+ [config.auditLog, 'maxFiles', 1, DEFAULT_CONFIG.auditLog.maxFiles],
428
+ [config.auditLog, 'argumentChars', 16, DEFAULT_CONFIG.auditLog.argumentChars],
429
+ [config.auditLog.anchor, 'everyN', 1, DEFAULT_CONFIG.auditLog.anchor.everyN],
430
+ [config.rules, 'updateIntervalMs', 60000, DEFAULT_CONFIG.rules.updateIntervalMs],
431
+ [config.notify, 'approvalTimeoutMs', 5000, DEFAULT_CONFIG.notify.approvalTimeoutMs],
432
+ [config.sage, 'timeoutMs', 10, DEFAULT_CONFIG.sage.timeoutMs],
433
+ ]
434
+ for (const [holder, field, minimum, fallback] of fields) {
435
+ const value = holder[field]
436
+ if (!Number.isFinite(value) || value < minimum) {
437
+ warnings.push(`${field} 数值无效;已重置为默认值`)
438
+ holder[field] = fallback
439
+ } else {
440
+ holder[field] = Math.floor(value)
441
+ }
442
+ }
443
+ for (const [value, label] of [
444
+ [config.sentinel.enabled, 'sentinel.enabled'],
445
+ [config.deleteGuard.enabled, 'deleteGuard.enabled'],
446
+ [config.integrity.enabled, 'integrity.enabled'],
447
+ [config.auditLog.enabled, 'auditLog.enabled'],
448
+ [config.tools.enabled, 'tools.enabled'],
449
+ [config.quarantine.enabled, 'quarantine.enabled'],
450
+ [config.notify.enabled, 'notify.enabled'],
451
+ [config.notify.includeAsk, 'notify.includeAsk'],
452
+ [config.notify.inlineApproval, 'notify.inlineApproval'],
453
+ [config.auditLog.anchor.enabled, 'auditLog.anchor.enabled'],
454
+ [config.scan.ast.enabled, 'scan.ast.enabled'],
455
+ [config.rules.autoUpdate, 'rules.autoUpdate'],
456
+ ]) {
457
+ if (typeof value !== 'boolean') warnings.push(`${label} 必须是布尔值;已按 truthy 处理`)
458
+ }
459
+ }
460
+
461
+ /**
462
+ * @param {any} config
463
+ * @param {string[]} warnings
464
+ */
465
+ function validateStringArrays(config, warnings) {
466
+ if (!config.auditLog.anchor || typeof config.auditLog.anchor !== 'object') {
467
+ warnings.push('auditLog.anchor 必须是对象;已重置为默认值')
468
+ config.auditLog.anchor = { ...DEFAULT_CONFIG.auditLog.anchor }
469
+ }
470
+ if (typeof config.auditLog.anchor.keyEnv !== 'string' || config.auditLog.anchor.keyEnv.trim() === '') {
471
+ warnings.push('auditLog.anchor.keyEnv 不是有效环境变量名;已回退默认')
472
+ config.auditLog.anchor.keyEnv = DEFAULT_CONFIG.auditLog.anchor.keyEnv
473
+ }
474
+ if (!config.rules || typeof config.rules !== 'object') {
475
+ warnings.push('rules 必须是对象;已重置为默认值')
476
+ config.rules = { dir: '' }
477
+ }
478
+ if (typeof config.rules.source !== 'string') {
479
+ warnings.push('rules.source 必须是字符串;已回退为空')
480
+ config.rules.source = ''
481
+ } else {
482
+ config.rules.source = config.rules.source.trim()
483
+ }
484
+ if (typeof config.rules.dir !== 'string') {
485
+ warnings.push('rules.dir 必须是字符串;已重置为空')
486
+ config.rules.dir = ''
487
+ } else {
488
+ config.rules.dir = config.rules.dir.trim()
489
+ }
490
+ if (typeof config.deleteGuard.projectRoot !== 'string') {
491
+ warnings.push('deleteGuard.projectRoot 必须是字符串;已重置为空')
492
+ config.deleteGuard.projectRoot = ''
493
+ } else {
494
+ config.deleteGuard.projectRoot = config.deleteGuard.projectRoot.trim()
495
+ }
496
+ for (const key of ['extraCriticalRoots', 'extraHighRoots']) {
497
+ const value = config.deleteGuard[key]
498
+ if (!Array.isArray(value)) {
499
+ warnings.push(`deleteGuard.${key} 必须是路径字符串数组;已重置`)
500
+ config.deleteGuard[key] = []
501
+ continue
502
+ }
503
+ config.deleteGuard[key] = value
504
+ .filter(item => typeof item === 'string' && item.trim() !== '')
505
+ .map(item => item.trim())
506
+ }
507
+ for (const key of ['allowedHosts', 'suspiciousHosts']) {
508
+ const value = config.sentinel[key]
509
+ if (!Array.isArray(value)) {
510
+ warnings.push(`sentinel.${key} 必须是字符串数组;已重置`)
511
+ config.sentinel[key] = [...DEFAULT_CONFIG.sentinel[key]]
512
+ continue
513
+ }
514
+ config.sentinel[key] = value.filter(item => typeof item === 'string' && item.trim() !== '').map(item => item.trim().toLowerCase())
515
+ }
516
+ if (!Array.isArray(config.sentinel.allowTools)) {
517
+ warnings.push('sentinel.allowTools 必须是字符串数组;已重置')
518
+ config.sentinel.allowTools = []
519
+ }
520
+ }
521
+
522
+ /**
523
+ * Derive absolute state paths from the resolved configuration.
524
+ * @param {any} config
525
+ * @returns {{ dshHome: string, stateDir: string, quarantineDir: string, auditDir: string, integrityDir: string, baselineFile: string, canaryFile: string, killSwitchFile: string }}
526
+ */
527
+ export function derivePaths(config) {
528
+ const dshHome = getDshHome()
529
+ const stateDir = join(dshHome, 'vigil')
530
+ return {
531
+ dshHome,
532
+ stateDir,
533
+ quarantineDir: config?.quarantine?.dir ? resolvePath(config.quarantine.dir, dshHome) : join(stateDir, 'quarantine'),
534
+ auditDir: config?.auditLog?.dir ? resolvePath(config.auditLog.dir, dshHome) : join(stateDir, 'log'),
535
+ integrityDir: join(stateDir, 'integrity'),
536
+ baselineFile: join(stateDir, 'integrity', 'baseline.json'),
537
+ canaryFile: join(stateDir, 'integrity', 'canary.txt'),
538
+ killSwitchFile: config?.killSwitch?.path ? resolvePath(config.killSwitch.path, dshHome) : join(stateDir, 'DISABLED'),
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Resolve the narrative locale against the process locale.
544
+ * @param {any} config
545
+ * @returns {'en'|'zh'}
546
+ */
547
+ export function resolveLocale(config) {
548
+ const configured = config?.locale
549
+ if (configured === 'en' || configured === 'zh') return configured
550
+ try {
551
+ const locale = Intl.DateTimeFormat().resolvedOptions().locale || ''
552
+ if (/^zh/i.test(locale)) return 'zh'
553
+ } catch {
554
+ // fall through
555
+ }
556
+ return 'en'
557
+ }
558
+
559
+ /**
560
+ * Whether the emergency disable switch is engaged. Environment wins over the
561
+ * marker file so an operator can always recover a broken installation.
562
+ * @param {any} config
563
+ * @param {{ existsSync: (path: string) => boolean }} fsApi injected for testability
564
+ * @returns {{ active: boolean, source: 'env'|'file'|null }}
565
+ */
566
+ export function killSwitchState(config, fsApi) {
567
+ const envVar = config?.killSwitch?.envVar
568
+ if (envVar && process.env[envVar] && process.env[envVar] !== '0') {
569
+ return { active: true, source: 'env' }
570
+ }
571
+ if (config?.killSwitch?.enabled !== false) {
572
+ const file = config?.paths?.killSwitchFile
573
+ try {
574
+ if (file && fsApi.existsSync(file)) return { active: true, source: 'file' }
575
+ } catch {
576
+ // an unreadable switch must not disable protection silently; report as off
577
+ }
578
+ }
579
+ return { active: false, source: null }
580
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Canonical delete/move/truncate command names.
3
+ *
4
+ * `parser.js` classifies chunks by shell, `parser-posix.js` dispatches POSIX
5
+ * delete commands and `sentinel/guard.js` decides which statements can destroy
6
+ * the plugin directory. They previously kept independent lists, so a command
7
+ * could be classified as POSIX yet missing from the POSIX dispatch table (the
8
+ * `mv`/`ren` self-protection bypass). New names go here once.
9
+ *
10
+ * @module delete/command-kinds
11
+ */
12
+
13
+ /** @type {ReadonlyMap<string, 'delete'|'move'|'truncate'>} */
14
+ export const COMMAND_KINDS = new Map([
15
+ ['rm', 'delete'],
16
+ ['rmdir', 'delete'],
17
+ ['unlink', 'delete'],
18
+ ['shred', 'delete'],
19
+ ['find', 'delete'],
20
+ ['xargs', 'delete'],
21
+ ['git', 'delete'],
22
+ ['rsync', 'delete'],
23
+ ['del', 'delete'],
24
+ ['erase', 'delete'],
25
+ ['rd', 'delete'],
26
+ ['mv', 'move'],
27
+ ['move', 'move'],
28
+ ['ren', 'move'],
29
+ ['rename', 'move'],
30
+ ['move-item', 'move'],
31
+ ['rename-item', 'move'],
32
+ ['clear-content', 'truncate'],
33
+ ['set-content', 'truncate'],
34
+ ['out-file', 'truncate'],
35
+ ])
36
+
37
+ /** POSIX commands the POSIX parser dispatches (including `mv` for guard targets). */
38
+ export const POSIX_DELETE_COMMANDS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'find', 'xargs', 'git', 'rsync', 'mv'])
39
+
40
+ /** Commands that move/rename rather than delete. */
41
+ export const MOVE_COMMANDS = new Set([...COMMAND_KINDS].filter(([, kind]) => kind === 'move').map(([name]) => name))
42
+
43
+ /** @param {string} name @returns {boolean} */
44
+ export function isMoveCommand(name) {
45
+ return MOVE_COMMANDS.has(String(name || '').toLowerCase())
46
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Shared lexical primitives for the three shell deletion parsers.
3
+ *
4
+ * The parsers used to define the same sentinel, token cap, unmask and basename
5
+ * helpers independently; a divergence there changes what counts as a delete
6
+ * target on only one shell. Keep the primitives here.
7
+ *
8
+ * @module delete/lex
9
+ */
10
+
11
+ /** Sentinel protecting literal characters from variable/glob expansion. */
12
+ export const ESC = '\u0001'
13
+
14
+ /** Hard cap on tokens per simple command (pathological input defence). */
15
+ export const MAX_TOKENS = 2048
16
+
17
+ /**
18
+ * Decode masked text (`\u0001$` -> `$`).
19
+ * @param {string} value
20
+ * @returns {string}
21
+ */
22
+ export function unmask(value) {
23
+ return typeof value === 'string' && value.indexOf(ESC) >= 0 ? value.split(ESC).join('') : String(value || '')
24
+ }
25
+
26
+ /**
27
+ * Lowercase basename of a command word without stripping a call operator.
28
+ * Handles `/usr/bin/rm` and `C:\tools\rm.exe`.
29
+ * @param {string} value
30
+ * @returns {string}
31
+ */
32
+ export function baseName(value) {
33
+ const text = unmask(value).trim()
34
+ const idx = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
35
+ return (idx >= 0 ? text.slice(idx + 1) : text).replace(/\.exe$/i, '').toLowerCase()
36
+ }
37
+
38
+ /**
39
+ * PowerShell command word: like {@link baseName}, but also strips a leading
40
+ * call operator (`& 'rm'`).
41
+ * @param {string} value
42
+ * @returns {string}
43
+ */
44
+ export function commandName(value) {
45
+ return baseName(String(value || '').replace(/^\s*&/, ''))
46
+ }