@shieldaai/security-watch 0.1.0-alpha.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +178 -0
  2. package/CONTRIBUTING.md +4 -2
  3. package/README.md +173 -48
  4. package/SECURITY.md +24 -9
  5. package/dist/assessment.d.ts +12 -1
  6. package/dist/assessment.js +223 -52
  7. package/dist/cli.js +340 -27
  8. package/dist/config.d.ts +62 -2
  9. package/dist/config.js +88 -5
  10. package/dist/coverage.d.ts +4 -0
  11. package/dist/coverage.js +11 -0
  12. package/dist/cve-now.d.ts +32 -2
  13. package/dist/cve-now.js +715 -126
  14. package/dist/cvss4.d.ts +3 -0
  15. package/dist/cvss4.js +39 -0
  16. package/dist/delivery.d.ts +34 -2
  17. package/dist/delivery.js +391 -98
  18. package/dist/ecosystems.d.ts +23 -0
  19. package/dist/ecosystems.js +88 -10
  20. package/dist/engine.d.ts +55 -1
  21. package/dist/engine.js +101 -20
  22. package/dist/everyday-words.d.ts +11 -0
  23. package/dist/everyday-words.js +256 -0
  24. package/dist/health.d.ts +7 -0
  25. package/dist/health.js +55 -3
  26. package/dist/http.d.ts +7 -0
  27. package/dist/http.js +31 -2
  28. package/dist/index.d.ts +22 -4
  29. package/dist/index.js +12 -4
  30. package/dist/inventory-evidence.d.ts +10 -0
  31. package/dist/inventory-evidence.js +206 -0
  32. package/dist/inventory.d.ts +273 -0
  33. package/dist/inventory.js +210 -17
  34. package/dist/maintenance.d.ts +5 -0
  35. package/dist/maintenance.js +73 -5
  36. package/dist/matching.d.ts +29 -0
  37. package/dist/matching.js +537 -0
  38. package/dist/models.d.ts +17 -4
  39. package/dist/models.js +359 -29
  40. package/dist/pilot-cases.d.ts +171 -0
  41. package/dist/pilot-cases.js +330 -0
  42. package/dist/pilot-input.d.ts +16 -0
  43. package/dist/pilot-input.js +125 -0
  44. package/dist/pilot-recall.d.ts +166 -0
  45. package/dist/pilot-recall.js +231 -0
  46. package/dist/pilot-report.d.ts +113 -0
  47. package/dist/pilot-report.js +279 -0
  48. package/dist/pilot-responses.d.ts +111 -0
  49. package/dist/pilot-responses.js +159 -0
  50. package/dist/python-version.d.ts +3 -0
  51. package/dist/python-version.js +30 -0
  52. package/dist/rehearsal.d.ts +440 -0
  53. package/dist/rehearsal.js +372 -0
  54. package/dist/sbom.d.ts +13 -0
  55. package/dist/sbom.js +193 -0
  56. package/dist/source-error.d.ts +17 -1
  57. package/dist/source-error.js +18 -3
  58. package/dist/sources.d.ts +2 -2
  59. package/dist/sources.js +699 -45
  60. package/dist/store.d.ts +38 -13
  61. package/dist/store.js +325 -23
  62. package/dist/types.d.ts +159 -2
  63. package/dist/util.d.ts +23 -0
  64. package/dist/util.js +81 -1
  65. package/dist/vendor/cvss4-reference.d.ts +2 -0
  66. package/dist/vendor/cvss4-reference.js +789 -0
  67. package/dist/word-filter.d.ts +3 -0
  68. package/dist/word-filter.js +3291 -0
  69. package/docs/alert-outcome-evaluation.md +150 -0
  70. package/docs/compatibility.md +35 -0
  71. package/docs/configuration.md +289 -29
  72. package/docs/cvss-v4-support.md +41 -0
  73. package/docs/offline-advisory-preview.md +114 -0
  74. package/docs/offline-rehearsal.md +44 -0
  75. package/docs/pilot-cases.md +58 -0
  76. package/docs/pilot-recall.md +124 -0
  77. package/docs/pilot-report.md +52 -0
  78. package/docs/validation/alert-outcome-evaluation-2026-11-05.json +2935 -0
  79. package/docs/validation/cvss-v4-reference-parity-2026-11-05.json +93 -0
  80. package/docs/validation/rehearsal-accepted-2026-11-05.json +175 -0
  81. package/docs/validation/rehearsal-unknown-2026-11-05.json +175 -0
  82. package/docs/vendor/cvss-v4-LICENSE.txt +22 -0
  83. package/docs/vendor/cvss-v4-provenance.json +38 -0
  84. package/examples/agent-advisories-2026.json +145 -0
  85. package/examples/agent-advisory-cases-2026.json +397 -0
  86. package/examples/libraries.example.txt +4 -2
  87. package/examples/libraries.example.yaml +2 -0
  88. package/examples/offline-advisory-preview.mjs +42 -0
  89. package/examples/rehearsal.json +75 -0
  90. package/examples/systems.example.yaml +4 -0
  91. package/package.json +24 -7
  92. package/docs/quality-review.md +0 -104
