@shieldaai/security-watch 0.1.0-alpha.0 → 1.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 (92) hide show
  1. package/CHANGELOG.md +178 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +24 -7
  92. package/docs/quality-review.md +0 -104
package/dist/cli.js CHANGED
@@ -1,27 +1,64 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
- import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
- import { resolve } from 'node:path';
3
+ import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
4
+ import { dirname, extname, join, resolve } from 'node:path';
5
5
  import { createInterface } from 'node:readline/promises';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { stringify } from 'yaml';
8
8
  import { z } from 'zod';
9
9
  import { loadConfig, parseConfig, missingCredentials } from './config.js';
10
10
  import { loadInventory } from './inventory.js';
11
- import { Store } from './store.js';
11
+ import { importCycloneDx } from './sbom.js';
12
+ import { refreshCoverage } from './coverage.js';
13
+ import { Store, readPilotReport } from './store.js';
14
+ import { PilotReportError } from './pilot-report.js';
12
15
  import { runScan, readFixture, healthFinding } from './engine.js';
13
- import { deliverPending } from './delivery.js';
14
- import { safeHttp } from './http.js';
16
+ import { deliverPending, slackProblem, smtpProblem } from './delivery.js';
17
+ import { safeHttp, validateDestination } from './http.js';
18
+ /** Whether the heartbeat would refuse this address. */
19
+ function heartbeatProblem(address, allowPrivate) {
20
+ try {
21
+ const url = validateDestination(address, allowPrivate ?? false);
22
+ return Boolean(url.username || url.password);
23
+ }
24
+ catch {
25
+ return true;
26
+ }
27
+ }
15
28
  import { acquireLock, unlockStoppedWorker } from './lock.js';
16
29
  import { decide } from './assessment.js';
17
- import { checkHealth } from './health.js';
30
+ import { catchingUpFrom, checkHealth } from './health.js';
18
31
  import { PROVIDERS, providerDefinition } from './providers.js';
19
32
  import { loadEnvFile, starterSystems, SYSTEM_TEMPLATES } from './setup.js';
20
33
  import { ECOSYSTEMS, parseLibraryList } from './ecosystems.js';
21
34
  import { HeartbeatMonitor } from './heartbeat.js';
22
35
  import { MaintenanceScheduler } from './operations.js';
23
- import { verifyBackup } from './maintenance.js';
24
- const help = `Shielda Security Watch (experimental alpha)
36
+ import { createPilotCasePacket, readPilotFeedback, scorePilotCases } from './pilot-cases.js';
37
+ import { createPilotResponseTemplate, readPilotIncidentReference, scorePilotRecall } from './pilot-recall.js';
38
+ import { readPilotResponseRegister, scorePilotResponses } from './pilot-responses.js';
39
+ import { verifyBackup, readPilotBackupReport } from './maintenance.js';
40
+ import { readRehearsal, runRehearsal } from './rehearsal.js';
41
+ const pilotCommands = new Set([
42
+ 'pilot-report',
43
+ 'pilot-cases',
44
+ 'pilot-score',
45
+ 'pilot-recall',
46
+ 'pilot-response-template',
47
+ ]);
48
+ /**
49
+ * The first scan of a new database reads a day of recent advisories at a polite pace.
50
+ * Say so on the error stream, so a silent terminal is not mistaken for a hang.
51
+ */
52
+ function firstScanNotice(config, store, offline) {
53
+ if (offline || !config.sources.cve_now || store.checkpoints().cve_now !== undefined)
54
+ return;
55
+ console.error('First scan: reading the last day of advisories from cve.now, about one request a second. ' +
56
+ 'This can take 15 to 20 minutes; later scans usually take a minute or two. ' +
57
+ 'A dry run saves nothing, so the next scan starts from the beginning again.');
58
+ }
59
+ /** The one place the version is defined is package.json, which ships beside the compiled files. */
60
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
61
+ const help = `Shielda Security Watch ${VERSION}
25
62
 
26
63
  security-watch init [--directory PATH] [--yes] [--systems nodejs,python]
27
64
  [--libraries PATH --ecosystem php] [--vendor-feeds nodejs,python,php] [--heartbeat]
