@shieldaai/security-watch 0.0.0-stage → 0.1.0-alpha.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 (62) hide show
  1. package/CONTRIBUTING.md +90 -0
  2. package/LICENSE +202 -0
  3. package/README.md +269 -2
  4. package/SECURITY.md +47 -0
  5. package/dist/assessment.d.ts +5 -0
  6. package/dist/assessment.js +398 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +792 -0
  9. package/dist/config.d.ts +242 -0
  10. package/dist/config.js +298 -0
  11. package/dist/cve-now.d.ts +5 -0
  12. package/dist/cve-now.js +413 -0
  13. package/dist/delivery.d.ts +26 -0
  14. package/dist/delivery.js +394 -0
  15. package/dist/ecosystems.d.ts +25 -0
  16. package/dist/ecosystems.js +254 -0
  17. package/dist/engine.d.ts +26 -0
  18. package/dist/engine.js +307 -0
  19. package/dist/health.d.ts +17 -0
  20. package/dist/health.js +70 -0
  21. package/dist/heartbeat.d.ts +13 -0
  22. package/dist/heartbeat.js +74 -0
  23. package/dist/http.d.ts +8 -0
  24. package/dist/http.js +251 -0
  25. package/dist/index.d.ts +18 -0
  26. package/dist/index.js +15 -0
  27. package/dist/inventory.d.ts +3 -0
  28. package/dist/inventory.js +143 -0
  29. package/dist/lock.d.ts +3 -0
  30. package/dist/lock.js +112 -0
  31. package/dist/maintenance.d.ts +43 -0
  32. package/dist/maintenance.js +227 -0
  33. package/dist/models.d.ts +20 -0
  34. package/dist/models.js +602 -0
  35. package/dist/operations.d.ts +17 -0
  36. package/dist/operations.js +117 -0
  37. package/dist/providers.d.ts +209 -0
  38. package/dist/providers.js +459 -0
  39. package/dist/setup.d.ts +113 -0
  40. package/dist/setup.js +100 -0
  41. package/dist/source-error.d.ts +22 -0
  42. package/dist/source-error.js +56 -0
  43. package/dist/sources.d.ts +3 -0
  44. package/dist/sources.js +1071 -0
  45. package/dist/store.d.ts +71 -0
  46. package/dist/store.js +651 -0
  47. package/dist/types.d.ts +247 -0
  48. package/dist/types.js +1 -0
  49. package/dist/util.d.ts +6 -0
  50. package/dist/util.js +14 -0
  51. package/dist/vendor-sources.d.ts +24 -0
  52. package/dist/vendor-sources.js +56 -0
  53. package/docs/configuration.md +406 -0
  54. package/docs/quality-review.md +104 -0
  55. package/examples/advisories.json +17 -0
  56. package/examples/common-systems.yaml +243 -0
  57. package/examples/libraries.example.txt +16 -0
  58. package/examples/libraries.example.yaml +38 -0
  59. package/examples/library-watch.example.yaml +27 -0
  60. package/examples/security-watch.example.yaml +86 -0
  61. package/examples/systems.example.yaml +31 -0
  62. package/package.json +69 -4
