@shieldaai/security-watch 1.2.1 → 1.4.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 (47) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/CONTRIBUTING.md +2 -0
  3. package/README.md +69 -42
  4. package/SECURITY.md +4 -1
  5. package/dist/check.d.ts +193 -0
  6. package/dist/check.js +1000 -0
  7. package/dist/cli.js +301 -6
  8. package/dist/config.d.ts +22 -0
  9. package/dist/config.js +32 -0
  10. package/dist/cve-now.js +2 -0
  11. package/dist/delivery.js +30 -0
  12. package/dist/engine.d.ts +25 -0
  13. package/dist/engine.js +64 -4
  14. package/dist/index.d.ts +8 -1
  15. package/dist/index.js +3 -0
  16. package/dist/inventory.d.ts +2 -1
  17. package/dist/inventory.js +2 -3
  18. package/dist/manifests.d.ts +7 -0
  19. package/dist/manifests.js +16 -0
  20. package/dist/mcp-server.d.ts +256 -0
  21. package/dist/mcp-server.js +755 -0
  22. package/dist/mitigations.d.ts +137 -0
  23. package/dist/mitigations.js +426 -0
  24. package/dist/rehearsal.d.ts +25 -0
  25. package/dist/rehearsal.js +2 -0
  26. package/dist/sbom.d.ts +12 -1
  27. package/dist/sbom.js +37 -7
  28. package/dist/shield-candidates.d.ts +97 -0
  29. package/dist/shield-candidates.js +251 -0
  30. package/dist/shield-inputs.d.ts +49 -0
  31. package/dist/shield-inputs.js +297 -0
  32. package/dist/shirudo-sboms.d.ts +62 -0
  33. package/dist/shirudo-sboms.js +598 -0
  34. package/dist/sources.d.ts +2 -0
  35. package/dist/sources.js +14 -0
  36. package/dist/store.js +6 -4
  37. package/dist/types.d.ts +31 -0
  38. package/dist/vex.d.ts +62 -0
  39. package/dist/vex.js +246 -0
  40. package/docs/agents.md +139 -0
  41. package/docs/configuration.md +20 -1
  42. package/docs/mitigations.md +139 -0
  43. package/docs/offline-advisory-preview.md +2 -2
  44. package/docs/sbom.md +4 -4
  45. package/docs/shirudo.md +113 -0
  46. package/npm-shrinkwrap.json +237 -0
  47. package/package.json +10 -5
