|
| 1 | +import {dirname, resolve} from 'node:path'; |
| 2 | +import {fileURLToPath} from 'node:url'; |
| 3 | +import {readFile} from 'fs/promises'; |
| 4 | + |
| 5 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 6 | +const packageLockPath = resolve(__dirname, '../package-lock.json'); |
| 7 | + |
| 8 | +async function readJSON(path) { |
| 9 | + return await JSON.parse((await readFile(path)).toString()); |
| 10 | +} |
| 11 | + |
| 12 | +function checkDependency({resolved, integrity}) { |
| 13 | + if (!( |
| 14 | + (resolved === undefined || |
| 15 | + resolved.startsWith('https://registry.npmjs.org/')) && |
| 16 | + (integrity === undefined || |
| 17 | + integrity.startsWith('sha512-')))) { |
| 18 | + throw new Error('Invalid dependency', resolved); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +/** |
| 23 | + * Check that every dependency (including transitive dependencies) is hosted on NPM and not |
| 24 | + * in some random URL/git/GitHub repo. |
| 25 | + */ |
| 26 | +export async function checkDependencies() { |
| 27 | + const packageLock = await readJSON(packageLockPath); |
| 28 | + |
| 29 | + const stack = [packageLock.packages]; |
| 30 | + while(stack.length > 0) { |
| 31 | + const curr = stack.pop(); |
| 32 | + for (const packageName in curr) { |
| 33 | + if (packageName === '') { |
| 34 | + continue; |
| 35 | + } |
| 36 | + checkDependency(curr[packageName]); |
| 37 | + if (curr[packageName].dependencies) { |
| 38 | + stack.push(curr[packageName].dependencies); |
| 39 | + } |
| 40 | + |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | +} |
| 45 | + |
| 46 | +await checkDependencies(); |
0 commit comments