Files

34 lines
2.4 KiB
Bash

#!/usr/bin/env bash
# usage: osv.sh <package-lock.json | third_party/editor/PROVENANCE.json> [out.json]
# Batch-queries OSV (https://api.osv.dev/v1/querybatch) for every npm package in the file and prints
# [{pkg, version, vulns[]}]. A PROVENANCE.json is read as its package list (name, version): the imported editor
# source is not in any lockfile, so the lockfile scan alone would not see it.
# Before it queries the file it runs a positive control: two versions with known advisories must come back with at
# least the recorded counts (dompurify 2.3.3 >= 20, markdown-it 12.2.0 >= 3, counts of 2026-10-18). If OSV returns
# fewer, the query path is broken and a clean result for the real file would mean nothing, so the script exits 3.
set -euo pipefail
input=$(realpath "$1")
out=${2:-/dev/stdout}
tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
to_queries() { # stdin: lock or provenance JSON
jq -c 'if (.packages | type) == "array"
then {queries: [.packages[] | {package:{ecosystem:"npm", name:.name}, version:.version}]}
else {queries: [.packages | to_entries[] | select(.key != "") | {package:{ecosystem:"npm", name:(.key | sub("^.*node_modules/";""))}, version:.value.version}]} end'
}
query() { # $1 request file -> stdout response
curl -sS --fail --max-time 60 -H 'content-type: application/json' -d @"$1" https://api.osv.dev/v1/querybatch
}
# Positive control: the shape a lock would have, with versions OSV is known to flag.
jq -n '{packages: {"": {}, "node_modules/dompurify": {version: "2.3.3"}, "node_modules/markdown-it": {version: "12.2.0"}}}' | to_queries > "$tmp/control-req.json"
query "$tmp/control-req.json" > "$tmp/control-resp.json"
read -r dompurify markdown_it < <(jq -r '[(.results[0].vulns // [] | length), (.results[1].vulns // [] | length)] | @tsv' "$tmp/control-resp.json")
echo "positive control: dompurify 2.3.3 -> $dompurify advisories (need >= 20), markdown-it 12.2.0 -> $markdown_it (need >= 3)" >&2
if [ "${dompurify:-0}" -lt 20 ] || [ "${markdown_it:-0}" -lt 3 ]; then echo "positive control FAILED: the OSV query returned too few advisories" >&2; exit 3; fi
to_queries < "$input" > "$tmp/req.json"
query "$tmp/req.json" > "$tmp/resp.json"
jq -n --slurpfile q "$tmp/req.json" --slurpfile r "$tmp/resp.json" \
'[range(0; $q[0].queries|length) as $i | {pkg: $q[0].queries[$i].package.name, version: $q[0].queries[$i].version, vulns: [$r[0].results[$i].vulns[]?.id]}]' > "$out"