@@ -0,0 +1,372 @@
1
+ import { createHmac, randomBytes } from 'node:crypto';
2
+ import { chmodSync, closeSync, constants, copyFileSync, fstatSync, mkdtempSync, openSync, readSync, rmSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { performance } from 'node:perf_hooks';
6
+ import { z } from 'zod';
7
+ import { parseConfig } from './config.js';
8
+ import { deliverPending } from './delivery.js';
9
+ import { evidenceSchema, runScan } from './engine.js';
10
+ import { inventorySnapshotSchema } from './inventory.js';
11
+ import { verifyBackup } from './maintenance.js';
12
+ import { Store } from './store.js';
13
+ import { canonicalHash } from './util.js';
14
+ const MAX_BYTES = 8 * 1024 * 1024;
15
+ const sinkSchema = z.enum(['disabled', 'accepted', 'failed', 'unknown']);
16
+ const rehearsalEvidence = evidenceSchema.refine((item) => item.id.length <= 500 &&
17
+ item.source.length <= 500 &&
18
+ item.title.length <= 500 &&
19
+ item.description.length <= 16_000 &&
20
+ item.url.length <= 2048 &&
21
+ item.aliases.length <= 100 &&
22
+ item.aliases.every((alias) => alias.length <= 500) &&
23
+ item.packages.length <= 500 &&
24
+ item.packages.every((claim) => claim.name.length <= 500 &&
25
+ claim.ecosystem.length <= 100 &&
26
+ (claim.range?.length ?? 0) <= 2000 &&
27
+ (claim.fixed?.length ?? 0) <= 2000 &&
28
+ [claim.versions, claim.matched_versions].every((values) => !values || (values.length <= 1000 && values.every((value) => value.length <= 500)))), 'Evidence bounds exceeded');
29
+ const scenarioSchema = z
30
+ .strictObject({
31
+ version: z.literal(1),
32
+ frames: z
33
+ .array(z.strictObject({
34
+ at: z.iso.datetime({ offset: true }),
35
+ evidence: z.array(rehearsalEvidence).max(1000),
36
+ inventory: inventorySnapshotSchema.optional(),
37
+ }))
38
+ .min(1)
39
+ .max(12),
40
+ })
41
+ .refine(({ frames }) => frames.every((frame, index) => Date.parse(frame.at) >= 0 &&
42
+ (index === 0 || Date.parse(frame.at) > Date.parse(frames[index - 1].at))), 'Times must increase')
43
+ .refine(({ frames }) => Date.parse(frames.at(-1).at) - Date.parse(frames[0].at) <= 31 * 86_400_000, 'At most 31 scenario days')
44
+ .refine(({ frames }) => frames.reduce((count, frame) => count + frame.evidence.length, 0) <= 1000, 'At most 1000 supplied evidence records')
45
+ .refine(({ frames }) => frames.some((frame) => frame.evidence.length > 0), 'Evidence is required')
46
+ .refine(({ frames }) => {
47
+ const sources = new Map();
48
+ for (const frame of frames)
49
+ for (const item of frame.evidence) {
50
+ if (sources.has(item.id) && sources.get(item.id) !== item.source)
51
+ return false;
52
+ sources.set(item.id, item.source);
53
+ }
54
+ return true;
55
+ }, 'Ambiguous evidence identity');
56
+ /** Errors intentionally omit paths, parser diagnostics and source-controlled strings. */
57
+ export function readRehearsal(path) {
58
+ let descriptor;
59
+ try {
60
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
61
+ const stat = fstatSync(descriptor);
62
+ if (!stat.isFile() || stat.size > MAX_BYTES)
63
+ throw new Error();
64
+ const input = Buffer.alloc(MAX_BYTES + 1);
65
+ let bytes = 0;
66
+ while (bytes < input.length) {
67
+ const received = readSync(descriptor, input, bytes, input.length - bytes, null);
68
+ if (!received)
69
+ break;
70
+ bytes += received;
71
+ }
72
+ if (bytes > MAX_BYTES)
73
+ throw new Error();
74
+ return scenarioSchema.parse(JSON.parse(input.subarray(0, bytes).toString('utf8')));
75
+ }
76
+ catch {
77
+ throw new Error('Invalid rehearsal scenario; check the documented schema and bounds.');
78
+ }
79
+ finally {
80
+ if (descriptor !== undefined) {
81
+ try {
82
+ closeSync(descriptor);
83
+ }
84
+ catch {
85
+ throw new Error('Rehearsal input could not be closed.');
86
+ }
87
+ }
88
+ }
89
+ }
90
+ const decisions = () => ({ record: 0, digest: 0, notify: 0 });
91
+ const deliveryStates = () => ({ pending: 0, sending: 0, accepted: 0, failed: 0, unknown: 0 });
92
+ const age = (value, now) => {
93
+ const at = Date.parse(value);
94
+ return Number.isFinite(at) && at <= now ? now - at : null;
95
+ };
96
+ function projectFrame(store, input, ref, index, now, elapsed, degraded) {
97
+ const evidence = store.evidence();
98
+ const evidenceRef = (item) => {
99
+ const { fetched_at: _fetch, ...content } = item;
100
+ return ref('evidence', content);
101
+ };
102
+ const evidenceRefs = new Map(evidence.map((item) => [item.id, evidenceRef(item)]));
103
+ const allEvidence = new Map([...input, ...evidence].map((item) => [evidenceRef(item), item]));
104
+ const counts = decisions();
105
+ const states = deliveryStates();
106
+ const findings = store.findings().map((finding) => {
107
+ const history = store.history(finding.id).at(-1);
108
+ counts[history.decision.action]++;
109
+ return {
110
+ ref: ref('finding', finding.id),
111
+ revision: history.revision,
112
+ active: finding.active !== false,
113
+ category: finding.category,
114
+ applicability: finding.applicability,
115
+ source_severity: finding.source_severity,
116
+ priority: finding.priority,
117
+ evidence_refs: finding.evidence_ids
118
+ .map((id) => evidenceRefs.get(id))
119
+ .filter((id) => !!id),
120
+ decision: history.decision.action,
121
+ channels: history.decision.channels,
122
+ };
123
+ });
124
+ const deliveries = store.jobs().map((job) => {
125
+ states[job.status]++;
126
+ return {
127
+ ref: ref('delivery', job.id),
128
+ finding_ref: ref('finding', job.finding_id),
129
+ revision: job.revision,
130
+ channel: job.channel,
131
+ status: job.status,
132
+ attempts: job.attempts,
133
+ scheduled_in_ms: Math.max(0, job.available_at - now),
134
+ };
135
+ });
136
+ return {
137
+ index,
138
+ ingest: { kind: 'fixture', ref: ref('ingest', index), evidence_refs: input.map(evidenceRef) },
139
+ scan_ms: Math.max(0, Math.round(elapsed)),
140
+ degraded,
141
+ evidence: [...allEvidence.values()].map((item) => ({
142
+ ref: evidenceRef(item),
143
+ kind: item.kind,
144
+ retained: evidenceRefs.get(item.id) === evidenceRef(item),
145
+ fetched_age_ms: age(item.fetched_at, now),
146
+ modified_age_ms: age(item.modified_at, now),
147
+ })),
148
+ findings,
149
+ deliveries,
150
+ counters: {
151
+ findings: findings.length,
152
+ active_findings: findings.filter((item) => item.active).length,
153
+ decisions: counts,
154
+ delivery_states: states,
155
+ },
156
+ review_backlog: store.reviewSummary(now).pending + store.reviewSummary(now).investigate,
157
+ oldest_review_age_ms: store.reviewSummary(now).oldest_open_age_ms,
158
+ };
159
+ }
160
+ /** Offline rehearsal only: never opens the configured live database or resolves its credentials. */
161
+ export async function runRehearsal(options) {
162
+ let config, inventory, scenario, sink;
163
+ try {
164
+ // Bound direct JS callers as well as file input; schema validation rejects unknown model-like fields.
165
+ if (Buffer.byteLength(JSON.stringify(options), 'utf8') > MAX_BYTES)
166
+ throw new Error();
167
+ config = parseConfig(options.config);
168
+ inventory = inventorySnapshotSchema.parse(options.inventory);
169
+ scenario = scenarioSchema.parse(options.scenario);
170
+ sink = sinkSchema.parse(options.sink ?? 'disabled');
171
+ let current = inventory;
172
+ let work = 0;
173
+ const retained = new Map();
174
+ for (const frame of scenario.frames) {
175
+ current = frame.inventory ?? current;
176
+ const targets = current.systems.reduce((sum, system) => sum + system.components.length + system.products.length + 1, 0);
177
+ if (current.systems.length > 20 || targets > 500)
178
+ throw new Error();
179
+ for (const item of frame.evidence)
180
+ retained.set(item.id, Math.max(retained.get(item.id) ?? 0, 1 +
181
+ item.packages.reduce((sum, claim) => sum + 1 + (claim.versions?.length ?? 0) + (claim.matched_versions?.length ?? 0), 0)));
182
+ work += targets * [...retained.values()].reduce((sum, count) => sum + count, 0);
183
+ }
184
+ if (work > 100_000)
185
+ throw new Error();
186
+ }
187
+ catch {
188
+ throw new Error('Invalid rehearsal input; check the documented schema and bounds.');
189
+ }
190
+ // Clone validated objects before changing effective runtime settings. No source/provider path can run.
191
+ config.models.enabled = false;
192
+ config.sources = {
193
+ ...config.sources,
194
+ cve_now: false,
195
+ hacker_news: false,
196
+ osv: false,
197
+ github: false,
198
+ kev: false,
199
+ feeds: [],
200
+ vendor_feeds: [],
201
+ };
202
+ config.notifications = {
203
+ max_attempts: config.notifications.max_attempts,
204
+ slack: { webhook_url_env: 'REHEARSAL_SLACK' },
205
+ email: {
206
+ smtp_url_env: 'REHEARSAL_SMTP',
207
+ from: 'rehearsal@example.invalid',
208
+ to: ['sink@example.invalid'],
209
+ },
210
+ };
211
+ const credentials = Object.freeze({
212
+ REHEARSAL_SLACK: 'https://hooks.slack.com/services/REHEARSAL/LOCAL/SINK',
213
+ REHEARSAL_SMTP: 'smtps://rehearsal.invalid:465',
214
+ });
215
+ let sinkCalls = 0;
216
+ const http = async (url, request) => {
217
+ if (url !== credentials.REHEARSAL_SLACK || request?.method !== 'POST')
218
+ throw new Error('Unexpected rehearsal transport call');
219
+ sinkCalls++;
220
+ return {
221
+ status: sink === 'failed' ? 400 : 200,
222
+ headers: {},
223
+ body: sink === 'unknown' ? 'simulated ambiguous receipt' : 'ok',
224
+ };
225
+ };
226
+ const email = async (message) => {
227
+ if (message.url !== credentials.REHEARSAL_SMTP ||
228
+ message.to.length !== 1 ||
229
+ message.to[0] !== 'sink@example.invalid')
230
+ throw new Error('Unexpected rehearsal email call');
231
+ sinkCalls++;
232
+ if (sink === 'unknown')
233
+ throw new Error('Simulated ambiguous receipt');
234
+ return sink === 'failed'
235
+ ? { accepted: [], rejected: [...message.to] }
236
+ : { accepted: [...message.to], rejected: [] };
237
+ };
238
+ const key = randomBytes(32);
239
+ const ref = (domain, value) => createHmac('sha256', key)
240
+ .update(JSON.stringify([domain, value]))
241
+ .digest('hex');
242
+ let temporary;
243
+ try {
244
+ temporary = mkdtempSync(join(tmpdir(), 'security-watch-rehearsal-'));
245
+ }
246
+ catch {
247
+ key.fill(0);
248
+ throw new Error('Could not create private rehearsal state.');
249
+ }
250
+ const database = join(temporary, 'rehearsal.db');
251
+ let store;
252
+ try {
253
+ store = new Store(database);
254
+ const frames = [];
255
+ for (const [index, frame] of scenario.frames.entries()) {
256
+ inventory = frame.inventory ?? inventory;
257
+ const now = Date.parse(frame.at);
258
+ const started = performance.now();
259
+ const scan = await runScan({
260
+ config,
261
+ inventory,
262
+ store,
263
+ fixture: frame.evidence,
264
+ now,
265
+ http: async () => {
266
+ throw new Error('Rehearsal source access forbidden');
267
+ },
268
+ });
269
+ const elapsed = performance.now() - started;
270
+ if (sink !== 'disabled')
271
+ await deliverPending(store, config, http, now, email, undefined, credentials);
272
+ if (store.findings().length > 2000 || store.jobs().length > 4000 || store.evidence().length > 1000)
273
+ throw new Error();
274
+ frames.push(projectFrame(store, frame.evidence, ref, index, now, elapsed, scan.degraded));
275
+ }
276
+ const lastTime = Date.parse(scenario.frames.at(-1).at);
277
+ const snapshot = (value) => canonicalHash({
278
+ evidence: value.evidence(),
279
+ findings: value.findings(),
280
+ jobs: value.jobs(),
281
+ budgets: value.budgets(),
282
+ histories: value.findings().map((item) => value.history(item.id)),
283
+ controls: value.findings().map((item) => value.controls(item.id, lastTime)),
284
+ reviews: value.reviews({ includeResolved: true, limit: 1000 }),
285
+ });
286
+ const before = snapshot(store);
287
+ store.close();
288
+ store = undefined;
289
+ store = new Store(database);
290
+ if (snapshot(store) !== before)
291
+ throw new Error();
292
+ const backup = join(temporary, 'backup.db');
293
+ await store.backup(backup);
294
+ const verified = await verifyBackup(backup, { max_bytes: 64 * 1024 * 1024 });
295
+ if (!verified.ok)
296
+ throw new Error();
297
+ store.close();
298
+ store = undefined;
299
+ const restored = join(temporary, 'restored.db');
300
+ copyFileSync(backup, restored, constants.COPYFILE_EXCL);
301
+ chmodSync(restored, 0o600);
302
+ store = new Store(restored);
303
+ store.recoverSending(lastTime);
304
+ if (snapshot(store) !== before)
305
+ throw new Error();
306
+ const beforeProbeCalls = sinkCalls;
307
+ const terminal = store.jobs().filter((job) => job.status !== 'pending');
308
+ if (sink !== 'disabled')
309
+ await deliverPending(store, config, http, lastTime, email, undefined, credentials);
310
+ const afterProbe = new Map(store.jobs().map((job) => [job.id, job]));
311
+ if (terminal.some((job) => canonicalHash(job) !== canonicalHash(afterProbe.get(job.id))))
312
+ throw new Error();
313
+ const report = {
314
+ version: 1,
315
+ mode: 'offline_rehearsal',
316
+ sink,
317
+ safety: {
318
+ models_disabled: true,
319
+ sources_disabled: true,
320
+ network_requests: 0,
321
+ external_deliveries: 0,
322
+ live_database_opened: false,
323
+ credentials_loaded: false,
324
+ },
325
+ frames,
326
+ summary: { ...frames.at(-1).counters, sink_calls: beforeProbeCalls, model_requests: 0, model_usd: 0 },
327
+ recovery: {
328
+ reopened: true,
329
+ backup_verified: true,
330
+ restored: true,
331
+ receipts_preserved: true,
332
+ automatically_dispatched: 0,
333
+ dispatcher_probe: sink === 'disabled' ? 'disabled' : 'passed',
334
+ terminal_receipts_not_retried: true,
335
+ probe_sink_calls: sinkCalls - beforeProbeCalls,
336
+ },
337
+ unmeasured: {
338
+ source_coverage: null,
339
+ ai_shadow: null,
340
+ urgent_recall: null,
341
+ false_alert_rate: null,
342
+ analyst_latency_ms: null,
343
+ },
344
+ };
345
+ if (Buffer.byteLength(JSON.stringify(report), 'utf8') > MAX_BYTES)
346
+ throw new Error();
347
+ return report;
348
+ }
349
+ catch {
350
+ throw new Error('Rehearsal failed; no external delivery was attempted.');
351
+ }
352
+ finally {
353
+ let cleanupFailed = false;
354
+ try {
355
+ store?.close();
356
+ }
357
+ catch {
358
+ cleanupFailed = true;
359
+ }
360
+ finally {
361
+ key.fill(0);
362
+ try {
363
+ rmSync(temporary, { recursive: true, force: true });
364
+ }
365
+ catch {
366
+ cleanupFailed = true;
367
+ }
368
+ }
369
+ if (cleanupFailed)
370
+ throw new Error('Rehearsal cleanup failed; inspect private temporary storage locally.');
371
+ }
372
+ }
package/dist/sbom.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Component, DependencyRelationship } from './types.js';
2
+ export interface SbomImport {
3
+ components: Component[];
4
+ warnings: string[];
5
+ dependencies: DependencyRelationship[];
6
+ source: {
7
+ format: 'CycloneDX';
8
+ spec_version: string;
9
+ digest: string;
10
+ };
11
+ }
12
+ /** Bounded local metadata import: never follows references, runs scripts or fetches packages. */
13
+ export declare function importCycloneDx(path: string): SbomImport;
package/dist/sbom.js ADDED
@@ -0,0 +1,193 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
3
+ import { exactLibraryVersion, normalizeEcosystem, normalizePackageName } from './ecosystems.js';
4
+ import { eq as samePythonVersion, valid as validPython } from '@renovatebot/pep440';
5
+ import { hash, LINE_BREAKING } from './util.js';
6
+ const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
7
+ const text = (value) => typeof value === 'string' && value.length > 0 && value.length <= 1000 && !LINE_BREAKING.test(value);
8
+ /** Bounded local metadata import: never follows references, runs scripts or fetches packages. */
9
+ export function importCycloneDx(path) {
10
+ const stat = statSync(path);
11
+ if (!stat.isFile() || stat.size > 20 * 1024 * 1024)
12
+ throw new Error('SBOM must be a regular JSON file of at most 20 MiB');
13
+ const bytes = readFileSync(path);
14
+ if (bytes.byteLength > 20 * 1024 * 1024)
15
+ throw new Error('SBOM exceeds 20 MiB');
16
+ const bom = JSON.parse(bytes.toString('utf8'));
17
+ if (!object(bom) ||
18
+ bom.bomFormat !== 'CycloneDX' ||
19
+ !['1.4', '1.5', '1.6'].includes(String(bom.specVersion)) ||
20
+ !Array.isArray(bom.components))
21
+ throw new Error('Expected CycloneDX JSON 1.4, 1.5 or 1.6 with components');
22
+ const digest = `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
23
+ const result = {
24
+ components: [],
25
+ warnings: [],
26
+ dependencies: [],
27
+ source: { format: 'CycloneDX', spec_version: String(bom.specVersion), digest },
28
+ };
29
+ const ids = new Set();
30
+ const componentIds = new Set();
31
+ const byReference = new Map();
32
+ const metadataRoot = object(bom.metadata) && object(bom.metadata.component) ? bom.metadata.component['bom-ref'] : undefined;
33
+ if (metadataRoot !== undefined && !text(metadataRoot))
34
+ throw new Error('Invalid SBOM metadata root reference');
35
+ let count = 0;
36
+ const visit = (entries, depth) => {
37
+ if (depth > 32)
38
+ throw new Error('SBOM component nesting exceeds 32');
39
+ for (const entry of entries) {
40
+ if (++count > 20_000)
41
+ throw new Error('SBOM exceeds 20000 component entries');
42
+ if (!object(entry))
43
+ throw new Error('Invalid SBOM component');
44
+ if (entry.components !== undefined) {
45
+ if (!Array.isArray(entry.components))
46
+ throw new Error('Invalid nested SBOM components');
47
+ visit(entry.components, depth + 1);
48
+ }
49
+ const ref = entry['bom-ref'];
50
+ if (ref !== undefined && !text(ref))
51
+ throw new Error('Invalid SBOM component reference');
52
+ if (ref !== undefined) {
53
+ if (ids.has(ref))
54
+ throw new Error('Duplicate SBOM component reference');
55
+ ids.add(ref);
56
+ }
57
+ if (!text(entry.purl)) {
58
+ result.warnings.push(`Component ${count}: missing package URL; not imported.`);
59
+ continue;
60
+ }
61
+ // The package type is case-insensitive in the purl specification; tools write `pkg:NPM/…` too.
62
+ const match = /^pkg:([A-Za-z][A-Za-z0-9.+-]*)\/([^?#]+)(?:\?[^#]*)?(?:#.*)?$/.exec(entry.purl);
63
+ if (!match) {
64
+ // One component this application cannot read must not block the rest of the document.
65
+ result.warnings.push(`Component ${count}: package URL is not valid; not imported.`);
66
+ continue;
67
+ }
68
+ let ecosystem;
69
+ try {
70
+ ecosystem = normalizeEcosystem(match[1].toLowerCase());
71
+ }
72
+ catch {
73
+ result.warnings.push(`Component ${count}: unsupported package ecosystem ${match[1].slice(0, 40)}; not imported.`);
74
+ continue;
75
+ }
76
+ // purl versions are separated before percent decoding (npm scopes use %40). A leading @ is
77
+ // an unencoded npm scope, not a version separator.
78
+ const split = match[2].lastIndexOf('@');
79
+ // An empty version string means the generator did not know the version.
80
+ const declared = entry.version === '' || entry.version === null ? undefined : entry.version;
81
+ if (declared !== undefined && !text(declared)) {
82
+ result.warnings.push(`Component ${count}: version is not text; not imported.`);
83
+ continue;
84
+ }
85
+ // Go tools write the same version as v1.8.0 or 1.8.0; Python treats 1.0 and 1.0.0 as equal.
86
+ const sameVersion = (first, second) => {
87
+ if (ecosystem === 'Go')
88
+ return first.replace(/^v/, '') === second.replace(/^v/, '');
89
+ if (ecosystem === 'PyPI' && validPython(first) && validPython(second))
90
+ return samePythonVersion(first, second);
91
+ return first === second;
92
+ };
93
+ const rawName = split <= 0 ? match[2] : match[2].slice(0, split);
94
+ const rawVersion = split <= 0 ? undefined : match[2].slice(split + 1);
95
+ let name;
96
+ let version;
97
+ let purlVersion;
98
+ try {
99
+ name = decodeURIComponent(rawName);
100
+ purlVersion = rawVersion === undefined ? undefined : decodeURIComponent(rawVersion);
101
+ if (ecosystem === 'Maven')
102
+ name = name.replace(/\/(?!.*\/)/, ':');
103
+ name = normalizePackageName(ecosystem, name);
104
+ version = purlVersion ?? declared;
105
+ if (version !== undefined)
106
+ version = exactLibraryVersion(version, ecosystem);
107
+ }
108
+ catch (error) {
109
+ // One component this application cannot read must not block the rest of the document.
110
+ result.warnings.push(`Component ${count}: ${error instanceof Error ? error.message.slice(0, 160) : 'unsupported package identity'}; not imported.`);
111
+ continue;
112
+ }
113
+ // Two different versions for one component is a contradiction in the document itself.
114
+ if (purlVersion && declared !== undefined && !sameVersion(purlVersion, declared))
115
+ throw new Error('Conflicting SBOM package versions');
116
+ const component = {
117
+ id: `sbom:${hash(ref ?? entry.purl).slice(0, 32)}`,
118
+ ecosystem,
119
+ name,
120
+ purl: entry.purl,
121
+ ...(typeof ref === 'string' ? { sbom_ref: ref } : {}),
122
+ ...(['application', 'library', 'container'].includes(String(entry.type))
123
+ ? { artifact_kind: entry.type }
124
+ : entry.type === 'machine-learning-model'
125
+ ? { artifact_kind: 'model' }
126
+ : {}),
127
+ ...(version === undefined ? {} : { version }),
128
+ provenance: { source: 'CycloneDX', reference: digest },
129
+ };
130
+ if (entry.hashes !== undefined) {
131
+ if (!Array.isArray(entry.hashes) || entry.hashes.length > 32)
132
+ throw new Error('Invalid SBOM hashes');
133
+ const hashes = entry.hashes.filter((value) => object(value) && value.alg === 'SHA-256');
134
+ if (hashes.length) {
135
+ const values = hashes.map((value) => value.content);
136
+ if (values.some((value) => typeof value !== 'string' || !/^[a-fA-F0-9]{64}$/.test(value)) ||
137
+ new Set(values.map((value) => String(value).toLowerCase())).size !== 1)
138
+ throw new Error('Invalid or conflicting SBOM SHA-256 hashes');
139
+ component.digest = `sha256:${String(values[0]).toLowerCase()}`;
140
+ }
141
+ }
142
+ if (componentIds.has(component.id)) {
143
+ // The same package listed twice without a reference of its own (nested under two parents)
144
+ // is one component. A reference used twice is a contradiction in the document.
145
+ if (typeof ref !== 'string')
146
+ continue;
147
+ throw new Error('Duplicate SBOM component identity');
148
+ }
149
+ componentIds.add(component.id);
150
+ if (typeof ref === 'string')
151
+ byReference.set(ref, component);
152
+ result.components.push(component);
153
+ }
154
+ };
155
+ visit(bom.components, 0);
156
+ if (bom.dependencies !== undefined) {
157
+ if (!Array.isArray(bom.dependencies) || bom.dependencies.length > 20_000)
158
+ throw new Error('Invalid SBOM dependencies');
159
+ const sources = new Set();
160
+ let edges = 0;
161
+ for (const dependency of bom.dependencies) {
162
+ // The schema requires only `ref`; generators omit `dependsOn` for a component with no dependencies.
163
+ if (object(dependency) && dependency.dependsOn === undefined)
164
+ dependency.dependsOn = [];
165
+ if (!object(dependency) ||
166
+ !text(dependency.ref) ||
167
+ !Array.isArray(dependency.dependsOn) ||
168
+ dependency.dependsOn.length > 1000 ||
169
+ dependency.dependsOn.some((ref) => !text(ref)))
170
+ throw new Error('Invalid SBOM dependency references');
171
+ if (sources.has(dependency.ref) || new Set(dependency.dependsOn).size !== dependency.dependsOn.length)
172
+ throw new Error('Duplicate SBOM dependency reference');
173
+ sources.add(dependency.ref);
174
+ edges += dependency.dependsOn.length;
175
+ if (edges > 100_000)
176
+ throw new Error('SBOM exceeds 100000 dependency edges');
177
+ const targets = dependency.dependsOn;
178
+ result.dependencies.push({ ref: dependency.ref, depends_on: [...targets] });
179
+ const component = byReference.get(dependency.ref);
180
+ if (!component && dependency.ref !== metadataRoot)
181
+ result.warnings.push(`Dependency source ${dependency.ref}: not an imported package; relationship retained as unverified metadata.`);
182
+ if (component)
183
+ component.dependencies = targets.map((ref) => ({
184
+ ref,
185
+ ...(byReference.has(ref) ? { component_id: byReference.get(ref).id } : {}),
186
+ }));
187
+ for (const ref of targets)
188
+ if (!byReference.has(ref))
189
+ result.warnings.push(`Dependency target ${ref}: not an imported package; reference retained without resolved identity.`);
190
+ }
191
+ }
192
+ return result;
193
+ }
@@ -9,7 +9,21 @@ export declare class SourceHttpError extends SourceError {
9
9
  export declare function sourceCanceled(error: unknown): boolean;
10
10
  export declare class PartialSourceError extends SourceError {
11
11
  readonly evidence: Evidence[];
12
- constructor(message: string, evidence: Evidence[]);
12
+ /** How far an ordered collection got. The source continues from here on its next run. */
13
+ readonly resume?: string | undefined;
14
+ /**
15
+ * Set when everything the source knows about the inventory's own packages was read, and only
16
+ * other records are missing. Version exclusions drawn from the source then still hold.
17
+ */
18
+ readonly packageResults?: 'complete' | undefined;
19
+ constructor(message: string, evidence: Evidence[],
20
+ /** How far an ordered collection got. The source continues from here on its next run. */
21
+ resume?: string | undefined,
22
+ /**
23
+ * Set when everything the source knows about the inventory's own packages was read, and only
24
+ * other records are missing. Version exclusions drawn from the source then still hold.
25
+ */
26
+ packageResults?: 'complete' | undefined);
13
27
  }
14
28
  export declare function throwSourceFailure(error: unknown, evidence: Evidence[]): never;
15
29
  /** Isolate malformed records without accepting a partially validated record. */
@@ -17,6 +31,8 @@ export declare class SourceItemFailures {
17
31
  private count;
18
32
  private first;
19
33
  read<T>(parse: () => T): T | undefined;
34
+ /** What was skipped, for a source that decides for itself how far its checkpoint moves. */
35
+ summary(source: string): string | undefined;
20
36
  message(source: string): string | undefined;
21
37
  finish(source: string, evidence: Evidence[]): Evidence[];
22
38
  }
@@ -15,9 +15,20 @@ export function sourceCanceled(error) {
15
15
  }
16
16
  export class PartialSourceError extends SourceError {
17
17
  evidence;
18
- constructor(message, evidence) {
18
+ resume;
19
+ packageResults;
20
+ constructor(message, evidence,
21
+ /** How far an ordered collection got. The source continues from here on its next run. */
22
+ resume,
23
+ /**
24
+ * Set when everything the source knows about the inventory's own packages was read, and only
25
+ * other records are missing. Version exclusions drawn from the source then still hold.
26
+ */
27
+ packageResults) {
19
28
  super(message);
20
29
  this.evidence = evidence;
30
+ this.resume = resume;
31
+ this.packageResults = packageResults;
21
32
  }
22
33
  }
23
34
  export function throwSourceFailure(error, evidence) {
@@ -42,11 +53,15 @@ export class SourceItemFailures {
42
53
  return undefined;
43
54
  }
44
55
  }
45
- message(source) {
56
+ /** What was skipped, for a source that decides for itself how far its checkpoint moves. */
57
+ summary(source) {
46
58
  return this.count
47
- ? `${source}: ${this.count} invalid item(s) were skipped. ${this.first} Collection remains incomplete and its checkpoint was not advanced.`
59
+ ? `${source}: ${this.count} invalid item(s) were skipped. ${this.first} Collection remains incomplete.`
48
60
  : undefined;
49
61
  }
62
+ message(source) {
63
+ return this.summary(source)?.replace(/\.$/, ' and its checkpoint was not advanced.');
64
+ }
50
65
  finish(source, evidence) {
51
66
  const message = this.message(source);
52
67
  if (message)
package/dist/sources.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import type { Config, Evidence, HttpClient, Inventory, SourceResult } from './types.js';
1
+ import type { Config, CoverageReceipt, Evidence, HttpClient, Inventory, SourceResult } from './types.js';
2
2
  /** Collect source evidence and report failures without advancing failed sources' checkpoints. */
3
- export declare function collectSources(inventory: Inventory, config: Config, checkpoints: Record<string, string>, http: HttpClient, now?: number, previousEvidence?: Evidence[]): Promise<SourceResult>;
3
+ export declare function collectSources(inventory: Inventory, config: Config, checkpoints: Record<string, string>, http: HttpClient, now?: number, previousEvidence?: Evidence[], previousCoverage?: CoverageReceipt[]): Promise<SourceResult>;