Public: anyone can read this; the crew can change it.
A lockfile reader lists every dependency a repository pins, from bun.lock and package-lock.json #17064
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/17046-a-lockfile-reader-lists-every-dependency → main 0 commits fork 2 threads · 2 unresolved
4 files
changed +367
−2
scripts/unreached-allow.json +2 −1
scripts/unused-exports-allow.json +2 −1
src/maintain/lockfiles.ts added +188
| @@ -0,0 +1,188 @@ | ||
| 1 | /** | |
| 2 | * Every dependency a lockfile pins (#17046, part of #6004): given a | |
| 3 | * lockfile's name and text, the packages it locks as | |
| 4 | * `{ecosystem, name, version}`, deduplicated and sorted, ready to be looked up | |
| 5 | * in OSV.dev. Plain data in, plain data out: no file is read and nothing is | |
| 6 | * fetched. A file that does not parse yields no dependencies and a reason | |
| 7 | * naming why; it never throws. | |
| 8 | * | |
| 9 | * Read: `bun.lock` (JSONC, trailing commas allowed: parsed with Bun.JSONC as | |
| 10 | * `checks/fillable.ts` does) and `package-lock.json` (lockfileVersion 2 and 3 | |
| 11 | * from `packages`, version 1 from nested `dependencies`). Only what came from | |
| 12 | * the npm registry is listed: the repository's own code (workspace, link and | |
| 13 | * file entries, the root package) and anything installed from git or a URL | |
| 14 | * (`github:u/r#sha`, `git+ssh://…`, `https://…tgz`) is left out, since OSV | |
| 15 | * matches npm versions and such a spec would read as "no vulnerabilities". | |
| 16 | */ | |
| 17 | ||
| 18 | /** An OSV ecosystem name (https://ossf.github.io/osv-schema/#affectedpackage-field). */ | |
| 19 | export type Ecosystem = "npm"; | |
| 20 | ||
| 21 | export type LockedDependency = { ecosystem: Ecosystem; name: string; version: string }; | |
| 22 | ||
| 23 | /** What a lockfile pins; `reason` is set, and the list empty, when it cannot be read. */ | |
| 24 | export type LockfileRead = { dependencies: LockedDependency[]; reason?: string }; | |
| 25 | ||
| 26 | /** The lockfile names this module reads, by the base name of the path. */ | |
| 27 | const READERS: Record<string, (text: string) => LockfileRead> = { | |
| 28 | "bun.lock": readBunLock, | |
| 29 | "package-lock.json": readPackageLock, | |
| 30 | }; | |
| 31 | ||
| 32 | /** | |
| 33 | * A version as the npm registry publishes it: semver 2.0.0 MAJOR.MINOR.PATCH | |
| 34 | * with optional pre-release and build | |
| 35 | * (https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions). Anything else in a | |
| 36 | * lockfile (workspace:, file:, link:, git, github:, a URL) did not come from the registry. | |
| 37 | */ | |
| 38 | const REGISTRY_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; | |
| 39 | ||
| 40 | /** A package-lock `resolved` that is not a registry tarball: git, a local path. */ | |
| 41 | const NON_REGISTRY_RESOLVED = /^(?:git\+|git:|github:|gitlab:|bitbucket:|file:)/; | |
| 42 | ||
| 43 | /** Every dependency `path`'s lockfile pins, or none and a reason. */ | |
| 44 | export function lockfileDependencies(path: string, text: string): LockfileRead { | |
| 45 | const base = path.slice(path.lastIndexOf("/") + 1); | |
| 46 | const reader = READERS[base]; | |
| 47 | if (!reader) return failed(`${base || "(no name)"} is not a lockfile this reader knows (bun.lock, package-lock.json)`); | |
| 48 | if (typeof text !== "string") return failed(`${base} is not text`); | |
| 49 | try { | |
| 50 | return reader(text); | |
| 51 | } catch { | |
| 52 | // The readers do not recurse; this is a backstop for a hostile input | |
| 53 | // nothing above foresaw, so the promise at the top holds: never a throw. | |
| 54 | return failed(`${base} could not be read`); | |
| 55 | } | |
| 56 | } | |
| 57 | ||
| 58 | /** | |
| 59 | * bun.lock: `packages` maps an install path to `[id, url, info, integrity]`, | |
| 60 | * where id is `name@version` (`@scope/[email protected]`; an npm alias's id names | |
| 61 | * the real package). Workspace members are `name@workspace:path`. | |
| 62 | */ | |
| 63 | function readBunLock(text: string): LockfileRead { | |
| 64 | let parsed: unknown; | |
| 65 | try { | |
| 66 | parsed = Bun.JSONC.parse(text); | |
| 67 | } catch { | |
| 68 | return failed("bun.lock does not parse"); | |
| 69 | } | |
| 70 | if (!isRecord(parsed)) return failed("bun.lock is not an object"); | |
| 71 | const packages = parsed["packages"] ?? {}; | |
| 72 | if (!isRecord(packages)) return failed("bun.lock packages is not an object"); | |
| 73 | const found: LockedDependency[] = []; | |
| 74 | for (const [key, entry] of Object.entries(packages)) { | |
| 75 | if (!Array.isArray(entry) || typeof entry[0] !== "string") return failed(`bun.lock package ${key} has no id`); | |
| 76 | const split = splitId(entry[0]); | |
| 77 | if (!split) return failed(`bun.lock package ${key} id ${entry[0]} is not name@version`); | |
| 78 | if (REGISTRY_VERSION.test(split.version)) found.push({ ecosystem: "npm", ...split }); | |
| 79 | } | |
| 80 | return { dependencies: tidy(found) }; | |
| 81 | } | |
| 82 | ||
| 83 | /** | |
| 84 | * package-lock.json: version 2 and 3 key `packages` by install path | |
| 85 | * (`node_modules/a/node_modules/@s/b`), the root at `""`; an entry's `name` | |
| 86 | * is set when it differs from the path (an alias). Version 1 has only nested | |
| 87 | * `dependencies`, where an alias's version is `npm:[email protected]`. | |
| 88 | */ | |
| 89 | function readPackageLock(text: string): LockfileRead { | |
| 90 | let parsed: unknown; | |
| 91 | try { | |
| 92 | parsed = JSON.parse(text); | |
| 93 | } catch { | |
| 94 | return failed("package-lock.json does not parse"); | |
| 95 | } | |
| 96 | if (!isRecord(parsed)) return failed("package-lock.json is not an object"); | |
| 97 | const found: LockedDependency[] = []; | |
| 98 | if (parsed["packages"] !== undefined) { | |
| 99 | const packages = parsed["packages"]; | |
| 100 | if (!isRecord(packages)) return failed("package-lock.json packages is not an object"); | |
| 101 | for (const [path, entry] of Object.entries(packages)) { | |
| 102 | const at = path.lastIndexOf("node_modules/"); | |
| 103 | if (at < 0) continue; // the root, or a workspace member's own directory | |
| 104 | if (!isRecord(entry)) return failed(`package-lock.json ${path} is not an object`); | |
| 105 | if (entry["link"] === true) continue; | |
| 106 | const name = typeof entry["name"] === "string" ? entry["name"] : path.slice(at + "node_modules/".length); | |
| 107 | const version = entry["version"]; | |
| 108 | if (typeof version !== "string" || !name) return failed(`package-lock.json ${path} has no version`); | |
| 109 | const resolved = entry["resolved"]; | |
| 110 | if (typeof resolved === "string" && NON_REGISTRY_RESOLVED.test(resolved)) continue; | |
| 111 | if (REGISTRY_VERSION.test(version)) found.push({ ecosystem: "npm", name, version }); | |
| 112 | } | |
| 113 | return { dependencies: tidy(found) }; | |
| 114 | } | |
| 115 | const bad = walkV1(parsed["dependencies"] ?? {}, found); | |
| 116 | return bad ? failed(bad) : { dependencies: tidy(found) }; | |
| 117 | } | |
| 118 | ||
| 119 | /** | |
| 120 | * Collect version 1's nested `dependencies` into `found`; the reason when one | |
| 121 | * is malformed. Walked with an explicit stack, not recursion: the nesting is | |
| 122 | * the file's to choose, and JSON.parse accepts far deeper input than the call | |
| 123 | * stack holds. | |
| 124 | */ | |
| 125 | function walkV1(root: unknown, found: LockedDependency[]): string | undefined { | |
| 126 | // Each level keeps a link to its parent, not its spelled-out path: a path | |
| 127 | // string per level would cost memory quadratic in the depth. | |
| 128 | const stack: { deps: unknown; at: Trail | undefined }[] = [{ deps: root, at: undefined }]; | |
| 129 | for (let next = stack.pop(); next; next = stack.pop()) { | |
| 130 | const { deps, at } = next; | |
| 131 | if (!isRecord(deps)) return `package-lock.json ${at ? where(at, ".dependencies") : "dependencies"} is not an object`; | |
| 132 | for (const [key, entry] of Object.entries(deps)) { | |
| 133 | const here: Trail = { key, parent: at }; | |
| 134 | if (!isRecord(entry) || typeof entry["version"] !== "string") return `package-lock.json ${where(here)} has no version`; | |
| 135 | const version = entry["version"]; | |
| 136 | const alias = version.startsWith("npm:") ? splitId(version.slice(4)) : undefined; | |
| 137 | if (alias && REGISTRY_VERSION.test(alias.version)) found.push({ ecosystem: "npm", ...alias }); | |
| 138 | else if (REGISTRY_VERSION.test(version)) found.push({ ecosystem: "npm", name: key, version }); | |
| 139 | if (entry["dependencies"] !== undefined) stack.push({ deps: entry["dependencies"], at: here }); | |
| 140 | } | |
| 141 | } | |
| 142 | return undefined; | |
| 143 | } | |
| 144 | ||
| 145 | /** A package's place in version 1's nesting: its key, and the package it sits under. */ | |
| 146 | type Trail = { key: string; parent: Trail | undefined }; | |
| 147 | ||
| 148 | /** | |
| 149 | * Levels of nesting a reason spells out before eliding the middle, so a hostile file cannot make it | |
| 150 | * long. | |
| 151 | */ | |
| 152 | const WHERE_SHOWN = 6; | |
| 153 | ||
| 154 | /** | |
| 155 | * `dependencies.a.dependencies.b` (then `tail`) for the trail to `b`; past WHERE_SHOWN levels, the | |
| 156 | * last ones after `…`. | |
| 157 | */ | |
| 158 | function where(at: Trail, tail = ""): string { | |
| 159 | const keys: string[] = []; | |
| 160 | let depth = 0; | |
| 161 | for (let t: Trail | undefined = at; t; t = t.parent) if (++depth <= WHERE_SHOWN) keys.push(t.key); | |
| 162 | const path = keys.reverse().join(".dependencies."); | |
| 163 | return depth > WHERE_SHOWN ? `dependencies.….${path}${tail} (${depth} levels deep)` : `dependencies.${path}${tail}`; | |
| 164 | } | |
| 165 | ||
| 166 | /** `@s/[email protected]` → `{name: "@s/b", version: "1.0.0"}`; undefined without a name or a version. */ | |
| 167 | function splitId(id: string): { name: string; version: string } | undefined { | |
| 168 | const at = id.indexOf("@", 1); | |
| 169 | if (at <= 0 || at === id.length - 1) return undefined; | |
| 170 | return { name: id.slice(0, at), version: id.slice(at + 1) }; | |
| 171 | } | |
| 172 | ||
| 173 | /** One entry per name and version, sorted by name then version, so two reads compare equal. */ | |
| 174 | function tidy(found: LockedDependency[]): LockedDependency[] { | |
| 175 | const seen = new Map<string, LockedDependency>(); | |
| 176 | for (const dep of found) seen.set(`${dep.name}@${dep.version}`, dep); | |
| 177 | return [...seen.values()].sort((a, b) => | |
| 178 | a.name === b.name ? (a.version < b.version ? -1 : a.version > b.version ? 1 : 0) : a.name < b.name ? -1 : 1, | |
| 179 | ); | |
| 180 | } | |
| 181 | ||
| 182 | function failed(reason: string): LockfileRead { | |
| 183 | return { dependencies: [], reason }; | |
| 184 | } | |
| 185 | ||
| 186 | function isRecord(value: unknown): value is Record<string, unknown> { | |
| 187 | return typeof value === "object" && value !== null && !Array.isArray(value); | |
| 188 | } |
test/lockfiles.test.ts added +175
| @@ -0,0 +1,175 @@ | ||
| 1 | import { describe, expect, test } from "bun:test"; | |
| 2 | import { lockfileDependencies } from "../src/maintain/lockfiles.ts"; | |
| 3 | ||
| 4 | // A bun.lock as bun 1.2 writes it: JSONC with trailing commas, a workspace | |
| 5 | // member, a scoped package, an alias and the same package at two paths. | |
| 6 | const BUN_LOCK = `{ | |
| 7 | "lockfileVersion": 1, | |
| 8 | "workspaces": { | |
| 9 | "": { "name": "app", "dependencies": { "zod": "^3.23.0", "@types/bun": "1.1.0", "old": "npm:[email protected]", }, }, | |
| 10 | "packages/ui": { "name": "ui", }, | |
| 11 | }, | |
| 12 | "packages": { | |
| 13 | "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.1.0" } }, "sha512-a",], | |
| 14 | "bun-types": ["[email protected]", "", {}, "sha512-b"], | |
| 15 | "old": ["[email protected]", "", {}, "sha512-c"], | |
| 16 | "ui": ["ui@workspace:packages/ui"], | |
| 17 | "zod": ["[email protected]", "", {}, "sha512-d"], | |
| 18 | "ui/zod": ["[email protected]", "", {}, "sha512-d"], | |
| 19 | }, | |
| 20 | } | |
| 21 | `; | |
| 22 | ||
| 23 | const PACKAGE_LOCK_V3 = JSON.stringify({ | |
| 24 | name: "app", | |
| 25 | lockfileVersion: 3, | |
| 26 | packages: { | |
| 27 | "": { name: "app", dependencies: { express: "^4.19.0" } }, | |
| 28 | "node_modules/express": { version: "4.19.2", resolved: "https://registry.npmjs.org/express/-/express-4.19.2.tgz" }, | |
| 29 | "node_modules/express/node_modules/@scope/qs": { version: "6.11.0" }, | |
| 30 | "node_modules/old": { name: "left-pad", version: "1.3.0" }, | |
| 31 | "node_modules/ui": { resolved: "packages/ui", link: true }, | |
| 32 | "packages/ui": { name: "ui", version: "0.0.1" }, | |
| 33 | }, | |
| 34 | }); | |
| 35 | ||
| 36 | const PACKAGE_LOCK_V1 = JSON.stringify({ | |
| 37 | name: "app", | |
| 38 | lockfileVersion: 1, | |
| 39 | dependencies: { | |
| 40 | express: { version: "4.17.1", dependencies: { qs: { version: "6.7.0" } } }, | |
| 41 | old: { version: "npm:[email protected]" }, | |
| 42 | mine: { version: "file:../mine" }, | |
| 43 | }, | |
| 44 | }); | |
| 45 | ||
| 46 | describe("lockfileDependencies", () => { | |
| 47 | test("bun.lock: every registry package once, by its real name; workspace members left out", () => { | |
| 48 | expect(lockfileDependencies("bun.lock", BUN_LOCK)).toEqual({ | |
| 49 | dependencies: [ | |
| 50 | { ecosystem: "npm", name: "@types/bun", version: "1.1.0" }, | |
| 51 | { ecosystem: "npm", name: "bun-types", version: "1.1.0" }, | |
| 52 | { ecosystem: "npm", name: "left-pad", version: "1.3.0" }, | |
| 53 | { ecosystem: "npm", name: "zod", version: "3.23.8" }, | |
| 54 | ], | |
| 55 | }); | |
| 56 | }); | |
| 57 | ||
| 58 | test("package-lock.json v3: nested and scoped paths, aliases by name, links and the root left out", () => { | |
| 59 | expect(lockfileDependencies("web/package-lock.json", PACKAGE_LOCK_V3)).toEqual({ | |
| 60 | dependencies: [ | |
| 61 | { ecosystem: "npm", name: "@scope/qs", version: "6.11.0" }, | |
| 62 | { ecosystem: "npm", name: "express", version: "4.19.2" }, | |
| 63 | { ecosystem: "npm", name: "left-pad", version: "1.3.0" }, | |
| 64 | ], | |
| 65 | }); | |
| 66 | }); | |
| 67 | ||
| 68 | test("package-lock.json v1: nested dependencies walked, npm: aliases resolved, file: left out", () => { | |
| 69 | expect(lockfileDependencies("package-lock.json", PACKAGE_LOCK_V1)).toEqual({ | |
| 70 | dependencies: [ | |
| 71 | { ecosystem: "npm", name: "express", version: "4.17.1" }, | |
| 72 | { ecosystem: "npm", name: "left-pad", version: "1.3.0" }, | |
| 73 | { ecosystem: "npm", name: "qs", version: "6.7.0" }, | |
| 74 | ], | |
| 75 | }); | |
| 76 | }); | |
| 77 | ||
| 78 | test("a malformed file yields no dependencies and a named reason, never a throw", () => { | |
| 79 | expect(lockfileDependencies("bun.lock", '{ "packages": { "a": ')).toEqual({ | |
| 80 | dependencies: [], | |
| 81 | reason: "bun.lock does not parse", | |
| 82 | }); | |
| 83 | expect(lockfileDependencies("package-lock.json", "{ trailing: 1, }")).toEqual({ | |
| 84 | dependencies: [], | |
| 85 | reason: "package-lock.json does not parse", | |
| 86 | }); | |
| 87 | expect(lockfileDependencies("bun.lock", "[]").reason).toBe("bun.lock is not an object"); | |
| 88 | expect(lockfileDependencies("bun.lock", '{"packages":{"a":["noversion"]}}').reason).toBe( | |
| 89 | "bun.lock package a id noversion is not name@version", | |
| 90 | ); | |
| 91 | expect(lockfileDependencies("package-lock.json", '{"packages":{"node_modules/a":{}}}').reason).toBe( | |
| 92 | "package-lock.json node_modules/a has no version", | |
| 93 | ); | |
| 94 | expect(lockfileDependencies("package-lock.json", '{"dependencies":{"a":{"version":1}}}').reason).toBe( | |
| 95 | "package-lock.json dependencies.a has no version", | |
| 96 | ); | |
| 97 | }); | |
| 98 | ||
| 99 | test("a v1 file nested deeper than the call stack is read, not thrown on", () => { | |
| 100 | // ~1.6 MB of nesting: recursion one frame per level raised RangeError here. | |
| 101 | const depth = 100_000; | |
| 102 | const text = '{"dependencies":' + '{"a":{"version":"1.0.0","dependencies":'.repeat(depth) + "{}" + "}}".repeat(depth) + "}"; | |
| 103 | expect(lockfileDependencies("package-lock.json", text)).toEqual({ | |
| 104 | dependencies: [{ ecosystem: "npm", name: "a", version: "1.0.0" }], | |
| 105 | }); | |
| 106 | const bad = '{"dependencies":' + '{"a":{"version":"1.0.0","dependencies":'.repeat(depth) + "[]" + "}}".repeat(depth) + "}"; | |
| 107 | const read = lockfileDependencies("package-lock.json", bad); | |
| 108 | expect(read.dependencies).toEqual([]); | |
| 109 | expect(read.reason).toBe( | |
| 110 | "package-lock.json dependencies.….a.dependencies.a.dependencies.a.dependencies.a.dependencies.a.dependencies.a.dependencies (100000 levels deep) is not an object", | |
| 111 | ); | |
| 112 | }); | |
| 113 | ||
| 114 | test("the error names the nested package it stopped at", () => { | |
| 115 | const text = JSON.stringify({ dependencies: { a: { version: "1.0.0", dependencies: { b: { version: 2 } } } } }); | |
| 116 | expect(lockfileDependencies("package-lock.json", text).reason).toBe( | |
| 117 | "package-lock.json dependencies.a.dependencies.b has no version", | |
| 118 | ); | |
| 119 | }); | |
| 120 | ||
| 121 | test("git, github and URL installs are not npm versions and are left out, so OSV is never asked about them", () => { | |
| 122 | const bun = JSON.stringify({ | |
| 123 | packages: { | |
| 124 | gh: ["gh@github:user/repo#0123abc", {}, "0123abc"], | |
| 125 | git: ["git@git+ssh://[email protected]/r.git#0123abc", {}, "0123abc"], | |
| 126 | tgz: ["tgz@https://example.com/tgz-1.0.0.tgz", {}], | |
| 127 | tag: ["tag@latest", {}], | |
| 128 | ok: ["[email protected]+build.5", "", {}, "sha512-e"], | |
| 129 | }, | |
| 130 | }); | |
| 131 | expect(lockfileDependencies("bun.lock", bun)).toEqual({ | |
| 132 | dependencies: [{ ecosystem: "npm", name: "ok", version: "1.2.3-beta.1+build.5" }], | |
| 133 | }); | |
| 134 | const v1 = JSON.stringify({ | |
| 135 | dependencies: { | |
| 136 | gh: { version: "github:user/repo#0123abc" }, | |
| 137 | git: { version: "git+ssh://[email protected]/r.git#0123abc" }, | |
| 138 | tgz: { version: "https://example.com/tgz-1.0.0.tgz" }, | |
| 139 | alias: { version: "npm:real@github:user/repo" }, | |
| 140 | ok: { version: "2.0.0" }, | |
| 141 | }, | |
| 142 | }); | |
| 143 | expect(lockfileDependencies("package-lock.json", v1)).toEqual({ | |
| 144 | dependencies: [{ ecosystem: "npm", name: "ok", version: "2.0.0" }], | |
| 145 | }); | |
| 146 | // v2/v3 write the package.json version for a git install; `resolved` says where it came from. | |
| 147 | const v3 = JSON.stringify({ | |
| 148 | lockfileVersion: 3, | |
| 149 | packages: { | |
| 150 | "node_modules/gh": { version: "1.0.0", resolved: "git+ssh://[email protected]/user/repo.git#0123abc" }, | |
| 151 | "node_modules/url": { version: "https://example.com/url-1.0.0.tgz" }, | |
| 152 | "node_modules/ok": { version: "3.0.0", resolved: "https://registry.npmjs.org/ok/-/ok-3.0.0.tgz" }, | |
| 153 | }, | |
| 154 | }); | |
| 155 | expect(lockfileDependencies("package-lock.json", v3)).toEqual({ | |
| 156 | dependencies: [{ ecosystem: "npm", name: "ok", version: "3.0.0" }], | |
| 157 | }); | |
| 158 | }); | |
| 159 | ||
| 160 | test("a file it does not know is named, not guessed at", () => { | |
| 161 | expect(lockfileDependencies("yarn.lock", "a@1:\n version 1\n")).toEqual({ | |
| 162 | dependencies: [], | |
| 163 | reason: "yarn.lock is not a lockfile this reader knows (bun.lock, package-lock.json)", | |
| 164 | }); | |
| 165 | }); | |
| 166 | ||
| 167 | test("an empty lockfile pins nothing and is not an error", () => { | |
| 168 | expect(lockfileDependencies("bun.lock", '{ "lockfileVersion": 1, "workspaces": { "": {} }, }')).toEqual({ | |
| 169 | dependencies: [], | |
| 170 | }); | |
| 171 | expect(lockfileDependencies("package-lock.json", '{"lockfileVersion":3,"packages":{"":{}}}')).toEqual({ | |
| 172 | dependencies: [], | |
| 173 | }); | |
| 174 | }); | |
| 175 | }); |
new above
offline
Only workspace/link/file are excluded. git:, github:, http(s):, git+ssh: and similar specs will be passed to OSV as npm versions. Exclude every non-registry spec.