@preventive/upstream 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,75 @@
1
+ import { assertRepo, assertion, isRefName, isSha } from '../args.js'
2
+ import { valid, validRange } from '../semver.js'
3
+ import { inRange, overlap } from './common.js'
4
+ import { bySemver, coversPlaceholder, repositoryAdvisories } from './github.js'
5
+ import { packageRecords, toAdvisory } from './osv.js'
6
+
7
+ const ACTIONS = 'GitHub Actions'
8
+
9
+ // OSV's `1.2` is 1.2.0, not semver's 1.2.x.
10
+ const full = (version) => (/^\d+(?:\.\d+)?$/u.test(version) ? `${version}.0.0`.split('.').slice(0, 3).join('.') : version)
11
+
12
+ // OSV can't match these versions itself: its records' ECOSYSTEM ranges, as
13
+ // semver's, and whether one is still open, no release having fixed it.
14
+ function readAffected(entry) {
15
+ const ranges = []
16
+ let open = false
17
+ for (const { type, events } of entry.ranges ?? []) {
18
+ if (type !== 'ECOSYSTEM' || !Array.isArray(events)) continue
19
+ let from
20
+ for (const event of events) {
21
+ if (typeof event?.introduced === 'string') from = full(event.introduced)
22
+ else if (from !== undefined && (typeof event?.fixed === 'string' || typeof event?.last_affected === 'string')) {
23
+ ranges.push(event.fixed === undefined ? `>=${from} <=${full(event.last_affected)}` : `>=${from} <${full(event.fixed)}`)
24
+ from = undefined
25
+ }
26
+ }
27
+ if (from !== undefined) ranges.push(`>=${from}`)
28
+ open ||= from !== undefined
29
+ }
30
+ const listed = new Set((Array.isArray(entry.versions) ? entry.versions : []).map((version) => full(String(version).replace(/^v/iu, ''))))
31
+ // Listed versions alone, or with neither, every version.
32
+ if (ranges.length === 0) return { listed, range: null, open: listed.size === 0, all: listed.size === 0 }
33
+ const range = ranges.join(' || ')
34
+ // A range semver can't read covers every version.
35
+ return { listed, range, open, all: validRange(range, { loose: true }) === null }
36
+ }
37
+
38
+ const isPartial = (tag) => /^\d+(?:\.\d+)?$/u.test(tag)
39
+
40
+ // A commit may be of any release. A branch, or stasis's 0.0.0, is at its
41
+ // newest, so only what no release has fixed covers it. A moving tag, `v4`
42
+ // or `v4.1`, may be anywhere in its line.
43
+ function covers(version, { listed, range, open, all }) {
44
+ if (isSha(version)) return true
45
+ const tag = version.replace(/^v/iu, '')
46
+ if (version === '0.0.0' || (!isPartial(tag) && valid(tag, { loose: true }) === null)) return open
47
+ if (all) return true
48
+ if (isPartial(tag)) return [...listed].some((listedVersion) => inRange(listedVersion, `${tag}.x`)) || (range !== null && overlap(range, `${tag}.x`))
49
+ return listed.has(tag) || (range !== null && inRange(tag, range))
50
+ }
51
+
52
+ async function actionRows(asked, details) {
53
+ const rows = []
54
+ for (const { record, names } of await packageRecords(ACTIONS, [...asked.keys()])) {
55
+ for (const name of names) {
56
+ const entries = (record.affected ?? []).filter((entry) => entry?.package?.ecosystem === ACTIONS && entry.package.name === name).map(readAffected)
57
+ const versions = asked.get(name).filter((version) => entries.some((entry) => covers(version, entry)))
58
+ if (versions.length > 0) rows.push(toAdvisory(ACTIONS, name, versions, record, details))
59
+ }
60
+ }
61
+ return rows
62
+ }
63
+
64
+ // GitHub repositories as dependencies: OSV's records of them as Actions,
65
+ // and every range their own advisories list, whichever package it names.
66
+ export const GITHUB = {
67
+ repositoryOnly: true,
68
+ assertName: assertRepo,
69
+ nameKey: (repo) => repo.toLowerCase(),
70
+ assertVersion: assertion('a version or a branch name', isRefName),
71
+ advisories: async (asked, { github, details, cache }) => (await Promise.all([
72
+ actionRows(asked, details),
73
+ repositoryAdvisories(github, asked, { repoOf: (repo) => repo, versionsIn: bySemver(coversPlaceholder), details, cache }),
74
+ ])).flat(),
75
+ }
@@ -1,13 +1,11 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
3
  import { isGhsa, isRepo, isStrings, matches, show } from '../args.js'
4
- import { satisfies, valid, validRange } from '../semver.js'
4
+ import { intersects, satisfies, valid, validRange } from '../semver.js'
5
5
 
