@shieldaai/security-watch 1.0.1 → 1.1.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.
package/dist/intake.js ADDED
@@ -0,0 +1,341 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import { mkdtempSync, readdirSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { createServer as createHttpServer, } from 'node:http';
4
+ import { createServer as createHttpsServer } from 'node:https';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { parse } from 'yaml';
7
+ import { systemFromSbom } from './inventory.js';
8
+ import { singleLine } from './util.js';
9
+ /**
10
+ * Receives SBOMs from CI pipelines and writes them into the inventory's SBOM folder, where the next
11
+ * scan picks them up. Every upload needs a bearer token; each token may be limited to some system
12
+ * IDs. An upload is checked exactly as the scanner will read it, and is written only if it imports,
13
+ * so a pipeline learns at once that its SBOM is unusable instead of a week later from a stale warning.
14
+ */
15
+ export const INTAKE_MAX_BYTES = 20 * 1024 * 1024;
16
+ const SYSTEM_ID = /^[a-z0-9][a-z0-9._-]{0,99}$/;
17
+ const SBOM_SUFFIX = /(?:\.(?:cdx|spdx|bom|sbom|cyclonedx))?\.json$/i;
18
+ const MIN_TOKEN_LENGTH = 32;
19
+ const MAX_ACTIVE_UPLOADS = 4;
20
+ const FAILURE_WINDOW_MS = 60_000;
21
+ const MAX_FAILURES = 20;
22
+ const digest = (value) => createHash('sha256').update(value).digest();
23
+ /** Reads the configured tokens from the environment and refuses missing or short ones. */
24
+ function readTokens(config) {
25
+ const intake = config.intake;
26
+ if (!intake)
27
+ throw new Error('Configure intake in the configuration file to receive SBOMs.');
28
+ return intake.tokens.map(({ token_env, systems }) => {
29
+ const value = process.env[token_env];
30
+ if (!value)
31
+ throw new Error(`Missing environment variable ${token_env} (an intake upload token).`);
32
+ if (value.length < MIN_TOKEN_LENGTH || /\s/.test(value))
33
+ throw new Error(`${token_env} must be at least ${MIN_TOKEN_LENGTH} characters without spaces; create one with: openssl rand -hex 32`);
34
+ return { env: token_env, digest: digest(value), systems };
35
+ });
36
+ }
37
+ /** The SBOM folder named by the inventory, which is where uploads go. */
38
+ export function intakeDirectory(inventoryPath) {
39
+ const inventory = readInventoryDocument(inventoryPath);
40
+ const folder = inventory.sbom_directory;
41
+ if (typeof folder !== 'string' || !folder.trim())
42
+ throw new Error('The inventory has no sbom_directory. Add "sbom_directory: ./sboms" to it so that uploads have a place to go.');
43
+ const directory = resolve(dirname(resolve(inventoryPath)), folder.trim());
44
+ if (!statSync(directory).isDirectory())
45
+ throw new Error(`sbom_directory is not a folder: ${directory}`);
46
+ return directory;
47
+ }
48
+ function readInventoryDocument(path) {
49
+ if (statSync(path).size > 2 * 1024 * 1024)
50
+ throw new Error('Inventory exceeds 2 MiB');
51
+ const document = parse(readFileSync(path, 'utf8'), { maxAliasCount: 0 });
52
+ return document && typeof document === 'object' && !Array.isArray(document)
53
+ ? document
54
+ : {};
55
+ }
56
+ /** IDs of systems written in the inventory itself. An upload may not replace one of them. */
57
+ function listedSystems(path) {
58
+ const systems = readInventoryDocument(path).systems;
59
+ return new Set(Array.isArray(systems)
60
+ ? systems
61
+ .map((system) => system && typeof system === 'object' ? system.id : undefined)
62
+ .filter((id) => typeof id === 'string')
63
+ : []);
64
+ }
65
+ /**
66
+ * Another file in the folder that names the same system in its metadata. The scanner would read
67
+ * that one first and ignore the upload, so the upload is refused instead of silently unused.
68
+ */
69
+ function claimedElsewhere(directory, id) {
70
+ for (const name of readdirSync(directory).sort()) {
71
+ if (name.startsWith('.') || !SBOM_SUFFIX.test(name) || name.replace(SBOM_SUFFIX, '') === id)
72
+ continue;
73
+ try {
74
+ const path = join(directory, name);
75
+ if (!statSync(path).isFile() || statSync(path).size > INTAKE_MAX_BYTES)
76
+ continue;
77
+ const document = JSON.parse(readFileSync(path, 'utf8'));
78
+ const properties = document.metadata?.properties;
79
+ if (Array.isArray(properties) &&
80
+ properties.some((entry) => entry?.name === 'security-watch:system-id' && entry.value === id))
81
+ return name;
82
+ }
83
+ catch {
84
+ // An unreadable file is reported by the scanner; it claims no system.
85
+ }
86
+ }
87
+ return undefined;
88
+ }
89
+ const allowed = (token, id) => token.systems.some((pattern) => pattern === '*' ? true : pattern.endsWith('*') ? id.startsWith(pattern.slice(0, -1)) : pattern === id);
90
+ /** The request handler, separate from the listening socket so that it can be tested and embedded. */
91
+ export function createIntakeHandler(config, options = {}) {
92
+ const tokens = readTokens(config);
93
+ const directory = intakeDirectory(config.inventory);
94
+ const now = options.now ?? Date.now;
95
+ const log = options.log ?? (() => { });
96
+ const failures = new Map();
97
+ let active = 0;
98
+ const send = (response, status, body, headers = {}) => {
99
+ if (response.headersSent)
100
+ return;
101
+ response.writeHead(status, {
102
+ 'content-type': 'application/json; charset=utf-8',
103
+ 'cache-control': 'no-store',
104
+ 'x-content-type-options': 'nosniff',
105
+ ...headers,
106
+ });
107
+ response.end(JSON.stringify(body) + '\n');
108
+ };
109
+ const record = (event) => log(JSON.stringify({ intake: event }));
110
+ const authenticate = (request) => {
111
+ const header = request.headers.authorization;
112
+ const match = typeof header === 'string' ? /^Bearer ([^\s]+)$/i.exec(header) : null;
113
+ if (!match)
114
+ return undefined;
115
+ const presented = digest(match[1]);
116
+ // Compare against every token so the time taken does not say which one nearly matched.
117
+ let found;
118
+ for (const token of tokens)
119
+ if (timingSafeEqual(presented, token.digest))
120
+ found ??= token;
121
+ return found;
122
+ };
123
+ const receive = async (request, response, id, token) => {
124
+ const declared = Number(request.headers['content-length']);
125
+ if (Number.isFinite(declared) && declared > INTAKE_MAX_BYTES) {
126
+ send(response, 413, { error: 'An SBOM may be at most 20 MiB.' }, { connection: 'close' });
127
+ request.destroy();
128
+ return;
129
+ }
130
+ const chunks = [];
131
+ let size = 0;
132
+ for await (const chunk of request) {
133
+ size += chunk.length;
134
+ if (size > INTAKE_MAX_BYTES) {
135
+ send(response, 413, { error: 'An SBOM may be at most 20 MiB.' }, { connection: 'close' });
136
+ request.destroy();
137
+ return;
138
+ }
139
+ chunks.push(chunk);
140
+ }
141
+ if (!size) {
142
+ send(response, 400, { error: 'The request body is empty; send the SBOM JSON.' });
143
+ return;
144
+ }
145
+ // Stage inside the folder: the final rename is then atomic, and the scanner skips dot-folders.
146
+ const staging = mkdtempSync(join(directory, '.intake-'));
147
+ try {
148
+ const staged = join(staging, 'upload.json');
149
+ writeFileSync(staged, Buffer.concat(chunks), { flag: 'wx', mode: 0o640 });
150
+ const file = `${id}.json`;
151
+ let loaded;
152
+ try {
153
+ loaded = systemFromSbom(staged, file, 'this SBOM');
154
+ }
155
+ catch (error) {
156
+ send(response, 422, {
157
+ error: `Not a usable SBOM: ${singleLine(error instanceof Error ? error.message : 'unreadable', 300)}`,
158
+ });
159
+ record({ system_id: id, refused: 'invalid SBOM', token_env: token.env });
160
+ return;
161
+ }
162
+ if (loaded.system.id !== id) {
163
+ send(response, 409, {
164
+ error: `The SBOM is for system ${singleLine(loaded.system.id, 100)}, not ${id}. Upload it to /v1/sboms/${encodeURIComponent(loaded.system.id)} or change --system-id.`,
165
+ });
166
+ return;
167
+ }
168
+ const claimant = claimedElsewhere(directory, id);
169
+ if (claimant) {
170
+ send(response, 409, {
171
+ error: `${claimant} in the SBOM folder already describes system ${id}; remove it on the monitor, or upload under its file name.`,
172
+ });
173
+ return;
174
+ }
175
+ if (listedSystems(config.inventory).has(id)) {
176
+ send(response, 409, {
177
+ error: `System ${id} is written in the inventory file; uploads cannot replace it. Choose another system ID.`,
178
+ });
179
+ return;
180
+ }
181
+ const components = loaded.system.components.length;
182
+ if (!components) {
183
+ send(response, 422, {
184
+ error: 'The SBOM has no package Security Watch can watch.',
185
+ warning_examples: [...loaded.notices, ...loaded.warnings].slice(0, 5),
186
+ });
187
+ return;
188
+ }
189
+ const format = loaded.system.provenance?.source === 'SPDX SBOM' ? 'SPDX' : 'CycloneDX';
190
+ const target = `${id}${format === 'SPDX' ? '.spdx.json' : '.cdx.json'}`;
191
+ renameSync(staged, join(directory, target));
192
+ // One system, one file: an earlier upload in the other format would otherwise be read twice.
193
+ for (const name of readdirSync(directory))
194
+ if (name !== target &&
195
+ !name.startsWith('.') &&
196
+ name.replace(SBOM_SUFFIX, '') === id &&
197
+ SBOM_SUFFIX.test(name))
198
+ unlinkSync(join(directory, name));
199
+ const messages = [...loaded.notices, ...loaded.warnings].map((message) => singleLine(message.startsWith(`${id}: `) ? message.slice(id.length + 2) : message, 300));
200
+ const result = {
201
+ system_id: id,
202
+ file: target,
203
+ format,
204
+ packages: components,
205
+ warnings: messages.length,
206
+ warning_examples: messages.slice(0, 5),
207
+ };
208
+ send(response, 200, result);
209
+ record({
210
+ system_id: id,
211
+ file: target,
212
+ packages: result.packages,
213
+ warnings: result.warnings,
214
+ token_env: token.env,
215
+ at: new Date(now()).toISOString(),
216
+ });
217
+ }
218
+ finally {
219
+ rmSync(staging, { recursive: true, force: true });
220
+ }
221
+ };
222
+ return (request, response) => {
223
+ void (async () => {
224
+ const remote = request.socket.remoteAddress ?? 'unknown';
225
+ let url;
226
+ try {
227
+ url = new URL(request.url ?? '/', 'http://intake.invalid');
228
+ }
229
+ catch {
230
+ send(response, 400, { error: 'Invalid request target' });
231
+ return;
232
+ }
233
+ if (url.pathname === '/healthz') {
234
+ if (request.method !== 'GET' && request.method !== 'HEAD')
235
+ send(response, 405, { error: 'Use GET' }, { allow: 'GET, HEAD' });
236
+ else
237
+ send(response, 200, { ok: true });
238
+ return;
239
+ }
240
+ const route = /^\/v1\/sboms\/([^/]+)$/.exec(url.pathname);
241
+ if (!route) {
242
+ send(response, 404, { error: 'Not found. Upload with PUT /v1/sboms/SYSTEM_ID.' });
243
+ return;
244
+ }
245
+ if (request.method !== 'PUT' && request.method !== 'POST') {
246
+ send(response, 405, { error: 'Use PUT' }, { allow: 'PUT, POST' });
247
+ return;
248
+ }
249
+ // A valid token is always served, so that someone sending bad tokens through the same proxy
250
+ // cannot lock a pipeline out. Bad tokens beyond the limit get a cheaper, unlogged refusal.
251
+ const token = authenticate(request);
252
+ if (!token) {
253
+ const recent = failures.get(remote);
254
+ const entry = recent && now() - recent.since < FAILURE_WINDOW_MS ? recent : { count: 0, since: now() };
255
+ entry.count++;
256
+ failures.set(remote, entry);
257
+ if (failures.size > 10_000)
258
+ failures.clear();
259
+ if (entry.count > MAX_FAILURES) {
260
+ send(response, 429, { error: 'Too many failed attempts; wait a minute.' }, { 'retry-after': '60' });
261
+ return;
262
+ }
263
+ send(response, 401, { error: 'A valid bearer token is required.' }, { 'www-authenticate': 'Bearer' });
264
+ record({ refused: 'unauthenticated', remote });
265
+ return;
266
+ }
267
+ let id;
268
+ try {
269
+ id = decodeURIComponent(route[1]);
270
+ }
271
+ catch {
272
+ id = '';
273
+ }
274
+ if (!SYSTEM_ID.test(id)) {
275
+ send(response, 400, {
276
+ error: 'A system ID is 1 to 100 lower-case letters, digits, dots, hyphens or underscores, starting with a letter or digit.',
277
+ });
278
+ return;
279
+ }
280
+ if (!allowed(token, id)) {
281
+ send(response, 403, { error: `This token may not upload system ${id}.` });
282
+ record({ system_id: id, refused: 'not allowed for this token', token_env: token.env });
283
+ return;
284
+ }
285
+ if (active >= MAX_ACTIVE_UPLOADS) {
286
+ send(response, 503, { error: 'Busy; retry shortly.' }, { 'retry-after': '5' });
287
+ return;
288
+ }
289
+ active++;
290
+ try {
291
+ await receive(request, response, id, token);
292
+ }
293
+ finally {
294
+ active--;
295
+ }
296
+ })().catch((error) => {
297
+ record({ error: singleLine(error instanceof Error ? error.message : 'unknown error', 300) });
298
+ send(response, 500, {
299
+ error: 'The upload could not be stored; check disk space and permissions of the SBOM folder on the monitor.',
300
+ });
301
+ });
302
+ };
303
+ }
304
+ /** Starts listening. The returned promise settles once the socket is bound. */
305
+ export async function startIntake(config, options = {}) {
306
+ const intake = config.intake;
307
+ if (!intake)
308
+ throw new Error('Configure intake in the configuration file to receive SBOMs.');
309
+ const handler = createIntakeHandler(config, options);
310
+ const tls = intake.tls_cert_file && intake.tls_key_file;
311
+ const server = tls
312
+ ? createHttpsServer({
313
+ cert: readFileSync(intake.tls_cert_file),
314
+ key: readFileSync(intake.tls_key_file),
315
+ minVersion: 'TLSv1.2',
316
+ }, handler)
317
+ : createHttpServer(handler);
318
+ server.headersTimeout = 15_000;
319
+ server.requestTimeout = 120_000;
320
+ server.keepAliveTimeout = 5_000;
321
+ server.maxHeadersCount = 50;
322
+ const separator = intake.listen.lastIndexOf(':');
323
+ const host = intake.listen.slice(0, separator).replace(/^\[|\]$/g, '');
324
+ const port = Number(intake.listen.slice(separator + 1));
325
+ await new Promise((resolveListen, reject) => {
326
+ server.once('error', reject);
327
+ server.listen({ host, port }, () => {
328
+ server.off('error', reject);
329
+ resolveListen();
330
+ });
331
+ });
332
+ const address = server.address();
333
+ const shown = address.family === 'IPv6' ? `[${address.address}]` : address.address;
334
+ return {
335
+ url: `${tls ? 'https' : 'http'}://${shown}:${address.port}`,
336
+ close: () => new Promise((resolveClose) => {
337
+ server.close(() => resolveClose());
338
+ server.closeAllConnections();
339
+ }),
340
+ };
341
+ }
@@ -272,5 +272,21 @@ export declare const inventorySnapshotSchema: z.ZodObject<{
272
272
  import_warnings: z.ZodOptional<z.ZodArray<z.ZodString>>;
273
273
  name_notices: z.ZodOptional<z.ZodArray<z.ZodString>>;
274
274
  }, z.core.$strict>;
275
+ /**
276
+ * Every `.json` SBOM in a folder becomes one system. Pipelines drop their SBOM there; the next scan
277
+ * picks it up. The SBOM's creation time is the system's `updated_at`, so an SBOM that is no longer
278
+ * refreshed is reported as stale. A file that cannot be imported is reported and left out; it does
279
+ * not stop the other systems from being watched.
280
+ */
281
+ /**
282
+ * One system from one SBOM file, described by the SBOM itself, exactly as a scan will read it. The
283
+ * SBOM receiver calls this before it accepts an upload, so an upload it accepts is one a scan uses.
284
+ * Throws when the file cannot be imported or describes the system with values the inventory refuses.
285
+ */
286
+ export declare function systemFromSbom(path: string, file: string, label: string): {
287
+ system: Inventory['systems'][number];
288
+ warnings: string[];
289
+ notices: string[];
290
+ };
275
291
  /** Load a local YAML/JSON inventory, checking its size and schema. */
276
292
  export declare function loadInventory(path: string): Inventory;
package/dist/inventory.js CHANGED
@@ -1,10 +1,10 @@
1
- import { readFileSync, statSync } from 'node:fs';
2
- import { dirname, resolve } from 'node:path';
1
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join, relative, resolve } from 'node:path';
3
3
  import { parseDocument } from 'yaml';
