@shieldaai/security-watch 0.0.0-stage → 1.0.0

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 (110) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +92 -0
  3. package/LICENSE +202 -0
  4. package/README.md +394 -2
  5. package/SECURITY.md +62 -0
  6. package/dist/assessment.d.ts +16 -0
  7. package/dist/assessment.js +569 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +1105 -0
  10. package/dist/config.d.ts +302 -0
  11. package/dist/config.js +381 -0
  12. package/dist/coverage.d.ts +4 -0
  13. package/dist/coverage.js +11 -0
  14. package/dist/cve-now.d.ts +35 -0
  15. package/dist/cve-now.js +1002 -0
  16. package/dist/cvss4.d.ts +3 -0
  17. package/dist/cvss4.js +39 -0
  18. package/dist/delivery.d.ts +58 -0
  19. package/dist/delivery.js +687 -0
  20. package/dist/ecosystems.d.ts +48 -0
  21. package/dist/ecosystems.js +332 -0
  22. package/dist/engine.d.ts +80 -0
  23. package/dist/engine.js +388 -0
  24. package/dist/everyday-words.d.ts +11 -0
  25. package/dist/everyday-words.js +256 -0
  26. package/dist/health.d.ts +24 -0
  27. package/dist/health.js +122 -0
  28. package/dist/heartbeat.d.ts +13 -0
  29. package/dist/heartbeat.js +74 -0
  30. package/dist/http.d.ts +15 -0
  31. package/dist/http.js +280 -0
  32. package/dist/index.d.ts +36 -0
  33. package/dist/index.js +23 -0
  34. package/dist/inventory-evidence.d.ts +10 -0
  35. package/dist/inventory-evidence.js +206 -0
  36. package/dist/inventory.d.ts +276 -0
  37. package/dist/inventory.js +336 -0
  38. package/dist/lock.d.ts +3 -0
  39. package/dist/lock.js +112 -0
  40. package/dist/maintenance.d.ts +48 -0
  41. package/dist/maintenance.js +295 -0
  42. package/dist/matching.d.ts +29 -0
  43. package/dist/matching.js +537 -0
  44. package/dist/models.d.ts +33 -0
  45. package/dist/models.js +932 -0
  46. package/dist/operations.d.ts +17 -0
  47. package/dist/operations.js +117 -0
  48. package/dist/pilot-cases.d.ts +171 -0
  49. package/dist/pilot-cases.js +330 -0
  50. package/dist/pilot-input.d.ts +16 -0
  51. package/dist/pilot-input.js +125 -0
  52. package/dist/pilot-recall.d.ts +166 -0
  53. package/dist/pilot-recall.js +231 -0
  54. package/dist/pilot-report.d.ts +113 -0
  55. package/dist/pilot-report.js +279 -0
  56. package/dist/pilot-responses.d.ts +111 -0
  57. package/dist/pilot-responses.js +159 -0
  58. package/dist/providers.d.ts +209 -0
  59. package/dist/providers.js +459 -0
  60. package/dist/python-version.d.ts +3 -0
  61. package/dist/python-version.js +30 -0
  62. package/dist/rehearsal.d.ts +440 -0
  63. package/dist/rehearsal.js +372 -0
  64. package/dist/sbom.d.ts +13 -0
  65. package/dist/sbom.js +193 -0
  66. package/dist/setup.d.ts +113 -0
  67. package/dist/setup.js +100 -0
  68. package/dist/source-error.d.ts +38 -0
  69. package/dist/source-error.js +71 -0
  70. package/dist/sources.d.ts +3 -0
  71. package/dist/sources.js +1725 -0
  72. package/dist/store.d.ts +96 -0
  73. package/dist/store.js +953 -0
  74. package/dist/types.d.ts +404 -0
  75. package/dist/types.js +1 -0
  76. package/dist/util.d.ts +29 -0
  77. package/dist/util.js +94 -0
  78. package/dist/vendor/cvss4-reference.d.ts +2 -0
  79. package/dist/vendor/cvss4-reference.js +789 -0
  80. package/dist/vendor-sources.d.ts +24 -0
  81. package/dist/vendor-sources.js +56 -0
  82. package/dist/word-filter.d.ts +3 -0
  83. package/dist/word-filter.js +3291 -0
  84. package/docs/alert-outcome-evaluation.md +150 -0
  85. package/docs/compatibility.md +35 -0
  86. package/docs/configuration.md +666 -0
  87. package/docs/cvss-v4-support.md +41 -0
  88. package/docs/offline-advisory-preview.md +114 -0
  89. package/docs/offline-rehearsal.md +44 -0
  90. package/docs/pilot-cases.md +58 -0
  91. package/docs/pilot-recall.md +124 -0
  92. package/docs/pilot-report.md +52 -0
  93. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  94. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  95. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  96. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  97. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  98. package/docs/vendor/cvss-v4-provenance.json +38 -0
  99. package/examples/advisories.json +17 -0
  100. package/examples/agent-advisories-2026.json +145 -0
  101. package/examples/agent-advisory-cases-2026.json +397 -0
  102. package/examples/common-systems.yaml +243 -0
  103. package/examples/libraries.example.txt +18 -0
  104. package/examples/libraries.example.yaml +40 -0
  105. package/examples/library-watch.example.yaml +27 -0
  106. package/examples/offline-advisory-preview.mjs +42 -0
  107. package/examples/rehearsal.json +75 -0
  108. package/examples/security-watch.example.yaml +86 -0
  109. package/examples/systems.example.yaml +35 -0
  110. package/package.json +85 -4