@@ -32,14 +69,24 @@ const help = `Shielda Security Watch (experimental alpha)
32
69
  security-watch providers
33
70
  security-watch templates
34
71
  security-watch ecosystems
72
+ security-watch import-sbom --input PATH [--output PATH]
73
+ security-watch coverage | inventory-drift [--config PATH]
35
74
  security-watch normalize-libraries --input PATH [--ecosystem php] [--output PATH]
36
75
  security-watch scan [--dry-run] [--notify] [--fixture PATH] [--no-ai]
76
+ security-watch rehearse --config PATH --input SCENARIO.json [--sink disabled|accepted|failed|unknown] [--output NEW.json]
37
77
  security-watch start [--config PATH]
38
78
  security-watch findings | status | deliveries | budget
79
+ security-watch pilot-report (--database PATH | --backup PATH) --from YYYY-MM-DD --until YYYY-MM-DD [--output NEW.json]
80
+ security-watch pilot-recall --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --input INCIDENTS.json [--responses RESPONSES.json] [--output NEW.json]
81
+ security-watch pilot-cases --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --output NEW.json
82
+ security-watch pilot-response-template --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --input INCIDENTS.json --output NEW.json
83
+ security-watch pilot-score --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --input LABELS.json [--output NEW.json]
39
84
  security-watch health [--scan-only]
40
85
  security-watch explain FINDING_ID
41
86
  security-watch history FINDING_ID
42
- security-watch acknowledge FINDING_ID
87
+ security-watch reviews [--all] [--limit 100] [--after CURSOR]
88
+ security-watch review FINDING_ID --revision N --disposition dismiss|investigate --reviewer NAME --reason TEXT
89
+ security-watch acknowledge FINDING_ID [--revision N]
43
90
  security-watch suppress FINDING_ID --hours 24 --reason TEXT
44
91
  security-watch retry DELIVERY_ID (verify receipt before retrying unknown delivery)
45
92
  security-watch backup --output PATH
@@ -52,13 +99,18 @@ Default config: ./security-watch.yaml. scan records findings; --dry-run writes n
52
99
  disables models and sends nothing. --notify sends due jobs. start runs the foreground scheduler and
53
100
  configured notification routes. Model/feed requests can leave this machine; fixture
54
101
  mode performs no source or model requests. No packages are installed or patched.
55
- Commands using a config accept --credentials-file PATH. Existing environment values take precedence.
102
+ Monitor commands accept --credentials-file PATH; rehearse uses no credentials.
103
+ Existing environment values take precedence for monitor commands.
56
104
  `;