4
4
  import { z } from 'zod';
5
5
  import { capitalisedName, exactLibraryVersion, mergeNotes, normalizeEcosystem, normalizePackageName, parseLibrary, } from './ecosystems.js';
6
6
  import { hash, LINE_BREAKING, singleLine } from './util.js';
7
- import { importCycloneDx } from './sbom.js';
7
+ import { importSbom } from './sbom.js';
8
8
  // Inventory text is shown in notifications, one value per line. A control character or a Unicode
9
9
  // line separator inside a name, owner or note would let that value start a line of its own.
10
10
  const shortText = z
@@ -149,7 +149,10 @@ const systemSchema = z.strictObject({
149
149
  keywords: z.array(shortText).max(100).default([]),
150
150
  lockfile: z.string().trim().min(1).max(4096).optional(),
151
151
  });
152
- const inventorySchema = z.strictObject({ systems: z.array(systemSchema).min(1).max(1000) });
152
+ const inventorySchema = z.strictObject({
153
+ sbom_directory: z.string().trim().min(1).max(4096).optional(),
154
+ systems: z.array(systemSchema).max(1000).default([]),
155
+ });
153
156
  /** Already materialized snapshots cannot import files or expand filesystem references. */
154
157
  export const inventorySnapshotSchema = z
155
158
  .strictObject({
@@ -224,6 +227,106 @@ function importLockfile(path) {
224
227
  }
225
228
  return { components, warnings };
226
229
  }
230
+ const SBOM_FILES = 1000;
231
+ const UNMATCHED_KIND = /unsupported package ecosystem (deb|rpm|apk|alpm|opkg|qpkg|bitnami|oci|docker|githubactions|github); not imported/i;
232
+ const isoTimestamp = z.iso.datetime({ offset: true });
233
+ /**
234
+ * Every `.json` SBOM in a folder becomes one system. Pipelines drop their SBOM there; the next scan
235
+ * picks it up. The SBOM's creation time is the system's `updated_at`, so an SBOM that is no longer
236
+ * refreshed is reported as stale. A file that cannot be imported is reported and left out; it does
237
+ * not stop the other systems from being watched.
238
+ */
239
+ /**
240
+ * One system from one SBOM file, described by the SBOM itself, exactly as a scan will read it. The
241
+ * SBOM receiver calls this before it accepts an upload, so an upload it accepts is one a scan uses.
242
+ * Throws when the file cannot be imported or describes the system with values the inventory refuses.
243
+ */
244
+ export function systemFromSbom(path, file, label) {
245
+ const imported = importSbom(path);
246
+ const properties = imported.subject?.properties ?? {};
247
+ const property = (name) => properties[`security-watch:${name}`];
248
+ const id = property('system-id') ?? basename(file).replace(/(?:\.(?:cdx|spdx|bom|sbom|cyclonedx))?\.json$/i, '');
249
+ const created = imported.subject?.created;
250
+ const enumValue = (value, allowed) => value !== undefined && allowed.includes(value) ? value : undefined;
251
+ const parsed = systemSchema.safeParse({
252
+ id,
253
+ name: imported.subject?.name ?? id,
254
+ updated_at: created && isoTimestamp.safeParse(created).success ? created : statSync(path).mtime.toISOString(),
255
+ note: property('note') ?? `SBOM ${label}`,
256
+ ...(property('owner') ? { owner: property('owner') } : {}),
257
+ ...(property('environment') ? { environment: property('environment') } : {}),
258
+ ...(enumValue(property('exposure'), ['internet', 'internal', 'unknown'])
259
+ ? { exposure: property('exposure') }
260
+ : {}),
261
+ ...(enumValue(property('criticality'), ['unknown', 'low', 'medium', 'high', 'critical'])
262
+ ? { criticality: property('criticality') }
263
+ : {}),
264
+ ...(property('source-url') ? { source_url: property('source-url') } : {}),
265
+ ...(property('source-revision') ? { source_revision: property('source-revision') } : {}),
266
+ provenance: { source: `${imported.source.format} SBOM`, reference: imported.source.digest },
267
+ });
268
+ if (!parsed.success) {
269
+ const issue = parsed.error.issues[0];
270
+ throw new Error(issue ? `${issue.path.join('.') || 'system'}: ${issue.message}` : 'invalid system description');
271
+ }
272
+ const { lockfile: _lockfile, libraries: _libraries, sbom: _sbom, ...system } = parsed.data;
273
+ system.components = imported.components;
274
+ if (imported.dependencies.length)
275
+ system.sbom_dependencies = dependencyGraph.parse(imported.dependencies);
276
+ // A container SBOM always lists the image's operating-system packages, and GitHub's export lists
277
+ // the workflow's actions. Security Watch does not match those (it has no distribution backport
278
+ // data), which is a known limit rather than a fault, so it is said once as a notice instead of
279
+ // degrading every scan, together with the dependency edges that lead to them.
280
+ const warnings = [];
281
+ const notices = [];
282
+ const unmatched = new Map();
283
+ for (const warning of imported.warnings) {
284
+ const kind = UNMATCHED_KIND.exec(warning)?.[1]?.toLowerCase();
285
+ if (kind)
286
+ unmatched.set(kind, (unmatched.get(kind) ?? 0) + 1);
287
+ else if (!unmatched.size || !/^Dependency (?:target|source) .*: not an imported package/.test(warning))
288
+ warnings.push(`${id}: ${warning}`);
289
+ }
290
+ if (unmatched.size) {
291
+ const count = [...unmatched.values()].reduce((sum, value) => sum + value, 0);
292
+ notices.push(`${id}: ${count} package${count === 1 ? '' : 's'} in ${label} ${count === 1 ? 'is' : 'are'} of a kind Security Watch does not match against advisories (${[...unmatched.keys()].sort().join(', ')}): operating-system packages and CI actions need your image or repository scanner. The other packages are watched.`);
293
+ }
294
+ return { system, warnings, notices };
295
+ }
296
+ function loadSbomDirectory(folder, base, taken) {
297
+ if (!statSync(folder).isDirectory())
298
+ throw new Error(`sbom_directory is not a folder: ${folder}`);
299
+ const files = readdirSync(folder)
300
+ .filter((name) => !name.startsWith('.') && name.toLowerCase().endsWith('.json'))
301
+ .sort();
302
+ if (files.length > SBOM_FILES)
303
+ throw new Error(`sbom_directory holds more than ${SBOM_FILES} SBOM files`);
304
+ const systems = [];
305
+ const warnings = [];
306
+ const notices = [];
307
+ for (const file of files) {
308
+ const path = join(folder, file);
309
+ const label = relative(base, path) || file;
310
+ try {
311
+ if (!statSync(path).isFile())
312
+ continue;
313
+ const loaded = systemFromSbom(path, file, label);
314
+ const id = loaded.system.id;
315
+ if (taken.has(id)) {
316
+ warnings.push(`${label}: system ID ${id} is already used in the inventory; this SBOM is not watched.`);
317
+ continue;
318
+ }
319
+ taken.add(id);
320
+ systems.push(loaded.system);
321
+ warnings.push(...loaded.warnings);
322
+ notices.push(...loaded.notices);
323
+ }
324
+ catch (error) {
325
+ warnings.push(`${label}: ${singleLine(error instanceof Error ? error.message : 'could not be imported', 200)}; this SBOM is not watched.`);
326
+ }
327
+ }
328
+ return { systems, warnings, notices };
329
+ }
227
330
  /** Load a local YAML/JSON inventory, checking its size and schema. */
228
331
  export function loadInventory(path) {
229
332
  const absolute = resolve(path);
@@ -292,7 +395,7 @@ export function loadInventory(path) {
292
395
  omittedNotices++;
293
396
  }
294
397
  if (sbom) {
295
- const imported = importCycloneDx(resolve(dirname(absolute), sbom));
398
+ const imported = importSbom(resolve(dirname(absolute), sbom));
296
399
  system.components.push(...imported.components);
297
400
  if (imported.dependencies.length) {
298
401
  system.sbom_dependencies = dependencyGraph.parse([
@@ -324,6 +427,27 @@ export function loadInventory(path) {
324
427
  }
325
428
  return system;
326
429
  });
430
+ if (parsed.sbom_directory) {
431
+ const folder = resolve(dirname(absolute), parsed.sbom_directory);
432
+ const loaded = loadSbomDirectory(folder, dirname(absolute), new Set(systems.map((system) => system.id)));
433
+ systems.push(...loaded.systems);
434
+ for (const warning of loaded.warnings)
435
+ if (importWarnings.length < 200)
436
+ importWarnings.push(singleLine(warning, 400));
437
+ else
438
+ omittedWarnings++;
439
+ for (const notice of loaded.notices)
440
+ if (nameNotices.length < 200)
441
+ nameNotices.push(singleLine(notice, 400));
442
+ else
443
+ omittedNotices++;
444
+ }
445
+ if (!systems.length && !parsed.sbom_directory)
446
+ throw new Error('No systems: add at least one system, or an sbom_directory with SBOM files.');
447
+ // An empty SBOM folder is how a monitor fed by pipelines starts. Scans report the empty inventory
448
+ // as degraded monitoring until the first SBOM arrives.
449
+ if (!systems.length)
450
+ nameNotices.push(`The SBOM folder ${parsed.sbom_directory} has no SBOM that could be imported, so nothing is watched yet. Upload one from CI (security-watch upload) or create one with: security-watch sbom --project PATH --output ${join(parsed.sbom_directory, 'NAME.cdx.json')}`);
327
451
  if (omittedWarnings)
328
452
  importWarnings.push(`${omittedWarnings} more import warning(s) are not shown.`);
329
453
  if (omittedNotices)
@@ -0,0 +1,67 @@
1
+ import { type Ecosystem } from './ecosystems.js';
2
+ /**
3
+ * Builds a CycloneDX software bill of materials from the dependency files already in a project:
4
+ * lockfiles first, manifests where no lockfile exists. It reads files only. It never runs a package
5
+ * manager, installs anything, follows a symbolic link or contacts a registry, so it is safe to run on
6
+ * an untrusted checkout and gives the same answer offline.
7
+ */
8
+ /** One dependency file that was read. */
9
+ export interface DependencyFile {
10
+ /** Path relative to the project, with `/` separators. */
11
+ path: string;
12
+ ecosystem: Ecosystem;
13
+ /** `lockfile` gives exact versions; `manifest` often only version ranges. */
14
+ kind: 'lockfile' | 'manifest';
15
+ packages: number;
16
+ }
17
+ /** What `generateSbom` describes the project as. Every field is optional. */
18
+ export interface SbomOptions {
19
+ /** Project folder, or one dependency file. Default: the current directory. */
20
+ project?: string;
21
+ /** Human-readable system name. Default: the name in package.json, pyproject.toml or the folder name. */
22
+ name?: string;
23
+ /** Stable system ID used by an SBOM folder. Default: derived from the name. */
24
+ systemId?: string;
25
+ owner?: string;
26
+ environment?: string;
27
+ /** Where the system runs and who to ask. Shown in alerts. */
28
+ note?: string;
29
+ exposure?: 'internet' | 'internal' | 'unknown';
30
+ criticality?: 'unknown' | 'low' | 'medium' | 'high' | 'critical';
31
+ /** HTTPS address of the source repository, without credentials. */
32
+ sourceUrl?: string;
33
+ /** Commit or build the SBOM was made from. */
34
+ sourceRevision?: string;
35
+ /** Leave out development-only dependencies where the dependency file says which they are. */
36
+ production?: boolean;
37
+ /** Time written as the SBOM timestamp. Default: now. */
38
+ now?: Date;
39
+ /** Version of the generating tool, written to the SBOM metadata. */
40
+ toolVersion?: string;
41
+ }
42
+ export interface GeneratedSbom {
43
+ /** A CycloneDX 1.6 JSON document. Write it with `JSON.stringify`. */
44
+ bom: Record<string, unknown>;
45
+ /** The system ID and name written into the document. */
46
+ system: {
47
+ id: string;
48
+ name: string;
49
+ };
50
+ files: DependencyFile[];
51
+ ecosystems: Ecosystem[];
52
+ /** Components in the document. */
53
+ packages: number;
54
+ /** Packages recorded without an exact version: they are watched by name only. */
55
+ unversioned: number;
56
+ warnings: string[];
57
+ }
58
+ /** Names of the dependency files `generateSbom` reads, for help text and documentation. */
59
+ export declare const DEPENDENCY_FILES: Readonly<Record<Ecosystem, readonly string[]>>;
60
+ /** A package URL (https://github.com/package-url/purl-spec) for a normalised package identity. */
61
+ export declare function packageUrl(ecosystem: Ecosystem, name: string, version?: string): string;
62
+ /**
63
+ * Reads every supported dependency file in a project and returns a CycloneDX 1.6 SBOM with one
64
+ * component per package and version. Each component records the files it was found in
65
+ * (`evidence.occurrences`), which Security Watch shows in alerts as the place to look.
66
+ */
67
+ export declare function generateSbom(options?: SbomOptions): GeneratedSbom;