package/dist/cli.js CHANGED
@@ -4,10 +4,15 @@ import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, renameSync,
4
4
  import { basename, 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
- import { stringify } from 'yaml';
7
+ import { parse as parseYaml, 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 { checkAdvisory, checkChange, checkPackages, checkProject, formatAdvisoryReport, formatChangeReport, formatCheckReport, failsAt, } from './check.js';
12
+ import { shieldCandidates } from './shield-candidates.js';
13
+ import { openVex } from './vex.js';
14
+ import { exportProblems, maxAges, readMitigationExport, withCurrentMitigations } from './mitigations.js';
15
+ import { syncShirudoSboms } from './shirudo-sboms.js';
11
16
  import { importSbom } from './sbom.js';
12
17
  import { DEPENDENCY_FILES, generateSbom } from './manifests.js';
13
18
  import { intakeDirectory, startIntake } from './intake.js';
@@ -63,6 +68,13 @@ function firstScanNotice(config, store, offline) {
63
68
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
64
69
  const help = `Shielda Security Watch ${VERSION}
65
70
 
71
+ security-watch check [PROJECT] [--production] [--epss] [--fail-on high] [--json]
72
+ security-watch check [PROJECT] --base REF (only what a change since REF brings in)
73
+ security-watch check --sbom FILE.json
74
+ security-watch check --package npm:lodash@4.17.21 [--package pypi:requests@2.31.0 ...]
75
+ security-watch check [PROJECT] --advisory CVE-2021-44906
76
+ security-watch mcp [PROJECT] (MCP server on stdio, for AI agents)
77
+
66
78
  security-watch sbom [--project PATH] [--output FILE.cdx.json] [--name NAME] [--system-id ID]
67
79
  [--owner TEXT] [--environment TEXT] [--note TEXT] [--exposure internet|internal|unknown]
68
80
  [--criticality low|medium|high|critical] [--production] [--source-url URL] [--source-revision REV]
@@ -85,6 +97,9 @@ const help = `Shielda Security Watch ${VERSION}
85
97
  security-watch rehearse --config PATH --input SCENARIO.json [--sink disabled|accepted|failed|unknown] [--output NEW.json]
86
98
  security-watch start [--config PATH]
87
99
  security-watch findings | status | deliveries | budget
100
+ security-watch shield-candidates [--all] [--unmitigated] [--omit-location] [--output NEW.json]
101
+ security-watch vex [--system ID] [--include-not-affected] [--omit-mitigations] [--author TEXT] [--output NEW.json]
102
+ security-watch shirudo-sboms --store DIR --directory SBOM_DIR [--running EXPORT.jsonl] [--config PATH] [--apply] [--allow-removals]
88
103
  security-watch pilot-report (--database PATH | --backup PATH) --from YYYY-MM-DD --until YYYY-MM-DD [--output NEW.json]
89
104
  security-watch pilot-recall --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --input INCIDENTS.json [--responses RESPONSES.json] [--output NEW.json]
90
105
  security-watch pilot-cases --backup PATH --from YYYY-MM-DD --until YYYY-MM-DD --output NEW.json
@@ -104,12 +119,24 @@ const help = `Shielda Security Watch ${VERSION}
104
119
  security-watch unlock (only removes a stopped worker's lock)
105
120
  security-watch test-notification --channel slack|email
106
121
 
122
+ check asks OSV about every package in a project now and marks CISA known-exploited entries; it
123
+ sends package names and versions (and, with --epss, CVE IDs to FIRST), stores nothing and needs no
124
+ configuration. Exit code 1: an installed version affected at or above --fail-on (high; malware and
125
+ known-exploited always count, an advisory without a severity counts as medium, a package without an
126
+ exact version never does; none never fails); 2: the check is incomplete (a source failed or a
127
+ dependency file could not be read). --base REF... compares with the point where the branch left REF.
128
+
107
129
  sbom reads the lockfiles and manifests in a project (npm, Python, Go, Rust, PHP, Ruby, Java,
108
130
  .NET, Dart, Elixir, Swift, Haskell) and writes a CycloneDX SBOM. It runs nothing and sends nothing.
109
131
  init --project creates a monitor for that project in one step. With an intake section in the
110
132
  configuration, start also receives SBOMs from CI (sbom --upload, upload); intake runs only that.
111
133
  Upload tokens are read from SECURITY_WATCH_INTAKE_TOKEN unless --token-env names another variable.
112
134
 
135
+ shield-candidates lists critical and exploited findings with what is known for writing a temporary
136
+ runtime shield (fix links, versions, exploit code) and what is missing; vex writes OpenVEX for
137
+ other scanners; both change nothing. shirudo-sboms copies Shirudo's image SBOMs into the SBOM
138
+ folder, showing its plan unless --apply is given.
139
+
113
140
  Default config: ./security-watch.yaml. scan records findings; --dry-run writes no state,
114
141
  disables models and sends nothing. --notify sends due jobs. start runs the foreground scheduler and
115
142
  configured notification routes. Model/feed requests can leave this machine; fixture
@@ -179,6 +206,22 @@ function argumentsFromCommandLine() {
179
206
  url: { type: 'string' },
180
207
  'token-env': { type: 'string' },
181
208
  'allow-http': { type: 'boolean' },
209
+ 'omit-location': { type: 'boolean' },
210
+ unmitigated: { type: 'boolean' },
211
+ 'allow-removals': { type: 'boolean' },
212
+ 'include-not-affected': { type: 'boolean' },
213
+ 'omit-mitigations': { type: 'boolean' },
214
+ author: { type: 'string' },
215
+ system: { type: 'string' },
216
+ store: { type: 'string' },
217
+ running: { type: 'string' },
218
+ sbom: { type: 'string' },
219
+ base: { type: 'string' },
220
+ package: { type: 'string', multiple: true },
221
+ advisory: { type: 'string' },
222
+ epss: { type: 'boolean' },
223
+ 'fail-on': { type: 'string' },
224
+ json: { type: 'boolean' },
182
225
  },
183
226
  });
184
227
  }
@@ -595,6 +638,76 @@ async function initialize() {
595
638
  (values.heartbeat ? 'HEARTBEAT_URL=\n' : '# HEARTBEAT_URL=\n'), { flag: 'wx', mode: 0o600 });
596
639
  console.log(`Created ${configPath} and ${inventoryPath}. ${sbomFiles.length ? 'Each SBOM in sboms/ is one system; add owners and notes with security-watch sbom --owner/--note, or describe more systems in systems.yaml.' : '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.`);
597
640
  }
641
+ /** `ecosystem:name@version`, such as npm:lodash@4.17.21, npm:@scope/pkg@1.0.0 or maven:org.x:lib@2.1. */
642
+ function packageArgument(value) {
643
+ const colon = value.indexOf(':');
644
+ if (colon < 1)
645
+ throw new Error(`--package ${value}: write it as ecosystem:name@version, such as npm:lodash@4.17.21.`);
646
+ const rest = value.slice(colon + 1).replace('==', '@');
647
+ const at = rest.lastIndexOf('@');
648
+ return at > 0
649
+ ? { ecosystem: value.slice(0, colon), name: rest.slice(0, at), version: rest.slice(at + 1) }
650
+ : { ecosystem: value.slice(0, colon), name: rest };
651
+ }
652
+ async function runCheck() {
653
+ if ((values.project?.length ?? 0) + (id ? 1 : 0) > 1)
654
+ throw new Error('check reads one project at a time.');
655
+ const project = id ?? values.project?.[0];
656
+ const failOn = values['fail-on'] ?? 'high';
657
+ if (!['critical', 'high', 'medium', 'low', 'none'].includes(failOn))
658
+ throw new Error('--fail-on must be critical, high, medium, low or none.');
659
+ if (values.package && (project || values.sbom || values.base || values.advisory))
660
+ throw new Error('--package checks the named packages only; leave out the project, --sbom, --base and --advisory.');
661
+ if (values.base && (values.sbom || values.advisory))
662
+ throw new Error('--base compares a project folder with git; it cannot be combined with --sbom or --advisory.');
663
+ if (values.sbom && project)
664
+ throw new Error('Give a project or --sbom, not both.');
665
+ const common = {
666
+ ...(values.epss ? { epss: true } : {}),
667
+ ...(values.production ? { production: true } : {}),
668
+ };
669
+ const target = {
670
+ ...common,
671
+ ...(project ? { project } : {}),
672
+ ...(values.sbom ? { sbom: values.sbom } : {}),
673
+ };
674
+ let failing;
675
+ let degraded;
676
+ let result;
677
+ let text;
678
+ if (values.package) {
679
+ const report = await checkPackages(values.package.map(packageArgument), common);
680
+ [failing, degraded, result, text] = [report.findings, report.degraded, report, formatCheckReport(report)];
681
+ }
682
+ else if (values.advisory) {
683
+ const report = await checkAdvisory(values.advisory, target);
684
+ [failing, degraded, result, text] = [
685
+ report.findings,
686
+ report.project.degraded,
687
+ report,
688
+ formatAdvisoryReport(report),
689
+ ];
690
+ }
691
+ else if (values.base) {
692
+ const report = await checkChange({ ...target, base: values.base });
693
+ [failing, degraded, result, text] = [
694
+ report.added,
695
+ report.head.degraded,
696
+ report,
697
+ formatChangeReport(report),
698
+ ];
699
+ }
700
+ else {
701
+ const report = await checkProject(target);
702
+ [failing, degraded, result, text] = [report.findings, report.degraded, report, formatCheckReport(report)];
703
+ }
704
+ if (values.json)
705
+ output(result);
706
+ else
707
+ console.log(text);
708
+ const fails = failing.some((finding) => failsAt(finding, failOn));
709
+ process.exitCode = fails ? 1 : degraded ? 2 : 0;
710
+ }
598
711
  async function main() {
599
712
  if (values.version) {
600
713
  console.log(VERSION);
@@ -605,6 +718,8 @@ async function main() {
605
718
  return;
606
719
  }
607
720
  const commandFlags = {
721
+ check: ['project', 'sbom', 'base', 'package', 'advisory', 'production', 'epss', 'fail-on', 'json'],
722
+ mcp: [],
608
723
  sbom: [
609
724
  'project',
610
725
  'output',
@@ -649,6 +764,7 @@ async function main() {
649
764
  ecosystems: [],
650
765
  'normalize-libraries': ['input', 'ecosystem', 'output'],
651
766
  'import-sbom': ['input', 'output'],
767
+ 'shirudo-sboms': ['store', 'directory', 'running', 'apply', 'allow-removals', 'config'],
652
768
  coverage: ['config'],
653
769
  'inventory-drift': ['config'],
654
770
  doctor: ['config', 'no-ai'],
@@ -662,6 +778,8 @@ async function main() {
662
778
  'pilot-report': ['database', 'backup', 'from', 'until', 'output'],
663
779
  start: ['config', 'no-ai'],
664
780
  findings: ['config'],
781
+ 'shield-candidates': ['config', 'all', 'omit-location', 'unmitigated', 'output'],
782
+ vex: ['config', 'system', 'include-not-affected', 'omit-mitigations', 'author', 'output'],
665
783
  status: ['config'],
666
784
  deliveries: ['config'],
667
785
  budget: ['config'],
@@ -686,9 +804,27 @@ async function main() {
686
804
  for (const flag of Object.keys(values))
687
805
  if (!commandFlags[command].includes(flag))
688
806
  throw new Error(`--${flag} is not supported by ${command}.`);
689
- const needsId = ['explain', 'history', 'review', 'acknowledge', 'suppress', 'retry'].includes(command);
807
+ const needsId = [
808
+ 'explain',
809
+ 'history',
810
+ 'review',
811
+ 'acknowledge',
812
+ 'suppress',
813
+ 'retry',
814
+ 'check',
815
+ 'mcp',
816
+ ].includes(command);
690
817
  if (positionals.length > (needsId ? 2 : 1))
691
818
  throw new Error('Unexpected positional arguments. Use --help.');
819
+ if (command === 'check') {
820
+ await runCheck();
821
+ return;
822
+ }
823
+ if (command === 'mcp') {
824
+ const { mcpMain } = await import('./mcp-server.js');
825
+ mcpMain(id ? [id] : []);
826
+ return;
827
+ }
692
828
  if (command === 'init') {
693
829
  await initialize();
694
830
  return;
@@ -719,6 +855,37 @@ async function main() {
719
855
  await sendSbom(body, values['system-id'] ?? systemIdOf(body, path));
720
856
  return;
721
857
  }
858
+ if (command === 'shirudo-sboms') {
859
+ if (!values.store || !values.directory)
860
+ throw new Error('--store DIR and --directory SBOM_DIR required');
861
+ // With --config, systems described by hand in the inventory are known, so an image with the same
862
+ // ID is reported instead of being refused by every scan.
863
+ let reserved = [];
864
+ if (values.config) {
865
+ const inventoryPath = loadConfig(resolve(values.config)).inventory;
866
+ const raw = parseYaml(readFileSync(inventoryPath, 'utf8'), { maxAliasCount: 0 });
867
+ const systems = raw && typeof raw === 'object' ? raw.systems : undefined;
868
+ reserved = Array.isArray(systems)
869
+ ? systems
870
+ .map((system) => system && typeof system === 'object' ? system.id : undefined)
871
+ .filter((value) => typeof value === 'string')
872
+ : [];
873
+ }
874
+ const plan = syncShirudoSboms({
875
+ reserved,
876
+ allowRemovals: Boolean(values['allow-removals']),
877
+ store: resolve(values.store),
878
+ output: resolve(values.directory),
879
+ ...(values.running ? { exposure: resolve(values.running) } : {}),
880
+ apply: Boolean(values.apply),
881
+ });
882
+ output(plan);
883
+ if (!values.apply && (plan.images.some((item) => item.action === 'write') || plan.remove.length))
884
+ console.error('Nothing was written. Run again with --apply to write this plan.');
885
+ if (plan.problems.length)
886
+ process.exitCode = 2;
887
+ return;
888
+ }
722
889
  if (command === 'import-sbom') {
723
890
  if (!values.input)
724
891
  throw new Error('--input PATH required');
@@ -860,6 +1027,38 @@ async function main() {
860
1027
  ? process.env[config.notifications.slack.webhook_url_env]
861
1028
  : undefined;
862
1029
  const heartbeat = config.monitoring ? process.env[config.monitoring.heartbeat_url_env] : undefined;
1030
+ // Each mitigation export is read as a scan reads it; what it covers is shown so a mapping
1031
+ // mistake (an image ID that is no system ID) is seen before the first alert.
1032
+ const systemIds = new Set(inventory.systems.map((system) => system.id));
1033
+ const mitigationProblems = [];
1034
+ const mitigations = (config.mitigations ?? []).map((source) => {
1035
+ try {
1036
+ const exported = readMitigationExport(source, Date.now());
1037
+ mitigationProblems.push(...exportProblems(exported, source, Date.now()));
1038
+ const keys = new Set(exported.rows.map((row) => row.system));
1039
+ const systems = [...keys].map((key) => Object.hasOwn(source.systems, key) ? source.systems[key] : key);
1040
+ const unknown = systems.filter((id) => !systemIds.has(id));
1041
+ if (unknown.length)
1042
+ mitigationProblems.push(`${source.name}: ${unknown.length} system key(s) in the export match no system in the inventory (${unknown
1043
+ .slice(0, 5)
1044
+ .join(', ')}${unknown.length > 5 ? ', …' : ''}); map them with systems: or add those systems.`);
1045
+ return {
1046
+ name: source.name,
1047
+ format: source.format,
1048
+ rows: exported.rows.length,
1049
+ hosts: new Set(exported.rows.map((row) => `${row.system}\u0000${row.host}`)).size,
1050
+ systems_matched: systems.filter((id) => systemIds.has(id)).length,
1051
+ exported_at: exported.exported_at,
1052
+ stale: exported.stale,
1053
+ };
1054
+ }
1055
+ catch (error) {
1056
+ mitigationProblems.push(`${source.name}: the export cannot be read: ${error.code === 'ENOENT'
1057
+ ? 'the file does not exist'
1058
+ : error.message}.`);
1059
+ return { name: source.name, format: source.format, readable: false };
1060
+ }
1061
+ });
863
1062
  const problems = [
864
1063
  // Delivery refuses such an address on every attempt; say so before the first alert is due.
865
1064
  ...(slack && slackProblem(slack)
@@ -871,6 +1070,7 @@ async function main() {
871
1070
  ]
872
1071
  : []),
873
1072
  ...intakeProblems(config),
1073
+ ...mitigationProblems,
874
1074
  // The heartbeat refuses such an address on every ping.
875
1075
  ...(heartbeat && heartbeatProblem(heartbeat, config.monitoring.allow_private_endpoint)
876
1076
  ? [`${config.monitoring.heartbeat_url_env}: the external heartbeat address cannot be used.`]
@@ -903,6 +1103,7 @@ async function main() {
903
1103
  feeds: config.sources.feeds.length + Number(config.sources.hacker_news),
904
1104
  notification_routes: routes,
905
1105
  notification_channels: enabledChannels,
1106
+ ...(mitigations.length ? { mitigations } : {}),
906
1107
  ecosystems: [
907
1108
  ...new Set(inventory.systems.flatMap((system) => system.components.map((component) => component.ecosystem))),
908
1109
  ],
@@ -964,6 +1165,8 @@ async function main() {
964
1165
  'scan',
965
1166
  'start',
966
1167
  'findings',
1168
+ 'shield-candidates',
1169
+ 'vex',
967
1170
  'status',
968
1171
  'coverage',
969
1172
  'inventory-drift',
@@ -991,6 +1194,8 @@ async function main() {
991
1194
  const readonly = (command === 'prune' && !values.apply) ||
992
1195
  [
993
1196
  'findings',
1197
+ 'shield-candidates',
1198
+ 'vex',
994
1199
  'status',
995
1200
  'coverage',
996
1201
  'inventory-drift',
@@ -1079,7 +1284,91 @@ async function main() {
1079
1284
  return;
1080
1285
  }
1081
1286
  if (command === 'findings') {
1082
- output(store.findings());
1287
+ const ages = maxAges(config.mitigations);
1288
+ output(store.findings().map((finding) => withCurrentMitigations(finding, ages, Date.now())));
1289
+ return;
1290
+ }
1291
+ if (command === 'vex') {
1292
+ const author = values.author ?? 'Security Watch';
1293
+ if (!author.trim() ||
1294
+ author.length > 200 ||
1295
+ /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(author))
1296
+ throw new Error('--author must be one line of at most 200 characters');
1297
+ // The packages and their versions come from the inventory as it is now.
1298
+ const inventory = loadInventory(config.inventory);
1299
+ if (values.system !== undefined && !inventory.systems.some((system) => system.id === values.system))
1300
+ throw new Error(`No system ${values.system} in the inventory`);
1301
+ const ages = maxAges(config.mitigations);
1302
+ const { document, skipped } = openVex({
1303
+ findings: store.findings().map((finding) => withCurrentMitigations(finding, ages, Date.now())),
1304
+ evidence: (ids) => store.getEvidence(ids),
1305
+ inventory,
1306
+ ...(values.system !== undefined ? { systemId: values.system } : {}),
1307
+ includeNotAffected: Boolean(values['include-not-affected']),
1308
+ author: author.trim(),
1309
+ // Fresh runtime mitigations are worth telling a consumer; they never change the status.
1310
+ mitigationNote: (finding) => {
1311
+ // Only a current status that covers at least one host is worth saying outside, with its time.
1312
+ if (values['omit-mitigations'])
1313
+ return undefined;
1314
+ const fresh = (finding.mitigations ?? []).filter((status) => !status.stale && !status.not_listed && (status.states.mitigated ?? 0) > 0);
1315
+ return fresh.length
1316
+ ? `Temporary runtime mitigation on ${fresh
1317
+ .map((status) => `${status.states.mitigated} of ${status.hosts} host(s) (${status.source}, ${status.exported_at.slice(0, 16).replace('T', ' ')} UTC)`)
1318
+ .join('; ')}.`
1319
+ : undefined;
1320
+ },
1321
+ });
1322
+ if (values.output) {
1323
+ writeFileSync(resolve(values.output), JSON.stringify(document, null, 2) + '\n', {
1324
+ flag: 'wx',
1325
+ mode: 0o600,
1326
+ });
1327
+ const left = Object.entries(skipped)
1328
+ .map(([reason, count]) => `${count} ${reason.replaceAll('_', ' ')}`)
1329
+ .join(', ');
1330
+ console.log(`${document.statements.length} VEX statement(s) saved.${left ? ` Not written: ${left}.` : ''}`);
1331
+ }
1332
+ else {
1333
+ output(document);
1334
+ const left = Object.entries(skipped)
1335
+ .map(([reason, count]) => `${count} ${reason.replaceAll('_', ' ')}`)
1336
+ .join(', ');
1337
+ if (left)
1338
+ console.error(`Not written: ${left}.`);
1339
+ }
1340
+ return;
1341
+ }
1342
+ if (command === 'shield-candidates') {
1343
+ // The inventory as it is now gives package versions; a stored location is the fallback.
1344
+ let inventory;
1345
+ try {
1346
+ inventory = loadInventory(config.inventory);
1347
+ }
1348
+ catch {
1349
+ inventory = undefined;
1350
+ }
1351
+ const report = shieldCandidates({
1352
+ findings: store.findings(),
1353
+ evidence: (ids) => store.getEvidence(ids),
1354
+ ...(inventory ? { inventory } : {}),
1355
+ controls: (findingId) => store.controls(findingId),
1356
+ all: Boolean(values.all),
1357
+ omitLocation: Boolean(values['omit-location']),
1358
+ unmitigatedOnly: Boolean(values.unmitigated),
1359
+ mitigationMaxAge: maxAges(config.mitigations),
1360
+ });
1361
+ if (!inventory)
1362
+ report.notes.push('The inventory could not be read: a package and its installed version are shown only where an advisory matched exactly one package by version.');
1363
+ if (values.output) {
1364
+ writeFileSync(resolve(values.output), JSON.stringify(report, null, 2) + '\n', {
1365
+ flag: 'wx',
1366
+ mode: 0o600,
1367
+ });
1368
+ console.log(`${report.candidates.length} shield candidate(s) saved.`);
1369
+ }
1370
+ else
1371
+ output(report);
1083
1372
  return;
1084
1373
  }
1085
1374
  if (command === 'deliveries') {
@@ -1118,9 +1407,10 @@ async function main() {
1118
1407
  return;
1119
1408
  }
1120
1409
  if (command === 'explain') {
1121
- const finding = id ? store.getFinding(id) : undefined;
1122
- if (!finding)
1410
+ const saved = id ? store.getFinding(id) : undefined;
1411
+ if (!saved)
1123
1412
  throw new Error('Finding not found');
1413
+ const finding = withCurrentMitigations(saved, maxAges(config.mitigations), Date.now());
1124
1414
  output({
1125
1415
  finding,
1126
1416
  decision: decide(finding, config),
@@ -1133,6 +1423,10 @@ async function main() {
1133
1423
  fetched_at: e.fetched_at,
1134
1424
  withdrawn: e.withdrawn ?? false,
1135
1425
  ...(e.cvss_v4 ? { cvss_v4: e.cvss_v4 } : {}),
1426
+ ...(e.references ? { references: e.references } : {}),
1427
+ ...(e.fix_commits ? { fix_commits: e.fix_commits } : {}),
1428
+ ...(e.weaknesses ? { weaknesses: e.weaknesses } : {}),
1429
+ ...(e.exploit_sources ? { exploit_sources: e.exploit_sources } : {}),
1136
1430
  })),
1137
1431
  note: 'Applicability reflects the cited evidence as last fetched. Inspect monitoring health for source outages.',
1138
1432
  });
@@ -1428,5 +1722,6 @@ main().catch((error) => {
1428
1722
  console.error('Invalid YAML; check configuration/inventory syntax.');
1429
1723
  else
1430
1724
  console.error(error instanceof Error ? error.message : 'Operation failed');
1431
- process.exitCode = 1;
1725
+ // check uses 1 for "found something"; a check that could not run is 2, like an incomplete one.
1726
+ process.exitCode = command === 'check' ? 2 : 1;
1432
1727
  });
package/dist/config.d.ts CHANGED
@@ -293,6 +293,28 @@ export declare const configSchema: z.ZodObject<{
293
293
  tls_key_file: z.ZodOptional<z.ZodString>;
294
294
  allow_plain_http: z.ZodDefault<z.ZodBoolean>;
295
295
  }, z.core.$strict>>;
296
+ mitigations: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodObject<{
297
+ name: z.ZodOptional<z.ZodString>;
298
+ format: z.ZodEnum<{
299
+ generic: "generic";
300
+ shirudo: "shirudo";
301
+ }>;
302
+ file: z.ZodString;
303
+ max_age_minutes: z.ZodDefault<z.ZodNumber>;
304
+ systems: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodString>>;
305
+ }, z.core.$strict>, z.ZodTransform<{
306
+ format: "generic" | "shirudo";
307
+ file: string;
308
+ max_age_minutes: number;
309
+ systems: Record<string, string>;
310
+ name: string;
311
+ }, {
312
+ name?: string | undefined;
313
+ format: "generic" | "shirudo";
314
+ file: string;
315
+ max_age_minutes: number;
316
+ systems: Record<string, string>;
317
+ }>>>>;
296
318
  maintenance: z.ZodOptional<z.ZodObject<{
297
319
  interval_hours: z.ZodDefault<z.ZodNumber>;
298
320
  retention: z.ZodOptional<z.ZodObject<{
package/dist/config.js CHANGED
@@ -260,6 +260,36 @@ export const configSchema = z
260
260
  ctx.addIssue({ code: 'custom', message: 'Each token needs its own token_env', path: ['tokens'] });
261
261
  })
262
262
  .optional(),
263
+ mitigations: z
264
+ .array(z
265
+ .object({
266
+ name: z
267
+ .string()
268
+ .trim()
269
+ .min(1)
270
+ .max(40)
271
+ .regex(/^[^\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]+$/, 'Use a short single-line name')
272
+ .optional(),
273
+ format: z.enum(['shirudo', 'generic']),
274
+ file: z.string().trim().min(1).max(4096),
275
+ max_age_minutes: z.number().int().min(5).max(10080).default(120),
276
+ systems: z
277
+ .record(z.string().trim().min(1).max(255), z.string().trim().min(1).max(200))
278
+ .refine((map) => Object.keys(map).length <= 1000, 'At most 1,000 system mappings')
279
+ .default({}),
280
+ })
281
+ .strict()
282
+ .transform(({ name, ...source }) => ({
283
+ ...source,
284
+ name: name ?? (source.format === 'shirudo' ? 'Shirudo' : 'Mitigations'),
285
+ })))
286
+ .max(10)
287
+ .superRefine((sources, ctx) => {
288
+ const names = sources.map((source) => source.name.toLowerCase());
289
+ if (new Set(names).size !== names.length)
290
+ ctx.addIssue({ code: 'custom', message: 'Give each mitigation source its own name' });
291
+ })
292
+ .optional(),
263
293
  maintenance: z
264
294
  .object({
265
295
  interval_hours: z.number().int().min(1).max(168).default(24),
@@ -435,6 +465,8 @@ export function loadConfig(path) {
435
465
  config.intake.tls_cert_file = resolve(dirname(resolve(path)), config.intake.tls_cert_file);
436
466
  if (config.intake?.tls_key_file)
437
467
  config.intake.tls_key_file = resolve(dirname(resolve(path)), config.intake.tls_key_file);
468
+ for (const source of config.mitigations ?? [])
469
+ source.file = resolve(dirname(resolve(path)), source.file);
438
470
  if (config.maintenance?.backup)
439
471
  config.maintenance.backup.directory = resolve(dirname(resolve(path)), config.maintenance.backup.directory);
440
472
  return config;
package/dist/cve-now.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { compare, valid } from 'semver';
2
2
  import { cleanText, highest, timestamp } from './util.js';
3
+ import { cveNowExploitSources, shieldInputs } from './shield-inputs.js';
3
4
  import { normalizeEcosystem, normalizePackageName, packageKey } from './ecosystems.js';
4
5
  import { inventoryMatcher } from './matching.js';
5
6
  import { PartialSourceError, SourceError, SourceHttpError, SourceItemFailures, sourceCanceled, throwSourceFailure, } from './source-error.js';
@@ -238,6 +239,7 @@ function parseEntry(data, now, expected, matched) {
238
239
  exploited: knownExploited,
239
240
  malware: /^MAL-/i.test(id),
240
241
  withdrawn: data.status !== 'published',
242
+ ...shieldInputs({ exploit_sources: cveNowExploitSources(exploitation) }),
241
243
  modified_at: modified,
242
244
  fetched_at: timestamp(now),
243
245
  ...(published ? { published_at: published } : {}),
package/dist/delivery.js CHANGED
@@ -305,6 +305,34 @@ function epssLine(a) {
305
305
  single(`EPSS for ${epss.cve}: ${shown} chance of exploitation in the next 30 days; higher than ${Math.floor(epss.percentile * 100)}% of scored CVEs (FIRST, ${epss.date})`, 200),
306
306
  ];
307
307
  }
308
+ /** Runtime mitigation status from the operator's exports, when configured. Shown only. */
309
+ function mitigationLines(a) {
310
+ const statuses = Array.isArray(a.mitigations) ? a.mitigations : [];
311
+ const lines = statuses.slice(0, 3).flatMap((status) => {
312
+ if (!status || typeof status.summary !== 'string')
313
+ return [];
314
+ const when = Date.parse(status.exported_at);
315
+ const at = Number.isFinite(when)
316
+ ? new Date(when).toISOString().slice(0, 16).replace('T', ' ')
317
+ : 'unknown time';
318
+ // The export time, an out-of-date mark and the reminder come before the mitigation names, which
319
+ // are the operator's free text and are shortened on their own, so they can never push those out.
320
+ // A mitigation that expires is covered only until then; a digest read later must say so.
321
+ const expires = typeof status.expires_at === 'string' ? Date.parse(status.expires_at) : Number.NaN;
322
+ const until = Number.isFinite(expires)
323
+ ? new Date(expires).toISOString().slice(0, 16).replace('T', ' ')
324
+ : undefined;
325
+ const ids = (Array.isArray(status.mitigations) ? status.mitigations.slice(0, 3) : [])
326
+ .filter((id) => typeof id === 'string')
327
+ .map((id) => single(id, 40));
328
+ return [
329
+ single(`${single(status.summary, 260)} (export ${at} UTC${status.stale ? ', out of date' : ''}${until ? `; expires ${until} UTC` : ''}; a mitigation is temporary and does not close the finding)${ids.length ? ` In place: ${ids.join(', ')}` : ''}`, 480),
330
+ ];
331
+ });
332
+ if (statuses.length > 3)
333
+ lines.push(`${statuses.length - 3} more mitigation source(s): see explain.`);
334
+ return lines;
335
+ }
308
336
  export function notificationText(job) {
309
337
  const { assessment: a, reason } = JSON.parse(job.payload);
310
338
  const subject = single(`[${a.priority.toUpperCase()}] ${a.title}`, 180);
@@ -320,6 +348,7 @@ export function notificationText(job) {
320
348
  ...(a.exploited ? ['Known exploitation reported.'] : []),
321
349
  ...newsSignalLine(a),
322
350
  ...epssLine(a),
351
+ ...mitigationLines(a),
323
352
  `Summary: ${single(a.summary, 750)}`,
324
353
  ];
325
354
  // In the order they give way when the text is too long for one Slack section: the last of these
@@ -406,6 +435,7 @@ export function digestText(jobs) {
406
435
  `Applicability: ${single(a.applicability, 40)}; source: ${single(a.source_severity, 40)}`,
407
436
  ...newsSignalLine(a),
408
437
  ...epssLine(a),
438
+ ...mitigationLines(a),
409
439
  ...(a.news_analysis
410
440
  ? [
411
441
  `AI news: ${single(a.news_analysis.classification, 60)}; impact: ${single(a.news_analysis.impact, 60)}`,
package/dist/engine.d.ts CHANGED
@@ -65,6 +65,31 @@ export declare const evidenceSchema: z.ZodObject<{
65
65
  withdrawn: z.ZodOptional<z.ZodBoolean>;
66
66
  exploited: z.ZodOptional<z.ZodBoolean>;
67
67
  malware: z.ZodOptional<z.ZodBoolean>;
68
+ references: z.ZodOptional<z.ZodArray<z.ZodObject<{
69
+ type: z.ZodEnum<{
70
+ advisory: "advisory";
71
+ detection: "detection";
72
+ evidence: "evidence";
73
+ fix: "fix";
74
+ introduced: "introduced";
75
+ package: "package";
76
+ report: "report";
77
+ source: "source";
78
+ web: "web";
79
+ }>;
80
+ url: z.ZodURL;
81
+ }, z.core.$strict>>>;
82
+ fix_commits: z.ZodOptional<z.ZodArray<z.ZodObject<{
83
+ repo: z.ZodURL;
84
+ commit: z.ZodString;
85
+ }, z.core.$strict>>>;
86
+ weaknesses: z.ZodOptional<z.ZodArray<z.ZodString>>;
87
+ exploit_sources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
88
+ "exploit-db": "exploit-db";
89
+ "github-poc": "github-poc";
90
+ metasploit: "metasploit";
91
+ nuclei: "nuclei";
92
+ }>>>;
68
93
  }, z.core.$strict>;
69
94
  export declare function readFixture(path: string): Evidence[];
70
95
  export declare function healthFinding(source: string, message: string, now?: number): Assessment;