Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion bin/stasis.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ function usage(prefix = '') {
stasis run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|ignore)] [--bundle-file=path/to/bundle.br] [--full] path/to/file.js ...
stasis bundle create path/to/lockfile
stasis bundle verify path/to/lockfile
stasis advisories path/to/lockfile
stasis prune [path/to/project]
stasis audit path/to/file ...
`.trim())
process.exit(1)
}
Expand Down Expand Up @@ -80,6 +80,13 @@ if (command === 'run') {
const { prune } = await import('../src/prune.js')
const { removed, validated } = prune({ root })
console.warn(`[stasis] prune: validated ${validated.length} file(s), removed ${removed.length} file(s)`)
} else if (command === 'audit') {
if (argv.length === 0) usage('Nothing to audit: no path to file given')
const { audit, printAuditReport } = await import('../src/audit.js')
const files = argv.map((f) => resolve(f))
const report = await audit(files)
printAuditReport(report)
process.exitCode = report.rows.length === 0 ? 0 : 1
} else {
usage()
}
26 changes: 17 additions & 9 deletions src/apis/npm/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import semver from './semver.cjs'

const packageNameRegex = /^(@[\da-z-]+\/)?[\w-]+(\.[\w-]+)*$/u

export async function advisories(list) {
export async function advisories(list, { signal = AbortSignal.timeout(30_000) } = {}) {
const groups = new Map()
for (const { name, version } of list) {
assert(name && version && typeof name === 'string' && typeof version === 'string')
assert(typeof name === 'string' && typeof version === 'string')
assert(packageNameRegex.test(name), `Unexpected package name: ${name}`)
assert(semver.valid(version), `Invalid version: ${version}`)
if (!groups.has(name)) groups.set(name, new Set())
Expand All @@ -17,12 +17,20 @@ export async function advisories(list) {
const entries = [...groups].map(([k, v]) => [k, [...v].sort((a, b) => semver.compare(a, b))])
const body = Object.fromEntries(entries.sort((a, b) => a[0] < b[0] ? -1 : 1))

const res = await fetch('https://registry.npmjs.org/-/npm/v1/security/advisories/bulk', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})

assert(res.ok)
let res
try {
res = await fetch('https://registry.npmjs.org/-/npm/v1/security/advisories/bulk', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
signal,
})
} catch (cause) {
throw new Error(`npm advisories request failed: ${cause.message}`, { cause })
}
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`npm advisories request failed: ${res.status} ${res.statusText}${text ? ` — ${text.slice(0, 200)}` : ''}`)
}
return res.json()
}
149 changes: 149 additions & 0 deletions src/audit.js
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 ?? '',
Comment thread
ChALkeR marked this conversation as resolved.
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)
Comment thread
ChALkeR marked this conversation as resolved.
Comment thread
ChALkeR marked this conversation as resolved.
Comment thread
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')
}
Loading
Loading