package/dist/cli.js ADDED
@@ -0,0 +1,792 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from 'node:util';
3
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
4
+ import { 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 { Store } from './store.js';
12
+ import { runScan, readFixture, healthFinding } from './engine.js';
13
+ import { deliverPending } from './delivery.js';
14
+ import { safeHttp } from './http.js';
15
+ import { acquireLock, unlockStoppedWorker } from './lock.js';
16
+ import { decide } from './assessment.js';
17
+ import { checkHealth } from './health.js';
18
+ import { PROVIDERS, providerDefinition } from './providers.js';
19
+ import { loadEnvFile, starterSystems, SYSTEM_TEMPLATES } from './setup.js';
20
+ import { ECOSYSTEMS, parseLibraryList } from './ecosystems.js';
21
+ import { HeartbeatMonitor } from './heartbeat.js';
22
+ import { MaintenanceScheduler } from './operations.js';
23
+ import { verifyBackup } from './maintenance.js';
24
+ const help = `Shielda Security Watch (experimental alpha)
25
+
26
+ security-watch init [--directory PATH] [--yes] [--systems nodejs,python]
27
+ [--libraries PATH --ecosystem php] [--vendor-feeds nodejs,python,php] [--heartbeat]
28
+ [--provider NAME --model ID] [--endpoint URL] [--allow-private-endpoint]
29
+ [--poll-minutes 30] [--lookback-minutes 40]
30
+ [--notifications slack,email] [--email-from ADDRESS] [--email-to ADDRESS,ADDRESS]
31
+ security-watch doctor [--config PATH] [--credentials-file PATH]
32
+ security-watch providers
33
+ security-watch templates
34
+ security-watch ecosystems
35
+ security-watch normalize-libraries --input PATH [--ecosystem php] [--output PATH]
36
+ security-watch scan [--dry-run] [--notify] [--fixture PATH] [--no-ai]
37
+ security-watch start [--config PATH]
38
+ security-watch findings | status | deliveries | budget
39
+ security-watch health [--scan-only]
40
+ security-watch explain FINDING_ID
41
+ security-watch history FINDING_ID
42
+ security-watch acknowledge FINDING_ID
43
+ security-watch suppress FINDING_ID --hours 24 --reason TEXT
44
+ security-watch retry DELIVERY_ID (verify receipt before retrying unknown delivery)
45
+ security-watch backup --output PATH
46
+ security-watch verify-backup --input PATH
47
+ security-watch prune [--apply] (shows the retention plan unless --apply is given)
48
+ security-watch unlock (only removes a stopped worker's lock)
49
+ security-watch test-notification --channel slack|email
50
+
51
+ Default config: ./security-watch.yaml. scan records findings; --dry-run writes no state,
52
+ disables models and sends nothing. --notify sends due jobs. start runs the foreground scheduler and
53
+ configured notification routes. Model/feed requests can leave this machine; fixture
54
+ 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.
56
+ `;
57
+ function argumentsFromCommandLine() {
58
+ return parseArgs({
59
+ allowPositionals: true,
60
+ options: {
61
+ config: { type: 'string' },
62
+ directory: { type: 'string' },
63
+ systems: { type: 'string' },
64
+ libraries: { type: 'string' },
65
+ ecosystem: { type: 'string' },
66
+ input: { type: 'string' },
67
+ 'vendor-feeds': { type: 'string' },
68
+ heartbeat: { type: 'boolean' },
69
+ apply: { type: 'boolean' },
70
+ provider: { type: 'string' },
71
+ model: { type: 'string' },
72
+ endpoint: { type: 'string' },
73
+ 'allow-private-endpoint': { type: 'boolean' },
74
+ 'poll-minutes': { type: 'string' },
75
+ 'lookback-minutes': { type: 'string' },
76
+ notifications: { type: 'string' },
77
+ 'email-from': { type: 'string' },
78
+ 'email-to': { type: 'string' },
79
+ 'credentials-file': { type: 'string' },
80
+ yes: { type: 'boolean' },
81
+ 'dry-run': { type: 'boolean' },
82
+ notify: { type: 'boolean' },
83
+ fixture: { type: 'string' },
84
+ 'no-ai': { type: 'boolean' },
85
+ hours: { type: 'string' },
86
+ reason: { type: 'string' },
87
+ output: { type: 'string' },
88
+ channel: { type: 'string' },
89
+ help: { type: 'boolean' },
90
+ version: { type: 'boolean' },
91
+ 'scan-only': { type: 'boolean' },
92
+ },
93
+ });
94
+ }
95
+ const { values, positionals } = (() => {
96
+ try {
97
+ return argumentsFromCommandLine();
98
+ }
99
+ catch (error) {
100
+ console.error(error instanceof Error ? error.message : 'Invalid arguments');
101
+ process.exit(1);
102
+ }
103
+ })();
104
+ const [command = 'help', id] = positionals;
105
+ function output(value) {
106
+ console.log(JSON.stringify(value, null, 2));
107
+ }
108
+ function shellArgument(value) {
109
+ return `'${value.replaceAll("'", "'\"'\"'")}'`;
110
+ }
111
+ function libraryInput(path, ecosystem) {
112
+ const absolute = resolve(path);
113
+ const stat = statSync(absolute);
114
+ if (!stat.isFile() || stat.size > 2 * 1024 * 1024)
115
+ throw new Error('Library input must be a regular file no larger than 2 MiB.');
116
+ const data = readFileSync(absolute);
117
+ if (data.byteLength > 2 * 1024 * 1024)
118
+ throw new Error('Library input exceeds 2 MiB.');
119
+ const components = parseLibraryList(data.toString('utf8'), ecosystem);
120
+ if (!components.length || components.length > 20_000)
121
+ throw new Error('Provide between 1 and 20000 libraries.');
122
+ return components;
123
+ }
124
+ async function initialize() {
125
+ const directory = resolve(values.directory ?? '.');
126
+ const configPath = resolve(directory, 'security-watch.yaml'), inventoryPath = resolve(directory, 'systems.yaml');
127
+ if (existsSync(configPath) || existsSync(inventoryPath))
128
+ throw new Error('Configuration or inventory already exists; init never overwrites it.');
129
+ 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'];
130
+ const systems = values.systems === undefined ? undefined : starterSystems(values.systems);
131
+ if (values.libraries && values.systems)
132
+ throw new Error('--libraries creates one application inventory; choose --systems separately.');
133
+ if (values.ecosystem && !values.libraries)
134
+ throw new Error('--ecosystem requires --libraries.');
135
+ const libraries = values.libraries ? libraryInput(values.libraries, values.ecosystem) : undefined;
136
+ if (provider === 'none' && (model || endpoint || allowPrivate))
137
+ throw new Error('--model, --endpoint and --allow-private-endpoint require --provider.');
138
+ if (provider !== 'none' && !PROVIDERS.some((entry) => entry.id === provider))
139
+ throw new Error('Unknown provider. Run security-watch providers for the available names.');
140
+ if (!values.yes && process.stdin.isTTY) {
141
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
142
+ try {
143
+ console.log('AI providers: ' + PROVIDERS.map((entry) => entry.id).join(', '));
144
+ if (!values.provider)
145
+ provider = (await prompt.question('AI provider (default none): ')).trim() || 'none';
146
+ if (provider !== 'none') {
147
+ if (!PROVIDERS.some((entry) => entry.id === provider))
148
+ throw new Error('Choose none or a provider from the list.');
149
+ const definition = providerDefinition(provider);
150
+ if (!model)
151
+ model = (await prompt.question('Exact model ID or Azure deployment name: ')).trim();
152
+ if (!model)
153
+ throw new Error('Model ID is required.');
154
+ if (!definition.endpoint && !endpoint) {
155
+ endpoint = (await prompt.question('Full API endpoint URL, including the request path: ')).trim();
156
+ if (!endpoint)
157
+ throw new Error('API endpoint is required.');
158
+ }
159
+ if ((definition.local || endpoint) && !allowPrivate) {
160
+ allowPrivate = /^y(es)?$/i.test((await prompt.question('Permit this model to use a local/private HTTP(S) endpoint? (y/N): ')).trim());
161
+ }
162
+ }
163
+ if (!values['poll-minutes'])
164
+ pollMinutes = (await prompt.question('Minutes between scans (default 30): ')).trim() || '30';
165
+ if (!values['lookback-minutes'])
166
+ lookbackMinutes =
167
+ (await prompt.question('Minutes of recent news to check (default 40): ')).trim() || '40';
168
+ if (!values.notifications)
169
+ notificationChoice =
170
+ (await prompt.question('Notification channels: none, slack, email, or slack,email (default none): ')).trim() || 'none';
171
+ if (notificationChoice
172
+ .split(',')
173
+ .map((value) => value.trim())
174
+ .includes('email')) {
175
+ emailFrom ??= (await prompt.question('Email sender address: ')).trim();
176
+ emailTo ??= (await prompt.question('Email recipient addresses, separated by commas: ')).trim();
177
+ }
178
+ }
179
+ finally {
180
+ prompt.close();
181
+ }
182
+ }
183
+ const channels = notificationChoice === 'none'
184
+ ? []
185
+ : [...new Set(notificationChoice.split(',').map((value) => value.trim()))];
186
+ if (channels.some((channel) => !['slack', 'email'].includes(channel)))
187
+ throw new Error('--notifications must be none, slack, email, or slack,email.');
188
+ if (channels.includes('email') && (!emailFrom || !emailTo))
189
+ throw new Error('Email notifications require --email-from and --email-to.');
190
+ if (!channels.includes('email') && (emailFrom || emailTo))
191
+ throw new Error('--email-from and --email-to require --notifications email.');
192
+ const config = parseConfig({
193
+ version: 1,
194
+ inventory: './systems.yaml',
195
+ database: './data/watch.db',
196
+ poll_interval_minutes: Number(pollMinutes),
197
+ news_lookback_minutes: Number(lookbackMinutes),
198
+ sources: {
199
+ ...(libraries ? { osv: true } : {}),
200
+ vendor_feeds: values['vendor-feeds']?.split(',').map((name) => name.trim()) ?? [],
201
+ },
202
+ ...(values.heartbeat ? { monitoring: { heartbeat_url_env: 'HEARTBEAT_URL' } } : {}),
203
+ models: provider === 'none'
204
+ ? { enabled: false }
205
+ : {
206
+ enabled: true,
207
+ analysis: {
208
+ provider,
209
+ model,
210
+ api_key_env: providerDefinition(provider).apiKeyEnv,
211
+ ...(endpoint ? { endpoint } : {}),
212
+ allow_private_endpoint: allowPrivate,
213
+ },
214
+ },
215
+ policy: {
216
+ library: { levels: ['critical'], basis: 'source_severity', channels },
217
+ product: { levels: ['high', 'critical'], channels },
218
+ news: { levels: ['high', 'critical'], channels },
219
+ health_channels: channels,
220
+ },
221
+ notifications: {
222
+ ...(channels.includes('slack') ? { slack: { webhook_url_env: 'SLACK_WEBHOOK_URL' } } : {}),
223
+ ...(channels.includes('email')
224
+ ? {
225
+ email: {
226
+ smtp_url_env: 'SMTP_URL',
227
+ from: emailFrom,
228
+ to: emailTo.split(',').map((address) => address.trim()),
229
+ },
230
+ }
231
+ : {}),
232
+ },
233
+ });
234
+ mkdirSync(directory, { recursive: true });
235
+ writeFileSync(configPath, '# Run doctor after editing this file. Credentials belong in a private env file.\n' + stringify(config), { flag: 'wx', mode: 0o600 });
236
+ writeFileSync(inventoryPath, stringify({
237
+ systems: systems ?? [
238
+ {
239
+ id: libraries ? 'application' : 'example-api',
240
+ name: libraries ? 'Application' : 'Example API',
241
+ environment: libraries ? 'unknown' : 'development',
242
+ exposure: 'unknown',
243
+ criticality: 'unknown',
244
+ updated_at: new Date().toISOString(),
245
+ components: libraries ?? [
246
+ { id: 'example-parser', ecosystem: 'npm', name: 'example-parser', version: '1.2.0' },
247
+ ],
248
+ products: [],
249
+ keywords: [],
250
+ },
251
+ ],
252
+ }), { flag: 'wx', mode: 0o600 });
253
+ const envExample = resolve(directory, '.env.example');
254
+ if (!existsSync(envExample))
255
+ writeFileSync(envExample, '# Copy this file to .env, set the values you use, then run chmod 600 .env.\n' +
256
+ '# Load it with security-watch doctor --credentials-file .env.\n' +
257
+ (provider === 'none'
258
+ ? '# OPENAI_API_KEY=\n# ANTHROPIC_API_KEY=\n'
259
+ : `${providerDefinition(provider).apiKeyEnv}=\n`) +
260
+ (channels.includes('slack') ? 'SLACK_WEBHOOK_URL=\n' : '# SLACK_WEBHOOK_URL=\n') +
261
+ (channels.includes('email') ? 'SMTP_URL=\n' : '# SMTP_URL=\n') +
262
+ (values.heartbeat ? 'HEARTBEAT_URL=\n' : '# HEARTBEAT_URL=\n'), { flag: 'wx', mode: 0o600 });
263
+ 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.`);
264
+ }
265
+ async function main() {
266
+ if (values.version) {
267
+ console.log('0.1.0-alpha.0');
268
+ return;
269
+ }
270
+ if (values.help || command === 'help') {
271
+ console.log(help);
272
+ return;
273
+ }
274
+ const commandFlags = {
275
+ init: [
276
+ 'directory',
277
+ 'yes',
278
+ 'systems',
279
+ 'libraries',
280
+ 'ecosystem',
281
+ 'vendor-feeds',
282
+ 'heartbeat',
283
+ 'provider',
284
+ 'model',
285
+ 'endpoint',
286
+ 'allow-private-endpoint',
287
+ 'poll-minutes',
288
+ 'lookback-minutes',
289
+ 'notifications',
290
+ 'email-from',
291
+ 'email-to',
292
+ ],
293
+ providers: [],
294
+ templates: [],
295
+ ecosystems: [],
296
+ 'normalize-libraries': ['input', 'ecosystem', 'output'],
297
+ doctor: ['config', 'no-ai'],
298
+ unlock: ['config'],
299
+ scan: ['config', 'dry-run', 'notify', 'fixture', 'no-ai'],
300
+ start: ['config', 'no-ai'],
301
+ findings: ['config'],
302
+ status: ['config'],
303
+ deliveries: ['config'],
304
+ budget: ['config'],
305
+ health: ['config', 'scan-only'],
306
+ explain: ['config', 'no-ai'],
307
+ history: ['config'],
308
+ acknowledge: ['config'],
309
+ suppress: ['config', 'hours', 'reason'],
310
+ retry: ['config'],
311
+ backup: ['config', 'output'],
312
+ 'verify-backup': ['input'],
313
+ prune: ['config', 'apply'],
314
+ 'test-notification': ['config', 'channel'],
315
+ };
316
+ for (const flags of Object.values(commandFlags))
317
+ if (flags.includes('config'))
318
+ flags.push('credentials-file');
319
+ if (!commandFlags[command])
320
+ throw new Error(`Unknown command ${command}. Use --help.`);
321
+ for (const flag of Object.keys(values))
322
+ if (!commandFlags[command].includes(flag))
323
+ throw new Error(`--${flag} is not supported by ${command}.`);
324
+ const needsId = ['explain', 'history', 'acknowledge', 'suppress', 'retry'].includes(command);
325
+ if (positionals.length > (needsId ? 2 : 1))
326
+ throw new Error('Unexpected positional arguments. Use --help.');
327
+ if (command === 'init') {
328
+ await initialize();
329
+ return;
330
+ }
331
+ if (command === 'providers') {
332
+ output(PROVIDERS);
333
+ return;
334
+ }
335
+ if (command === 'templates') {
336
+ output(SYSTEM_TEMPLATES);
337
+ return;
338
+ }
339
+ if (command === 'ecosystems') {
340
+ output(ECOSYSTEMS);
341
+ return;
342
+ }
343
+ if (command === 'normalize-libraries') {
344
+ if (!values.input)
345
+ throw new Error('--input PATH required');
346
+ const components = libraryInput(values.input, values.ecosystem);
347
+ if (values.output) {
348
+ writeFileSync(resolve(values.output), JSON.stringify(components, null, 2) + '\n', {
349
+ flag: 'wx',
350
+ mode: 0o600,
351
+ });
352
+ console.log('Normalized library list saved.');
353
+ }
354
+ else
355
+ output(components);
356
+ return;
357
+ }
358
+ if (command === 'verify-backup') {
359
+ if (!values.input)
360
+ throw new Error('--input PATH required');
361
+ output(await verifyBackup(resolve(values.input)));
362
+ return;
363
+ }
364
+ if (values['credentials-file'])
365
+ loadEnvFile(resolve(values['credentials-file']));
366
+ const config = loadConfig(resolve(values.config ?? 'security-watch.yaml'));
367
+ if (command === 'prune' && !config.maintenance?.retention)
368
+ throw new Error('Configure maintenance.retention before planning or applying pruning.');
369
+ if (values['no-ai'])
370
+ config.models.enabled = false;
371
+ if (command === 'unlock') {
372
+ unlockStoppedWorker(config.database);
373
+ console.log('Stopped-worker lock removed.');
374
+ return;
375
+ }
376
+ if (command === 'doctor') {
377
+ const inventory = loadInventory(config.inventory);
378
+ const missing = missingCredentials(config);
379
+ const routes = {
380
+ library: config.policy.library.channels,
381
+ product: config.policy.product.channels,
382
+ news: config.policy.news.channels,
383
+ health: config.policy.health_channels,
384
+ };
385
+ const enabledChannels = [...new Set(Object.values(routes).flat())];
386
+ output({
387
+ ok: missing.length === 0,
388
+ systems: inventory.systems.length,
389
+ components: inventory.systems.reduce((sum, s) => sum + s.components.length, 0),
390
+ missing_environment_variables: missing,
391
+ database: config.database,
392
+ models_enabled: config.models.enabled,
393
+ poll_interval_minutes: config.poll_interval_minutes,
394
+ news_lookback_minutes: config.news_lookback_minutes,
395
+ sources: config.sources,
396
+ feeds: config.sources.feeds.length + Number(config.sources.hacker_news),
397
+ notification_routes: routes,
398
+ notification_channels: enabledChannels,
399
+ ecosystems: [
400
+ ...new Set(inventory.systems.flatMap((system) => system.components.map((component) => component.ecosystem))),
401
+ ],
402
+ external_heartbeat: config.monitoring
403
+ ? {
404
+ configured: true,
405
+ interval_seconds: config.monitoring.interval_seconds,
406
+ credential: config.monitoring.heartbeat_url_env,
407
+ }
408
+ : { configured: false },
409
+ maintenance: config.maintenance ?? null,
410
+ notices: [
411
+ 'Model compatibility is verified only by a real analysis request; doctor does not spend tokens or send notifications.',
412
+ 'Public advisory queries disclose package names/versions. Models receive relevant inventory context.',
413
+ 'System news impact is an AI assessment with citations; structured CVE version matching remains separate.',
414
+ ...(!config.sources.osv &&
415
+ inventory.systems.some((system) => system.components.some((component) => component.ecosystem !== 'npm'))
416
+ ? [
417
+ 'Enable sources.osv for exact library queries outside npm. Other configured sources may not cover those libraries.',
418
+ ]
419
+ : []),
420
+ ...(!config.monitoring
421
+ ? [
422
+ 'External outage monitoring is not configured. A stopped host cannot send its own failure alert.',
423
+ ]
424
+ : []),
425
+ ...(config.monitoring
426
+ ? ['Configure the external service to alert when healthy pings stop. doctor does not send a ping.']
427
+ : []),
428
+ ...(enabledChannels.length
429
+ ? [
430
+ 'Notification routes are enabled. Use test-notification to verify delivery; start sends queued notifications continuously.',
431
+ ]
432
+ : [
433
+ 'No notification routes are enabled. Scans will record findings without delivering alerts. Configure policy channels and notification destinations.',
434
+ ]),
435
+ ...((config.sources.hacker_news || config.sources.feeds.length) && !config.models.enabled
436
+ ? ['Enable an analysis model to classify system news and assess deployment impact.']
437
+ : []),
438
+ ],
439
+ });
440
+ if (missing.length)
441
+ process.exitCode = 2;
442
+ return;
443
+ }
444
+ const allowed = new Set([
445
+ 'scan',
446
+ 'start',
447
+ 'findings',
448
+ 'status',
449
+ 'deliveries',
450
+ 'budget',
451
+ 'health',
452
+ 'explain',
453
+ 'history',
454
+ 'acknowledge',
455
+ 'suppress',
456
+ 'retry',
457
+ 'backup',
458
+ 'prune',
459
+ 'test-notification',
460
+ ]);
461
+ if (!allowed.has(command))
462
+ throw new Error(`Unknown command ${command}. Use --help.`);
463
+ const dry = command === 'scan' && Boolean(values['dry-run']);
464
+ if (dry && values.notify)
465
+ throw new Error('--dry-run and --notify cannot be combined.');
466
+ if (dry)
467
+ config.models.enabled = false;
468
+ const readonly = (command === 'prune' && !values.apply) ||
469
+ ['findings', 'status', 'deliveries', 'budget', 'health', 'explain', 'history'].includes(command);
470
+ if (readonly && !existsSync(config.database)) {
471
+ output({ status: 'not_started', message: 'No database exists yet. Run scan or start.' });
472
+ if (command === 'health')
473
+ process.exitCode = 2;
474
+ return;
475
+ }
476
+ const memory = dry || command === 'test-notification';
477
+ const worker = command === 'scan' || command === 'start';
478
+ const release = memory || !worker ? () => { } : acquireLock(config.database);
479
+ let store;
480
+ try {
481
+ store = new Store(memory ? ':memory:' : config.database, readonly ? { readOnly: true } : !worker && !memory ? { migrate: false } : {});
482
+ }
483
+ catch (error) {
484
+ release();
485
+ throw error;
486
+ }
487
+ try {
488
+ if (command === 'findings') {
489
+ output(store.findings());
490
+ return;
491
+ }
492
+ if (command === 'deliveries') {
493
+ output(store.jobs().map(({ payload, ...job }) => job));
494
+ return;
495
+ }
496
+ if (command === 'budget') {
497
+ output({
498
+ reservations: store.budgets(),
499
+ note: 'Reservations are conservative allowances, not provider invoices.',
500
+ });
501
+ return;
502
+ }
503
+ if (command === 'health') {
504
+ const report = checkHealth(store, config, Date.now(), !values['scan-only']);
505
+ output(report);
506
+ if (!report.ok)
507
+ process.exitCode = 2;
508
+ return;
509
+ }
510
+ if (command === 'status') {
511
+ const summary = store.summary();
512
+ output({
513
+ last_scan: JSON.parse(store.getMeta('last_scan') ?? 'null'),
514
+ findings: summary.active_findings,
515
+ delivery_states: summary.delivery_states,
516
+ worker_lock: existsSync(`${config.database}.lock`),
517
+ worker_lock_note: 'Informational metadata can remain after a crash; exclusive SQLite ownership prevents concurrent workers.',
518
+ external_heartbeat: JSON.parse(store.getMeta('external_heartbeat') ?? 'null'),
519
+ maintenance: JSON.parse(store.getMeta('maintenance:last_run') ?? 'null'),
520
+ });
521
+ return;
522
+ }
523
+ if (command === 'explain') {
524
+ const finding = id ? store.getFinding(id) : undefined;
525
+ if (!finding)
526
+ throw new Error('Finding not found');
527
+ output({
528
+ finding,
529
+ decision: decide(finding, config),
530
+ controls: store.controls(finding.id),
531
+ evidence: store.getEvidence(finding.evidence_ids).map((e) => ({
532
+ id: e.id,
533
+ source: e.source,
534
+ url: e.url,
535
+ modified_at: e.modified_at,
536
+ fetched_at: e.fetched_at,
537
+ withdrawn: e.withdrawn ?? false,
538
+ })),
539
+ note: 'Applicability reflects the cited evidence as last fetched. Inspect monitoring health for source outages.',
540
+ });
541
+ return;
542
+ }
543
+ if (command === 'history') {
544
+ if (!id)
545
+ throw new Error('Finding ID required');
546
+ output(store.history(id));
547
+ return;
548
+ }
549
+ if (command === 'acknowledge') {
550
+ if (!id)
551
+ throw new Error('Finding ID required');
552
+ store.acknowledge(id);
553
+ console.log('Finding acknowledged.');
554
+ return;
555
+ }
556
+ if (command === 'suppress') {
557
+ const hours = Number(values.hours);
558
+ if (!id || !values.reason || !Number.isFinite(hours) || hours <= 0 || hours > 8760)
559
+ throw new Error('Provide finding ID, --hours (1–8760) and --reason.');
560
+ store.suppress(id, Date.now() + Math.floor(hours * 3_600_000), values.reason);
561
+ console.log('Suppression saved with expiry.');
562
+ return;
563
+ }
564
+ if (command === 'retry') {
565
+ if (!id)
566
+ throw new Error('Delivery ID required');
567
+ store.retryJob(id);
568
+ console.log('Delivery queued. A previous uncertain delivery may already have reached its destination.');
569
+ return;
570
+ }
571
+ if (command === 'backup') {
572
+ if (!values.output)
573
+ 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);
576
+ output({ backup_created: true, verification });
577
+ return;
578
+ }
579
+ if (command === 'prune') {
580
+ output(store.prune(config.maintenance.retention, Date.now(), Boolean(values.apply)));
581
+ return;
582
+ }
583
+ if (command === 'test-notification') {
584
+ if (values.channel !== 'slack' && values.channel !== 'email')
585
+ throw new Error('--channel slack|email required');
586
+ const a = {
587
+ id: 'test',
588
+ event_id: 'test',
589
+ system_id: 'monitor',
590
+ category: 'health',
591
+ applicability: 'relevant',
592
+ source_severity: 'low',
593
+ priority: 'low',
594
+ title: 'Security Watch notification test',
595
+ summary: 'This is a user-requested delivery test, not a vulnerability finding.',
596
+ reasons: [],
597
+ evidence_ids: [],
598
+ urls: [],
599
+ exploited: false,
600
+ updated_at: new Date().toISOString(),
601
+ };
602
+ store.saveAssessment(a, {
603
+ action: 'notify',
604
+ channels: [values.channel],
605
+ reason: 'Explicit notification test',
606
+ });
607
+ const delivery = await deliverPending(store, {
608
+ ...config,
609
+ notifications: { ...config.notifications, max_attempts: 1 },
610
+ policy: { ...config.policy, health_channels: [values.channel] },
611
+ }, safeHttp);
612
+ const job = store.jobs()[0];
613
+ output({
614
+ ...delivery,
615
+ channel: values.channel,
616
+ status: job?.status ?? 'not_sent',
617
+ error: job?.last_error ?? null,
618
+ note: 'This sends one test and does not change the monitor database or retry automatically.',
619
+ });
620
+ if (store.jobs().some((j) => j.status !== 'accepted'))
621
+ process.exitCode = 2;
622
+ return;
623
+ }
624
+ if (command === 'scan') {
625
+ const inventory = loadInventory(config.inventory);
626
+ if (values.notify)
627
+ store.recoverSending();
628
+ const delivery = { accepted: 0, failed: 0, unknown: 0 };
629
+ const deliver = async () => {
630
+ const result = await deliverPending(store, config, safeHttp);
631
+ delivery.accepted += result.accepted;
632
+ delivery.failed += result.failed;
633
+ delivery.unknown += result.unknown;
634
+ };
635
+ const report = await runScan({
636
+ config,
637
+ inventory,
638
+ store,
639
+ ...(values.fixture ? { fixture: readFixture(resolve(values.fixture)) } : {}),
640
+ ...(values.notify ? { onUrgent: deliver } : {}),
641
+ });
642
+ output(report);
643
+ if (values.notify) {
644
+ await deliver();
645
+ const summary = store.summary();
646
+ output({
647
+ delivery,
648
+ pending: summary.pending,
649
+ next_attempt_at: summary.next_pending_at === null ? null : new Date(summary.next_pending_at).toISOString(),
650
+ note: 'Rate-limited retries and future digest jobs remain queued. Run start to keep delivering them.',
651
+ });
652
+ if (delivery.failed || delivery.unknown)
653
+ process.exitCode = 2;
654
+ }
655
+ if (report.degraded)
656
+ process.exitCode = 2;
657
+ return;
658
+ }
659
+ if (values.fixture || values['dry-run'])
660
+ throw new Error('start does not accept fixture or dry-run; use scan.');
661
+ const missing = missingCredentials(config);
662
+ if (missing.length) {
663
+ console.error(`Missing environment variables: ${missing.join(', ')}. Monitoring will continue with explicit degraded status.`);
664
+ const finding = healthFinding('credentials', 'Configured model or delivery credentials are missing. Structured advisory matching continues.');
665
+ store.saveAssessment(finding, decide(finding, config));
666
+ }
667
+ store.recoverSending();
668
+ const controller = new AbortController();
669
+ const startedAt = new Date().toISOString();
670
+ let lastHeartbeat = 0;
671
+ const heartbeat = (status) => {
672
+ const now = Date.now();
673
+ store.setMeta('worker', JSON.stringify({
674
+ pid: process.pid,
675
+ status,
676
+ started_at: startedAt,
677
+ heartbeat_at: new Date(now).toISOString(),
678
+ }));
679
+ lastHeartbeat = now;
680
+ };
681
+ heartbeat('running');
682
+ let stop = false, nextScan = 0;
683
+ let scanning;
684
+ let maintaining;
685
+ const monitor = new HeartbeatMonitor();
686
+ const maintenance = new MaintenanceScheduler();
687
+ let monitorStatus;
688
+ const shutdown = () => {
689
+ stop = true;
690
+ controller.abort();
691
+ };
692
+ process.on('SIGINT', shutdown);
693
+ process.on('SIGTERM', shutdown);
694
+ console.log('Security Watch is running in the foreground. Configured routes are active.');
695
+ try {
696
+ while (!stop) {
697
+ if (Date.now() - lastHeartbeat >= 15_000)
698
+ heartbeat('running');
699
+ if (!scanning && !maintaining && Date.now() >= nextScan) {
700
+ nextScan = Date.now() + config.poll_interval_minutes * 60_000;
701
+ scanning = (async () => {
702
+ try {
703
+ const report = await runScan({
704
+ config,
705
+ inventory: loadInventory(config.inventory),
706
+ store,
707
+ signal: controller.signal,
708
+ });
709
+ console.log(JSON.stringify({
710
+ at: report.at,
711
+ findings: report.findings.length,
712
+ degraded: report.degraded,
713
+ errors: report.errors,
714
+ }));
715
+ }
716
+ catch {
717
+ if (controller.signal.aborted)
718
+ return;
719
+ const finding = healthFinding('worker', 'Scan failed. Check configuration, inventory and local storage. Previous findings are retained.');
720
+ store.setMeta('last_scan', JSON.stringify({
721
+ at: new Date().toISOString(),
722
+ degraded: true,
723
+ errors: [{ source: 'worker', message: finding.summary }],
724
+ }));
725
+ store.saveAssessment(finding, decide(finding, config));
726
+ console.error('Scan failed; previous findings retained.');
727
+ }
728
+ })()
729
+ .catch(() => {
730
+ console.error('Worker cannot persist monitoring state; stopping.');
731
+ process.exitCode = 1;
732
+ stop = true;
733
+ })
734
+ .finally(() => {
735
+ scanning = undefined;
736
+ });
737
+ }
738
+ const delivery = await deliverPending(store, config, safeHttp, Date.now(), undefined, controller.signal);
739
+ if (delivery.failed || delivery.unknown)
740
+ console.error(JSON.stringify({ delivery, action: 'Inspect deliveries and destination configuration.' }));
741
+ if (!scanning && !maintaining && config.maintenance && !stop)
742
+ maintaining = maintenance
743
+ .tick(store, config)
744
+ .then((report) => {
745
+ if (report)
746
+ console.log(JSON.stringify({ maintenance: report }));
747
+ })
748
+ .catch(() => {
749
+ console.error('Worker cannot persist maintenance state; stopping.');
750
+ process.exitCode = 1;
751
+ stop = true;
752
+ })
753
+ .finally(() => {
754
+ maintaining = undefined;
755
+ });
756
+ const ping = await monitor.tick(store, config, safeHttp, Date.now(), controller.signal);
757
+ if (ping && ping.status !== monitorStatus) {
758
+ monitorStatus = ping.status;
759
+ console.log(JSON.stringify({ external_heartbeat: ping }));
760
+ }
761
+ await delay(1000);
762
+ }
763
+ if (scanning)
764
+ await scanning;
765
+ if (maintaining)
766
+ await maintaining;
767
+ }
768
+ finally {
769
+ controller.abort();
770
+ if (scanning)
771
+ await scanning;
772
+ if (maintaining)
773
+ await maintaining;
774
+ heartbeat('stopped');
775
+ process.off('SIGINT', shutdown);
776
+ process.off('SIGTERM', shutdown);
777
+ }
778
+ }
779
+ finally {
780
+ store.close();
781
+ release();
782
+ }
783
+ }
784
+ main().catch((error) => {
785
+ if (error instanceof z.ZodError)
786
+ console.error('Validation failed: ' + error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; '));
787
+ else if (error instanceof Error && /YAML/i.test(error.name))
788
+ console.error('Invalid YAML; check configuration/inventory syntax.');
789
+ else
790
+ console.error(error instanceof Error ? error.message : 'Operation failed');
791
+ process.exitCode = 1;
792
+ });