package/dist/cli.js ADDED
@@ -0,0 +1,1105 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync, } from 'node:fs';
4
+ import { dirname, extname, join, resolve } from 'node:path';
5
+ import { createInterface } from 'node:readline/promises';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { stringify } from 'yaml';
8
+ import { z } from 'zod';
9
+ import { loadConfig, parseConfig, missingCredentials } from './config.js';
10
+ import { loadInventory } from './inventory.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';
15
+ import { runScan, readFixture, healthFinding } from './engine.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
+ }
28
+ import { acquireLock, unlockStoppedWorker } from './lock.js';
29
+ import { decide } from './assessment.js';
30
+ import { catchingUpFrom, checkHealth } from './health.js';
31
+ import { PROVIDERS, providerDefinition } from './providers.js';
32
+ import { loadEnvFile, starterSystems, SYSTEM_TEMPLATES } from './setup.js';
33
+ import { ECOSYSTEMS, parseLibraryList } from './ecosystems.js';
34
+ import { HeartbeatMonitor } from './heartbeat.js';
35
+ import { MaintenanceScheduler } from './operations.js';
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}
62
+
63
+ security-watch init [--directory PATH] [--yes] [--systems nodejs,python]
64
+ [--libraries PATH --ecosystem php] [--vendor-feeds nodejs,python,php] [--heartbeat]
65
+ [--provider NAME --model ID] [--endpoint URL] [--allow-private-endpoint]
66
+ [--poll-minutes 30] [--lookback-minutes 40]
67
+ [--notifications slack,email] [--email-from ADDRESS] [--email-to ADDRESS,ADDRESS]
68
+ security-watch doctor [--config PATH] [--credentials-file PATH]
69
+ security-watch providers
70
+ security-watch templates
71
+ security-watch ecosystems
72
+ security-watch import-sbom --input PATH [--output PATH]
73
+ security-watch coverage | inventory-drift [--config PATH]
74
+ security-watch normalize-libraries --input PATH [--ecosystem php] [--output PATH]
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]
77
+ security-watch start [--config PATH]
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]
84
+ security-watch health [--scan-only]
85
+ security-watch explain FINDING_ID
86
+ security-watch history 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]
90
+ security-watch suppress FINDING_ID --hours 24 --reason TEXT
91
+ security-watch retry DELIVERY_ID (verify receipt before retrying unknown delivery)
92
+ security-watch backup --output PATH
93
+ security-watch verify-backup --input PATH
94
+ security-watch prune [--apply] (shows the retention plan unless --apply is given)
95
+ security-watch unlock (only removes a stopped worker's lock)
96
+ security-watch test-notification --channel slack|email
97
+
98
+ Default config: ./security-watch.yaml. scan records findings; --dry-run writes no state,
99
+ disables models and sends nothing. --notify sends due jobs. start runs the foreground scheduler and
100
+ configured notification routes. Model/feed requests can leave this machine; fixture
101
+ mode performs no source or model requests. No packages are installed or patched.
102
+ Monitor commands accept --credentials-file PATH; rehearse uses no credentials.
103
+ Existing environment values take precedence for monitor commands.
104
+ `;
105
+ function argumentsFromCommandLine() {
106
+ return parseArgs({
107
+ allowPositionals: true,
108
+ options: {
109
+ config: { type: 'string' },
110
+ database: { type: 'string' },
111
+ backup: { type: 'string' },
112
+ from: { type: 'string' },
113
+ until: { type: 'string' },
114
+ directory: { type: 'string' },
115
+ systems: { type: 'string' },
116
+ libraries: { type: 'string' },
117
+ ecosystem: { type: 'string' },
118
+ input: { type: 'string' },
119
+ 'vendor-feeds': { type: 'string' },
120
+ heartbeat: { type: 'boolean' },
121
+ apply: { type: 'boolean' },
122
+ provider: { type: 'string' },
123
+ model: { type: 'string' },
124
+ endpoint: { type: 'string' },
125
+ 'allow-private-endpoint': { type: 'boolean' },
126
+ 'poll-minutes': { type: 'string' },
127
+ 'lookback-minutes': { type: 'string' },
128
+ notifications: { type: 'string' },
129
+ 'email-from': { type: 'string' },
130
+ 'email-to': { type: 'string' },
131
+ 'credentials-file': { type: 'string' },
132
+ yes: { type: 'boolean' },
133
+ 'dry-run': { type: 'boolean' },
134
+ notify: { type: 'boolean' },
135
+ fixture: { type: 'string' },
136
+ 'no-ai': { type: 'boolean' },
137
+ hours: { type: 'string' },
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' },
145
+ output: { type: 'string' },
146
+ responses: { type: 'string' },
147
+ channel: { type: 'string' },
148
+ sink: { type: 'string' },
149
+ help: { type: 'boolean' },
150
+ version: { type: 'boolean' },
151
+ 'scan-only': { type: 'boolean' },
152
+ },
153
+ });
154
+ }
155
+ const { values, positionals } = (() => {
156
+ try {
157
+ return argumentsFromCommandLine();
158
+ }
159
+ catch (error) {
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');
167
+ process.exit(1);
168
+ }
169
+ })();
170
+ const [command = 'help', id] = positionals;
171
+ function output(value) {
172
+ console.log(JSON.stringify(value, null, 2));
173
+ }
174
+ function shellArgument(value) {
175
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
176
+ }
177
+ function libraryInput(path, ecosystem) {
178
+ const absolute = resolve(path);
179
+ const stat = statSync(absolute);
180
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
181
+ throw new Error('Library input must be a regular file no larger than 2 MiB.');
182
+ const data = readFileSync(absolute);
183
+ if (data.byteLength > 2 * 1024 * 1024)
184
+ throw new Error('Library input exceeds 2 MiB.');
185
+ const components = parseLibraryList(data.toString('utf8'), ecosystem);
186
+ if (!components.length || components.length > 20_000)
187
+ throw new Error('Provide between 1 and 20000 libraries.');
188
+ return components;
189
+ }
190
+ async function initialize() {
191
+ const directory = resolve(values.directory ?? '.');
192
+ const configPath = resolve(directory, 'security-watch.yaml'), inventoryPath = resolve(directory, 'systems.yaml');
193
+ if (existsSync(configPath) || existsSync(inventoryPath))
194
+ throw new Error('Configuration or inventory already exists; init never overwrites it.');
195
+ let provider = values.provider ?? 'none', model = values.model ?? '', endpoint = values.endpoint, allowPrivate = values['allow-private-endpoint'] ?? false, pollMinutes = values['poll-minutes'] ?? '30', lookbackMinutes = values['lookback-minutes'] ?? '40', notificationChoice = values.notifications ?? 'none', emailFrom = values['email-from'], emailTo = values['email-to'];
196
+ const systems = values.systems === undefined ? undefined : starterSystems(values.systems);
197
+ if (values.libraries && values.systems)
198
+ throw new Error('--libraries creates one application inventory; choose --systems separately.');
199
+ if (values.ecosystem && !values.libraries)
200
+ throw new Error('--ecosystem requires --libraries.');
201
+ const libraries = values.libraries ? libraryInput(values.libraries, values.ecosystem) : undefined;
202
+ if (provider === 'none' && (model || endpoint || allowPrivate))
203
+ throw new Error('--model, --endpoint and --allow-private-endpoint require --provider.');
204
+ if (provider !== 'none' && !PROVIDERS.some((entry) => entry.id === provider))
205
+ throw new Error('Unknown provider. Run security-watch providers for the available names.');
206
+ if (!values.yes && process.stdin.isTTY) {
207
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
208
+ try {
209
+ console.log('AI providers: ' + PROVIDERS.map((entry) => entry.id).join(', '));
210
+ if (!values.provider)
211
+ provider = (await prompt.question('AI provider (default none): ')).trim() || 'none';
212
+ if (provider !== 'none') {
213
+ if (!PROVIDERS.some((entry) => entry.id === provider))
214
+ throw new Error('Choose none or a provider from the list.');
215
+ const definition = providerDefinition(provider);
216
+ if (!model)
217
+ model = (await prompt.question('Exact model ID or Azure deployment name: ')).trim();
218
+ if (!model)
219
+ throw new Error('Model ID is required.');
220
+ if (!definition.endpoint && !endpoint) {
221
+ endpoint = (await prompt.question('Full API endpoint URL, including the request path: ')).trim();
222
+ if (!endpoint)
223
+ throw new Error('API endpoint is required.');
224
+ }
225
+ if ((definition.local || endpoint) && !allowPrivate) {
226
+ allowPrivate = /^y(es)?$/i.test((await prompt.question('Permit this model to use a local/private HTTP(S) endpoint? (y/N): ')).trim());
227
+ }
228
+ }
229
+ if (!values['poll-minutes'])
230
+ pollMinutes = (await prompt.question('Minutes between scans (default 30): ')).trim() || '30';
231
+ if (!values['lookback-minutes'])
232
+ lookbackMinutes =
233
+ (await prompt.question('Minutes of recent news to check (default 40): ')).trim() || '40';
234
+ if (!values.notifications)
235
+ notificationChoice =
236
+ (await prompt.question('Notification channels: none, slack, email, or slack,email (default none): ')).trim() || 'none';
237
+ if (notificationChoice
238
+ .split(',')
239
+ .map((value) => value.trim())
240
+ .includes('email')) {
241
+ emailFrom ??= (await prompt.question('Email sender address: ')).trim();
242
+ emailTo ??= (await prompt.question('Email recipient addresses, separated by commas: ')).trim();
243
+ }
244
+ }
245
+ finally {
246
+ prompt.close();
247
+ }
248
+ }
249
+ const channels = notificationChoice === 'none'
250
+ ? []
251
+ : [...new Set(notificationChoice.split(',').map((value) => value.trim()))];
252
+ if (channels.some((channel) => !['slack', 'email'].includes(channel)))
253
+ throw new Error('--notifications must be none, slack, email, or slack,email.');
254
+ if (channels.includes('email') && (!emailFrom || !emailTo))
255
+ throw new Error('Email notifications require --email-from and --email-to.');
256
+ if (!channels.includes('email') && (emailFrom || emailTo))
257
+ throw new Error('--email-from and --email-to require --notifications email.');
258
+ const config = parseConfig({
259
+ version: 1,
260
+ inventory: './systems.yaml',
261
+ database: './data/watch.db',
262
+ poll_interval_minutes: Number(pollMinutes),
263
+ news_lookback_minutes: Number(lookbackMinutes),
264
+ sources: {
265
+ ...(libraries ? { osv: true } : {}),
266
+ vendor_feeds: values['vendor-feeds']?.split(',').map((name) => name.trim()) ?? [],
267
+ },
268
+ ...(values.heartbeat ? { monitoring: { heartbeat_url_env: 'HEARTBEAT_URL' } } : {}),
269
+ models: provider === 'none'
270
+ ? { enabled: false }
271
+ : {
272
+ enabled: true,
273
+ analysis: {
274
+ provider,
275
+ model,
276
+ api_key_env: providerDefinition(provider).apiKeyEnv,
277
+ ...(endpoint ? { endpoint } : {}),
278
+ allow_private_endpoint: allowPrivate,
279
+ },
280
+ },
281
+ policy: {
282
+ library: { levels: ['critical'], basis: 'source_severity', channels },
283
+ product: { levels: ['high', 'critical'], channels },
284
+ news: { levels: ['high', 'critical'], channels },
285
+ health_channels: channels,
286
+ },
287
+ notifications: {
288
+ ...(channels.includes('slack') ? { slack: { webhook_url_env: 'SLACK_WEBHOOK_URL' } } : {}),
289
+ ...(channels.includes('email')
290
+ ? {
291
+ email: {
292
+ smtp_url_env: 'SMTP_URL',
293
+ from: emailFrom,
294
+ to: emailTo.split(',').map((address) => address.trim()),
295
+ },
296
+ }
297
+ : {}),
298
+ },
299
+ });
300
+ mkdirSync(directory, { recursive: true });
301
+ writeFileSync(configPath, '# Run doctor after editing this file. Credentials belong in a private env file.\n' + stringify(config), { flag: 'wx', mode: 0o600 });
302
+ writeFileSync(inventoryPath, stringify({
303
+ systems: systems ?? [
304
+ {
305
+ id: libraries ? 'application' : 'example-api',
306
+ name: libraries ? 'Application' : 'Example API',
307
+ note: 'Replace me: where this system runs and who to ask',
308
+ environment: libraries ? 'unknown' : 'development',
309
+ exposure: 'unknown',
310
+ criticality: 'unknown',
311
+ updated_at: new Date().toISOString(),
312
+ components: libraries ?? [
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
+ },
320
+ ],
321
+ products: [],
322
+ keywords: [],
323
+ },
324
+ ],
325
+ }), { flag: 'wx', mode: 0o600 });
326
+ const envExample = resolve(directory, '.env.example');
327
+ if (!existsSync(envExample))
328
+ writeFileSync(envExample, '# Copy this file to .env, set the values you use, then run chmod 600 .env.\n' +
329
+ '# Load it with security-watch doctor --credentials-file .env.\n' +
330
+ (provider === 'none'
331
+ ? '# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n'
332
+ : `${providerDefinition(provider).apiKeyEnv}=\n`) +
333
+ (channels.includes('slack') ? 'SLACK_WEBHOOK_URL=\n' : '# SLACK_WEBHOOK_URL=\n') +
334
+ (channels.includes('email') ? 'SMTP_URL=\n' : '# SMTP_URL=\n') +
335
+ (values.heartbeat ? 'HEARTBEAT_URL=\n' : '# HEARTBEAT_URL=\n'), { flag: 'wx', mode: 0o600 });
336
+ console.log(`Created ${configPath} and ${inventoryPath}. Add installed versions and deployment details to systems.yaml. Copy .env.example to .env and fill in any required credentials. Then run:\n security-watch doctor --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))}\n security-watch scan --config ${shellArgument(configPath)} --credentials-file ${shellArgument(resolve(directory, '.env'))} --dry-run\nNo messages were sent.`);
337
+ }
338
+ async function main() {
339
+ if (values.version) {
340
+ console.log(VERSION);
341
+ return;
342
+ }
343
+ if (values.help || command === 'help') {
344
+ console.log(help);
345
+ return;
346
+ }
347
+ const commandFlags = {
348
+ init: [
349
+ 'directory',
350
+ 'yes',
351
+ 'systems',
352
+ 'libraries',
353
+ 'ecosystem',
354
+ 'vendor-feeds',
355
+ 'heartbeat',
356
+ 'provider',
357
+ 'model',
358
+ 'endpoint',
359
+ 'allow-private-endpoint',
360
+ 'poll-minutes',
361
+ 'lookback-minutes',
362
+ 'notifications',
363
+ 'email-from',
364
+ 'email-to',
365
+ ],
366
+ providers: [],
367
+ templates: [],
368
+ ecosystems: [],
369
+ 'normalize-libraries': ['input', 'ecosystem', 'output'],
370
+ 'import-sbom': ['input', 'output'],
371
+ coverage: ['config'],
372
+ 'inventory-drift': ['config'],
373
+ doctor: ['config', 'no-ai'],
374
+ unlock: ['config'],
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'],
382
+ start: ['config', 'no-ai'],
383
+ findings: ['config'],
384
+ status: ['config'],
385
+ deliveries: ['config'],
386
+ budget: ['config'],
387
+ health: ['config', 'scan-only'],
388
+ explain: ['config', 'no-ai'],
389
+ history: ['config'],
390
+ reviews: ['config', 'all', 'limit', 'after'],
391
+ review: ['config', 'revision', 'disposition', 'reviewer', 'reason'],
392
+ acknowledge: ['config', 'revision'],
393
+ suppress: ['config', 'hours', 'reason'],
394
+ retry: ['config'],
395
+ backup: ['config', 'output'],
396
+ 'verify-backup': ['input'],
397
+ prune: ['config', 'apply'],
398
+ 'test-notification': ['config', 'channel'],
399
+ };
400
+ for (const [name, flags] of Object.entries(commandFlags))
401
+ if (name !== 'rehearse' && flags.includes('config'))
402
+ flags.push('credentials-file');
403
+ if (!commandFlags[command])
404
+ throw new Error(`Unknown command ${command}. Use --help.`);
405
+ for (const flag of Object.keys(values))
406
+ if (!commandFlags[command].includes(flag))
407
+ throw new Error(`--${flag} is not supported by ${command}.`);
408
+ const needsId = ['explain', 'history', 'review', 'acknowledge', 'suppress', 'retry'].includes(command);
409
+ if (positionals.length > (needsId ? 2 : 1))
410
+ throw new Error('Unexpected positional arguments. Use --help.');
411
+ if (command === 'init') {
412
+ await initialize();
413
+ return;
414
+ }
415
+ if (command === 'providers') {
416
+ output(PROVIDERS);
417
+ return;
418
+ }
419
+ if (command === 'templates') {
420
+ output(SYSTEM_TEMPLATES);
421
+ return;
422
+ }
423
+ if (command === 'ecosystems') {
424
+ output(ECOSYSTEMS);
425
+ return;
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
+ }
442
+ if (command === 'normalize-libraries') {
443
+ if (!values.input)
444
+ throw new Error('--input PATH required');
445
+ const components = libraryInput(values.input, values.ecosystem);
446
+ if (values.output) {
447
+ writeFileSync(resolve(values.output), JSON.stringify(components, null, 2) + '\n', {
448
+ flag: 'wx',
449
+ mode: 0o600,
450
+ });
451
+ console.log('Normalized library list saved.');
452
+ }
453
+ else
454
+ output(components);
455
+ return;
456
+ }
457
+ if (command === 'verify-backup') {
458
+ if (!values.input)
459
+ throw new Error('--input PATH required');
460
+ output(await verifyBackup(resolve(values.input)));
461
+ return;
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
+ }
529
+ if (values['credentials-file'])
530
+ loadEnvFile(resolve(values['credentials-file']));
531
+ const config = loadConfig(resolve(values.config ?? 'security-watch.yaml'));
532
+ if (command === 'prune' && !config.maintenance?.retention)
533
+ throw new Error('Configure maintenance.retention before planning or applying pruning.');
534
+ if (values['no-ai'])
535
+ config.models.enabled = false;
536
+ if (command === 'unlock') {
537
+ unlockStoppedWorker(config.database);
538
+ console.log('Stopped-worker lock removed.');
539
+ return;
540
+ }
541
+ if (command === 'doctor') {
542
+ const inventory = loadInventory(config.inventory);
543
+ const missing = missingCredentials(config);
544
+ const routes = {
545
+ library: config.policy.library.channels,
546
+ product: config.policy.product.channels,
547
+ news: config.policy.news.channels,
548
+ health: config.policy.health_channels,
549
+ };
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
+ };
582
+ output({
583
+ ok: missing.length === 0 && problems.length === 0,
584
+ problems,
585
+ systems: inventory.systems.length,
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 ?? [],
591
+ missing_environment_variables: missing,
592
+ database: config.database,
593
+ models_enabled: config.models.enabled,
594
+ poll_interval_minutes: config.poll_interval_minutes,
595
+ news_lookback_minutes: config.news_lookback_minutes,
596
+ sources: { ...config.sources, feeds: config.sources.feeds.map(feedHost) },
597
+ feeds: config.sources.feeds.length + Number(config.sources.hacker_news),
598
+ notification_routes: routes,
599
+ notification_channels: enabledChannels,
600
+ ecosystems: [
601
+ ...new Set(inventory.systems.flatMap((system) => system.components.map((component) => component.ecosystem))),
602
+ ],
603
+ external_heartbeat: config.monitoring
604
+ ? {
605
+ configured: true,
606
+ interval_seconds: config.monitoring.interval_seconds,
607
+ credential: config.monitoring.heartbeat_url_env,
608
+ }
609
+ : { configured: false },
610
+ maintenance: config.maintenance ?? null,
611
+ notices: [
612
+ 'Model compatibility is verified only by a real analysis request; doctor does not spend tokens or send notifications.',
613
+ 'Public advisory queries disclose package names/versions. Models receive relevant inventory context.',
614
+ 'System news impact is an AI assessment with citations; structured CVE version matching remains separate.',
615
+ ...(!config.sources.osv &&
616
+ inventory.systems.some((system) => system.components.some((component) => component.ecosystem !== 'npm'))
617
+ ? [
618
+ 'Enable sources.osv for exact library queries outside npm. Other configured sources may not cover those libraries.',
619
+ ]
620
+ : []),
621
+ ...(!config.monitoring
622
+ ? [
623
+ 'External outage monitoring is not configured. A stopped host cannot send its own failure alert.',
624
+ ]
625
+ : []),
626
+ ...(config.monitoring
627
+ ? ['Configure the external service to alert when healthy pings stop. doctor does not send a ping.']
628
+ : []),
629
+ ...(enabledChannels.length
630
+ ? [
631
+ 'Notification routes are enabled. Use test-notification to verify delivery; start sends queued notifications continuously.',
632
+ ]
633
+ : [
634
+ 'No notification routes are enabled. Scans will record findings without delivering alerts. Configure policy channels and notification destinations.',
635
+ ]),
636
+ ...((config.sources.hacker_news || config.sources.feeds.length) && !config.models.enabled
637
+ ? ['Enable an analysis model to classify system news and assess deployment impact.']
638
+ : []),
639
+ ],
640
+ });
641
+ // `ok: false` always comes with a failing exit status, so a script can rely on either.
642
+ if (missing.length || problems.length)
643
+ process.exitCode = 2;
644
+ return;
645
+ }
646
+ const allowed = new Set([
647
+ 'scan',
648
+ 'start',
649
+ 'findings',
650
+ 'status',
651
+ 'coverage',
652
+ 'inventory-drift',
653
+ 'deliveries',
654
+ 'budget',
655
+ 'health',
656
+ 'explain',
657
+ 'history',
658
+ 'reviews',
659
+ 'review',
660
+ 'acknowledge',
661
+ 'suppress',
662
+ 'retry',
663
+ 'backup',
664
+ 'prune',
665
+ 'test-notification',
666
+ ]);
667
+ if (!allowed.has(command))
668
+ throw new Error(`Unknown command ${command}. Use --help.`);
669
+ const dry = command === 'scan' && Boolean(values['dry-run']);
670
+ if (dry && values.notify)
671
+ throw new Error('--dry-run and --notify cannot be combined.');
672
+ if (dry)
673
+ config.models.enabled = false;
674
+ const readonly = (command === 'prune' && !values.apply) ||
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);
687
+ if (readonly && !existsSync(config.database)) {
688
+ output({ status: 'not_started', message: 'No database exists yet. Run scan or start.' });
689
+ if (command === 'health')
690
+ process.exitCode = 2;
691
+ return;
692
+ }
693
+ const memory = dry || command === 'test-notification';
694
+ const worker = command === 'scan' || command === 'start';
695
+ const release = memory || !worker ? () => { } : acquireLock(config.database);
696
+ let store;
697
+ try {
698
+ store = new Store(memory ? ':memory:' : config.database, readonly ? { readOnly: true } : !worker && !memory ? { migrate: false } : {});
699
+ }
700
+ catch (error) {
701
+ release();
702
+ throw error;
703
+ }
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
+ }
764
+ if (command === 'findings') {
765
+ output(store.findings());
766
+ return;
767
+ }
768
+ if (command === 'deliveries') {
769
+ output(store.jobs().map(({ payload, ...job }) => job));
770
+ return;
771
+ }
772
+ if (command === 'budget') {
773
+ output({
774
+ reservations: store.budgets(),
775
+ note: 'Reservations are conservative allowances, not provider invoices.',
776
+ });
777
+ return;
778
+ }
779
+ if (command === 'health') {
780
+ const report = checkHealth(store, config, Date.now(), !values['scan-only']);
781
+ output(report);
782
+ if (!report.ok)
783
+ process.exitCode = 2;
784
+ return;
785
+ }
786
+ if (command === 'status') {
787
+ const summary = store.summary();
788
+ output({
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') ?? '[]'),
792
+ findings: summary.active_findings,
793
+ reviews: store.reviewSummary(),
794
+ ai_dismissal_policy: config.policy.ai_dismissals ?? 'review',
795
+ delivery_states: summary.delivery_states,
796
+ worker_lock: existsSync(`${config.database}.lock`),
797
+ worker_lock_note: 'Informational metadata can remain after a crash; exclusive SQLite ownership prevents concurrent workers.',
798
+ external_heartbeat: JSON.parse(store.getMeta('external_heartbeat') ?? 'null'),
799
+ maintenance: JSON.parse(store.getMeta('maintenance:last_run') ?? 'null'),
800
+ });
801
+ return;
802
+ }
803
+ if (command === 'explain') {
804
+ const finding = id ? store.getFinding(id) : undefined;
805
+ if (!finding)
806
+ throw new Error('Finding not found');
807
+ output({
808
+ finding,
809
+ decision: decide(finding, config),
810
+ controls: store.controls(finding.id),
811
+ evidence: store.getEvidence(finding.evidence_ids).map((e) => ({
812
+ id: e.id,
813
+ source: e.source,
814
+ url: e.url,
815
+ modified_at: e.modified_at,
816
+ fetched_at: e.fetched_at,
817
+ withdrawn: e.withdrawn ?? false,
818
+ ...(e.cvss_v4 ? { cvss_v4: e.cvss_v4 } : {}),
819
+ })),
820
+ note: 'Applicability reflects the cited evidence as last fetched. Inspect monitoring health for source outages.',
821
+ });
822
+ return;
823
+ }
824
+ if (command === 'history') {
825
+ if (!id)
826
+ throw new Error('Finding ID required');
827
+ output(store.history(id));
828
+ return;
829
+ }
830
+ if (command === 'acknowledge') {
831
+ if (!id)
832
+ throw new Error('Finding ID required');
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}.`);
838
+ return;
839
+ }
840
+ if (command === 'suppress') {
841
+ const hours = Number(values.hours);
842
+ if (!id || !values.reason || !Number.isFinite(hours) || hours <= 0 || hours > 8760)
843
+ throw new Error('Provide finding ID, --hours (1–8760) and --reason.');
844
+ store.suppress(id, Date.now() + Math.floor(hours * 3_600_000), values.reason);
845
+ console.log('Suppression saved with expiry.');
846
+ return;
847
+ }
848
+ if (command === 'retry') {
849
+ if (!id)
850
+ throw new Error('Delivery ID required');
851
+ store.retryJob(id);
852
+ console.log('Delivery queued. A previous uncertain delivery may already have reached its destination.');
853
+ return;
854
+ }
855
+ if (command === 'backup') {
856
+ if (!values.output)
857
+ throw new Error('--output PATH required');
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
+ });
863
+ output({ backup_created: true, verification });
864
+ return;
865
+ }
866
+ if (command === 'prune') {
867
+ output(store.prune(config.maintenance.retention, Date.now(), Boolean(values.apply)));
868
+ return;
869
+ }
870
+ if (command === 'test-notification') {
871
+ if (values.channel !== 'slack' && values.channel !== 'email')
872
+ throw new Error('--channel slack|email required');
873
+ const a = {
874
+ id: 'test',
875
+ event_id: 'test',
876
+ system_id: 'monitor',
877
+ category: 'health',
878
+ applicability: 'relevant',
879
+ source_severity: 'low',
880
+ priority: 'low',
881
+ title: 'Security Watch notification test',
882
+ summary: 'This is a user-requested delivery test, not a vulnerability finding.',
883
+ reasons: [],
884
+ evidence_ids: [],
885
+ urls: [],
886
+ exploited: false,
887
+ updated_at: new Date().toISOString(),
888
+ };
889
+ store.saveAssessment(a, {
890
+ action: 'notify',
891
+ channels: [values.channel],
892
+ reason: 'Explicit notification test',
893
+ });
894
+ const delivery = await deliverPending(store, {
895
+ ...config,
896
+ notifications: { ...config.notifications, max_attempts: 1 },
897
+ policy: { ...config.policy, health_channels: [values.channel] },
898
+ }, safeHttp);
899
+ const job = store.jobs()[0];
900
+ output({
901
+ ...delivery,
902
+ channel: values.channel,
903
+ status: job?.status ?? 'not_sent',
904
+ error: job?.last_error ?? null,
905
+ note: 'This sends one test and does not change the monitor database or retry automatically.',
906
+ });
907
+ if (store.jobs().some((j) => j.status !== 'accepted'))
908
+ process.exitCode = 2;
909
+ return;
910
+ }
911
+ if (command === 'scan') {
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();
920
+ if (values.notify)
921
+ store.recoverSending();
922
+ const delivery = { accepted: 0, failed: 0, unknown: 0 };
923
+ const deliver = async () => {
924
+ const result = await deliverPending(store, config, safeHttp);
925
+ delivery.accepted += result.accepted;
926
+ delivery.failed += result.failed;
927
+ delivery.unknown += result.unknown;
928
+ };
929
+ firstScanNotice(config, store, Boolean(values.fixture));
930
+ const report = await runScan({
931
+ config,
932
+ inventory,
933
+ store,
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
+ : {}),
944
+ ...(values.notify ? { onUrgent: deliver } : {}),
945
+ });
946
+ output(report);
947
+ if (values.notify) {
948
+ await deliver();
949
+ const summary = store.summary();
950
+ output({
951
+ delivery,
952
+ pending: summary.pending,
953
+ next_attempt_at: summary.next_pending_at === null ? null : new Date(summary.next_pending_at).toISOString(),
954
+ note: 'Rate-limited retries and future digest jobs remain queued. Run start to keep delivering them.',
955
+ });
956
+ if (delivery.failed || delivery.unknown)
957
+ process.exitCode = 2;
958
+ }
959
+ if (report.degraded)
960
+ process.exitCode = 2;
961
+ return;
962
+ }
963
+ if (values.fixture || values['dry-run'])
964
+ throw new Error('start does not accept fixture or dry-run; use scan.');
965
+ const missing = missingCredentials(config);
966
+ if (missing.length) {
967
+ console.error(`Missing environment variables: ${missing.join(', ')}. Monitoring will continue with explicit degraded status.`);
968
+ const finding = healthFinding('credentials', 'Configured model or delivery credentials are missing. Structured advisory matching continues.');
969
+ store.saveAssessment(finding, decide(finding, config));
970
+ }
971
+ store.recoverSending();
972
+ const controller = new AbortController();
973
+ const startedAt = new Date().toISOString();
974
+ const catchingUpSince = catchingUpFrom(store, startedAt);
975
+ let lastHeartbeat = 0;
976
+ const heartbeat = (status) => {
977
+ const now = Date.now();
978
+ store.setMeta('worker', JSON.stringify({
979
+ pid: process.pid,
980
+ status,
981
+ started_at: startedAt,
982
+ catching_up_since: catchingUpSince,
983
+ heartbeat_at: new Date(now).toISOString(),
984
+ }));
985
+ lastHeartbeat = now;
986
+ };
987
+ heartbeat('running');
988
+ let stop = false, nextScan = 0;
989
+ let scanning;
990
+ let maintaining;
991
+ const monitor = new HeartbeatMonitor();
992
+ const maintenance = new MaintenanceScheduler();
993
+ let monitorStatus;
994
+ const shutdown = () => {
995
+ stop = true;
996
+ controller.abort();
997
+ };
998
+ process.on('SIGINT', shutdown);
999
+ process.on('SIGTERM', shutdown);
1000
+ console.log('Security Watch is running in the foreground. Configured routes are active.');
1001
+ try {
1002
+ firstScanNotice(config, store, false);
1003
+ while (!stop) {
1004
+ if (Date.now() - lastHeartbeat >= 15_000)
1005
+ heartbeat('running');
1006
+ if (!scanning && !maintaining && Date.now() >= nextScan) {
1007
+ nextScan = Date.now() + config.poll_interval_minutes * 60_000;
1008
+ scanning = (async () => {
1009
+ try {
1010
+ const report = await runScan({
1011
+ config,
1012
+ inventory: loadInventory(config.inventory),
1013
+ store,
1014
+ signal: controller.signal,
1015
+ });
1016
+ console.log(JSON.stringify({
1017
+ at: report.at,
1018
+ findings: report.findings.length,
1019
+ degraded: report.degraded,
1020
+ errors: report.errors,
1021
+ }));
1022
+ }
1023
+ catch {
1024
+ if (controller.signal.aborted)
1025
+ return;
1026
+ const finding = healthFinding('worker', 'Scan failed. Check configuration, inventory and local storage. Previous findings are retained.');
1027
+ store.setMeta('last_scan', JSON.stringify({
1028
+ at: new Date().toISOString(),
1029
+ degraded: true,
1030
+ errors: [{ source: 'worker', message: finding.summary }],
1031
+ }));
1032
+ store.saveAssessment(finding, decide(finding, config));
1033
+ console.error('Scan failed; previous findings retained.');
1034
+ }
1035
+ })()
1036
+ .catch(() => {
1037
+ console.error('Worker cannot persist monitoring state; stopping.');
1038
+ process.exitCode = 1;
1039
+ stop = true;
1040
+ })
1041
+ .finally(() => {
1042
+ scanning = undefined;
1043
+ });
1044
+ }
1045
+ const delivery = await deliverPending(store, config, safeHttp, Date.now(), undefined, controller.signal);
1046
+ if (delivery.failed || delivery.unknown)
1047
+ console.error(JSON.stringify({ delivery, action: 'Inspect deliveries and destination configuration.' }));
1048
+ if (!scanning && !maintaining && config.maintenance && !stop)
1049
+ maintaining = maintenance
1050
+ .tick(store, config)
1051
+ .then((report) => {
1052
+ if (report)
1053
+ console.log(JSON.stringify({ maintenance: report }));
1054
+ })
1055
+ .catch(() => {
1056
+ console.error('Worker cannot persist maintenance state; stopping.');
1057
+ process.exitCode = 1;
1058
+ stop = true;
1059
+ })
1060
+ .finally(() => {
1061
+ maintaining = undefined;
1062
+ });
1063
+ const ping = await monitor.tick(store, config, safeHttp, Date.now(), controller.signal);
1064
+ if (ping && ping.status !== monitorStatus) {
1065
+ monitorStatus = ping.status;
1066
+ console.log(JSON.stringify({ external_heartbeat: ping }));
1067
+ }
1068
+ await delay(1000);
1069
+ }
1070
+ if (scanning)
1071
+ await scanning;
1072
+ if (maintaining)
1073
+ await maintaining;
1074
+ }
1075
+ finally {
1076
+ controller.abort();
1077
+ if (scanning)
1078
+ await scanning;
1079
+ if (maintaining)
1080
+ await maintaining;
1081
+ heartbeat('stopped');
1082
+ process.off('SIGINT', shutdown);
1083
+ process.off('SIGTERM', shutdown);
1084
+ }
1085
+ }
1086
+ finally {
1087
+ store.close();
1088
+ release();
1089
+ }
1090
+ }
1091
+ main().catch((error) => {
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)
1099
+ console.error('Validation failed: ' + error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '));
1100
+ else if (error instanceof Error && /YAML/i.test(error.name))
1101
+ console.error('Invalid YAML; check configuration/inventory syntax.');
1102
+ else
1103
+ console.error(error instanceof Error ? error.message : 'Operation failed');
1104
+ process.exitCode = 1;
1105
+ });