6
6
  export const order = (a, b) => (a > b) - (a < b)
7
7
 
8
- // GitHub's page for a GHSA: the advisory database's, which has every one
9
- // the registry and OSV answer with, or the page of the `repo` that
10
- // published it, which has it before GitHub reviews it into the database.
8
+ // The repository's page for a GHSA where `repo` is given, else the database's.
11
9
  export function advisoryUrl(ghsa, repo) {
12
10
  assert.ok(isGhsa(ghsa) && (repo === undefined || isRepo(repo)), `advisories: no GitHub advisory page for ${show(ghsa)} on ${show(repo)}`)
13
11
  return repo === undefined ? `https://github.com/advisories/${ghsa}` : `https://github.com/${repo}/security/advisories/${ghsa}`
@@ -18,39 +16,37 @@ const SEMVER = { includePrerelease: true, loose: true }
18
16
 
19
17
  export const inRange = (version, range) => satisfies(version, range, SEMVER)
20
18
 
21
- // A version semver cannot read may be in any range. Whatever it reads is
22
- // a version, `v1.2.3` and `1.2.3+build` included.
19
+ // A version semver can't read may be in any range.
23
20
  export const mayBeInRange = (version, range) => valid(version) === null || inRange(version, range)
24
21
 
25
- // The asked versions a range `covers`. One semver cannot read, range or
26
- // version, covers them all: a missed advisory is worse than a spare one.
22
+ export const overlap = (a, b) => validRange(a, SEMVER) !== null && intersects(a, b, SEMVER)
23
+
24
+ // One set with no upper bound, as `>= 0` and `*` are.
25
+ const HIGHEST = `${Number.MAX_SAFE_INTEGER}.${Number.MAX_SAFE_INTEGER}.${Number.MAX_SAFE_INTEGER}`
26
+ export const isOpenAbove = (range) => !range.includes('|') && inRange(HIGHEST, range)
27
+
28
+ // A range or version semver can't read covers every version: a missed
29
+ // advisory is worse than a spare one.
27
30
  export const covered = (asked, range, covers = mayBeInRange) => (validRange(range, SEMVER) === null ? [...asked] : asked.filter((version) => covers(version, range)))
28
31
 
29
- // Remote text, as long as it is well-formed; anything else is refused as
30
- // malformed by whoever reads it.
31
32
  export const isText = (value) => typeof value === 'string' && value.isWellFormed()
32
33
 
33
- // An advisory's full text, for `details`: none where its source has none,
34
- // and refused where it is not well-formed.
35
34
  export function detailsOf(text, id) {
36
35
  if (text == null || text === '') return {}
37
36
  assert.ok(isText(text), `advisories: malformed details in ${id}`)
38
37
  return { details: text }
39
38
  }
40
39
 
41
- // Malware, not a vulnerability: an OSV MAL- record (by id or alias),
42
- // CWE-506 (how GitHub files malware), or a title with the word "malware"
43
- // (@solana/web3.js's GHSA-jcxm-7wvp-g6p5 has only CWE-200). The same rule
44
- // as triage's npmMalwareAdvisory.
40
+ // MAL- records, CWE-506 (how GitHub files malware), or "malware" in the
41
+ // title (@solana/web3.js's GHSA-jcxm-7wvp-g6p5 has only CWE-200).
45
42
  export const isMalware = ({ id, aliases, cwe, title }) => [id, ...aliases].some((each) => each.startsWith('MAL-')) || cwe.includes('CWE-506') || /\bmalware\b/iu.test(title ?? '')
46
43
 
47
44
  export const SEVERITIES = ['critical', 'high', 'moderate', 'low', 'info']
48
45
  const isCvssVector = matches(/^CVSS:[34]\.\d(?:\/[A-Z]{1,4}:[A-Z]{1,2})+$/u)
49
46
  const isCwe = matches(/^CWE-\d{1,6}$/u)
50
47
 
51
- // The fields every source may carry, kept only in the shape they are
52
- // documented in: npm's severity words (GitHub's `medium` read `moderate`),
53
- // a score in (0, 10] (npm spells "not scored" 0), a CVSS vector, CWE ids.
48
+ // Each field only in its documented shape: GitHub's `medium` is `moderate`,
49
+ // and npm's unscored 0 no score.
54
50
  export function metrics({ severity, score, vector, cwe }) {
55
51
  const word = typeof severity === 'string' ? severity.toLowerCase().replace(/^medium$/u, 'moderate') : undefined
56
52
  return {
@@ -1,21 +1,21 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
- import { assertRepo, assertSoldeerName, assertSoldeerVersion, assertion, isGhsa, isRefName, isRepo, isStrings } from '../args.js'
3
+ import { assertPodName, assertPodVersion, assertSoldeerName, assertSoldeerVersion, assertion, isGhsa, isRepo, isStrings } from '../args.js'
4
4
  import { readRecord, writeRecord } from '../cache.js'
5
5
  import { isGone } from '../github/client.js'
6
6
  import { HttpError, recover } from '../http.js'
7
7
  import { pool } from '../pool.js'
8
+ import { boundRange, compareVersions, readRange } from '../rubygems/version.js'
8
9
  import { isExactVersion } from '../semver.js'
9
- import { advisoryUrl, covered, detailsOf, isText, mayBeInRange, metrics } from './common.js'
10
- import { soldeerRepos } from './repos.js'
10
+ import { advisoryUrl, covered, detailsOf, isOpenAbove, isText, mayBeInRange, metrics, order, overlap } from './common.js'
11
+ import { podRepos, soldeerRepos } from './repos.js'
11
12
 
12
13
  const REPOS_AT_ONCE = 4
13
14
  const DIR = 'github/advisories'
14
- // A maintainer publishes one whenever they are ready, and seeing it before
15
- // GitHub reviews it is what a repository is asked for: 90 minutes, not a month.
15
+ // Not a month: a maintainer's advisory is wanted before GitHub reviews it.
16
16
  const LISTING_TTL_MS = 90 * 60 * 1000
17
- // Stamped on each entry, and raised when a listing is kept differently.
18
- const VERSION = 2
17
+ // Raised when a listing is kept differently.
18
+ const VERSION = 3
19
19
 
20
20
  const isRepoAdvisory = (advisory) => advisory && typeof advisory === 'object' && isGhsa(advisory.ghsa_id)
21
21
  && advisory.state === 'published' && isText(advisory.summary)
@@ -23,23 +23,17 @@ const isRepoAdvisory = (advisory) => advisory && typeof advisory === 'object' &&
23
23
 
24
24
  export const assertClient = assertion('a GitHub client from createClient', (value) => typeof value?.listRepoAdvisories === 'function' && typeof value.getRepo === 'function')
25
25
 
26
- // A maintainer may give a vulnerable range only its lower bound, and the
27
- // version that fixed it apart (`>= 5.0.0-beta.1`, patched in `5.0.0-rc.2`),
28
- // as GitHub's page shows them side by side: such a range ends below its one
29
- // patched version. A range bounded above, or patched in more than one
30
- // version, is as given.
26
+ // A range with no upper bound ends below its one patched version, where
27
+ // that leaves some of it; any other is as given.
31
28
  function boundedRange(range, patched) {
32
- const fixed = typeof patched === 'string' ? patched.trim() : null
33
- if (!isExactVersion(fixed) || range.includes('<')) return range
34
- return range.trim() === '' ? `< ${fixed}` : `${range.trim()}, < ${fixed}`
29
+ if (!isExactVersion(patched)) return range
30
+ if (range.trim() === '') return `< ${patched}`
31
+ const npm = range.replaceAll(',', ' ')
32
+ return isOpenAbove(npm) && overlap(npm, `< ${patched}`) ? `${range.trim()}, < ${patched}` : range
35
33
  }
36
34
 
37
- // What rows are made from, and all that is kept of a listing: each advisory
38
- // not withdrawn, with its CVSS vector GitHub prefers, and each vulnerable
39
- // range with the package it names, ended below its patched version where it
40
- // has no end of its own (boundedRange). A listing that is malformed is
41
- // refused whole, and never kept; one whose only fault is a description
42
- // (isDigest) is answered, but not kept either.
35
+ // What is kept of a listing. One whose only fault is a description is
36
+ // answered but not kept.
43
37
  function digest(repo, list) {
44
38
  return list.flatMap((advisory) => {
45
39
  assert.ok(isRepoAdvisory(advisory), `advisories: malformed advisory from ${repo}`)
@@ -49,7 +43,8 @@ function digest(repo, list) {
49
43
  const range = vulnerability?.vulnerable_version_range ?? ''
50
44
  assert.ok(typeof range === 'string', `advisories: malformed range in ${advisory.ghsa_id}`)
51
45
  const { ecosystem, name } = vulnerability?.package ?? {}
52
- return { range: boundedRange(range, vulnerability?.patched_versions), ...(typeof ecosystem === 'string' && { ecosystem }), ...(typeof name === 'string' && { name }) }
46
+ const patched = vulnerability?.patched_versions
47
+ return { range, ...(typeof patched === 'string' && { patched: patched.trim() }), ...(typeof ecosystem === 'string' && { ecosystem }), ...(typeof name === 'string' && { name }) }
53
48
  })
54
49
  return [{
55
50
  ghsa: advisory.ghsa_id,
@@ -61,14 +56,11 @@ function digest(repo, list) {
61
56
  })
62
57
  }
63
58
 
64
- // A description is checked only for `details` (detailsOf), so a malformed
65
- // one leaves the listing usable, but not kept.
66
59
  const isDigest = (advisory) => advisory && typeof advisory === 'object' && isGhsa(advisory.ghsa) && isText(advisory.title)
67
60
  && (advisory.description === undefined || isText(advisory.description))
68
- && Array.isArray(advisory.ranges) && advisory.ranges.every((entry) => typeof entry?.range === 'string')
61
+ && Array.isArray(advisory.ranges) && advisory.ranges.every((entry) => typeof entry?.range === 'string' && (entry.patched === undefined || typeof entry.patched === 'string'))
69
62
 
70
- // GitHub answers for a repository renamed or transferred with a redirect,
71
- // which getRepo follows to the repository it is now, listed by that name.
63
+ // A renamed or transferred repository redirects; getRepo follows it.
72
64
  const isRedirect = (err) => err instanceof HttpError && err.status >= 300 && err.status < 400
73
65
 
74
66
  async function listingOf(github, repo) {
@@ -81,12 +73,8 @@ async function listingOf(github, repo) {
81
73
  return { repo: moved, list: await github.listRepoAdvisories({ repo: moved }) }
82
74
  }
83
75
 
84
- // A repository's listing, digested, through the cache, and the repository
85
- // it is of: GitHub's names are case-insensitive, so one entry answers every
86
- // spelling, and one renamed or transferred is kept under the name asked,
87
- // with `repo` the one it has now. A repository gone or blocked, or
88
- // redirected anywhere getRepo does not follow, has none, and that is not
89
- // kept.
76
+ // A repository's listing and the name it has now, one cache entry for every
77
+ // spelling; none for one gone, blocked or redirected elsewhere, and not kept.
90
78
  async function listAdvisories(github, repo, cache) {
91
79
  const name = repo.toLowerCase()
92
80
  const entry = await readRecord(DIR, name, cache, LISTING_TTL_MS)
@@ -100,12 +88,11 @@ async function listAdvisories(github, repo, cache) {
100
88
  return { repo: found.repo, advisories }
101
89
  }
102
90
 
103
- // GitHub's `>= 1.0.0, < 1.2.6` is npm's with the commas dropped.
104
- // Maintainers write these unreviewed: one without a range, or with one
105
- // semver cannot read, covers every version. Its page is on `repo`, which
106
- // may publish it long before the advisory database has one, and its
107
- // `description` is the text `details` asks for: the listing has it all.
108
- function fromRepository(repo, name, advisory, range, asked, { covers, details }) {
91
+ // GitHub's `>= 1.0.0, < 1.2.6` is npm's without the commas. One semver
92
+ // can't read, or none, covers every version.
93
+ export const bySemver = (covers) => (asked, range) => covered(asked, range.replaceAll(',', ' '), covers)
94
+
95
+ function fromRepository(repo, name, advisory, range, versions, details) {
109
96
  return {
110
97
  name,
111
98
  source: 'repository',
@@ -117,24 +104,21 @@ function fromRepository(repo, name, advisory, range, asked, { covers, details })
117
104
  ...(details && detailsOf(advisory.description, advisory.ghsa)),
118
105
  ...metrics({ severity: advisory.severity, score: advisory.cvss, vector: advisory.cvssVector, cwe: advisory.cwe }),
119
106
  range,
120
- versions: covered(asked, range.replaceAll(',', ' '), covers),
107
+ versions,
121
108
  }
122
109
  }
123
110
 
124
- // Each asked name's repository, `repoOf` it, is asked once, and its
125
- // advisories' vulnerable ranges become rows for the names that `takes` a
126
- // range's package, one per name, advisory and range, holding the asked
127
- // versions it `covers`, and with `details`, its text.
128
- async function repositoryAdvisories(github, asked, { repoOf, takes = () => true, covers, details, cache }) {
129
- // GitHub's names are case-insensitive: one spelling asks for all.
111
+ // A row per advisory, range and asked name `takes` it for.
112
+ export async function repositoryAdvisories(github, asked, { repoOf, takes = () => true, versionsIn = bySemver(), bound = boundedRange, details, cache }) {
130
113
  const namesOf = Map.groupBy([...asked.keys()].filter(repoOf), (name) => repoOf(name).toLowerCase())
131
114
  const listed = await pool([...namesOf.values()], REPOS_AT_ONCE, async (names) => ({ names, ...(await listAdvisories(github, repoOf(names[0]), cache)) }))
132
115
  const rows = new Map()
133
116
  for (const { repo, names, advisories } of listed) {
134
117
  for (const advisory of advisories) {
135
- for (const { range, ...pkg } of advisory.ranges) {
118
+ for (const { range: given, patched, ...pkg } of advisory.ranges) {
119
+ const range = bound(given, patched)
136
120
  for (const name of names.filter((candidate) => takes(candidate, pkg))) {
137
- rows.set(`${name} ${advisory.ghsa} ${range}`, fromRepository(repo, name, advisory, range, asked.get(name), { covers, details }))
121
+ rows.set(`${name} ${advisory.ghsa} ${range}`, fromRepository(repo, name, advisory, range, versionsIn(asked.get(name), range), details))
138
122
  }
139
123
  }
140
124
  }
@@ -142,47 +126,50 @@ async function repositoryAdvisories(github, asked, { repoOf, takes = () => true,
142
126
  return [...rows.values()]
143
127
  }
144
128
 
145
- // Each asked name's repository: as given, `known`, or else looked up,
146
- // through `cache`.
147
129
  async function reposOf(asked, known, lookUp, cache) {
148
130
  const found = await lookUp([...asked.keys()].filter((name) => !known.has(name)), { asked, cache })
149
131
  return (name) => known.get(name) ?? found.get(name)
150
132
  }
151
133
 
152
- // A maintainer's advisory is on the repository before GitHub reviews it
153
- // into the databases the registries answer from. With `repoAdvisories`,
154
- // each package's repository, `known` or else looked up, adds what it
155
- // publishes for GitHub's `ecosystem` entries naming the package, for the
156
- // versions `rows` do not already report under that GHSA.
157
- export async function withRepositories(rows, asked, { github, repoAdvisories, known, details, cache }, { ecosystem, lookUp, covers }) {
134
+ // With `repoAdvisories`, what each package's repository publishes for it,
135
+ // in versions `rows` don't already report under that GHSA.
136
+ export async function withRepositories(rows, asked, { github, repoAdvisories, known, details, cache }, { github: ecosystem, lookUp, versionsIn, bound, nameKey = (name) => name }) {
158
137
  if (!repoAdvisories) return rows
159
138
  const reported = new Set(rows.flatMap((row) => [row.id, row.ghsa, ...row.aliases].filter(isGhsa).flatMap((id) => row.versions.map((version) => `${row.name} ${id} ${version}`))))
160
139
  const repoOf = await reposOf(asked, known, lookUp, cache)
161
- const takes = (name, pkg) => pkg.ecosystem === ecosystem && pkg.name === name
162
- const added = await repositoryAdvisories(github, asked, { repoOf, takes, covers, details, cache })
140
+ const takes = (name, pkg) => pkg.ecosystem === ecosystem && typeof pkg.name === 'string' && nameKey(pkg.name) === nameKey(name)
141
+ const added = await repositoryAdvisories(github, asked, { repoOf, takes, versionsIn, bound, details, cache })
163
142
  return [...rows, ...added.map((row) => ({ ...row, versions: row.versions.filter((version) => !reported.has(`${row.name} ${row.id} ${version}`)) }))]
164
143
  }
165
144
 
166
- // stasis versions a repository with no version of its own by its branch,
167
- // or 0.0.0: every range covers those.
168
- const coversPlaceholder = (version, range) => version === '0.0.0' || mayBeInRange(version, range)
145
+ // stasis versions a repository without versions by its branch, or 0.0.0:
146
+ // every range covers those.
147
+ export const coversPlaceholder = (version, range) => version === '0.0.0' || mayBeInRange(version, range)
169
148
 
170
- // Dependencies that are GitHub repositories themselves: every range their
171
- // own published advisories list counts, whichever package it names.
172
- export const GITHUB = {
173
- repositoryOnly: true,
174
- assertName: assertRepo,
175
- assertVersion: assertion('a version or a branch name', isRefName),
176
- advisories: (asked, { github, details, cache }) => repositoryAdvisories(github, asked, { repoOf: (repo) => repo, covers: coversPlaceholder, details, cache }),
177
- }
178
-
179
- // Soldeer packages, which no advisory database has: the repository each
180
- // is published from, as given or else as Soldeer's project names it, is
181
- // their only source, and every range its advisories list counts, whichever
182
- // package it names (often the npm package the same release went out as).
149
+ // No database has Soldeer packages: their repository's advisories are the
150
+ // only source, every range counting.
183
151
  export const SOLDEER = {
184
152
  repositoryOnly: true,
185
153
  assertName: assertSoldeerName,
186
154
  assertVersion: assertSoldeerVersion,
187
155
  advisories: async (asked, { github, known, details, cache }) => await repositoryAdvisories(github, asked, { repoOf: await reposOf(asked, known, soldeerRepos, cache), details, cache }),
188
156
  }
157
+
158
+ // Pod::Version is a Gem::Version, ordered without build metadata.
159
+ const podRelease = (version) => version.split('+')[0]
160
+
161
+ // A range Gem::Requirement can't read covers every version.
162
+ function podsIn(versions, range) {
163
+ const test = readRange(range)
164
+ return test === undefined ? [...versions] : versions.filter((version) => test(podRelease(version)))
165
+ }
166
+
167
+ // No database has pods: the repository their podspec names is the only
168
+ // source, every range counting.
169
+ export const COCOAPODS = {
170
+ repositoryOnly: true,
171
+ assertName: assertPodName,
172
+ assertVersion: assertPodVersion,
173
+ compare: (a, b) => compareVersions(podRelease(a), podRelease(b)) || order(a, b),
174
+ advisories: async (asked, { github, known, details, cache }) => await repositoryAdvisories(github, asked, { repoOf: await reposOf(asked, known, podRepos, cache), versionsIn: podsIn, bound: boundRange, details, cache }),
175
+ }
@@ -3,29 +3,33 @@ import assert from 'node:assert/strict'
3
3
  import { assertArgs, assertBoolean, assertRepo, assertion, isIterable, optional, sameName } from '../args.js'
4
4
  import { assertCache } from '../cache.js'
5
5
  import { SEVERITIES, isMalware, order } from './common.js'
6
- import { GITHUB, SOLDEER, assertClient } from './github.js'
6
+ import { GITHUB } from './actions.js'
7
+ import { COCOAPODS, SOLDEER, assertClient } from './github.js'
7
8
  import { NPM } from './npm.js'
8
- import { CARGO, COMPOSER } from './osv.js'
9
+ import { CARGO, COMPOSER, GEM, PYPI, SWIFT } from './osv.js'
10
+ import { RUBY } from './rubysec.js'
9
11
 
10
- const ECOSYSTEMS = { npm: NPM, cargo: CARGO, composer: COMPOSER, soldeer: SOLDEER, github: GITHUB }
12
+ const ECOSYSTEMS = { npm: NPM, cargo: CARGO, composer: COMPOSER, gem: GEM, ruby: RUBY, pypi: PYPI, swift: SWIFT, cocoapods: COCOAPODS, soldeer: SOLDEER, github: GITHUB }
11
13
  const byNumbers = new Intl.Collator('en', { numeric: true }).compare
12
14
  const assertEcosystem = assertion(`one of ${Object.keys(ECOSYSTEMS).join(', ')}`, (value) => typeof value === 'string' && Object.hasOwn(ECOSYSTEMS, value))
13
15
  const assertVersions = assertion('a non-empty array', (value) => Array.isArray(value) && value.length > 0)
14
16
 
15
- // Ecosystem -> name -> { versions, github? }, a name given twice merged.
16
- // Every package is checked before any is used.
17
+ // Ecosystem -> name -> { versions, github? }, every package checked first.
17
18
  function collect(packages) {
18
19
  assert.ok(isIterable(packages), 'advisories: packages must be an iterable of { ecosystem, name, github?, versions }')
19
20
  const byEcosystem = new Map()
21
+ const spelled = new Map()
20
22
  for (const pkg of packages) {
21
23
  assertArgs('advisories', pkg, { ecosystem: assertEcosystem, name: null, github: optional(assertRepo), versions: assertVersions }, 'package')
22
- const { assertName, assertVersion } = ECOSYSTEMS[pkg.ecosystem]
24
+ const { assertName, assertVersion, nameKey } = ECOSYSTEMS[pkg.ecosystem]
23
25
  assertName('advisories', 'package.name', pkg.name)
24
26
  for (const version of pkg.versions) assertVersion('advisories', 'package.versions', version)
25
27
  assert.ok(pkg.ecosystem !== 'github' || pkg.github === undefined, 'advisories: a github package is its own repository, and takes no package.github')
26
28
  const named = byEcosystem.get(pkg.ecosystem) ?? byEcosystem.set(pkg.ecosystem, new Map()).get(pkg.ecosystem)
27
- // A repository's name is GitHub's, in any case: the first spelling stands.
28
- const name = pkg.ecosystem === 'github' ? [...named.keys()].find((known) => sameName(known, pkg.name)) ?? pkg.name : pkg.name
29
+ // A repository's name in any case, a Python package's as PEP 503
30
+ // normalizes it: the first spelling stands.
31
+ const key = nameKey && `${pkg.ecosystem}\0${nameKey(pkg.name)}`
32
+ const name = key ? spelled.get(key) ?? spelled.set(key, pkg.name).get(key) : pkg.name
29
33
  const entry = named.get(name) ?? named.set(name, { versions: new Set() }).get(name)
30
34
  assert.ok(pkg.github === undefined || entry.github === undefined || sameName(entry.github, pkg.github), `advisories: ${pkg.name} is given two repositories`)
31
35
  entry.github ??= pkg.github
@@ -34,20 +38,16 @@ function collect(packages) {
34
38
  return byEcosystem
35
39
  }
36
40
 
37
- // Which of an advisory's rows stands for it: npm's registry's, then OSV's,
38
- // then its repository's.
39
- const SOURCES = ['registry', 'osv', 'repository']
41
+ // Which of an advisory's rows stands for it, first to last.
42
+ const SOURCES = ['registry', 'osv', 'packagist', 'rubysec', 'repository']
40
43
  const worse = (a, b) => (b === undefined || (a !== undefined && SEVERITIES.indexOf(a) < SEVERITIES.indexOf(b)) ? a : b)
41
44
 
42
- // An advisory's rows as one: the first's by source, what it lacks from the
43
- // first of the rest that has it, the others' aliases, and of them all the
44
- // worst severity, the highest CVSS score with its own vector (else the first
45
- // vector), the ranges (` || `), CWEs and versions (in the order `asked` has
46
- // them). RustSec's kind of advisory that is not a vulnerability as such only
47
- // where each of them has that kind: a row without one is a vulnerability.
45
+ // An advisory's rows as one: the first by source, filled from the rest,
46
+ // with the worst severity, the highest CVSS, and every range, CWE and
47
+ // version. `informational` only where every row has it.
48
48
  function joinRows(rows, asked) {
49
- const [head, ...rest] = rows.toSorted((a, b) => SOURCES.indexOf(a.source) - SOURCES.indexOf(b.source))
50
- const all = [head, ...rest]
49
+ const all = rows.toSorted((a, b) => SOURCES.indexOf(a.source) - SOURCES.indexOf(b.source))
50
+ const [head, ...rest] = all
51
51
  const ranges = [...new Set(all.map((row) => row.range).filter((range) => range !== undefined))]
52
52
  const versions = new Set(all.flatMap((row) => row.versions))
53
53
  const joined = {
@@ -68,17 +68,13 @@ function joinRows(rows, asked) {
68
68
  delete joined.cvssVector
69
69
  if (scored?.cvss !== undefined) joined.cvss = scored.cvss
70
70
  if (scored?.cvssVector !== undefined) joined.cvssVector = scored.cvssVector
71
- // A range of none ('') covers every version, as they then do together.
71
+ // A range of none ('') covers every version.
72
72
  if (ranges.length > 0) joined.range = ranges.includes('') ? '' : ranges.join(' || ')
73
73
  return joined
74
74
  }
75
75
 
76
- // One row for each advisory id on a package, where its sources answer more
77
- // than one: npm's registry one per range, and OSV's record of it, or its
78
- // repository, another for the versions they cover beyond that. Records of
79
- // other ids that name it as an alias stay rows of their own, each version
80
- // reported under one, as their sources rate them. Rows keep the place of the
81
- // first answered.
76
+ // One row per advisory id; records of other ids that name it as an alias
77
+ // stay rows of their own.
82
78
  function oneRowPerAdvisory(rows, asked) {
83
79
  const byId = Map.groupBy(rows, (row) => `${row.name}\0${row.id}`)
84
80
  return [...byId.values()].map((same) => (same.length === 1 ? same[0] : joinRows(same, asked.get(same[0].name))))
@@ -13,8 +13,7 @@ import { npmRepos } from './repos.js'
13
13
  const BULK_URL = buildUrl(NPM_REGISTRY, ['-', 'npm', 'v1', 'security', 'advisories', 'bulk'])
14
14
  const NAMES_PER_REQUEST = 250
15
15
  const GHSA_PAGE = 'https://github.com/advisories/'
16
- // Names checked at once for whether they are public: each a small document,
17
- // answered in about a tenth of a second.
16
+ // Each a small document, answered in about a tenth of a second.
18
17
  const NAMES_AT_ONCE = 32
19
18
 
20
19
  const isRow = (row) => row && typeof row === 'object' && Number.isSafeInteger(row.id)
@@ -55,9 +54,7 @@ async function registryAdvisories(asked) {
55
54
  }
56
55
 
57
56
  // The registry's rows carry no text: each GHSA's is OSV's record of it,
58
- // GitHub's advisory database as published, asked once for the rows that
59
- // cover an asked version, but where `osv` already read it. One OSV does
60
- // not have yet has none.
57
+ // asked once, unless `osv` already read it.
61
58
  async function withDetails(rows) {
62
59
  const asks = (row) => row.source === 'registry' && row.details === undefined
63
60
  const ghsas = [...new Set(rows.filter((row) => asks(row) && row.ghsa && row.versions.length > 0).map((row) => row.ghsa))]
@@ -66,13 +63,9 @@ async function withDetails(rows) {
66
63
  return rows.map((row) => (asks(row) ? { ...row, ...detailsOf(text.get(row.ghsa), row.ghsa) } : row))
67
64
  }
68
65
 
69
- // With `osv`, OSV's records of the asked versions besides the registry's
70
- // rows, the malicious packages' (MAL-...), which the registry has none
71
- // of, among them. A version a registry row reports under the same
72
- // advisory, the row's id one of an OSV row's ids or aliases, is left to
73
- // that row, which takes the OSV row's ids among its aliases, and its text
74
- // where it is the same record; an OSV row keeps the versions no such row
75
- // reports, which advisories() joins to a registry row of its own id.
66
+ // With `osv`, OSV's records too, malware's among them. A version a registry
67
+ // row reports under the same advisory is left to that row, which takes the
68
+ // record's ids as aliases.
76
69
  function withOsv(registry, osv) {
77
70
  const rows = registry.map((row) => ({ ...row }))
78
71
  const added = []
@@ -89,14 +82,9 @@ function withOsv(registry, osv) {
89
82
  return [...rows, ...added]
90
83
  }
91
84
 
92
- // Whether npm's registry serves `name` to anyone: its latest version's
93
- // document, for that name, read with no token. Private packages and other
94
- // registries' answer 404; any other answer, or none, counts as private too,
95
- // as in triage. That document first, as npm answers a HEAD of the package's
96
- // in two seconds or more about one time in ten; but a 404 for it may only
97
- // mean no `latest` tag (a package published with `--tag` alone, or one
98
- // unpublished whole, its name kept), so then the package's document, a HEAD
99
- // with no token, decides.
85
+ // Whether npm serves `name` without a token: its latest version's document,
86
+ // else (no `latest` tag) a HEAD of the package's; anything but 200 is
87
+ // private, as in triage. That order, as the HEAD is often slow.
100
88
  async function servesAnyone(name) {
101
89
  try {
102
90
  const json = await request(buildUrl(NPM_REGISTRY, [...name.split('/'), 'latest']), { as: 'json' })
@@ -111,37 +99,36 @@ async function servesAnyone(name) {
111
99
  }
112
100
  }
113
101
 
114
- // The packages of `asked` whose name is public (servesAnyone). The name
115
- // decides, not the version: npm takes down malicious versions but keeps
116
- // their name. Public names are kept a month, as a scoped package can be
117
- // made private; the rest are asked again each time.
102
+ // The name decides, not the version: npm takes down malicious versions but
103
+ // keeps their name. Only public names are cached, a month.
118
104
  async function publicOnly(asked, cache) {
119
105
  const names = [...asked.keys()]
120
106
  const kept = await pool(names, NAMES_AT_ONCE, (name) => readRecord('npm/public', name, cache))
121
- const missing = names.filter((name, i) => kept[i]?.public !== true)
107
+ const serving = new Set(names.filter((name, i) => kept[i]?.public === true))
108
+ const missing = names.filter((name) => !serving.has(name))
122
109
  const found = await pool(missing, NAMES_AT_ONCE, servesAnyone)
123
110
  const added = missing.filter((name, i) => found[i])
124
111
  await pool(added, NAMES_AT_ONCE, (name) => writeRecord('npm/public', name, { public: true }, cache))
125
- const serving = new Set([...names.filter((name, i) => kept[i]?.public === true), ...added])
112
+ for (const name of added) serving.add(name)
126
113
  return new Map([...asked].filter(([name]) => serving.has(name)))
127
114
  }
128
115
 
129
- // OSV's records of the public packages only: no request to OSV names a
130
- // private one.
116
+ // No request to OSV names a private package.
131
117
  async function osvOfPublic(asked, options) {
132
118
  const told = await publicOnly(asked, options.cache)
133
119
  return told.size > 0 ? await osvRows({ osv: 'npm' }, told, options) : []
134
120
  }
135
121
 
136
- // What `npm audit` asks the registry, one row per vulnerable range, and
137
- // with `osv`, OSV's records of the public packages.
122
+ // What `npm audit` asks, and with `osv`, OSV's records of public packages.
138
123
  export const NPM = {
124
+ github: 'npm',
125
+ lookUp: npmRepos,
139
126
  assertName: assertPackageName,
140
127
  assertVersion: assertPackageVersion,
141
128
  compare: compareVersions,
142
129
  advisories: async (asked, options) => {
143
130
  const [registry, osv] = await Promise.all([registryAdvisories(asked), options.osv ? osvOfPublic(asked, options) : []])
144
131
  const rows = withOsv(registry, osv)
145
- return await withRepositories(options.details ? await withDetails(rows) : rows, asked, options, { ecosystem: 'npm', lookUp: npmRepos })
132
+ return await withRepositories(options.details ? await withDetails(rows) : rows, asked, options, NPM)
146
133
  },
147
134
  }