forked from AlextheYounga/keyv_scan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpackage_inventory.js
More file actions
380 lines (326 loc) · 11.3 KB
/
Copy pathpackage_inventory.js
File metadata and controls
380 lines (326 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
'use strict';
const fs = require('fs');
const path = require('path');
const [, , csvFile, mode, target] = process.argv;
if (!csvFile || !mode || !target) {
process.stderr.write('Usage: package_inventory.js <packages.csv> <mode> <path>\n');
process.exit(2);
}
function loadAffected(file) {
const affected = new Set();
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
for (const line of lines.slice(1)) {
if (!line.trim()) continue;
const comma = line.indexOf(',');
if (comma === -1) continue;
const packageName = line.slice(0, comma).trim();
const versions = line.slice(comma + 1);
for (const match of versions.matchAll(/==\s*([^|,\s]+)/g)) {
affected.add(`${packageName}\0${match[1]}`);
}
}
return affected;
}
const affected = loadAffected(csvFile);
const findings = new Set();
function record(packageName, version) {
if (typeof packageName !== 'string' || typeof version !== 'string') return;
const key = `${packageName}\0${version}`;
if (affected.has(key)) findings.add(key);
}
function readJson(file) {
try {
return JSON.parse(fs.readFileSync(file, 'utf8'));
} catch (error) {
if (error.code === 'ENOENT') return null;
// Cache stores can contain arbitrary JSON-like project files. A malformed
// unrelated file must not make the package scan incomplete.
if (error instanceof SyntaxError) return null;
throw new Error(`cannot read ${file}: ${error.message}`);
}
}
function realDirectory(directory) {
try {
const realPath = fs.realpathSync(directory);
return fs.statSync(realPath).isDirectory() ? realPath : null;
} catch {
return null;
}
}
function scanNodeModules(directory, visited = new Set()) {
const realPath = realDirectory(directory);
if (!realPath || visited.has(realPath)) return;
visited.add(realPath);
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch (error) {
throw new Error(`cannot read ${directory}: ${error.message}`);
}
for (const entry of entries) {
if (entry.name === '.bin') continue;
const entryPath = path.join(realPath, entry.name);
if (entry.name === '.pnpm') {
scanPnpmVirtualStore(entryPath, visited);
} else if (entry.name.startsWith('@')) {
scanScope(entryPath, visited);
} else {
scanPackage(entryPath, visited);
}
}
}
function scanScope(directory, visited) {
const realPath = realDirectory(directory);
if (!realPath) return;
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch (error) {
throw new Error(`cannot read ${directory}: ${error.message}`);
}
for (const entry of entries) {
scanPackage(path.join(realPath, entry.name), visited);
}
}
function scanPackage(directory, visited) {
const realPath = realDirectory(directory);
if (!realPath) return;
const manifest = readJson(path.join(realPath, 'package.json'));
if (manifest) record(manifest.name, manifest.version);
scanNodeModules(path.join(realPath, 'node_modules'), visited);
}
function scanPnpmVirtualStore(directory, visited) {
const realPath = realDirectory(directory);
if (!realPath || visited.has(realPath)) return;
visited.add(realPath);
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch (error) {
throw new Error(`cannot read ${directory}: ${error.message}`);
}
for (const entry of entries) {
scanNodeModules(path.join(realPath, entry.name, 'node_modules'), visited);
}
}
function scanPackageTree(directory) {
const root = realDirectory(directory);
if (!root) return;
const stack = [root];
const visited = new Set();
while (stack.length) {
const current = stack.pop();
const realPath = realDirectory(current);
if (!realPath || visited.has(realPath)) continue;
visited.add(realPath);
const manifest = readJson(path.join(realPath, 'package.json'));
if (manifest) record(manifest.name, manifest.version);
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch (error) {
throw new Error(`cannot read ${current}: ${error.message}`);
}
for (const entry of entries) {
if (entry.isDirectory() || entry.isSymbolicLink()) {
stack.push(path.join(realPath, entry.name));
}
}
}
}
function scanNpmCache(file) {
const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
for (const line of lines) {
let decoded = line;
try {
decoded = decodeURIComponent(line);
} catch {
// Keep the original cache key when it is not URL encoded.
}
const match = decoded.match(/\/(?:registry\.npmjs\.org\/)?(@[^/]+\/[^/]+|[^/]+)\/-\/([^/?#]+)\.tgz(?:[?#]|$)/);
if (!match) continue;
const packageName = match[1];
const baseName = packageName.slice(packageName.lastIndexOf('/') + 1);
const prefix = `${baseName}-`;
if (match[2].startsWith(prefix)) {
record(packageName, match[2].slice(prefix.length));
}
}
}
function inspectMetadata(value, seen = new Set()) {
if (!value || typeof value !== 'object' || seen.has(value)) return;
seen.add(value);
record(value.name, value.version);
for (const child of Object.values(value)) inspectMetadata(child, seen);
}
function walkFiles(directory, visitor, skipDirectory) {
const root = realDirectory(directory);
if (!root) return;
const stack = [root];
const visited = new Set();
while (stack.length) {
const current = stack.pop();
const realPath = realDirectory(current);
if (!realPath || visited.has(realPath)) continue;
visited.add(realPath);
let entries;
try {
entries = fs.readdirSync(realPath, { withFileTypes: true });
} catch (error) {
throw new Error(`cannot read ${current}: ${error.message}`);
}
for (const entry of entries) {
const entryPath = path.join(realPath, entry.name);
if (entry.isDirectory() || entry.isSymbolicLink()) {
if (!skipDirectory || !skipDirectory(entry.name)) stack.push(entryPath);
} else visitor(entryPath, entry.name);
}
}
}
function scanPnpmStore(directory) {
walkFiles(directory, (file, name) => {
if (!name.endsWith('.json')) return;
const metadata = readJson(file);
if (metadata) inspectMetadata(metadata);
for (const key of affected) {
const [packageName, version] = key.split('\0');
const storeName = packageName.replace('/', '+');
if (name.endsWith(`-${storeName}@${version}.json`)) {
record(packageName, version);
}
}
});
}
function scanYarnCache(directory) {
walkFiles(directory, (file, name) => {
if (name === 'package.json') {
const manifest = readJson(file);
if (manifest) record(manifest.name, manifest.version);
return;
}
if (!name.endsWith('.zip')) return;
for (const key of affected) {
const [packageName, version] = key.split('\0');
const archivePrefix = `${packageName.replace('/', '-')}-npm-${version}-`;
if (name.startsWith(archivePrefix)) record(packageName, version);
}
});
}
// Lockfiles pin exact versions, so an affected release can be recorded in a
// project that has not installed its dependencies yet. Nothing is present on
// disk to find, but the next install resolves to the affected version.
function scanNpmLockfile(file) {
const lockfile = readJson(file);
if (!lockfile) return;
// lockfileVersion 2 and 3 key every package by its install path.
for (const [installPath, meta] of Object.entries(lockfile.packages || {})) {
if (!meta || typeof meta !== 'object' || typeof meta.version !== 'string') continue;
const marker = 'node_modules/';
const index = installPath.lastIndexOf(marker);
const name = meta.name || (index === -1 ? '' : installPath.slice(index + marker.length));
record(name, meta.version);
}
// lockfileVersion 1 nests dependencies instead.
(function walkDependencies(dependencies) {
for (const [name, meta] of Object.entries(dependencies || {})) {
if (!meta || typeof meta !== 'object') continue;
record(name, meta.version);
walkDependencies(meta.dependencies);
}
})(lockfile.dependencies);
}
// Accepts every pnpm and Yarn Berry descriptor shape seen in the wild:
// name@1.2.3, @scope/name@1.2.3, /name/1.2.3, /@scope/name/1.2.3, and any of
// those carrying a (peer@1.0.0) suffix or an npm: protocol prefix.
function parseDescriptor(descriptor) {
let token = descriptor.trim().replace(/\(.*$/, '');
if (token.startsWith('/')) token = token.slice(1);
token = token.replace(/@npm(?::|%3A)/i, '@');
const at = token.lastIndexOf('@');
if (at > 0) {
const version = token.slice(at + 1);
if (/^\d/.test(version)) return [token.slice(0, at), version];
}
const slash = token.lastIndexOf('/');
if (slash > 0 && /^\d/.test(token.slice(slash + 1))) {
return [token.slice(0, slash), token.slice(slash + 1)];
}
return null;
}
function scanPnpmLockfile(file) {
const text = fs.readFileSync(file, 'utf8');
// Entry keys are the only indented, colon-terminated lines that carry a
// version, across lockfile versions 5 through 9.
for (const [, descriptor] of text.matchAll(/^\s{2,}'?([^'\s#][^'\n]*?)'?:\s*$/gm)) {
const parsed = parseDescriptor(descriptor);
if (parsed) record(parsed[0], parsed[1]);
}
}
function scanYarnLockfile(file) {
const text = fs.readFileSync(file, 'utf8');
let names = [];
for (const line of text.split(/\r?\n/)) {
if (!line.trim() || line.trimStart().startsWith('#')) continue;
// A descriptor header is unindented; one header can list several ranges.
if (!/^\s/.test(line) && line.trimEnd().endsWith(':')) {
names = line
.trimEnd()
.slice(0, -1)
.split(',')
.map((entry) => {
const token = entry.trim().replace(/^"|"$/g, '');
const at = token.lastIndexOf('@');
return at > 0 ? token.slice(0, at) : token;
})
.filter(Boolean);
continue;
}
// Yarn Classic quotes the version, Yarn Berry does not.
const match = line.match(/^\s+version:?\s+"?([^"\s]+)"?\s*$/);
if (match) for (const name of names) record(name, match[1]);
}
}
function scanLockfiles(directory) {
walkFiles(
directory,
(file, name) => {
if (name === 'package-lock.json' || name === 'npm-shrinkwrap.json') scanNpmLockfile(file);
else if (name === 'pnpm-lock.yaml') scanPnpmLockfile(file);
else if (name === 'yarn.lock') scanYarnLockfile(file);
},
// Lockfiles vendored inside a dependency describe that dependency's own
// development tree, not what this project installs. The installed tree is
// already covered by the node-modules mode.
(name) => name === 'node_modules' || name === '.git'
);
}
try {
switch (mode) {
case 'node-modules':
scanNodeModules(target);
break;
case 'package-tree':
scanPackageTree(target);
break;
case 'npm-cache':
scanNpmCache(target);
break;
case 'pnpm-store':
scanPnpmStore(target);
break;
case 'yarn-cache':
scanYarnCache(target);
break;
case 'lockfiles':
scanLockfiles(target);
break;
default:
throw new Error(`unknown scan mode: ${mode}`);
}
for (const key of [...findings].sort()) {
process.stdout.write(`${key.replace('\0', '\t')}\n`);
}
} catch (error) {
process.stderr.write(`Inventory error: ${error.message}\n`);
process.exit(2);
}