@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/CHANGELOG.md +32 -0
- package/README.md +79 -38
- package/SECURITY.md +3 -2
- package/dist/cli.js +356 -32
- package/dist/config.d.ts +10 -0
- package/dist/config.js +56 -0
- package/dist/index.d.ts +7 -1
- package/dist/index.js +4 -1
- package/dist/intake.d.ts +36 -0
- package/dist/intake.js +341 -0
- package/dist/inventory.d.ts +16 -0
- package/dist/inventory.js +129 -5
- package/dist/manifests.d.ts +67 -0
- package/dist/manifests.js +1193 -0
- package/dist/sbom.d.ts +16 -1
- package/dist/sbom.js +156 -5
- package/dist/sources.js +45 -3
- package/dist/types.d.ts +18 -1
- package/dist/upload.d.ts +21 -0
- package/dist/upload.js +76 -0
- package/docs/compatibility.md +10 -10
- package/docs/configuration.md +27 -3
- package/docs/offline-advisory-preview.md +2 -2
- package/docs/sbom.md +266 -0
- package/package.json +9 -5
|
@@ -0,0 +1,1193 @@
|
|
|
1
|
+
import { lstatSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { XMLParser } from 'fast-xml-parser';
|
|
4
|
+
import { parse as parseYaml, parseAllDocuments } from 'yaml';
|
|
5
|
+
import { exactLibraryVersion, normalizePackageName, packageKey } from './ecosystems.js';
|
|
6
|
+
import { LINE_BREAKING, singleLine } from './util.js';
|
|
7
|
+
const MAX_FILE_BYTES = 20 * 1024 * 1024;
|
|
8
|
+
const MAX_DEPTH = 12;
|
|
9
|
+
const MAX_ENTRIES = 200_000;
|
|
10
|
+
const MAX_FILES = 2_000;
|
|
11
|
+
const MAX_COMPONENTS = 20_000;
|
|
12
|
+
const MAX_LOCATIONS = 10;
|
|
13
|
+
/** Folders that hold installed, generated or vendored copies rather than the project's own declarations. */
|
|
14
|
+
const SKIPPED_FOLDERS = new Set([
|
|
15
|
+
'node_modules',
|
|
16
|
+
'bower_components',
|
|
17
|
+
'jspm_packages',
|
|
18
|
+
'vendor',
|
|
19
|
+
'venv',
|
|
20
|
+
'site-packages',
|
|
21
|
+
'__pycache__',
|
|
22
|
+
'target',
|
|
23
|
+
'dist',
|
|
24
|
+
'build',
|
|
25
|
+
'out',
|
|
26
|
+
'coverage',
|
|
27
|
+
'Pods',
|
|
28
|
+
'Carthage',
|
|
29
|
+
'deps',
|
|
30
|
+
'_build',
|
|
31
|
+
'obj',
|
|
32
|
+
'bin',
|
|
33
|
+
// Test data describes other projects, not this one.
|
|
34
|
+
'fixtures',
|
|
35
|
+
'__fixtures__',
|
|
36
|
+
'testdata',
|
|
37
|
+
'__mocks__',
|
|
38
|
+
]);
|
|
39
|
+
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
40
|
+
const string = (value) => typeof value === 'string' && value.length > 0;
|
|
41
|
+
function found(ecosystem, name, version, dev) {
|
|
42
|
+
return {
|
|
43
|
+
ecosystem,
|
|
44
|
+
name,
|
|
45
|
+
...(version ? { version } : {}),
|
|
46
|
+
...(dev ? { dev: true } : {}),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
// ---------------------------------------------------------------------------------------------- npm
|
|
50
|
+
/** The registry package a dependency specifier points at, or undefined for Git, file and link specifiers. */
|
|
51
|
+
function npmSpecifier(name, specifier) {
|
|
52
|
+
let spec = specifier.trim();
|
|
53
|
+
if (spec.length > 1000)
|
|
54
|
+
return undefined;
|
|
55
|
+
if (spec.startsWith('npm:')) {
|
|
56
|
+
const target = spec.slice(4);
|
|
57
|
+
const at = target.lastIndexOf('@');
|
|
58
|
+
return at > 0 ? { name: target.slice(0, at), range: target.slice(at + 1) } : { name: target, range: '' };
|
|
59
|
+
}
|
|
60
|
+
if (/^(?:file|link|workspace|portal|patch|git|git\+[a-z]+|https?|github|gitlab|bitbucket):/i.test(spec))
|
|
61
|
+
return undefined;
|
|
62
|
+
// `user/repo` is a GitHub shorthand, not a registry version.
|
|
63
|
+
if (/^[^@\s][^\s]*\/[^\s]+$/.test(spec) && !/^\d/.test(spec))
|
|
64
|
+
return undefined;
|
|
65
|
+
spec = spec.replace(/^=\s*/, '').replace(/^v(?=\d)/, '');
|
|
66
|
+
return { name, range: spec };
|
|
67
|
+
}
|
|
68
|
+
const npmPackageLock = (text) => {
|
|
69
|
+
const lock = JSON.parse(text);
|
|
70
|
+
if (!record(lock))
|
|
71
|
+
throw new Error('not a package-lock document');
|
|
72
|
+
const packages = [];
|
|
73
|
+
let skipped = 0;
|
|
74
|
+
if (record(lock.packages)) {
|
|
75
|
+
for (const [location, value] of Object.entries(lock.packages)) {
|
|
76
|
+
const match = /(?:^|\/)node_modules\/((?:@[^/]+\/)?[^/]+)$/.exec(location);
|
|
77
|
+
if (!match || !record(value))
|
|
78
|
+
continue;
|
|
79
|
+
if (value.link === true || (string(value.resolved) && /^(?:file|git|git\+)/.test(value.resolved))) {
|
|
80
|
+
skipped++;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const name = string(value.name) ? value.name : match[1];
|
|
84
|
+
packages.push(found('npm', name, string(value.version) ? value.version : undefined, value.dev === true));
|
|
85
|
+
}
|
|
86
|
+
return { packages, skipped };
|
|
87
|
+
}
|
|
88
|
+
// lockfileVersion 1: a nested tree of `dependencies`.
|
|
89
|
+
const visit = (dependencies, depth) => {
|
|
90
|
+
if (!record(dependencies) || depth > 64)
|
|
91
|
+
return;
|
|
92
|
+
for (const [name, value] of Object.entries(dependencies)) {
|
|
93
|
+
if (!record(value))
|
|
94
|
+
continue;
|
|
95
|
+
const version = string(value.version) ? value.version : undefined;
|
|
96
|
+
if (version?.startsWith('npm:')) {
|
|
97
|
+
const target = npmSpecifier(name, version);
|
|
98
|
+
packages.push(found('npm', target.name, target.range, value.dev === true));
|
|
99
|
+
}
|
|
100
|
+
else if (version && /^(?:file|link|git|git\+|https?):/.test(version))
|
|
101
|
+
skipped++;
|
|
102
|
+
else
|
|
103
|
+
packages.push(found('npm', name, version, value.dev === true));
|
|
104
|
+
visit(value.dependencies, depth + 1);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
visit(lock.dependencies, 0);
|
|
108
|
+
return { packages, skipped };
|
|
109
|
+
};
|
|
110
|
+
/** Yarn 1 (`version "1.2.3"`) and Yarn 2+ (`resolution: "name@npm:1.2.3"`) lockfiles. */
|
|
111
|
+
const yarnLock = (text) => {
|
|
112
|
+
const packages = [];
|
|
113
|
+
let skipped = 0;
|
|
114
|
+
let header;
|
|
115
|
+
let fields = {};
|
|
116
|
+
const flush = () => {
|
|
117
|
+
if (header === undefined || header.startsWith('__metadata'))
|
|
118
|
+
return;
|
|
119
|
+
const unquote = (value) => value.trim().replace(/^"|"$/g, '');
|
|
120
|
+
if (fields.resolution !== undefined) {
|
|
121
|
+
const resolution = unquote(fields.resolution);
|
|
122
|
+
const match = /^((?:@[^@/]+\/)?[^@]+)@npm:(.+)$/.exec(resolution);
|
|
123
|
+
if (match)
|
|
124
|
+
packages.push(found('npm', match[1], match[2]));
|
|
125
|
+
else
|
|
126
|
+
skipped++;
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const first = unquote(header.split(/,\s*/)[0]);
|
|
130
|
+
// `"string-width-cjs@npm:string-width@^4.2.0"` installs string-width under another name.
|
|
131
|
+
const alias = first.indexOf('@npm:', 1);
|
|
132
|
+
const at = alias > 0 ? alias : first.lastIndexOf('@');
|
|
133
|
+
if (at <= 0)
|
|
134
|
+
return;
|
|
135
|
+
const target = npmSpecifier(first.slice(0, at), first.slice(at + 1));
|
|
136
|
+
if (!target) {
|
|
137
|
+
skipped++;
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
packages.push(found('npm', target.name, fields.version === undefined ? undefined : unquote(fields.version)));
|
|
141
|
+
};
|
|
142
|
+
for (const line of text.split(/\r?\n/)) {
|
|
143
|
+
if (!line.trim() || line.trimStart().startsWith('#'))
|
|
144
|
+
continue;
|
|
145
|
+
if (!/^\s/.test(line)) {
|
|
146
|
+
flush();
|
|
147
|
+
header = line.replace(/:\s*$/, '');
|
|
148
|
+
fields = {};
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const match = /^ {2}([A-Za-z]+):?\s+(.+)$/.exec(line);
|
|
152
|
+
if (match && (match[1] === 'version' || match[1] === 'resolution'))
|
|
153
|
+
fields[match[1]] = match[2];
|
|
154
|
+
}
|
|
155
|
+
flush();
|
|
156
|
+
return { packages, skipped };
|
|
157
|
+
};
|
|
158
|
+
const pnpmLock = (text) => {
|
|
159
|
+
// pnpm 10 can write two YAML documents (the package manager's own lockfile first).
|
|
160
|
+
const documents = parseAllDocuments(text);
|
|
161
|
+
const parsed = (Array.isArray(documents) ? documents : [documents])
|
|
162
|
+
.map((document) => document.toJS({ maxAliasCount: 0 }))
|
|
163
|
+
.filter(record);
|
|
164
|
+
// The project's lockfile is the document with the most packages; the other one pins pnpm itself.
|
|
165
|
+
const size = (document) => record(document.packages) ? Object.keys(document.packages).length : record(document.importers) ? 0 : -1;
|
|
166
|
+
const lock = parsed.reduce((best, document) => (size(document) >= 0 && (!best || size(document) > size(best)) ? document : best), undefined);
|
|
167
|
+
if (!lock)
|
|
168
|
+
throw new Error('not a pnpm lockfile');
|
|
169
|
+
const packages = [];
|
|
170
|
+
let skipped = 0;
|
|
171
|
+
const legacy = String(lock.lockfileVersion ?? '').startsWith('5');
|
|
172
|
+
for (const [key, value] of Object.entries(record(lock.packages) ? lock.packages : {})) {
|
|
173
|
+
const entry = key.replace(/^\//, '').split('(')[0];
|
|
174
|
+
let name;
|
|
175
|
+
let version;
|
|
176
|
+
if (legacy) {
|
|
177
|
+
const slash = entry.lastIndexOf('/');
|
|
178
|
+
if (slash <= 0)
|
|
179
|
+
continue;
|
|
180
|
+
name = entry.slice(0, slash);
|
|
181
|
+
version = entry.slice(slash + 1).split('_')[0];
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
const at = entry.lastIndexOf('@');
|
|
185
|
+
if (at <= 0)
|
|
186
|
+
continue;
|
|
187
|
+
name = entry.slice(0, at);
|
|
188
|
+
version = entry.slice(at + 1);
|
|
189
|
+
}
|
|
190
|
+
if (/[:]/.test(version) || (name.includes('/') && !name.startsWith('@'))) {
|
|
191
|
+
skipped++;
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
packages.push(found('npm', name, version, record(value) && value.dev === true));
|
|
195
|
+
}
|
|
196
|
+
return { packages, skipped };
|
|
197
|
+
};
|
|
198
|
+
const packageJson = (text) => {
|
|
199
|
+
const manifest = JSON.parse(text);
|
|
200
|
+
if (!record(manifest))
|
|
201
|
+
throw new Error('not a package.json document');
|
|
202
|
+
const packages = [];
|
|
203
|
+
let skipped = 0;
|
|
204
|
+
for (const [field, dev] of [
|
|
205
|
+
['dependencies', false],
|
|
206
|
+
['optionalDependencies', false],
|
|
207
|
+
['devDependencies', true],
|
|
208
|
+
]) {
|
|
209
|
+
const dependencies = manifest[field];
|
|
210
|
+
if (!record(dependencies))
|
|
211
|
+
continue;
|
|
212
|
+
for (const [name, specifier] of Object.entries(dependencies)) {
|
|
213
|
+
const target = typeof specifier === 'string' ? npmSpecifier(name, specifier) : undefined;
|
|
214
|
+
if (!target) {
|
|
215
|
+
skipped++;
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
packages.push(found('npm', target.name, target.range, dev));
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
return { packages, skipped };
|
|
222
|
+
};
|
|
223
|
+
// --------------------------------------------------------------------------------------------- PyPI
|
|
224
|
+
/** One PEP 508 requirement: the name, and the version only when it is pinned with `==` or `===`. */
|
|
225
|
+
function pep508(requirement) {
|
|
226
|
+
const text = requirement.split(';')[0].trim();
|
|
227
|
+
const match = /^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(.*)$/.exec(text);
|
|
228
|
+
if (!match)
|
|
229
|
+
return undefined;
|
|
230
|
+
const rest = match[2].trim();
|
|
231
|
+
if (rest.startsWith('@'))
|
|
232
|
+
return { name: match[1], direct: true };
|
|
233
|
+
const pinned = /^===?\s*([A-Za-z0-9][A-Za-z0-9.!+_-]*)$/.exec(rest);
|
|
234
|
+
return { name: match[1], ...(pinned && !pinned[1].includes('*') ? { version: pinned[1] } : {}) };
|
|
235
|
+
}
|
|
236
|
+
const requirementsTxt = (text) => {
|
|
237
|
+
const packages = [];
|
|
238
|
+
let skipped = 0;
|
|
239
|
+
// A trailing backslash continues a requirement (hashes are usually written that way).
|
|
240
|
+
const lines = text.replace(/\\\r?\n/g, ' ').split(/\r?\n/);
|
|
241
|
+
for (const raw of lines) {
|
|
242
|
+
const line = raw
|
|
243
|
+
.replace(/(?:^|\s)#.*$/, '')
|
|
244
|
+
.replace(/\s--hash[=\s]\S+/g, '')
|
|
245
|
+
.trim();
|
|
246
|
+
if (!line || line.startsWith('-'))
|
|
247
|
+
continue;
|
|
248
|
+
if (/^(?:\.|\/|[a-z+]+:\/\/|git\+)/i.test(line)) {
|
|
249
|
+
skipped++;
|
|
250
|
+
continue;
|
|
251
|
+
}
|
|
252
|
+
const requirement = pep508(line);
|
|
253
|
+
if (!requirement || requirement.direct) {
|
|
254
|
+
skipped++;
|
|
255
|
+
continue;
|
|
256
|
+
}
|
|
257
|
+
packages.push(found('PyPI', requirement.name, requirement.version));
|
|
258
|
+
}
|
|
259
|
+
return { packages, skipped };
|
|
260
|
+
};
|
|
261
|
+
const pipfileLock = (text) => {
|
|
262
|
+
const lock = JSON.parse(text);
|
|
263
|
+
if (!record(lock))
|
|
264
|
+
throw new Error('not a Pipfile.lock document');
|
|
265
|
+
const packages = [];
|
|
266
|
+
let skipped = 0;
|
|
267
|
+
for (const [section, dev] of [
|
|
268
|
+
['default', false],
|
|
269
|
+
['develop', true],
|
|
270
|
+
]) {
|
|
271
|
+
const entries = lock[section];
|
|
272
|
+
if (!record(entries))
|
|
273
|
+
continue;
|
|
274
|
+
for (const [name, value] of Object.entries(entries)) {
|
|
275
|
+
if (!record(value) || !string(value.version)) {
|
|
276
|
+
skipped++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
packages.push(found('PyPI', name, value.version.replace(/^===?/, ''), dev));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return { packages, skipped };
|
|
283
|
+
};
|
|
284
|
+
/** The `[[package]]` tables of a generated TOML lockfile (Cargo, Poetry, uv, PDM), as flat key/value text. */
|
|
285
|
+
function tomlPackages(text) {
|
|
286
|
+
const tables = [];
|
|
287
|
+
let current;
|
|
288
|
+
let prefix = '';
|
|
289
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
290
|
+
const line = raw.trim();
|
|
291
|
+
if (line === '[[package]]') {
|
|
292
|
+
current = {};
|
|
293
|
+
tables.push(current);
|
|
294
|
+
prefix = '';
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
const table = /^\[\[?([^\]]+)\]\]?$/.exec(line);
|
|
298
|
+
if (table) {
|
|
299
|
+
if (current && table[1].startsWith('package.'))
|
|
300
|
+
prefix = `${table[1].slice(8)}.`;
|
|
301
|
+
else
|
|
302
|
+
current = undefined;
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (!current)
|
|
306
|
+
continue;
|
|
307
|
+
const pair = /^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/.exec(line);
|
|
308
|
+
if (!pair)
|
|
309
|
+
continue;
|
|
310
|
+
const quoted = /^"((?:[^"\\]|\\.)*)"/.exec(pair[2]);
|
|
311
|
+
current[prefix + pair[1]] = quoted ? quoted[1].replace(/\\(.)/g, '$1') : pair[2];
|
|
312
|
+
}
|
|
313
|
+
return tables;
|
|
314
|
+
}
|
|
315
|
+
const poetryLock = (text) => {
|
|
316
|
+
const packages = [];
|
|
317
|
+
let skipped = 0;
|
|
318
|
+
for (const table of tomlPackages(text)) {
|
|
319
|
+
if (!string(table.name))
|
|
320
|
+
continue;
|
|
321
|
+
const source = table['source.type'];
|
|
322
|
+
if (source && source !== 'legacy') {
|
|
323
|
+
skipped++;
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
packages.push(found('PyPI', table.name, table.version, table.category === 'dev'));
|
|
327
|
+
}
|
|
328
|
+
return { packages, skipped };
|
|
329
|
+
};
|
|
330
|
+
const uvLock = (text) => {
|
|
331
|
+
const packages = [];
|
|
332
|
+
let skipped = 0;
|
|
333
|
+
for (const table of tomlPackages(text)) {
|
|
334
|
+
if (!string(table.name))
|
|
335
|
+
continue;
|
|
336
|
+
const source = table.source;
|
|
337
|
+
if (source !== undefined && !/\bregistry\s*=/.test(source)) {
|
|
338
|
+
skipped++;
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
packages.push(found('PyPI', table.name, table.version));
|
|
342
|
+
}
|
|
343
|
+
return { packages, skipped };
|
|
344
|
+
};
|
|
345
|
+
/** Dependencies named in pyproject.toml: PEP 621, PEP 735 dependency groups and Poetry tables. */
|
|
346
|
+
const pyprojectToml = (text) => {
|
|
347
|
+
const packages = [];
|
|
348
|
+
let skipped = 0;
|
|
349
|
+
let table = '';
|
|
350
|
+
let collecting;
|
|
351
|
+
const add = (requirement, dev) => {
|
|
352
|
+
const parsed = pep508(requirement);
|
|
353
|
+
if (!parsed || parsed.direct)
|
|
354
|
+
skipped++;
|
|
355
|
+
else
|
|
356
|
+
packages.push(found('PyPI', parsed.name, parsed.version, dev));
|
|
357
|
+
};
|
|
358
|
+
const finish = (value, dev) => {
|
|
359
|
+
for (const match of value.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g))
|
|
360
|
+
add(match[1] ?? match[2], dev);
|
|
361
|
+
};
|
|
362
|
+
const poetryDev = (name) => name === 'tool.poetry.dev-dependencies' || /^tool\.poetry\.group\.[^.]+\.dependencies$/.test(name);
|
|
363
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
364
|
+
const line = raw.replace(/\s#.*$/, '').trim();
|
|
365
|
+
if (collecting) {
|
|
366
|
+
collecting.text += ` ${line}`;
|
|
367
|
+
collecting.depth += (line.match(/\[/g) ?? []).length - (line.match(/\]/g) ?? []).length;
|
|
368
|
+
if (collecting.depth <= 0) {
|
|
369
|
+
finish(collecting.text, collecting.dev);
|
|
370
|
+
collecting = undefined;
|
|
371
|
+
}
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
const header = /^\[([^\]]+)\]$/.exec(line);
|
|
375
|
+
if (header) {
|
|
376
|
+
table = header[1].trim();
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const pair = /^("?[A-Za-z0-9_.-]+"?)\s*=\s*(.*)$/.exec(line);
|
|
380
|
+
if (!pair)
|
|
381
|
+
continue;
|
|
382
|
+
const key = pair[1].replace(/"/g, '');
|
|
383
|
+
const value = pair[2];
|
|
384
|
+
const pep621 = (table === 'project' && key === 'dependencies') ||
|
|
385
|
+
table === 'project.optional-dependencies' ||
|
|
386
|
+
table === 'dependency-groups';
|
|
387
|
+
if (pep621 && value.startsWith('[')) {
|
|
388
|
+
const dev = table === 'dependency-groups';
|
|
389
|
+
const depth = (value.match(/\[/g) ?? []).length - (value.match(/\]/g) ?? []).length;
|
|
390
|
+
if (depth <= 0)
|
|
391
|
+
finish(value, dev);
|
|
392
|
+
else
|
|
393
|
+
collecting = { dev, text: value, depth };
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
if (table === 'tool.poetry.dependencies' || poetryDev(table)) {
|
|
397
|
+
if (key.toLowerCase() === 'python')
|
|
398
|
+
continue;
|
|
399
|
+
const constraint = /^"([^"]*)"/.exec(value)?.[1] ?? /\bversion\s*=\s*"([^"]*)"/.exec(value)?.[1];
|
|
400
|
+
if (/\b(?:git|path|url)\s*=/.test(value)) {
|
|
401
|
+
skipped++;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
// Poetry reads a bare version ("2.31.0") as an exact pin.
|
|
405
|
+
const exact = constraint && /^(?:==)?\s*\d[A-Za-z0-9.!+_-]*$/.test(constraint.trim());
|
|
406
|
+
packages.push(found('PyPI', key, exact ? constraint.trim().replace(/^==\s*/, '') : undefined, poetryDev(table)));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return { packages, skipped };
|
|
410
|
+
};
|
|
411
|
+
// ------------------------------------------------------------------------------------- Go and Rust
|
|
412
|
+
const goMod = (text) => {
|
|
413
|
+
const required = [];
|
|
414
|
+
const replaced = new Map();
|
|
415
|
+
let block;
|
|
416
|
+
const replace = (line) => {
|
|
417
|
+
const match = /^(\S+)(?:\s+\S+)?\s*=>\s*(\S+)(?:\s+(\S+))?$/.exec(line);
|
|
418
|
+
if (!match)
|
|
419
|
+
return;
|
|
420
|
+
replaced.set(match[1], /^(?:\.|\/)/.test(match[2]) || !match[3] ? null : { name: match[2], version: match[3] });
|
|
421
|
+
};
|
|
422
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
423
|
+
const line = raw.replace(/\/\/.*$/, '').trim();
|
|
424
|
+
if (!line)
|
|
425
|
+
continue;
|
|
426
|
+
if (block) {
|
|
427
|
+
if (line === ')')
|
|
428
|
+
block = undefined;
|
|
429
|
+
else if (block === 'require') {
|
|
430
|
+
const [name, version] = line.split(/\s+/);
|
|
431
|
+
if (name && version)
|
|
432
|
+
required.push({ name, version });
|
|
433
|
+
}
|
|
434
|
+
else
|
|
435
|
+
replace(line);
|
|
436
|
+
continue;
|
|
437
|
+
}
|
|
438
|
+
const directive = /^(require|replace)\s*(\(|.+)$/.exec(line);
|
|
439
|
+
if (!directive)
|
|
440
|
+
continue;
|
|
441
|
+
if (directive[2] === '(')
|
|
442
|
+
block = directive[1];
|
|
443
|
+
else if (directive[1] === 'require') {
|
|
444
|
+
const [name, version] = directive[2].trim().split(/\s+/);
|
|
445
|
+
if (name && version)
|
|
446
|
+
required.push({ name, version });
|
|
447
|
+
}
|
|
448
|
+
else
|
|
449
|
+
replace(directive[2].trim());
|
|
450
|
+
}
|
|
451
|
+
const packages = [];
|
|
452
|
+
let skipped = 0;
|
|
453
|
+
for (const module of required) {
|
|
454
|
+
const replacement = replaced.get(module.name);
|
|
455
|
+
if (replacement === null)
|
|
456
|
+
skipped++;
|
|
457
|
+
else
|
|
458
|
+
packages.push(found('Go', (replacement ?? module).name, (replacement ?? module).version));
|
|
459
|
+
}
|
|
460
|
+
return { packages, skipped };
|
|
461
|
+
};
|
|
462
|
+
const cargoLock = (text) => {
|
|
463
|
+
const packages = [];
|
|
464
|
+
let skipped = 0;
|
|
465
|
+
for (const table of tomlPackages(text)) {
|
|
466
|
+
if (!string(table.name))
|
|
467
|
+
continue;
|
|
468
|
+
// Workspace members have no source; Git and path dependencies are not on crates.io.
|
|
469
|
+
if (!table.source || !/^"?(?:registry|sparse)\+/.test(table.source)) {
|
|
470
|
+
if (table.source)
|
|
471
|
+
skipped++;
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
packages.push(found('crates.io', table.name, table.version));
|
|
475
|
+
}
|
|
476
|
+
return { packages, skipped };
|
|
477
|
+
};
|
|
478
|
+
// ------------------------------------------------------------------------------------- PHP and Ruby
|
|
479
|
+
/** Composer writes tags as `v6.4.0` and branches as `dev-main` or `2.x-dev`; only a tag is a release. */
|
|
480
|
+
function composerVersion(value) {
|
|
481
|
+
if (!string(value) || /^dev-|-dev$/.test(value))
|
|
482
|
+
return undefined;
|
|
483
|
+
return value.replace(/^v(?=\d)/, '');
|
|
484
|
+
}
|
|
485
|
+
// Platform requirements (php, ext-json, lib-icu, composer-plugin-api) have no vendor; every real
|
|
486
|
+
// package does, including vendors whose name starts with "php" (phpmailer/phpmailer, phpunit/phpunit).
|
|
487
|
+
const composerPlatform = (name) => !name.includes('/');
|
|
488
|
+
const composerLock = (text) => {
|
|
489
|
+
const lock = JSON.parse(text);
|
|
490
|
+
if (!record(lock))
|
|
491
|
+
throw new Error('not a composer.lock document');
|
|
492
|
+
const packages = [];
|
|
493
|
+
for (const [field, dev] of [
|
|
494
|
+
['packages', false],
|
|
495
|
+
['packages-dev', true],
|
|
496
|
+
]) {
|
|
497
|
+
const entries = lock[field];
|
|
498
|
+
if (!Array.isArray(entries))
|
|
499
|
+
continue;
|
|
500
|
+
for (const entry of entries)
|
|
501
|
+
if (record(entry) && string(entry.name) && !composerPlatform(entry.name))
|
|
502
|
+
packages.push(found('Packagist', entry.name, composerVersion(entry.version), dev));
|
|
503
|
+
}
|
|
504
|
+
return { packages, skipped: 0 };
|
|
505
|
+
};
|
|
506
|
+
const composerJson = (text) => {
|
|
507
|
+
const manifest = JSON.parse(text);
|
|
508
|
+
if (!record(manifest))
|
|
509
|
+
throw new Error('not a composer.json document');
|
|
510
|
+
const packages = [];
|
|
511
|
+
for (const [field, dev] of [
|
|
512
|
+
['require', false],
|
|
513
|
+
['require-dev', true],
|
|
514
|
+
]) {
|
|
515
|
+
const entries = manifest[field];
|
|
516
|
+
if (!record(entries))
|
|
517
|
+
continue;
|
|
518
|
+
for (const [name, constraint] of Object.entries(entries)) {
|
|
519
|
+
if (composerPlatform(name))
|
|
520
|
+
continue;
|
|
521
|
+
const exact = typeof constraint === 'string' && /^v?\d+(?:\.\d+)*$/.test(constraint.trim());
|
|
522
|
+
packages.push(found('Packagist', name, exact ? composerVersion(constraint.trim()) : undefined, dev));
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return { packages, skipped: 0 };
|
|
526
|
+
};
|
|
527
|
+
const gemfileLock = (text) => {
|
|
528
|
+
const packages = [];
|
|
529
|
+
let section = '';
|
|
530
|
+
let specs = false;
|
|
531
|
+
let skipped = 0;
|
|
532
|
+
for (const line of text.split(/\r?\n/)) {
|
|
533
|
+
if (/^\S/.test(line)) {
|
|
534
|
+
section = line.trim();
|
|
535
|
+
specs = false;
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
if (/^ {2}specs:\s*$/.test(line)) {
|
|
539
|
+
specs = true;
|
|
540
|
+
continue;
|
|
541
|
+
}
|
|
542
|
+
const spec = /^ {4}([^\s(]+) \(([^)]+)\)\s*$/.exec(line);
|
|
543
|
+
if (!specs || !spec)
|
|
544
|
+
continue;
|
|
545
|
+
if (section !== 'GEM') {
|
|
546
|
+
skipped++;
|
|
547
|
+
continue;
|
|
548
|
+
}
|
|
549
|
+
// `nokogiri (1.16.5-x86_64-linux)`: the platform follows the version after a hyphen.
|
|
550
|
+
packages.push(found('RubyGems', spec[1], spec[2].split('-')[0]));
|
|
551
|
+
}
|
|
552
|
+
return { packages, skipped };
|
|
553
|
+
};
|
|
554
|
+
const gemfile = (text) => {
|
|
555
|
+
const packages = [];
|
|
556
|
+
let skipped = 0;
|
|
557
|
+
for (const line of text.split(/\r?\n/)) {
|
|
558
|
+
const match = /^\s*gem\s+["']([^"']+)["']\s*(?:,\s*["']([^"']+)["'])?(.*)$/.exec(line);
|
|
559
|
+
if (!match)
|
|
560
|
+
continue;
|
|
561
|
+
if (/\b(?:git|github|path):/.test(match[3])) {
|
|
562
|
+
skipped++;
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
const exact = match[2] && /^(?:=\s*)?\d[\w.]*$/.test(match[2].trim());
|
|
566
|
+
packages.push(found('RubyGems', match[1], exact ? match[2].replace(/^=\s*/, '').trim() : undefined));
|
|
567
|
+
}
|
|
568
|
+
return { packages, skipped };
|
|
569
|
+
};
|
|
570
|
+
// ----------------------------------------------------------------------------------- Java and .NET
|
|
571
|
+
const xml = (attributes) => new XMLParser({
|
|
572
|
+
ignoreAttributes: !attributes,
|
|
573
|
+
attributeNamePrefix: '',
|
|
574
|
+
processEntities: false,
|
|
575
|
+
parseTagValue: false,
|
|
576
|
+
trimValues: true,
|
|
577
|
+
});
|
|
578
|
+
const list = (value) => Array.isArray(value) ? value : value === undefined ? [] : [value];
|
|
579
|
+
const pomXml = (text) => {
|
|
580
|
+
const document = xml(false).parse(text);
|
|
581
|
+
const project = record(document) && record(document.project) ? document.project : undefined;
|
|
582
|
+
if (!project)
|
|
583
|
+
throw new Error('not a Maven project file');
|
|
584
|
+
const properties = new Map();
|
|
585
|
+
if (record(project.properties))
|
|
586
|
+
for (const [key, value] of Object.entries(project.properties))
|
|
587
|
+
if (typeof value === 'string' || typeof value === 'number')
|
|
588
|
+
properties.set(key, String(value));
|
|
589
|
+
const parent = record(project.parent) ? project.parent : {};
|
|
590
|
+
const projectVersion = project.version ?? parent.version;
|
|
591
|
+
if (string(projectVersion))
|
|
592
|
+
properties.set('project.version', projectVersion);
|
|
593
|
+
const resolveValue = (value) => {
|
|
594
|
+
if (typeof value !== 'string' && typeof value !== 'number')
|
|
595
|
+
return undefined;
|
|
596
|
+
let text = String(value);
|
|
597
|
+
for (let round = 0; round < 5 && text.includes('${'); round++)
|
|
598
|
+
text = text.replace(/\$\{([^}]+)\}/g, (whole, key) => properties.get(key) ?? whole);
|
|
599
|
+
return text.includes('${') ? undefined : text;
|
|
600
|
+
};
|
|
601
|
+
const dependencies = (container) => record(container) && record(container.dependencies) ? list(container.dependencies.dependency) : [];
|
|
602
|
+
const managed = new Map();
|
|
603
|
+
for (const entry of dependencies(project.dependencyManagement)) {
|
|
604
|
+
if (!record(entry))
|
|
605
|
+
continue;
|
|
606
|
+
const version = resolveValue(entry.version);
|
|
607
|
+
if (version)
|
|
608
|
+
managed.set(`${String(entry.groupId)}:${String(entry.artifactId)}`, version);
|
|
609
|
+
}
|
|
610
|
+
const packages = [];
|
|
611
|
+
let skipped = 0;
|
|
612
|
+
for (const entry of [...dependencies(project), ...dependencies(project.dependencyManagement)]) {
|
|
613
|
+
if (!record(entry))
|
|
614
|
+
continue;
|
|
615
|
+
const group = resolveValue(entry.groupId);
|
|
616
|
+
const artifact = resolveValue(entry.artifactId);
|
|
617
|
+
if (!group || !artifact || entry.scope === 'import') {
|
|
618
|
+
skipped++;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
const version = resolveValue(entry.version) ?? managed.get(`${group}:${artifact}`);
|
|
622
|
+
const exact = version && !/[[\](),]/.test(version) ? version : undefined;
|
|
623
|
+
packages.push(found('Maven', `${group}:${artifact}`, exact, entry.scope === 'test'));
|
|
624
|
+
}
|
|
625
|
+
return { packages, skipped };
|
|
626
|
+
};
|
|
627
|
+
const gradleLockfile = (text) => {
|
|
628
|
+
const packages = [];
|
|
629
|
+
for (const line of text.split(/\r?\n/)) {
|
|
630
|
+
const match = /^([^:#\s]+):([^:\s]+):([^=\s]+)=(.*)$/.exec(line.trim());
|
|
631
|
+
if (!match)
|
|
632
|
+
continue;
|
|
633
|
+
const configurations = match[4].split(',').filter(Boolean);
|
|
634
|
+
const dev = configurations.length > 0 && configurations.every((name) => /^test/i.test(name));
|
|
635
|
+
packages.push(found('Maven', `${match[1]}:${match[2]}`, match[3], dev));
|
|
636
|
+
}
|
|
637
|
+
return { packages, skipped: 0 };
|
|
638
|
+
};
|
|
639
|
+
const nugetLock = (text) => {
|
|
640
|
+
const lock = JSON.parse(text);
|
|
641
|
+
if (!record(lock) || !record(lock.dependencies))
|
|
642
|
+
throw new Error('not a NuGet packages.lock.json');
|
|
643
|
+
const packages = [];
|
|
644
|
+
let skipped = 0;
|
|
645
|
+
for (const framework of Object.values(lock.dependencies)) {
|
|
646
|
+
if (!record(framework))
|
|
647
|
+
continue;
|
|
648
|
+
for (const [name, value] of Object.entries(framework)) {
|
|
649
|
+
if (!record(value) || value.type === 'Project') {
|
|
650
|
+
skipped++;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
packages.push(found('NuGet', name, string(value.resolved) ? value.resolved : undefined));
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
return { packages, skipped };
|
|
657
|
+
};
|
|
658
|
+
/** `1.2.3` and `[1.2.3]` name one version; anything else in NuGet range syntax does not. */
|
|
659
|
+
function nugetVersion(value) {
|
|
660
|
+
if (!string(value))
|
|
661
|
+
return undefined;
|
|
662
|
+
const match = /^\[?\s*(\d[A-Za-z0-9.+-]*)\s*\]?$/.exec(value.trim());
|
|
663
|
+
return match && value.trim().startsWith('[') === value.trim().endsWith(']') ? match[1] : undefined;
|
|
664
|
+
}
|
|
665
|
+
/** PackageReference (project files) and PackageVersion (central package management) entries. */
|
|
666
|
+
const msbuildProject = (text) => {
|
|
667
|
+
const document = xml(true).parse(text);
|
|
668
|
+
const packages = [];
|
|
669
|
+
const visit = (node, depth) => {
|
|
670
|
+
if (depth > 16)
|
|
671
|
+
return;
|
|
672
|
+
if (Array.isArray(node)) {
|
|
673
|
+
for (const item of node)
|
|
674
|
+
visit(item, depth + 1);
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
if (!record(node))
|
|
678
|
+
return;
|
|
679
|
+
for (const [key, value] of Object.entries(node)) {
|
|
680
|
+
if (key === 'PackageReference' || key === 'PackageVersion') {
|
|
681
|
+
for (const entry of list(value)) {
|
|
682
|
+
if (!record(entry))
|
|
683
|
+
continue;
|
|
684
|
+
const name = entry.Include ?? entry.Update;
|
|
685
|
+
if (string(name))
|
|
686
|
+
packages.push(found('NuGet', name, nugetVersion(entry.Version ?? entry.VersionOverride)));
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
else
|
|
690
|
+
visit(value, depth + 1);
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
visit(document, 0);
|
|
694
|
+
return { packages, skipped: 0 };
|
|
695
|
+
};
|
|
696
|
+
// ------------------------------------------------------------------------- Dart, Elixir, Swift, Haskell
|
|
697
|
+
const pubspecLock = (text) => {
|
|
698
|
+
const lock = parseYaml(text, { maxAliasCount: 0 });
|
|
699
|
+
if (!record(lock) || !record(lock.packages))
|
|
700
|
+
throw new Error('not a pubspec.lock document');
|
|
701
|
+
const packages = [];
|
|
702
|
+
let skipped = 0;
|
|
703
|
+
for (const [name, value] of Object.entries(lock.packages)) {
|
|
704
|
+
if (!record(value) || value.source !== 'hosted') {
|
|
705
|
+
if (!record(value) || value.source !== 'sdk')
|
|
706
|
+
skipped++;
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
packages.push(found('Pub', name, string(value.version) ? value.version : undefined, value.dependency === 'direct dev'));
|
|
710
|
+
}
|
|
711
|
+
return { packages, skipped };
|
|
712
|
+
};
|
|
713
|
+
const pubspecYaml = (text) => {
|
|
714
|
+
const manifest = parseYaml(text, { maxAliasCount: 0 });
|
|
715
|
+
if (!record(manifest))
|
|
716
|
+
throw new Error('not a pubspec.yaml document');
|
|
717
|
+
const packages = [];
|
|
718
|
+
let skipped = 0;
|
|
719
|
+
for (const [field, dev] of [
|
|
720
|
+
['dependencies', false],
|
|
721
|
+
['dev_dependencies', true],
|
|
722
|
+
]) {
|
|
723
|
+
const entries = manifest[field];
|
|
724
|
+
if (!record(entries))
|
|
725
|
+
continue;
|
|
726
|
+
for (const [name, value] of Object.entries(entries)) {
|
|
727
|
+
const constraint = typeof value === 'string' ? value : record(value) ? value.version : undefined;
|
|
728
|
+
if (record(value) && (value.sdk !== undefined || value.path !== undefined || value.git !== undefined)) {
|
|
729
|
+
if (value.sdk === undefined)
|
|
730
|
+
skipped++;
|
|
731
|
+
continue;
|
|
732
|
+
}
|
|
733
|
+
const exact = typeof constraint === 'string' && /^\d[\w.+-]*$/.test(constraint.trim());
|
|
734
|
+
packages.push(found('Pub', name, exact ? constraint.trim() : undefined, dev));
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return { packages, skipped };
|
|
738
|
+
};
|
|
739
|
+
/** `.package(url: "https://github.com/vapor/vapor.git", from: "4.0.0")` and its variants. */
|
|
740
|
+
const packageSwift = (text) => {
|
|
741
|
+
const packages = [];
|
|
742
|
+
for (const match of text.matchAll(/\.package\s*\(([^)]{0,2000})\)/g)) {
|
|
743
|
+
const url = /url:\s*"([^"]+)"/.exec(match[1])?.[1];
|
|
744
|
+
const name = swiftIdentity(url);
|
|
745
|
+
if (!name)
|
|
746
|
+
continue;
|
|
747
|
+
const exact = /\bexact:\s*"([^"]+)"/.exec(match[1])?.[1] ?? /\.exact\(\s*"([^"]+)"/.exec(match[1])?.[1];
|
|
748
|
+
packages.push(found('SwiftURL', name, exact));
|
|
749
|
+
}
|
|
750
|
+
return { packages, skipped: 0 };
|
|
751
|
+
};
|
|
752
|
+
const mixLock = (text) => {
|
|
753
|
+
const packages = [];
|
|
754
|
+
let skipped = 0;
|
|
755
|
+
for (const line of text.split(/\r?\n/)) {
|
|
756
|
+
const hex = /^\s*"[^"]+":\s*\{:hex,\s*:"?([A-Za-z0-9_]+)"?,\s*"([^"]+)"/.exec(line);
|
|
757
|
+
if (hex)
|
|
758
|
+
packages.push(found('Hex', hex[1], hex[2]));
|
|
759
|
+
else if (/^\s*"[^"]+":\s*\{:(?:git|path)/.test(line))
|
|
760
|
+
skipped++;
|
|
761
|
+
}
|
|
762
|
+
return { packages, skipped };
|
|
763
|
+
};
|
|
764
|
+
/** `https://github.com/apple/swift-nio.git` → `github.com/apple/swift-nio`. */
|
|
765
|
+
function swiftIdentity(location) {
|
|
766
|
+
if (!string(location))
|
|
767
|
+
return undefined;
|
|
768
|
+
const scp = /^git@([^:]+):(.+)$/.exec(location);
|
|
769
|
+
const text = scp ? `https://${scp[1]}/${scp[2]}` : location;
|
|
770
|
+
try {
|
|
771
|
+
const url = new URL(text);
|
|
772
|
+
if (url.protocol !== 'https:' && url.protocol !== 'ssh:')
|
|
773
|
+
return undefined;
|
|
774
|
+
return `${url.hostname}${url.pathname.replace(/\.git$/, '').replace(/\/$/, '')}`;
|
|
775
|
+
}
|
|
776
|
+
catch {
|
|
777
|
+
return undefined;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
const packageResolved = (text) => {
|
|
781
|
+
const document = JSON.parse(text);
|
|
782
|
+
if (!record(document))
|
|
783
|
+
throw new Error('not a Package.resolved document');
|
|
784
|
+
const pins = Array.isArray(document.pins)
|
|
785
|
+
? document.pins
|
|
786
|
+
: record(document.object) && Array.isArray(document.object.pins)
|
|
787
|
+
? document.object.pins
|
|
788
|
+
: [];
|
|
789
|
+
const packages = [];
|
|
790
|
+
let skipped = 0;
|
|
791
|
+
for (const pin of pins) {
|
|
792
|
+
if (!record(pin))
|
|
793
|
+
continue;
|
|
794
|
+
const name = swiftIdentity(pin.location ?? pin.repositoryURL);
|
|
795
|
+
if (!name) {
|
|
796
|
+
skipped++;
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
const state = record(pin.state) ? pin.state : {};
|
|
800
|
+
packages.push(found('SwiftURL', name, string(state.version) ? state.version : undefined));
|
|
801
|
+
}
|
|
802
|
+
return { packages, skipped };
|
|
803
|
+
};
|
|
804
|
+
const cabalFreeze = (text) => {
|
|
805
|
+
const packages = [];
|
|
806
|
+
for (const match of text.matchAll(/\bany\.([A-Za-z0-9][A-Za-z0-9-]*)\s*==\s*([0-9][0-9.]*)/g))
|
|
807
|
+
packages.push(found('Hackage', match[1], match[2].replace(/\.$/, '')));
|
|
808
|
+
return { packages, skipped: 0 };
|
|
809
|
+
};
|
|
810
|
+
/** Which reader handles a file, by its name and the name of its folder. */
|
|
811
|
+
function classify(name, folder) {
|
|
812
|
+
const lock = (ecosystem, read) => ({ ecosystem, kind: 'lockfile', read });
|
|
813
|
+
const manifest = (ecosystem, read) => ({ ecosystem, kind: 'manifest', read });
|
|
814
|
+
switch (name) {
|
|
815
|
+
case 'package-lock.json':
|
|
816
|
+
case 'npm-shrinkwrap.json':
|
|
817
|
+
return lock('npm', npmPackageLock);
|
|
818
|
+
case 'yarn.lock':
|
|
819
|
+
return lock('npm', yarnLock);
|
|
820
|
+
case 'pnpm-lock.yaml':
|
|
821
|
+
return lock('npm', pnpmLock);
|
|
822
|
+
case 'package.json':
|
|
823
|
+
return manifest('npm', packageJson);
|
|
824
|
+
case 'Pipfile.lock':
|
|
825
|
+
return lock('PyPI', pipfileLock);
|
|
826
|
+
case 'poetry.lock':
|
|
827
|
+
case 'pdm.lock':
|
|
828
|
+
return lock('PyPI', poetryLock);
|
|
829
|
+
case 'uv.lock':
|
|
830
|
+
return lock('PyPI', uvLock);
|
|
831
|
+
case 'pyproject.toml':
|
|
832
|
+
return manifest('PyPI', pyprojectToml);
|
|
833
|
+
case 'go.mod':
|
|
834
|
+
return lock('Go', goMod);
|
|
835
|
+
case 'Cargo.lock':
|
|
836
|
+
return lock('crates.io', cargoLock);
|
|
837
|
+
case 'composer.lock':
|
|
838
|
+
return lock('Packagist', composerLock);
|
|
839
|
+
case 'composer.json':
|
|
840
|
+
return manifest('Packagist', composerJson);
|
|
841
|
+
case 'Gemfile.lock':
|
|
842
|
+
case 'gems.locked':
|
|
843
|
+
return lock('RubyGems', gemfileLock);
|
|
844
|
+
case 'Gemfile':
|
|
845
|
+
case 'gems.rb':
|
|
846
|
+
return manifest('RubyGems', gemfile);
|
|
847
|
+
case 'pom.xml':
|
|
848
|
+
return lock('Maven', pomXml);
|
|
849
|
+
case 'gradle.lockfile':
|
|
850
|
+
case 'buildscript-gradle.lockfile':
|
|
851
|
+
return lock('Maven', gradleLockfile);
|
|
852
|
+
case 'packages.lock.json':
|
|
853
|
+
return lock('NuGet', nugetLock);
|
|
854
|
+
case 'Directory.Packages.props':
|
|
855
|
+
return manifest('NuGet', msbuildProject);
|
|
856
|
+
case 'pubspec.lock':
|
|
857
|
+
return lock('Pub', pubspecLock);
|
|
858
|
+
case 'pubspec.yaml':
|
|
859
|
+
return manifest('Pub', pubspecYaml);
|
|
860
|
+
case 'Package.swift':
|
|
861
|
+
return manifest('SwiftURL', packageSwift);
|
|
862
|
+
case 'mix.lock':
|
|
863
|
+
return lock('Hex', mixLock);
|
|
864
|
+
case 'Package.resolved':
|
|
865
|
+
return lock('SwiftURL', packageResolved);
|
|
866
|
+
case 'cabal.project.freeze':
|
|
867
|
+
return lock('Hackage', cabalFreeze);
|
|
868
|
+
}
|
|
869
|
+
if (/^requirements.*\.txt$/i.test(name) || (folder === 'requirements' && name.endsWith('.txt')))
|
|
870
|
+
return lock('PyPI', requirementsTxt);
|
|
871
|
+
if (/\.(?:cs|fs|vb)proj$/.test(name))
|
|
872
|
+
return manifest('NuGet', msbuildProject);
|
|
873
|
+
if (folder === 'dependency-locks' && name.endsWith('.lockfile'))
|
|
874
|
+
return lock('Maven', gradleLockfile);
|
|
875
|
+
return undefined;
|
|
876
|
+
}
|
|
877
|
+
/** Names of the dependency files `generateSbom` reads, for help text and documentation. */
|
|
878
|
+
export const DEPENDENCY_FILES = {
|
|
879
|
+
npm: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock', 'pnpm-lock.yaml', 'package.json'],
|
|
880
|
+
PyPI: ['requirements*.txt', 'poetry.lock', 'uv.lock', 'Pipfile.lock', 'pdm.lock', 'pyproject.toml'],
|
|
881
|
+
Go: ['go.mod'],
|
|
882
|
+
'crates.io': ['Cargo.lock'],
|
|
883
|
+
Packagist: ['composer.lock', 'composer.json'],
|
|
884
|
+
RubyGems: ['Gemfile.lock', 'Gemfile'],
|
|
885
|
+
Maven: ['pom.xml', 'gradle.lockfile'],
|
|
886
|
+
NuGet: ['packages.lock.json', '*.csproj', 'Directory.Packages.props'],
|
|
887
|
+
Pub: ['pubspec.lock', 'pubspec.yaml'],
|
|
888
|
+
Hex: ['mix.lock'],
|
|
889
|
+
SwiftURL: ['Package.resolved', 'Package.swift'],
|
|
890
|
+
Hackage: ['cabal.project.freeze'],
|
|
891
|
+
};
|
|
892
|
+
/** Walks a project for dependency files without following links or entering installed-package folders. */
|
|
893
|
+
function discover(root, warnings) {
|
|
894
|
+
const stat = statSync(root);
|
|
895
|
+
// A link named like a dependency file can point at any file on the machine. The folder given as
|
|
896
|
+
// the project may be a link (the user chose it); a file must be the file itself.
|
|
897
|
+
if (stat.isFile() && lstatSync(root).isSymbolicLink())
|
|
898
|
+
throw new Error(`${basename(root)} is a symbolic link; give the dependency file itself.`);
|
|
899
|
+
if (stat.isFile()) {
|
|
900
|
+
const kind = classify(basename(root), basename(dirname(root)));
|
|
901
|
+
if (!kind)
|
|
902
|
+
throw new Error(`${basename(root)} is not a supported dependency file.`);
|
|
903
|
+
return [{ ...kind, absolute: root, path: basename(root) }];
|
|
904
|
+
}
|
|
905
|
+
if (!stat.isDirectory())
|
|
906
|
+
throw new Error('The project must be a folder or a dependency file.');
|
|
907
|
+
const candidates = [];
|
|
908
|
+
const queue = [{ folder: root, depth: 0 }];
|
|
909
|
+
let entries = 0;
|
|
910
|
+
while (queue.length) {
|
|
911
|
+
const { folder, depth } = queue.shift();
|
|
912
|
+
let names;
|
|
913
|
+
try {
|
|
914
|
+
names = readdirSync(folder, { withFileTypes: true });
|
|
915
|
+
}
|
|
916
|
+
catch {
|
|
917
|
+
warnings.push(`${relative(root, folder) || '.'}: folder could not be read; skipped.`);
|
|
918
|
+
continue;
|
|
919
|
+
}
|
|
920
|
+
names.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
921
|
+
for (const entry of names) {
|
|
922
|
+
if (++entries > MAX_ENTRIES)
|
|
923
|
+
throw new Error(`More than ${MAX_ENTRIES} files and folders; point --project at a smaller folder.`);
|
|
924
|
+
if (entry.isSymbolicLink())
|
|
925
|
+
continue;
|
|
926
|
+
const absolute = join(folder, entry.name);
|
|
927
|
+
if (entry.isDirectory()) {
|
|
928
|
+
if (entry.name.startsWith('.') || SKIPPED_FOLDERS.has(entry.name))
|
|
929
|
+
continue;
|
|
930
|
+
if (depth + 1 > MAX_DEPTH)
|
|
931
|
+
continue;
|
|
932
|
+
queue.push({ folder: absolute, depth: depth + 1 });
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (!entry.isFile())
|
|
936
|
+
continue;
|
|
937
|
+
const kind = classify(entry.name, basename(folder));
|
|
938
|
+
if (!kind)
|
|
939
|
+
continue;
|
|
940
|
+
if (candidates.length >= MAX_FILES)
|
|
941
|
+
throw new Error(`More than ${MAX_FILES} dependency files; point --project at a smaller folder.`);
|
|
942
|
+
candidates.push({ ...kind, absolute, path: relative(root, absolute).split(sep).join('/') });
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
// A manifest only adds information where no lockfile of the same ecosystem sits beside it. One
|
|
946
|
+
// below a folder with a lockfile is usually a workspace member that the lockfile already resolves:
|
|
947
|
+
// it is read for anything the lockfile lacks, without warning about its version ranges.
|
|
948
|
+
const locked = new Set(candidates
|
|
949
|
+
.filter((file) => file.kind === 'lockfile')
|
|
950
|
+
.map((file) => `${dirname(file.absolute)}\0${file.ecosystem}`));
|
|
951
|
+
const coveredBy = (file) => {
|
|
952
|
+
for (let folder = dirname(dirname(file.absolute)); folder.length >= root.length; folder = dirname(folder)) {
|
|
953
|
+
if (locked.has(`${folder}\0${file.ecosystem}`))
|
|
954
|
+
return true;
|
|
955
|
+
if (folder === dirname(folder))
|
|
956
|
+
break;
|
|
957
|
+
}
|
|
958
|
+
return false;
|
|
959
|
+
};
|
|
960
|
+
return candidates
|
|
961
|
+
.filter((file) => file.kind === 'lockfile' || !locked.has(`${dirname(file.absolute)}\0${file.ecosystem}`))
|
|
962
|
+
.map((file) => (file.kind === 'manifest' && coveredBy(file) ? { ...file, workspace: true } : file))
|
|
963
|
+
.sort((a, b) => Number(a.kind === 'manifest') - Number(b.kind === 'manifest'));
|
|
964
|
+
}
|
|
965
|
+
// ---------------------------------------------------------------------------------------- Package URLs
|
|
966
|
+
const PURL_TYPES = {
|
|
967
|
+
npm: 'npm',
|
|
968
|
+
PyPI: 'pypi',
|
|
969
|
+
Packagist: 'composer',
|
|
970
|
+
Go: 'golang',
|
|
971
|
+
Maven: 'maven',
|
|
972
|
+
'crates.io': 'cargo',
|
|
973
|
+
RubyGems: 'gem',
|
|
974
|
+
NuGet: 'nuget',
|
|
975
|
+
Hex: 'hex',
|
|
976
|
+
Pub: 'pub',
|
|
977
|
+
Hackage: 'hackage',
|
|
978
|
+
SwiftURL: 'swift',
|
|
979
|
+
};
|
|
980
|
+
/** A package URL (https://github.com/package-url/purl-spec) for a normalised package identity. */
|
|
981
|
+
export function packageUrl(ecosystem, name, version) {
|
|
982
|
+
const path = ecosystem === 'Maven' ? name.replace(':', '/') : name;
|
|
983
|
+
const encoded = path.split('/').map(encodeURIComponent).join('/');
|
|
984
|
+
return `pkg:${PURL_TYPES[ecosystem]}/${encoded}${version ? `@${encodeURIComponent(version)}` : ''}`;
|
|
985
|
+
}
|
|
986
|
+
// -------------------------------------------------------------------------------------------- Output
|
|
987
|
+
function slug(value) {
|
|
988
|
+
const text = value
|
|
989
|
+
.toLowerCase()
|
|
990
|
+
.replace(/^@/, '')
|
|
991
|
+
.replace(/[^a-z0-9._-]+/g, '-')
|
|
992
|
+
.replace(/^[-.]+|[-.]+$/g, '')
|
|
993
|
+
.slice(0, 100);
|
|
994
|
+
return text || 'application';
|
|
995
|
+
}
|
|
996
|
+
/** The name a project gives itself in package.json or pyproject.toml, or its folder name. */
|
|
997
|
+
function projectName(root, isFile) {
|
|
998
|
+
const folder = isFile ? dirname(root) : root;
|
|
999
|
+
const read = (file) => {
|
|
1000
|
+
try {
|
|
1001
|
+
const path = join(folder, file);
|
|
1002
|
+
if (!lstatSync(path).isFile() || statSync(path).size > 1024 * 1024)
|
|
1003
|
+
return undefined;
|
|
1004
|
+
return readFileSync(path, 'utf8');
|
|
1005
|
+
}
|
|
1006
|
+
catch {
|
|
1007
|
+
return undefined;
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
1010
|
+
try {
|
|
1011
|
+
const manifest = JSON.parse(read('package.json') ?? 'null');
|
|
1012
|
+
if (record(manifest) && string(manifest.name))
|
|
1013
|
+
return manifest.name;
|
|
1014
|
+
}
|
|
1015
|
+
catch {
|
|
1016
|
+
// Fall through to the next source of a name.
|
|
1017
|
+
}
|
|
1018
|
+
const pyproject = read('pyproject.toml');
|
|
1019
|
+
const name = pyproject && /^\[(?:project|tool\.poetry)\][^[]*?^name\s*=\s*"([^"]+)"/ms.exec(pyproject);
|
|
1020
|
+
if (name)
|
|
1021
|
+
return name[1];
|
|
1022
|
+
return basename(folder) || 'application';
|
|
1023
|
+
}
|
|
1024
|
+
function text(value, field) {
|
|
1025
|
+
if (value === undefined)
|
|
1026
|
+
return undefined;
|
|
1027
|
+
const trimmed = value.trim();
|
|
1028
|
+
if (!trimmed)
|
|
1029
|
+
return undefined;
|
|
1030
|
+
if (trimmed.length > 500 || LINE_BREAKING.test(trimmed))
|
|
1031
|
+
throw new Error(`${field} must be one line of at most 500 characters.`);
|
|
1032
|
+
return trimmed;
|
|
1033
|
+
}
|
|
1034
|
+
/**
|
|
1035
|
+
* Reads every supported dependency file in a project and returns a CycloneDX 1.6 SBOM with one
|
|
1036
|
+
* component per package and version. Each component records the files it was found in
|
|
1037
|
+
* (`evidence.occurrences`), which Security Watch shows in alerts as the place to look.
|
|
1038
|
+
*/
|
|
1039
|
+
export function generateSbom(options = {}) {
|
|
1040
|
+
const root = resolve(options.project ?? '.');
|
|
1041
|
+
const warnings = [];
|
|
1042
|
+
const isFile = statSync(root).isFile();
|
|
1043
|
+
const candidates = discover(root, warnings);
|
|
1044
|
+
const files = [];
|
|
1045
|
+
const versioned = new Map();
|
|
1046
|
+
const unversioned = new Map();
|
|
1047
|
+
for (const file of candidates) {
|
|
1048
|
+
let parsed;
|
|
1049
|
+
try {
|
|
1050
|
+
const size = statSync(file.absolute).size;
|
|
1051
|
+
if (size > MAX_FILE_BYTES) {
|
|
1052
|
+
warnings.push(`${file.path}: larger than 20 MiB; skipped.`);
|
|
1053
|
+
continue;
|
|
1054
|
+
}
|
|
1055
|
+
parsed = file.read(readFileSync(file.absolute, 'utf8').replace(/^/, ''), file.path);
|
|
1056
|
+
}
|
|
1057
|
+
catch (error) {
|
|
1058
|
+
warnings.push(`${file.path}: could not be read (${singleLine(error instanceof Error ? error.message : 'unknown error', 160)}); skipped.`);
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
let invalid = 0;
|
|
1062
|
+
let ranges = 0;
|
|
1063
|
+
let accepted = 0;
|
|
1064
|
+
for (const entry of parsed.packages) {
|
|
1065
|
+
if (options.production && entry.dev)
|
|
1066
|
+
continue;
|
|
1067
|
+
let name;
|
|
1068
|
+
try {
|
|
1069
|
+
name = normalizePackageName(entry.ecosystem, entry.name);
|
|
1070
|
+
}
|
|
1071
|
+
catch {
|
|
1072
|
+
invalid++;
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
let version;
|
|
1076
|
+
if (entry.version !== undefined) {
|
|
1077
|
+
try {
|
|
1078
|
+
version = exactLibraryVersion(entry.version, entry.ecosystem);
|
|
1079
|
+
}
|
|
1080
|
+
catch {
|
|
1081
|
+
version = undefined;
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
if (version === undefined)
|
|
1085
|
+
ranges++;
|
|
1086
|
+
accepted++;
|
|
1087
|
+
const target = version === undefined ? unversioned : versioned;
|
|
1088
|
+
const key = version === undefined
|
|
1089
|
+
? (packageKey({ ecosystem: entry.ecosystem, name }) ?? `${entry.ecosystem}\0${name}`)
|
|
1090
|
+
: packageUrl(entry.ecosystem, name, version);
|
|
1091
|
+
const existing = target.get(key);
|
|
1092
|
+
if (existing) {
|
|
1093
|
+
if (existing.locations.size < MAX_LOCATIONS)
|
|
1094
|
+
existing.locations.add(file.path);
|
|
1095
|
+
existing.dev &&= entry.dev === true;
|
|
1096
|
+
}
|
|
1097
|
+
else
|
|
1098
|
+
target.set(key, {
|
|
1099
|
+
ecosystem: entry.ecosystem,
|
|
1100
|
+
name,
|
|
1101
|
+
...(version === undefined ? {} : { version }),
|
|
1102
|
+
dev: entry.dev === true,
|
|
1103
|
+
locations: new Set([file.path]),
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
files.push({ path: file.path, ecosystem: file.ecosystem, kind: file.kind, packages: accepted });
|
|
1107
|
+
if (file.workspace)
|
|
1108
|
+
continue;
|
|
1109
|
+
if (invalid)
|
|
1110
|
+
warnings.push(`${file.path}: ${invalid} entr${invalid === 1 ? 'y has' : 'ies have'} a name that is not a valid ${file.ecosystem} package name; skipped.`);
|
|
1111
|
+
if (parsed.skipped)
|
|
1112
|
+
warnings.push(`${file.path}: ${parsed.skipped} entr${parsed.skipped === 1 ? 'y comes' : 'ies come'} from Git, a local path or another source that is not a package registry; not monitored.`);
|
|
1113
|
+
if (ranges && file.kind === 'manifest')
|
|
1114
|
+
warnings.push(`${file.path}: ${ranges} of ${accepted} dependencies have a version range, not an exact version; they are watched by name only. Commit a lockfile for exact versions.`);
|
|
1115
|
+
else if (ranges)
|
|
1116
|
+
warnings.push(`${file.path}: ${ranges} of ${accepted} dependencies have no exact version; they are watched by name only.${file.ecosystem === 'Maven'
|
|
1117
|
+
? ' Versions inherited from a parent POM or BOM are not resolved here: use Gradle dependency locking, the CycloneDX Maven plugin or Trivy for exact versions (docs/sbom.md).'
|
|
1118
|
+
: ''}`);
|
|
1119
|
+
}
|
|
1120
|
+
// A name-only entry adds nothing where an exact version of the same package is already known.
|
|
1121
|
+
const known = new Set([...versioned.values()].map((entry) => packageKey(entry) ?? `${entry.ecosystem}\0${entry.name}`));
|
|
1122
|
+
const entries = [
|
|
1123
|
+
...versioned.values(),
|
|
1124
|
+
...[...unversioned.entries()].filter(([key]) => !known.has(key)).map(([, entry]) => entry),
|
|
1125
|
+
];
|
|
1126
|
+
if (entries.length > MAX_COMPONENTS)
|
|
1127
|
+
throw new Error(`The project has ${entries.length} packages; at most ${MAX_COMPONENTS} fit one system. Generate one SBOM per service with --project.`);
|
|
1128
|
+
const components = entries
|
|
1129
|
+
.map((entry) => {
|
|
1130
|
+
const purl = packageUrl(entry.ecosystem, entry.name, entry.version);
|
|
1131
|
+
return {
|
|
1132
|
+
type: 'library',
|
|
1133
|
+
'bom-ref': purl,
|
|
1134
|
+
name: entry.name,
|
|
1135
|
+
...(entry.version ? { version: entry.version } : {}),
|
|
1136
|
+
purl,
|
|
1137
|
+
...(entry.dev ? { scope: 'optional' } : {}),
|
|
1138
|
+
evidence: { occurrences: [...entry.locations].sort().map((location) => ({ location })) },
|
|
1139
|
+
};
|
|
1140
|
+
})
|
|
1141
|
+
.sort((a, b) => (a.purl < b.purl ? -1 : a.purl > b.purl ? 1 : 0));
|
|
1142
|
+
const name = text(options.name, 'Name') ?? singleLine(projectName(root, isFile), 200);
|
|
1143
|
+
const id = slug(text(options.systemId, 'System ID') ?? name);
|
|
1144
|
+
if (options.sourceUrl !== undefined) {
|
|
1145
|
+
const url = new URL(options.sourceUrl);
|
|
1146
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash)
|
|
1147
|
+
throw new Error('The source URL must be an HTTPS address without credentials, query or fragment.');
|
|
1148
|
+
}
|
|
1149
|
+
const properties = [
|
|
1150
|
+
['security-watch:system-id', id],
|
|
1151
|
+
['security-watch:owner', text(options.owner, 'Owner')],
|
|
1152
|
+
['security-watch:environment', text(options.environment, 'Environment')],
|
|
1153
|
+
['security-watch:note', text(options.note, 'Note')],
|
|
1154
|
+
['security-watch:exposure', options.exposure],
|
|
1155
|
+
['security-watch:criticality', options.criticality],
|
|
1156
|
+
['security-watch:source-url', options.sourceUrl],
|
|
1157
|
+
['security-watch:source-revision', text(options.sourceRevision, 'Source revision')],
|
|
1158
|
+
]
|
|
1159
|
+
.filter(([, value]) => value !== undefined)
|
|
1160
|
+
.map(([key, value]) => ({ name: key, value: value }));
|
|
1161
|
+
const ecosystems = [...new Set(entries.map((entry) => entry.ecosystem))];
|
|
1162
|
+
const bom = {
|
|
1163
|
+
$schema: 'http://cyclonedx.org/schema/bom-1.6.schema.json',
|
|
1164
|
+
bomFormat: 'CycloneDX',
|
|
1165
|
+
specVersion: '1.6',
|
|
1166
|
+
version: 1,
|
|
1167
|
+
metadata: {
|
|
1168
|
+
timestamp: (options.now ?? new Date()).toISOString(),
|
|
1169
|
+
tools: {
|
|
1170
|
+
components: [
|
|
1171
|
+
{
|
|
1172
|
+
type: 'application',
|
|
1173
|
+
group: '@shieldaai',
|
|
1174
|
+
name: 'security-watch',
|
|
1175
|
+
...(options.toolVersion ? { version: options.toolVersion } : {}),
|
|
1176
|
+
},
|
|
1177
|
+
],
|
|
1178
|
+
},
|
|
1179
|
+
component: { type: 'application', 'bom-ref': `security-watch:system:${id}`, name },
|
|
1180
|
+
properties,
|
|
1181
|
+
},
|
|
1182
|
+
components,
|
|
1183
|
+
};
|
|
1184
|
+
return {
|
|
1185
|
+
bom,
|
|
1186
|
+
system: { id, name },
|
|
1187
|
+
files,
|
|
1188
|
+
ecosystems: ecosystems.sort(),
|
|
1189
|
+
packages: components.length,
|
|
1190
|
+
unversioned: components.filter((component) => component.version === undefined).length,
|
|
1191
|
+
warnings,
|
|
1192
|
+
};
|
|
1193
|
+
}
|