@shieldaai/security-watch 0.1.0-alpha.0 → 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 (92) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +23 -7
  92. package/docs/quality-review.md +0 -104
@@ -1,5 +1,6 @@
1
- import { hash } from './util.js';
1
+ import { hash, LINE_BREAKING } from './util.js';
2
2
  import { valid } from 'semver';
3
+ import { valid as validPython } from '@renovatebot/pep440';
3
4
  /** Package identities follow the registry named by the OSV ecosystem. */
4
5
  export const ECOSYSTEMS = [
5
6
  'npm',
@@ -62,17 +63,22 @@ export function normalizeEcosystem(value) {
62
63
  export function normalizePackageName(ecosystem, value) {
63
64
  const name = value.trim();
64
65
  let normalized = name;
65
- let valid = name.length > 0 && name.length <= 500 && !/[\s\u0000-\u001f\u007f]/u.test(name);
66
+ let valid = name.length > 0 && name.length <= 500 && !/\s/u.test(name) && !LINE_BREAKING.test(name);
66
67
  switch (ecosystem) {
67
68
  case 'npm':
68
- valid &&= name.length <= 214 && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(name);
69
+ // Names registered before 2017 may contain capitals (JSONStream) and are case-sensitive.
70
+ valid &&=
71
+ name.length <= 214 && /^(?:@[a-z0-9][a-z0-9._-]*\/[a-z0-9]|[A-Za-z0-9])[A-Za-z0-9._-]*$/.test(name);
72
+ valid &&= !name.startsWith('@') || name === name.toLowerCase();
69
73
  break;
70
74
  case 'PyPI':
71
75
  valid &&= /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(name);
72
76
  normalized = name.toLowerCase().replace(/[-_.]+/g, '-');
73
77
  break;
74
78
  case 'Packagist':
75
- valid &&= /^[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?$/.test(name);
79
+ // Composer treats names as case-insensitive and publishes them in lower case.
80
+ normalized = name.toLowerCase();
81
+ valid &&= /^[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?\/[a-z0-9](?:[a-z0-9_.-]*[a-z0-9])?$/.test(normalized);
76
82
  break;
77
83
  case 'Maven':
78
84
  valid &&= /^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+$/.test(name);
@@ -145,6 +151,25 @@ export function osvPackageNames(ecosystem, value) {
145
151
  }
146
152
  return [name];
147
153
  }
154
+ const identityKeys = new Map();
155
+ /** One comparable key per package identity, or undefined when the ecosystem or name is not recognised. */
156
+ export function packageKey(value) {
157
+ const cacheKey = `${value.ecosystem}\u0000${value.name}`;
158
+ let key = identityKeys.get(cacheKey);
159
+ if (key === undefined) {
160
+ try {
161
+ const ecosystem = normalizeEcosystem(value.ecosystem);
162
+ key = `${ecosystem}\u0000${packageIdentity(ecosystem, value.name)}`;
163
+ }
164
+ catch {
165
+ key = null;
166
+ }
167
+ if (identityKeys.size >= 200_000)
168
+ identityKeys.clear();
169
+ identityKeys.set(cacheKey, key);
170
+ }
171
+ return key ?? undefined;
172
+ }
148
173
  export function samePackage(left, right) {
149
174
  try {
150
175
  const ecosystem = normalizeEcosystem(left.ecosystem);
@@ -167,18 +192,65 @@ export function exactLibraryVersion(value, ecosystem) {
167
192
  ['npm', 'Go', 'crates.io', 'Hex', 'Pub', 'SwiftURL'].includes(ecosystem) &&
168
193
  !valid(version))
169
194
  throw new Error(`Use an exact installed ${ecosystem} version, or omit the version`);
170
- // Validate PEP 440 syntax without ordering versions or rewriting the declared installation.
171
- if (ecosystem === 'PyPI' &&
172
- !/^v?(?:\d+!)?\d+(?:\.\d+)*(?:[-_.]?(?:alpha|beta|preview|pre|rc|a|b|c)[-_.]?\d*)?(?:-\d+|[-_.]?(?:post|rev|r)[-_.]?\d*)?(?:[-_.]?dev[-_.]?\d*)?(?:\+[a-z0-9]+(?:[-_.][a-z0-9]+)*)?$/i.test(version))
195
+ // Keep the declared spelling; assessment separately restricts supported ordering.
196
+ if (ecosystem === 'PyPI' && !validPython(version))
173
197
  throw new Error('Use an exact installed Python version in PEP 440 syntax, or omit the version');
174
198
  return version;
175
199
  }
200
+ /** Packages published before npm required lower-case names. Their capitals are part of the name. */
201
+ const LEGACY_NPM_NAMES = new Set(['JSONStream', 'Base64', 'JSONPath', 'JSONSelect']);
202
+ /**
203
+ * What to tell the operator about a name typed by hand with capital letters, in a registry that
204
+ * compares names by exact spelling and publishes them in lower case. npm: every name registered
205
+ * since 2017 is lower case, so `Lodash` is not `lodash` and matches no advisory; a few packages
206
+ * from before that rule keep their capitals, so the name is accepted, and anything but a known
207
+ * legacy name is pointed out. RubyGems, Hex and Pub: `Rails`, `Phoenix` and `Flutter_Bloc` are not
208
+ * the published `rails`, `phoenix` and `flutter_bloc`.
209
+ */
210
+ export function capitalisedName(component) {
211
+ const { ecosystem, name } = component;
212
+ if (name === name.toLowerCase())
213
+ return undefined;
214
+ if (ecosystem === 'npm') {
215
+ if (LEGACY_NPM_NAMES.has(name))
216
+ return undefined;
217
+ return `npm package name ${name} contains capital letters. npm names are case-sensitive and current names are lower case, so this entry matches only advisories published for exactly that spelling. Write ${name.toLowerCase()} unless this is a package from before 2017 that kept its capitals; names imported from a lockfile or SBOM are taken as published.`;
218
+ }
219
+ if (ecosystem === 'RubyGems' || ecosystem === 'Hex' || ecosystem === 'Pub')
220
+ return `${ecosystem} package name ${name} contains capital letters. Names are compared by exact spelling and are almost always published in lower case, so this entry matches only advisories published for exactly that spelling. Write ${name.toLowerCase()} unless the package really is published with capitals; names imported from an SBOM are taken as published.`;
221
+ return undefined;
222
+ }
223
+ /** A short, single-line pointer written by the operator, such as a service, repository path or owner. */
224
+ export function libraryNote(value) {
225
+ const note = value.trim();
226
+ if (!note || note.length > 500 || LINE_BREAKING.test(note))
227
+ throw new Error('A library note must be 1 to 500 characters on one line');
228
+ return note;
229
+ }
230
+ /** Keep each distinct note once, in the order given, within the note length limit. */
231
+ export function mergeNotes(first, second) {
232
+ if (!first || !second)
233
+ return first ?? second;
234
+ if (first.split(' | ').includes(second))
235
+ return first;
236
+ const merged = `${first} | ${second}`;
237
+ return merged.length > 500 ? first : merged;
238
+ }
176
239
  export function parseLibrary(value, defaultEcosystem) {
177
240
  let ecosystem;
178
241
  let name;
179
242
  let version;
243
+ let note;
180
244
  if (typeof value === 'string') {
181
245
  let entry = value.trim();
246
+ // "npm:lodash@4.17.21 # checkout service, apps/checkout" keeps the text after # as the note.
247
+ const comment = /\s#/.exec(entry);
248
+ if (comment) {
249
+ const text = entry.slice(comment.index + comment[0].length).trim();
250
+ if (text)
251
+ note = libraryNote(text);
252
+ entry = entry.slice(0, comment.index).trim();
253
+ }
182
254
  if (defaultEcosystem)
183
255
  ecosystem = normalizeEcosystem(defaultEcosystem);
184
256
  else {
@@ -209,11 +281,12 @@ export function parseLibrary(value, defaultEcosystem) {
209
281
  }
210
282
  else if (value && typeof value === 'object' && !Array.isArray(value)) {
211
283
  const input = value;
212
- if (Object.keys(input).some((key) => !['name', 'version', 'ecosystem'].includes(key)) ||
284
+ if (Object.keys(input).some((key) => !['name', 'version', 'ecosystem', 'note'].includes(key)) ||
213
285
  typeof input.name !== 'string' ||
286
+ (input.note !== undefined && typeof input.note !== 'string') ||
214
287
  (input.version !== undefined && typeof input.version !== 'string') ||
215
288
  (input.ecosystem !== undefined && typeof input.ecosystem !== 'string'))
216
- throw new Error('Library objects accept name, optional version and ecosystem only');
289
+ throw new Error('Library objects accept name, optional version, ecosystem and note only');
217
290
  if (!defaultEcosystem && typeof input.ecosystem !== 'string')
218
291
  throw new Error('Library ecosystem is required');
219
292
  ecosystem = normalizeEcosystem(defaultEcosystem ?? String(input.ecosystem));
@@ -221,6 +294,8 @@ export function parseLibrary(value, defaultEcosystem) {
221
294
  throw new Error('Library ecosystem does not match its group');
222
295
  name = input.name;
223
296
  version = input.version;
297
+ if (input.note !== undefined)
298
+ note = libraryNote(input.note);
224
299
  }
225
300
  else
226
301
  throw new Error('Expected a library string or object');
@@ -228,6 +303,7 @@ export function parseLibrary(value, defaultEcosystem) {
228
303
  ecosystem,
229
304
  name: normalizePackageName(ecosystem, name),
230
305
  ...(version === undefined ? {} : { version: exactLibraryVersion(version, ecosystem) }),
306
+ ...(note === undefined ? {} : { note }),
231
307
  };
232
308
  }
233
309
  /** Parse one entry per line; the ecosystem is explicit or supplied for the whole list. */
@@ -245,7 +321,9 @@ export function parseLibraryList(text, ecosystem) {
245
321
  const unique = new Map();
246
322
  for (const entry of entries) {
247
323
  const library = parseLibrary(entry, ecosystem);
248
- unique.set(JSON.stringify(library), library);
324
+ const key = JSON.stringify([library.ecosystem, library.name, library.version ?? null]);
325
+ const note = mergeNotes(unique.get(key)?.note, library.note);
326
+ unique.set(key, { ...library, ...(note ? { note } : {}) });
249
327
  }
250
328
  return [...unique.values()].map((library) => ({
251
329
  id: `library:${hash(JSON.stringify([library.ecosystem, library.name, library.version ?? null])).slice(0, 24)}`,
package/dist/engine.d.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { z } from 'zod';
1
2
  import { Store } from './store.js';
2
- import type { Assessment, Config, Decision, Evidence, HttpClient, Inventory } from './types.js';
3
+ import type { Assessment, Config, Decision, Evidence, HttpClient, Inventory, CoverageReceipt, InventoryDrift } from './types.js';
3
4
  export interface ScanReport {
4
5
  at: string;
5
6
  completed_at: string;
@@ -10,8 +11,61 @@ export interface ScanReport {
10
11
  source: string;
11
12
  message: string;
12
13
  }[];
14
+ /** Information about how the monitor is set up. A notice is not a fault and does not degrade a scan. */
15
+ notices: string[];
13
16
  evidence_count: number;
17
+ coverage: CoverageReceipt[];
18
+ inventory_drift: InventoryDrift[];
14
19
  }
20
+ export declare const evidenceSchema: z.ZodObject<{
21
+ id: z.ZodString;
22
+ source: z.ZodString;
23
+ kind: z.ZodEnum<{
24
+ advisory: "advisory";
25
+ health: "health";
26
+ kev: "kev";
27
+ news: "news";
28
+ }>;
29
+ title: z.ZodString;
30
+ url: z.ZodString;
31
+ description: z.ZodString;
32
+ aliases: z.ZodArray<z.ZodString>;
33
+ severity: z.ZodEnum<{
34
+ critical: "critical";
35
+ high: "high";
36
+ low: "low";
37
+ medium: "medium";
38
+ unknown: "unknown";
39
+ }>;
40
+ cvss_v4: z.ZodOptional<z.ZodObject<{
41
+ base_scores: z.ZodArray<z.ZodObject<{
42
+ vector: z.ZodString;
43
+ base_vector: z.ZodString;
44
+ score: z.ZodNumber;
45
+ context_removed: z.ZodBoolean;
46
+ }, z.core.$strict>>;
47
+ unsupported_vectors: z.ZodNumber;
48
+ }, z.core.$strict>>;
49
+ modified_at: z.ZodISODateTime;
50
+ fetched_at: z.ZodISODateTime;
51
+ published_at: z.ZodOptional<z.ZodISODateTime>;
52
+ content_status: z.ZodOptional<z.ZodEnum<{
53
+ excerpt: "excerpt";
54
+ full: "full";
55
+ unavailable: "unavailable";
56
+ }>>;
57
+ packages: z.ZodArray<z.ZodObject<{
58
+ ecosystem: z.ZodString;
59
+ name: z.ZodString;
60
+ range: z.ZodOptional<z.ZodString>;
61
+ versions: z.ZodOptional<z.ZodArray<z.ZodString>>;
62
+ matched_versions: z.ZodOptional<z.ZodArray<z.ZodString>>;
63
+ fixed: z.ZodOptional<z.ZodString>;
64
+ }, z.core.$strict>>;
65
+ withdrawn: z.ZodOptional<z.ZodBoolean>;
66
+ exploited: z.ZodOptional<z.ZodBoolean>;
67
+ malware: z.ZodOptional<z.ZodBoolean>;
68
+ }, z.core.$strict>;
15
69
  export declare function readFixture(path: string): Evidence[];
16
70
  export declare function healthFinding(source: string, message: string, now?: number): Assessment;
17
71
  export declare function runScan(options: {
package/dist/engine.js CHANGED
@@ -1,13 +1,15 @@
1
1
  import { readFileSync, statSync } from 'node:fs';
2
2
  import { z } from 'zod';
3
+ import { cvssV4BaseScore } from './cvss4.js';
3
4
  import { assess, decide } from './assessment.js';
4
5
  import { collectSources } from './sources.js';
6
+ import { attachLocation, attachRemediation, compareInventories } from './inventory-evidence.js';
5
7
  import { ModelAnalyzer, PROMPT_VERSION } from './models.js';
6
8
  import { Store } from './store.js';
7
9
  import { safeHttp } from './http.js';
8
10
  import { missingCredentials } from './config.js';
9
- import { hash, severityRank, timestamp } from './util.js';
10
- const evidenceSchema = z
11
+ import { canonicalHash, hash, severityRank, timestamp } from './util.js';
12
+ export const evidenceSchema = z
11
13
  .object({
12
14
  id: z.string().min(1),
13
15
  source: z.string().min(1),
@@ -17,6 +19,27 @@ const evidenceSchema = z
17
19
  description: z.string(),
18
20
  aliases: z.array(z.string()),
19
21
  severity: z.enum(['unknown', 'low', 'medium', 'high', 'critical']),
22
+ cvss_v4: z
23
+ .strictObject({
24
+ base_scores: z
25
+ .array(z
26
+ .strictObject({
27
+ vector: z.string().max(1024),
28
+ base_vector: z.string().max(1024),
29
+ score: z.number().min(0).max(10),
30
+ context_removed: z.boolean(),
31
+ })
32
+ .refine((item) => {
33
+ const actual = cvssV4BaseScore(item.vector);
34
+ return (actual?.score === item.score &&
35
+ actual.base_vector === item.base_vector &&
36
+ actual.context_removed === item.context_removed);
37
+ }, 'Invalid CVSS v4 base projection'))
38
+ .max(32),
39
+ unsupported_vectors: z.number().int().min(0).max(32),
40
+ })
41
+ .refine((value) => value.base_scores.length + value.unsupported_vectors <= 32, 'CVSS v4 candidate limit exceeded')
42
+ .optional(),
20
43
  modified_at: z.iso.datetime(),
21
44
  fetched_at: z.iso.datetime(),
22
45
  published_at: z.iso.datetime().optional(),
@@ -83,6 +106,24 @@ function generalNews(assessment) {
83
106
  assessment.news_analysis?.classification === 'general_news' &&
84
107
  assessment.news_analysis.impact === 'not_applicable');
85
108
  }
109
+ // An exclusion rests on the version ranges of its own advisory records. While they were read
110
+ // within the last two poll intervals it holds, whatever else a source missed; after that the
111
+ // assessment treats them as stale evidence and the finding becomes `unknown` (assessment.ts).
112
+ /** When stored evidence was last collected: the start of the last scan, or its newest fetch time. */
113
+ function lastCollection(store, cached) {
114
+ try {
115
+ const started = Date.parse(JSON.parse(store.getMeta('last_scan') ?? '{}').started_at ?? '');
116
+ if (Number.isFinite(started))
117
+ return started;
118
+ }
119
+ catch {
120
+ /* An unreadable record falls back to the evidence itself. */
121
+ }
122
+ return cached.reduce((latest, item) => {
123
+ const fetched = Date.parse(item.fetched_at);
124
+ return Number.isFinite(fetched) && fetched > latest ? fetched : latest;
125
+ }, 0);
126
+ }
86
127
  export async function runScan(options) {
87
128
  const { config, inventory, store, signal } = options;
88
129
  checkCancellation(signal);
@@ -92,12 +133,27 @@ export async function runScan(options) {
92
133
  checkCancellation(signal);
93
134
  return transport(url, { ...request, ...(signal ? { signal } : {}) });
94
135
  };
136
+ const priorInventory = store.getMeta('inventory:baseline');
137
+ const drift = compareInventories(priorInventory ? JSON.parse(priorInventory) : undefined, inventory);
95
138
  const previousById = new Map(store.findings().map((a) => [a.id, a]));
139
+ // Events of findings still reported keep their identifier when a record gains an alias.
140
+ const knownEvents = new Set([...previousById.values()]
141
+ .filter((finding) => finding.active !== false && finding.category !== 'health')
142
+ .map((finding) => finding.event_id));
143
+ const knownFindings = new Set([...previousById.values()].filter((finding) => finding.active !== false).map((finding) => finding.id));
96
144
  const decisions = {};
145
+ let remediationEvidence = store.evidence();
97
146
  const persist = (assessment) => {
147
+ assessment = attachLocation(attachRemediation(assessment, inventory, remediationEvidence, config, now), inventory);
98
148
  const decision = decide(assessment, config);
99
149
  decisions[assessment.id] = decision;
100
- store.saveAssessment(assessment, decision, now, config.digest_interval_hours * 3_600_000);
150
+ store.saveAssessment(assessment, decision, now, config.digest_interval_hours * 3_600_000, decision.review
151
+ ? canonicalHash({
152
+ system: reviewSystemHashes.get(assessment.system_id),
153
+ models: config.models,
154
+ policy: config.policy.ai_dismissals ?? config.policy.review_before_news_suppression ?? 'review',
155
+ })
156
+ : undefined);
101
157
  };
102
158
  const retire = (assessment) => {
103
159
  store.saveAssessment({
@@ -114,11 +170,19 @@ export async function runScan(options) {
114
170
  reason: 'No current inventory/evidence match or monitoring issue recovered',
115
171
  }, now);
116
172
  };
117
- const systemHashes = new Map(inventory.systems.map((system) => {
118
- const { updated_at: _updated, ...context } = system;
119
- return [system.id, hash(context)];
120
- }));
121
- const basis = (finding, evidenceById) => {
173
+ // Notes and the owner say where to look. They are shown in notifications and never reach a model,
174
+ // so they are left out of everything that decides analysis reuse, reviews, revisions or alerts.
175
+ const context = (system) => {
176
+ const { updated_at: _updated, note: _note, owner: _owner, ...rest } = system;
177
+ return {
178
+ ...rest,
179
+ components: system.components.map(({ note: _componentNote, ...component }) => component),
180
+ products: system.products.map(({ note: _productNote, ...product }) => product),
181
+ };
182
+ };
183
+ const systemHashes = new Map(inventory.systems.map((system) => [system.id, hash(context(system))]));
184
+ const reviewSystemHashes = new Map(inventory.systems.map((system) => [system.id, canonicalHash(context(system))]));
185
+ const basis = (finding, evidenceById, evidenceAsOf = now) => {
122
186
  const { updated_at: _updated, ...assessment } = finding;
123
187
  return hash({
124
188
  assessment,
@@ -140,7 +204,7 @@ export async function runScan(options) {
140
204
  fresh: generalNews(previousById.get(finding.id)) ||
141
205
  (Number.isFinite(fetched) &&
142
206
  fetched <= now + 300_000 &&
143
- now - fetched <= Math.max(120_000, config.poll_interval_minutes * 120_000)),
207
+ evidenceAsOf - fetched <= Math.max(120_000, config.poll_interval_minutes * 120_000)),
144
208
  };
145
209
  }),
146
210
  });
@@ -168,25 +232,34 @@ export async function runScan(options) {
168
232
  if (!options.fixture && previousById.size) {
169
233
  // Apply known inventory changes before yielding to network I/O. The worker can deliver concurrently.
170
234
  const cachedById = new Map(cached.map((e) => [e.id, e]));
171
- const current = assess(inventory, cached, config, now);
235
+ // This pass applies inventory changes to evidence that is about to be refreshed. Judge the age
236
+ // of that evidence as of the last collection: time that passed while the monitor was stopped
237
+ // must not turn an exclusion into an urgent "unknown" that the refresh then takes back.
238
+ const collectedAt = Math.min(now, lastCollection(store, cached));
239
+ const current = assess(inventory, cached, config, now, collectedAt, knownEvents, knownFindings);
172
240
  const ids = new Set(current.map((a) => a.id));
173
241
  for (const finding of current)
174
242
  if (previousById.has(finding.id))
175
- persist(interim(finding, basis(finding, cachedById)));
243
+ persist(interim(finding, basis(finding, cachedById, collectedAt)));
176
244
  for (const previous of previousById.values())
177
245
  if (previous.category !== 'health' && previous.active !== false && !ids.has(previous.id))
178
246
  retire(previous);
179
247
  }
180
248
  const result = options.fixture
181
- ? { evidence: options.fixture, errors: [], checkpoints: {} }
182
- : await collectSources(inventory, config, store.checkpoints(), http, now, cached);
249
+ ? { evidence: options.fixture, errors: [], checkpoints: {}, coverage: [] }
250
+ : await collectSources(inventory, config, store.checkpoints(), http, now, cached, JSON.parse(store.getMeta('source:coverage') ?? '[]'));
183
251
  checkCancellation(signal);
184
252
  store.saveEvidence(result.evidence, result.checkpoints);
185
253
  const evidence = store.evidence();
254
+ remediationEvidence = evidence;
186
255
  const evidenceById = new Map(evidence.map((e) => [e.id, e]));
187
- const findings = assess(inventory, evidence, config, now);
256
+ const findings = assess(inventory, evidence, config, now, now, knownEvents, knownFindings);
188
257
  const bases = new Map(findings.map((a) => [a.id, basis(a, evidenceById)]));
189
- const errors = [...result.errors];
258
+ const errors = [
259
+ ...result.errors,
260
+ ...(inventory.import_warnings ?? []).map((message) => ({ source: 'inventory:sbom', message })),
261
+ ];
262
+ const notices = [...(inventory.name_notices ?? [])];
190
263
  if (!options.fixture && missingCredentials(config).length)
191
264
  errors.push({
192
265
  source: 'credentials',
@@ -203,15 +276,14 @@ export async function runScan(options) {
203
276
  !config.sources.github &&
204
277
  !config.sources.kev &&
205
278
  !config.sources.feeds.length &&
279
+ !config.sources.vendor_feeds?.length &&
206
280
  !options.fixture)
207
281
  errors.push({ source: 'sources', message: 'All sources are disabled.' });
208
282
  if (!options.fixture &&
209
- (config.sources.hacker_news || config.sources.feeds.length) &&
283
+ (config.sources.hacker_news || config.sources.feeds.length || config.sources.vendor_feeds?.length) &&
210
284
  !config.models.enabled)
211
- errors.push({
212
- source: 'models',
213
- message: 'AI is disabled. System news receives candidate matching only; enable an analysis model to distinguish vulnerability impact from general system coverage.',
214
- });
285
+ // Running without a model is a supported setup, not a fault: say what it means and carry on.
286
+ notices.push('AI is disabled. System news receives candidate matching only; enable an analysis model to distinguish vulnerability impact from general system coverage.');
215
287
  for (const system of inventory.systems) {
216
288
  const updated = Date.parse(system.updated_at);
217
289
  if (!Number.isFinite(updated) ||
@@ -273,6 +345,7 @@ export async function runScan(options) {
273
345
  if (!errors.some((e) => e.source === 'models' && e.message === code))
274
346
  errors.push({ source: 'models', message: code });
275
347
  }
348
+ enriched = attachRemediation(enriched, inventory, evidence, config, now);
276
349
  analyzed.push(enriched);
277
350
  persist(enriched);
278
351
  store.setMeta(`assessment-basis:${finding.id}`, bases.get(finding.id));
@@ -293,8 +366,14 @@ export async function runScan(options) {
293
366
  decisions,
294
367
  degraded: errors.length > 0,
295
368
  errors,
369
+ notices,
296
370
  evidence_count: evidence.length,
371
+ coverage: result.coverage,
372
+ inventory_drift: drift,
297
373
  };
374
+ store.setMeta('inventory:baseline', JSON.stringify(inventory));
375
+ store.setMeta('inventory:last_drift', JSON.stringify(drift));
376
+ store.setMeta('source:coverage', JSON.stringify(result.coverage));
298
377
  store.setMeta('last_scan', JSON.stringify({
299
378
  at: report.completed_at,
300
379
  started_at: report.at,
@@ -302,6 +381,8 @@ export async function runScan(options) {
302
381
  degraded: report.degraded,
303
382
  errors: report.errors,
304
383
  findings: report.findings.length,
384
+ coverage: report.coverage,
385
+ inventory_drift: report.inventory_drift,
305
386
  }));
306
387
  return report;
307
388
  }
@@ -0,0 +1,11 @@
1
+ /** Whether a name is one of the commonest words of security prose ("send", "buffer", "next"). */
2
+ export declare function everydayWord(name: string): boolean;
3
+ /** Whether a dictionary word is also the name of a well-known library, written with a capital. */
4
+ export declare function properName(name: string): boolean;
5
+ /**
6
+ * Whether a package name reads as ordinary English: one word ("entities", "scheduler", "immediate")
7
+ * or a compound that prose writes with a hyphen ("side-channel", "one-time", "stack-trace"). Prose uses such a name in its
8
+ * ordinary sense far more often than it names the package, so a mention of it needs more than the
9
+ * word itself. A name that is not English ("axios", "lodash", "webpack") does not.
10
+ */
11
+ export declare function dictionaryName(name: string): boolean;