-
Notifications
You must be signed in to change notification settings - Fork 0
Add audit command to scan packages for security advisories #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
250f01d
feat: add audit command
claude af07d7e
audit: render results in a boxed table
claude 42fa021
audit: parse via Bundle and Lockfile classes
claude 3b0a779
audit: read modules from new v1 bundle format
claude da91ad4
audit: address copilot review
claude 5def705
audit: address subagent review
claude 6064f7c
audit: support resource bundles and friendly missing-file error
claude e0c94bd
audit: address second-pass review findings
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,149 @@ | ||
| import { readFileSync } from 'node:fs' | ||
| import { brotliDecompressSync } from 'node:zlib' | ||
|
|
||
| import { advisories } from './apis/npm/index.js' | ||
| import semver from './apis/npm/semver.cjs' | ||
| import { Bundle } from './bundle.js' | ||
| import { Lockfile } from './lockfile.js' | ||
|
|
||
| function parseFile(file) { | ||
| let buf | ||
| try { | ||
| buf = readFileSync(file) | ||
| } catch (cause) { | ||
| if (cause.code === 'ENOENT') throw new Error(`File not found: ${file}`, { cause }) | ||
| throw new Error(`Failed to read ${file}: ${cause.message}`, { cause }) | ||
| } | ||
| // Lockfiles are JSON text starting with `{`; code/resource bundles are | ||
| // brotli-compressed JSON. Sniff to route to the right parser so its | ||
| // diagnostic surfaces on failure. | ||
| if (buf[0] === 0x7b /* '{' */) { | ||
| try { | ||
| return Lockfile.parse(buf.toString('utf8')) | ||
| } catch (cause) { | ||
| throw new Error(`Failed to parse stasis lockfile: ${file}`, { cause }) | ||
| } | ||
| } | ||
| let text | ||
| try { | ||
| text = brotliDecompressSync(buf).toString('utf8') | ||
| } catch (cause) { | ||
| throw new Error(`Failed to read ${file} as a stasis bundle (not brotli)`, { cause }) | ||
| } | ||
| // Code bundles carry `formats`/`imports`; resource bundles don't. Route on shape. | ||
| try { | ||
| const isCode = JSON.parse(text).formats !== undefined | ||
| return isCode ? Bundle.parseCode(text) : Bundle.parseResources(text) | ||
| } catch (cause) { | ||
| throw new Error(`Failed to parse stasis bundle: ${file}`, { cause }) | ||
| } | ||
| } | ||
|
|
||
| // Only audit installed dependencies; workspace/first-party packages live under | ||
| // non-`node_modules` keys in .modules (Lockfile/Bundle merge sources in) and | ||
| // shouldn't be sent to the public registry — they leak names and produce noise. | ||
| export function collectPackagesFromFile(file) { | ||
| const out = [] | ||
| for (const [dir, { name, version }] of parseFile(file).modules) { | ||
| if (!dir.includes('node_modules')) continue | ||
| if (name && version) out.push({ name, version }) | ||
| } | ||
| return out | ||
| } | ||
|
|
||
| export function collectPackages(files) { | ||
| const seen = new Set() | ||
| const out = [] | ||
| for (const file of files) { | ||
| for (const { name, version } of collectPackagesFromFile(file)) { | ||
| const key = `${name}@${version}` | ||
| if (seen.has(key)) continue | ||
| seen.add(key) | ||
| out.push({ name, version }) | ||
| } | ||
| } | ||
| return out.sort((a, b) => a.name.localeCompare(b.name) || semver.compare(a.version, b.version)) | ||
| } | ||
|
|
||
| const SEVERITY_ORDER = { critical: 0, high: 1, moderate: 2, low: 3, info: 4, none: 5 } | ||
|
|
||
| export function flattenAdvisories(result, packages = []) { | ||
| const installed = new Map() | ||
| for (const { name, version } of packages) { | ||
| if (!installed.has(name)) installed.set(name, []) | ||
| installed.get(name).push(version) | ||
| } | ||
| const rows = [] | ||
| for (const [pkg, list] of Object.entries(result)) { | ||
| if (!Array.isArray(list)) continue | ||
| const installedVersions = installed.get(pkg) ?? [] | ||
| for (const adv of list) { | ||
| const range = adv.vulnerable_versions ?? '' | ||
| const affected = range | ||
| ? installedVersions.filter((v) => semver.satisfies(v, range)) | ||
| : installedVersions | ||
| // npm occasionally returns advisories whose vulnerable range matches none | ||
| // of the versions we submitted; drop them so the table (and the CLI exit | ||
| // code) reflect only real hits. | ||
| if (installedVersions.length > 0 && affected.length === 0) continue | ||
| rows.push({ | ||
| package: pkg, | ||
| installed: affected.join(', '), | ||
| vulnerable: range, | ||
| severity: adv.severity ?? '', | ||
| title: adv.title ?? '', | ||
| url: adv.url ?? '', | ||
| }) | ||
| } | ||
| } | ||
| rows.sort((a, b) => { | ||
| const sa = SEVERITY_ORDER[a.severity] ?? 99 | ||
| const sb = SEVERITY_ORDER[b.severity] ?? 99 | ||
| if (sa !== sb) return sa - sb | ||
| if (a.package !== b.package) return a.package < b.package ? -1 : 1 | ||
| return a.title < b.title ? -1 : 1 | ||
| }) | ||
| return rows | ||
| } | ||
|
|
||
| // Line breaks in npm advisory titles would otherwise break the box layout. | ||
| // Covers LF, bare CR (and CRLF), and U+2028 / U+2029 line/paragraph separators. | ||
| const cell = (v) => String(v ?? '').replace(/[\r\n\u2028\u2029]+/gu, ' ') | ||
|
|
||
| export function formatTable(rows, columns) { | ||
| if (rows.length === 0) return '' | ||
| const widths = columns.map((c) => Math.max(c.length, ...rows.map((r) => cell(r[c]).length))) | ||
| const pad = (s, w) => s.padEnd(w) | ||
| const line = (l, m, r, fill) => l + widths.map((w) => fill.repeat(w + 2)).join(m) + r | ||
| const row = (vals) => '│ ' + vals.map((v, i) => pad(cell(v), widths[i])).join(' │ ') + ' │' | ||
| return [ | ||
| line('┌', '┬', '┐', '─'), | ||
| row(columns), | ||
| line('├', '┼', '┤', '─'), | ||
| ...rows.map((r) => row(columns.map((c) => r[c]))), | ||
| line('└', '┴', '┘', '─'), | ||
| ].join('\n') | ||
| } | ||
|
|
||
| export async function audit(files) { | ||
| const packages = collectPackages(files) | ||
| if (packages.length === 0) { | ||
| return { packages, advisories: {}, rows: [] } | ||
| } | ||
| const result = await advisories(packages) | ||
|
ChALkeR marked this conversation as resolved.
ChALkeR marked this conversation as resolved.
ChALkeR marked this conversation as resolved.
|
||
| const rows = flattenAdvisories(result, packages) | ||
| return { packages, advisories: result, rows } | ||
| } | ||
|
|
||
| export function printAuditReport({ packages, rows }, { out = process.stdout, err = process.stderr } = {}) { | ||
| err.write(`Scanned ${packages.length} package${packages.length === 1 ? '' : 's'}\n`) | ||
| if (packages.length === 0) { | ||
| err.write('No node_modules entries found in the input files\n') | ||
| return | ||
| } | ||
| if (rows.length === 0) { | ||
| err.write('No advisories found\n') | ||
| return | ||
| } | ||
| out.write(formatTable(rows, ['severity', 'package', 'installed', 'vulnerable', 'title', 'url']) + '\n') | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.