57
105
  function argumentsFromCommandLine() {
58
106
  return parseArgs({
59
107
  allowPositionals: true,
60
108
  options: {
61
109
  config: { type: 'string' },
110
+ database: { type: 'string' },
111
+ backup: { type: 'string' },
112
+ from: { type: 'string' },
113
+ until: { type: 'string' },
62
114
  directory: { type: 'string' },
63
115
  systems: { type: 'string' },
64
116
  libraries: { type: 'string' },
@@ -84,8 +136,16 @@ function argumentsFromCommandLine() {
84
136
  'no-ai': { type: 'boolean' },
85
137
  hours: { type: 'string' },
86
138
  reason: { type: 'string' },
139
+ revision: { type: 'string' },
140
+ disposition: { type: 'string' },
141
+ reviewer: { type: 'string' },
142
+ all: { type: 'boolean' },
143
+ limit: { type: 'string' },
144
+ after: { type: 'string' },
87
145
  output: { type: 'string' },
146
+ responses: { type: 'string' },
88
147
  channel: { type: 'string' },
148
+ sink: { type: 'string' },
89
149
  help: { type: 'boolean' },
90
150
  version: { type: 'boolean' },
91
151
  'scan-only': { type: 'boolean' },
@@ -97,7 +157,13 @@ const { values, positionals } = (() => {
97
157
  return argumentsFromCommandLine();
98
158
  }
99
159
  catch (error) {
100
- console.error(error instanceof Error ? error.message : 'Invalid arguments');
160
+ console.error(pilotCommands.has(process.argv[2] ?? '')
161
+ ? 'Invalid pilot-report arguments.'
162
+ : process.argv[2] === 'rehearse'
163
+ ? 'Invalid rehearsal arguments.'
164
+ : error instanceof Error
165
+ ? error.message
166
+ : 'Invalid arguments');
101
167
  process.exit(1);
102
168
  }
103
169
  })();
@@ -238,12 +304,19 @@ async function initialize() {
238
304
  {
239
305
  id: libraries ? 'application' : 'example-api',
240
306
  name: libraries ? 'Application' : 'Example API',
307
+ note: 'Replace me: where this system runs and who to ask',
241
308
  environment: libraries ? 'unknown' : 'development',
242
309
  exposure: 'unknown',
243
310
  criticality: 'unknown',
244
311
  updated_at: new Date().toISOString(),
245
312
  components: libraries ?? [
246
- { id: 'example-parser', ecosystem: 'npm', name: 'example-parser', version: '1.2.0' },
313
+ {
314
+ id: 'example-parser',
315
+ ecosystem: 'npm',
316
+ name: 'example-parser',
317
+ version: '1.2.0',
318
+ note: 'Replace me: where this library is used',
319
+ },
247
320
  ],
248
321
  products: [],
249
322
  keywords: [],
@@ -264,7 +337,7 @@ async function initialize() {
264
337
  }
265
338
  async function main() {
266
339
  if (values.version) {
267
- console.log('0.1.0-alpha.0');
340
+ console.log(VERSION);
268
341
  return;
269
342
  }
270
343
  if (values.help || command === 'help') {
@@ -294,9 +367,18 @@ async function main() {
294
367
  templates: [],
295
368
  ecosystems: [],
296
369
  'normalize-libraries': ['input', 'ecosystem', 'output'],
370
+ 'import-sbom': ['input', 'output'],
371
+ coverage: ['config'],
372
+ 'inventory-drift': ['config'],
297
373
  doctor: ['config', 'no-ai'],
298
374
  unlock: ['config'],
299
375
  scan: ['config', 'dry-run', 'notify', 'fixture', 'no-ai'],
376
+ rehearse: ['config', 'input', 'sink', 'output'],
377
+ 'pilot-cases': ['backup', 'from', 'until', 'output'],
378
+ 'pilot-response-template': ['backup', 'from', 'until', 'input', 'output'],
379
+ 'pilot-recall': ['backup', 'from', 'until', 'input', 'responses', 'output'],
380
+ 'pilot-score': ['backup', 'from', 'until', 'input', 'output'],
381
+ 'pilot-report': ['database', 'backup', 'from', 'until', 'output'],
300
382
  start: ['config', 'no-ai'],
301
383
  findings: ['config'],
302
384
  status: ['config'],
@@ -305,7 +387,9 @@ async function main() {
305
387
  health: ['config', 'scan-only'],
306
388
  explain: ['config', 'no-ai'],
307
389
  history: ['config'],
308
- acknowledge: ['config'],
390
+ reviews: ['config', 'all', 'limit', 'after'],
391
+ review: ['config', 'revision', 'disposition', 'reviewer', 'reason'],
392
+ acknowledge: ['config', 'revision'],
309
393
  suppress: ['config', 'hours', 'reason'],
310
394
  retry: ['config'],
311
395
  backup: ['config', 'output'],
@@ -313,15 +397,15 @@ async function main() {
313
397
  prune: ['config', 'apply'],
314
398
  'test-notification': ['config', 'channel'],
315
399
  };
316
- for (const flags of Object.values(commandFlags))
317
- if (flags.includes('config'))
400
+ for (const [name, flags] of Object.entries(commandFlags))
401
+ if (name !== 'rehearse' && flags.includes('config'))
318
402
  flags.push('credentials-file');
319
403
  if (!commandFlags[command])
320
404
  throw new Error(`Unknown command ${command}. Use --help.`);
321
405
  for (const flag of Object.keys(values))
322
406
  if (!commandFlags[command].includes(flag))
323
407
  throw new Error(`--${flag} is not supported by ${command}.`);
324
- const needsId = ['explain', 'history', 'acknowledge', 'suppress', 'retry'].includes(command);
408
+ const needsId = ['explain', 'history', 'review', 'acknowledge', 'suppress', 'retry'].includes(command);
325
409
  if (positionals.length > (needsId ? 2 : 1))
326
410
  throw new Error('Unexpected positional arguments. Use --help.');
327
411
  if (command === 'init') {
@@ -340,6 +424,21 @@ async function main() {
340
424
  output(ECOSYSTEMS);
341
425
  return;
342
426
  }
427
+ if (command === 'import-sbom') {
428
+ if (!values.input)
429
+ throw new Error('--input PATH required');
430
+ const report = importCycloneDx(resolve(values.input));
431
+ if (values.output)
432
+ writeFileSync(resolve(values.output), JSON.stringify(report, null, 2) + '\n', {
433
+ flag: 'wx',
434
+ mode: 0o600,
435
+ });
436
+ else
437
+ output(report);
438
+ if (report.warnings.length)
439
+ process.exitCode = 2;
440
+ return;
441
+ }
343
442
  if (command === 'normalize-libraries') {
344
443
  if (!values.input)
345
444
  throw new Error('--input PATH required');
@@ -361,6 +460,72 @@ async function main() {
361
460
  output(await verifyBackup(resolve(values.input)));
362
461
  return;
363
462
  }
463
+ if (pilotCommands.has(command)) {
464
+ if (!values.from || !values.until || Boolean(values.database) === Boolean(values.backup))
465
+ throw new Error();
466
+ if ((command === 'pilot-cases' || command === 'pilot-response-template') && !values.output)
467
+ throw new Error();
468
+ if (command === 'pilot-response-template' && !values.input)
469
+ throw new Error();
470
+ if ((command === 'pilot-score' || command === 'pilot-recall') && !values.input)
471
+ throw new Error();
472
+ const destination = values.output === undefined ? undefined : resolve(values.output);
473
+ // Reject SQLite sidecar and worker lock filenames before opening either input.
474
+ if (destination && extname(destination).toLowerCase() !== '.json')
475
+ throw new Error();
476
+ const window = { from: values.from, until: values.until };
477
+ let report;
478
+ if (command === 'pilot-cases')
479
+ report = await createPilotCasePacket(values.backup, window);
480
+ else if (command === 'pilot-response-template')
481
+ report = await createPilotResponseTemplate(values.backup, window, readPilotIncidentReference(values.input));
482
+ else if (command === 'pilot-recall') {
483
+ const reference = readPilotIncidentReference(values.input);
484
+ report =
485
+ values.responses === undefined
486
+ ? await scorePilotRecall(values.backup, window, reference)
487
+ : await scorePilotResponses(values.backup, window, reference, readPilotResponseRegister(values.responses));
488
+ }
489
+ else if (command === 'pilot-score')
490
+ report = await scorePilotCases(values.backup, window, readPilotFeedback(values.input));
491
+ else
492
+ report = values.backup
493
+ ? await readPilotBackupReport(values.backup, window)
494
+ : readPilotReport(values.database, window);
495
+ if (!destination)
496
+ output(report);
497
+ else {
498
+ const directory = mkdtempSync(join(dirname(destination), '.pilot-report-'));
499
+ try {
500
+ const staged = join(directory, 'report.json');
501
+ writeFileSync(staged, JSON.stringify(report, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
502
+ linkSync(staged, destination);
503
+ }
504
+ finally {
505
+ rmSync(directory, { recursive: true, force: true });
506
+ }
507
+ }
508
+ return;
509
+ }
510
+ if (command === 'rehearse') {
511
+ if (!values.input)
512
+ throw new Error('--input required');
513
+ const config = loadConfig(resolve(values.config ?? 'security-watch.yaml'));
514
+ const report = await runRehearsal({
515
+ config,
516
+ inventory: loadInventory(config.inventory),
517
+ scenario: readRehearsal(resolve(values.input)),
518
+ sink: (values.sink ?? 'disabled'),
519
+ });
520
+ if (values.output)
521
+ writeFileSync(resolve(values.output), JSON.stringify(report, null, 2) + '\n', {
522
+ flag: 'wx',
523
+ mode: 0o600,
524
+ });
525
+ else
526
+ output(report);
527
+ return;
528
+ }
364
529
  if (values['credentials-file'])
365
530
  loadEnvFile(resolve(values['credentials-file']));
366
531
  const config = loadConfig(resolve(values.config ?? 'security-watch.yaml'));
@@ -383,16 +548,52 @@ async function main() {
383
548
  health: config.policy.health_channels,
384
549
  };
385
550
  const enabledChannels = [...new Set(Object.values(routes).flat())];
551
+ const smtp = config.notifications.email
552
+ ? process.env[config.notifications.email.smtp_url_env]
553
+ : undefined;
554
+ const slack = config.notifications.slack
555
+ ? process.env[config.notifications.slack.webhook_url_env]
556
+ : undefined;
557
+ const heartbeat = config.monitoring ? process.env[config.monitoring.heartbeat_url_env] : undefined;
558
+ const problems = [
559
+ // Delivery refuses such an address on every attempt; say so before the first alert is due.
560
+ ...(slack && slackProblem(slack)
561
+ ? [`${config.notifications.slack.webhook_url_env}: ${slackProblem(slack)}.`]
562
+ : []),
563
+ ...(smtp && smtpProblem(smtp)
564
+ ? [
565
+ `${config.notifications.email.smtp_url_env}: ${smtpProblem(smtp)}.${/%/.test(smtp) ? ' Write a literal % in a password as %25.' : ''}`,
566
+ ]
567
+ : []),
568
+ // The heartbeat refuses such an address on every ping.
569
+ ...(heartbeat && heartbeatProblem(heartbeat, config.monitoring.allow_private_endpoint)
570
+ ? [`${config.monitoring.heartbeat_url_env}: the external heartbeat address cannot be used.`]
571
+ : []),
572
+ ];
573
+ // Feed addresses can carry access tokens; show where each one points, not the whole address.
574
+ const feedHost = (value) => {
575
+ try {
576
+ return `${new URL(value).origin}/…`;
577
+ }
578
+ catch {
579
+ return 'invalid URL';
580
+ }
581
+ };
386
582
  output({
387
- ok: missing.length === 0,
583
+ ok: missing.length === 0 && problems.length === 0,
584
+ problems,
388
585
  systems: inventory.systems.length,
389
586
  components: inventory.systems.reduce((sum, s) => sum + s.components.length, 0),
587
+ // Entries that were left out or will not match as written. Scans report the same list.
588
+ import_warnings: inventory.import_warnings ?? [],
589
+ // Entries accepted as written that may be a typing mistake, such as a capitalised npm name.
590
+ name_notices: inventory.name_notices ?? [],
390
591
  missing_environment_variables: missing,
391
592
  database: config.database,
392
593
  models_enabled: config.models.enabled,
393
594
  poll_interval_minutes: config.poll_interval_minutes,
394
595
  news_lookback_minutes: config.news_lookback_minutes,
395
- sources: config.sources,
596
+ sources: { ...config.sources, feeds: config.sources.feeds.map(feedHost) },
396
597
  feeds: config.sources.feeds.length + Number(config.sources.hacker_news),
397
598
  notification_routes: routes,
398
599
  notification_channels: enabledChannels,
@@ -437,7 +638,8 @@ async function main() {
437
638
  : []),
438
639
  ],
439
640
  });
440
- if (missing.length)
641
+ // `ok: false` always comes with a failing exit status, so a script can rely on either.
642
+ if (missing.length || problems.length)
441
643
  process.exitCode = 2;
442
644
  return;
443
645
  }
@@ -446,11 +648,15 @@ async function main() {
446
648
  'start',
447
649
  'findings',
448
650
  'status',
651
+ 'coverage',
652
+ 'inventory-drift',
449
653
  'deliveries',
450
654
  'budget',
451
655
  'health',
452
656
  'explain',
453
657
  'history',
658
+ 'reviews',
659
+ 'review',
454
660
  'acknowledge',
455
661
  'suppress',
456
662
  'retry',
@@ -466,7 +672,18 @@ async function main() {
466
672
  if (dry)
467
673
  config.models.enabled = false;
468
674
  const readonly = (command === 'prune' && !values.apply) ||
469
- ['findings', 'status', 'deliveries', 'budget', 'health', 'explain', 'history'].includes(command);
675
+ [
676
+ 'findings',
677
+ 'status',
678
+ 'coverage',
679
+ 'inventory-drift',
680
+ 'deliveries',
681
+ 'budget',
682
+ 'health',
683
+ 'explain',
684
+ 'history',
685
+ 'reviews',
686
+ ].includes(command);
470
687
  if (readonly && !existsSync(config.database)) {
471
688
  output({ status: 'not_started', message: 'No database exists yet. Run scan or start.' });
472
689
  if (command === 'health')
@@ -485,6 +702,65 @@ async function main() {
485
702
  throw error;
486
703
  }
487
704
  try {
705
+ if (command === 'coverage' || command === 'inventory-drift') {
706
+ const saved = JSON.parse(store.getMeta(command === 'coverage' ? 'source:coverage' : 'inventory:last_drift') ?? '[]');
707
+ output(command === 'coverage' ? refreshCoverage(saved) : saved);
708
+ return;
709
+ }
710
+ if (command === 'reviews') {
711
+ const limit = values.limit === undefined ? 100 : Number(values.limit);
712
+ let after;
713
+ if (values.after) {
714
+ if (values.after.length > 2048 || !/^[A-Za-z0-9_-]+$/.test(values.after))
715
+ throw new Error('Invalid review cursor');
716
+ try {
717
+ after = JSON.parse(Buffer.from(values.after, 'base64url').toString('utf8'));
718
+ if (!after || typeof after !== 'object' || Array.isArray(after))
719
+ throw new Error('Invalid review cursor');
720
+ }
721
+ catch {
722
+ throw new Error('Invalid review cursor');
723
+ }
724
+ }
725
+ const reviews = store.reviews({
726
+ includeResolved: Boolean(values.all),
727
+ limit,
728
+ ...(after ? { after } : {}),
729
+ });
730
+ const last = reviews.at(-1);
731
+ output({
732
+ reviews,
733
+ summary: store.reviewSummary(),
734
+ next_cursor: reviews.length === limit && last
735
+ ? Buffer.from(JSON.stringify({
736
+ created_at: last.created_at,
737
+ finding_id: last.finding_id,
738
+ revision: last.revision,
739
+ })).toString('base64url')
740
+ : null,
741
+ });
742
+ return;
743
+ }
744
+ if (command === 'review') {
745
+ if (!id ||
746
+ !values.revision ||
747
+ !values.reviewer ||
748
+ !values.reason ||
749
+ !['dismiss', 'investigate'].includes(values.disposition ?? ''))
750
+ throw new Error('Provide finding ID, --revision, --disposition dismiss|investigate, --reviewer and --reason');
751
+ store.reviewFinding(id, Number(values.revision), {
752
+ disposition: values.disposition,
753
+ reviewer: values.reviewer,
754
+ reason: values.reason,
755
+ });
756
+ output({
757
+ finding_id: id,
758
+ revision: Number(values.revision),
759
+ disposition: values.disposition,
760
+ delivery_sent: false,
761
+ });
762
+ return;
763
+ }
488
764
  if (command === 'findings') {
489
765
  output(store.findings());
490
766
  return;
@@ -511,7 +787,11 @@ async function main() {
511
787
  const summary = store.summary();
512
788
  output({
513
789
  last_scan: JSON.parse(store.getMeta('last_scan') ?? 'null'),
790
+ coverage: refreshCoverage(JSON.parse(store.getMeta('source:coverage') ?? '[]')),
791
+ inventory_drift: JSON.parse(store.getMeta('inventory:last_drift') ?? '[]'),
514
792
  findings: summary.active_findings,
793
+ reviews: store.reviewSummary(),
794
+ ai_dismissal_policy: config.policy.ai_dismissals ?? 'review',
515
795
  delivery_states: summary.delivery_states,
516
796
  worker_lock: existsSync(`${config.database}.lock`),
517
797
  worker_lock_note: 'Informational metadata can remain after a crash; exclusive SQLite ownership prevents concurrent workers.',
@@ -535,6 +815,7 @@ async function main() {
535
815
  modified_at: e.modified_at,
536
816
  fetched_at: e.fetched_at,
537
817
  withdrawn: e.withdrawn ?? false,
818
+ ...(e.cvss_v4 ? { cvss_v4: e.cvss_v4 } : {}),
538
819
  })),
539
820
  note: 'Applicability reflects the cited evidence as last fetched. Inspect monitoring health for source outages.',
540
821
  });
@@ -549,8 +830,11 @@ async function main() {
549
830
  if (command === 'acknowledge') {
550
831
  if (!id)
551
832
  throw new Error('Finding ID required');
552
- store.acknowledge(id);
553
- console.log('Finding acknowledged.');
833
+ const expected = values.revision === undefined ? undefined : Number(values.revision);
834
+ if (expected !== undefined && (!Number.isSafeInteger(expected) || expected < 1))
835
+ throw new Error('--revision must be a positive whole number');
836
+ const revision = store.acknowledge(id, expected);
837
+ console.log(`Finding acknowledged at revision ${revision}.`);
554
838
  return;
555
839
  }
556
840
  if (command === 'suppress') {
@@ -571,8 +855,11 @@ async function main() {
571
855
  if (command === 'backup') {
572
856
  if (!values.output)
573
857
  throw new Error('--output PATH required');
574
- await store.backup(resolve(values.output));
575
- const verification = await verifyBackup(resolve(values.output), config.maintenance?.backup ? { max_bytes: config.maintenance.backup.max_bytes } : undefined);
858
+ let verification;
859
+ // Check the snapshot before it appears at the requested path; a failed check leaves nothing behind.
860
+ await store.backup(resolve(values.output), async (snapshot) => {
861
+ verification = await verifyBackup(snapshot, config.maintenance?.backup ? { max_bytes: config.maintenance.backup.max_bytes } : undefined);
862
+ });
576
863
  output({ backup_created: true, verification });
577
864
  return;
578
865
  }
@@ -623,6 +910,13 @@ async function main() {
623
910
  }
624
911
  if (command === 'scan') {
625
912
  const inventory = loadInventory(config.inventory);
913
+ // A fixture preview shows how findings are matched, not how fresh the inventory is: like the
914
+ // demo, it counts the inventory as current, so the fixed-date examples keep working.
915
+ // Only a dry run: a fixture scan that saves its results must not record a stale inventory as
916
+ // current in the configured database.
917
+ if (values.fixture && dry)
918
+ for (const system of inventory.systems)
919
+ system.updated_at = new Date().toISOString();
626
920
  if (values.notify)
627
921
  store.recoverSending();
628
922
  const delivery = { accepted: 0, failed: 0, unknown: 0 };
@@ -632,11 +926,21 @@ async function main() {
632
926
  delivery.failed += result.failed;
633
927
  delivery.unknown += result.unknown;
634
928
  };
929
+ firstScanNotice(config, store, Boolean(values.fixture));
635
930
  const report = await runScan({
636
931
  config,
637
932
  inventory,
638
933
  store,
639
- ...(values.fixture ? { fixture: readFixture(resolve(values.fixture)) } : {}),
934
+ // A fixture stands for what the sources answer now: its records count as read now, so that a
935
+ // preview does not turn into "unknown" as the file ages.
936
+ ...(values.fixture
937
+ ? {
938
+ fixture: readFixture(resolve(values.fixture)).map((item) => ({
939
+ ...item,
940
+ fetched_at: new Date().toISOString(),
941
+ })),
942
+ }
943
+ : {}),
640
944
  ...(values.notify ? { onUrgent: deliver } : {}),
641
945
  });
642
946
  output(report);
@@ -667,6 +971,7 @@ async function main() {
667
971
  store.recoverSending();
668
972
  const controller = new AbortController();
669
973
  const startedAt = new Date().toISOString();
974
+ const catchingUpSince = catchingUpFrom(store, startedAt);
670
975
  let lastHeartbeat = 0;
671
976
  const heartbeat = (status) => {
672
977
  const now = Date.now();
@@ -674,6 +979,7 @@ async function main() {
674
979
  pid: process.pid,
675
980
  status,
676
981
  started_at: startedAt,
982
+ catching_up_since: catchingUpSince,
677
983
  heartbeat_at: new Date(now).toISOString(),
678
984
  }));
679
985
  lastHeartbeat = now;
@@ -693,6 +999,7 @@ async function main() {
693
999
  process.on('SIGTERM', shutdown);
694
1000
  console.log('Security Watch is running in the foreground. Configured routes are active.');
695
1001
  try {
1002
+ firstScanNotice(config, store, false);
696
1003
  while (!stop) {
697
1004
  if (Date.now() - lastHeartbeat >= 15_000)
698
1005
  heartbeat('running');
@@ -782,7 +1089,13 @@ async function main() {
782
1089
  }
783
1090
  }
784
1091
  main().catch((error) => {
785
- if (error instanceof z.ZodError)
1092
+ if (pilotCommands.has(command))
1093
+ console.error(error instanceof PilotReportError
1094
+ ? error.message
1095
+ : 'Pilot report failed. Supply one database or backup, a UTC date window and a new .json output path.');
1096
+ else if (command === 'rehearse')
1097
+ console.error('Rehearsal failed. Check input, bounds, sink mode and a new output path; no external delivery was attempted.');
1098
+ else if (error instanceof z.ZodError)
786
1099
  console.error('Validation failed: ' + error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '));
787
1100
  else if (error instanceof Error && /YAML/i.test(error.name))
788
1101
  console.error('Invalid YAML; check configuration/inventory syntax.');