@preventive/upstream 1.5.1 → 1.7.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.
@@ -1,24 +1,27 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
- import { assertCrateName, assertCrateVersion, assertion, isGhsa, isStrings, matches, show } from '../args.js'
4
- import { OSV_API, buildUrl, request } from '../http.js'
3
+ import { assertCrateName, assertCrateVersion, assertGemName, assertGemVersion, assertion, isGhsa, isRepo, isStrings, matches, show } from '../args.js'
4
+ import { readJSON, writeJSON } from '../cache.js'
5
+ import { OSV_API, OSV_EXPORTS, buildUrl, request } from '../http.js'
5
6
  import { chunks, pool } from '../pool.js'
7
+ import { assertPypiName, assertPypiVersion, boundRange as boundPypiRange, compareVersions as comparePypiVersions, normalName, readRange as readPypiRange } from '../pypi/version.js'
8
+ import { boundRange as boundGemRange, compareVersions as compareGemVersions, readRange as readGemRange } from '../rubygems/version.js'
6
9
  import { isExactVersion } from '../semver.js'
7
10
  import { advisoryUrl, detailsOf, inRange, isText, metrics, order } from './common.js'
8
- import { withRepositories } from './github.js'
9
- import { composerRepos, crateRepos } from './repos.js'
11
+ import { bySemver, withRepositories } from './github.js'
12
+ import { packagistRows } from './packagist.js'
13
+ import { composerRepos, crateRepos, gemRepos, pypiRepos } from './repos.js'
14
+ import { rubysecRows, sameIds } from './rubysec.js'
10
15
 
11
16
  const QUERY_URL = buildUrl(OSV_API, ['v1', 'querybatch'])
12
17
  const QUERIES_PER_REQUEST = 1000
13
18
  export const RECORDS_AT_ONCE = 8
14
19
  const isOsvId = matches(/^(?=.{1,128}$)[A-Z][\dA-Z]*(?:-[\dA-Za-z]+)+$/u)
15
- // osv.dev's page for one of its records. An id that is only another's
16
- // alias (PKSA-...) has none, and redirects to a search.
20
+ // An id that is only another's alias (PKSA-...) has no page of its own.
17
21
  const osvPage = (id) => `https://osv.dev/vulnerability/${id}`
18
22
  const INFORMATIONAL = new Set(['unmaintained', 'unsound', 'notice'])
19
- // Of the records that publish one advisory, the first answered for a
20
- // version stands for the rest on it: RustSec's, what `cargo audit` reads
21
- // and GitHub mirrors, then the GHSA, then any other (MAL-...), then by id.
23
+ // Of one advisory's records, which a version is reported under: RustSec's
24
+ // (what `cargo audit` reads), then the GHSA, then by id.
22
25
  const rank = (id) => (id.startsWith('RUSTSEC-') ? 0 : (isGhsa(id) ? 1 : 2))
23
26
  const first = (a, b) => rank(a.id) - rank(b.id) || order(a.id, b.id)
24
27
  const named = (a, b) => a.aliases.includes(b.id) || b.aliases.includes(a.id)
@@ -31,22 +34,141 @@ export const CARGO = {
31
34
  assertVersion: assertCrateVersion,
32
35
  advisories: (asked, options) => osvAdvisories(CARGO, asked, options),
33
36
  }
34
- // TODO: packagist.org's API, what `composer audit` reads, also has the
35
- // FriendsOfPHP advisories OSV lacks; using it means matching Composer
36
- // version ranges here.
37
+ // OSV, and Packagist's own, which has the FriendsOfPHP advisories OSV lacks.
37
38
  export const COMPOSER = {
38
39
  osv: 'Packagist',
39
40
  github: 'composer',
40
41
  lookUp: composerRepos,
41
42
  assertName: assertion('a Composer package name', matches(/^(?=.{3,256}$)[a-z\d](?:[_.-]?[a-z\d]+)*\/[a-z\d](?:(?:[_.]|-{1,2})?[a-z\d]+)*$/u)),
42
43
  assertVersion: assertion('a Composer release version', matches(/^(?=.{1,64}$)v?\d+(?:\.\d+){0,3}(?:[._-]?(?:stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?\d+)*)?$/iu)),
43
- // Composer's `v1.2.3` is semver's 1.2.3; what semver cannot read at all
44
- // (1.2.3.4, 1.0.0-p1) is covered by every range.
45
- covers: (version, range) => {
44
+ // What semver can't read (1.2.3.4, 1.0.0-p1) is covered by every range.
45
+ versionsIn: bySemver((version, range) => {
46
46
  const plain = version.replace(/^v/iu, '')
47
47
  return !isExactVersion(plain) || inRange(plain, range)
48
+ }),
49
+ advisories: async (asked, options) => {
50
+ const [osv, packagist] = await Promise.all([osvRows(COMPOSER, asked, options), packagistRows(asked)])
51
+ return await withRepositories([...osv, ...sameIds(packagist, osv)], asked, options, COMPOSER)
48
52
  },
49
- advisories: (asked, options) => osvAdvisories(COMPOSER, asked, options),
53
+ }
54
+
55
+ // OSV, and with a GitHub client ruby-advisory-db, which OSV lacks.
56
+ export const GEM = {
57
+ osv: 'RubyGems',
58
+ github: 'rubygems',
59
+ lookUp: gemRepos,
60
+ assertName: assertGemName,
61
+ assertVersion: assertGemVersion,
62
+ // `1.0` and `1.0.0` are equal, so are ordered by their text.
63
+ compare: (a, b) => compareGemVersions(a, b) || order(a, b),
64
+ bound: boundGemRange,
65
+ versionsIn: (asked, range) => {
66
+ const test = readGemRange(range)
67
+ return test === undefined ? [...asked] : asked.filter(test)
68
+ },
69
+ advisories: async (asked, options) => {
70
+ const [osv, rubysec] = await Promise.all([osvRows(GEM, asked, options), options.github ? rubysecRows(options.github, asked, options) : []])
71
+ return await withRepositories([...osv, ...sameIds(rubysec, osv)], asked, options, GEM)
72
+ },
73
+ }
74
+
75
+ // As OSV's SwiftURL names it, `github.com/vapor/vapor`, in any case.
76
+ const SWIFT_NAME = /^(?=.{1,512}$)[a-z\d-]+(?:\.[a-z\d-]+)+(?:\/(?!\.\.?(?:\/|$))[\w.~-]+)+(?<!\.git)$/u
77
+ // TSCUtility.Version: SemVer, but an identifier may be empty, or a number
78
+ // have a leading zero.
79
+ const SWIFT_VERSION = /^(?=.{5,256}$)(?:0|[1-9]\d*)(?:\.(?:0|[1-9]\d*)){2}(?:-[\dA-Za-z.-]*)?(?:\+[\dA-Za-z.-]*)?$/u
80
+ const swiftRepo = (name) => {
81
+ const repo = name.startsWith('github.com/') ? name.slice('github.com/'.length) : ''
82
+ return isRepo(repo) ? repo : null
83
+ }
84
+
85
+ // How late a package OSV adds is asked in its spelling.
86
+ const NAMES_TTL_MS = 90 * 60 * 1000
87
+ const LISTED = /^(?<modified>[^,]{1,64}),(?<id>[^,]+)$/u
88
+ const namesIn = (record, ecosystem) => (Array.isArray(record.affected) ? record.affected : []).map((entry) => entry?.package)
89
+ .filter((pkg) => pkg?.ecosystem === ecosystem && typeof pkg.name === 'string').map((pkg) => pkg.name)
90
+ const isKept = (value) => value && typeof value === 'object' && typeof value.at === 'number' && value.records && typeof value.records === 'object'
91
+ && Object.values(value.records).every((record) => typeof record?.modified === 'string' && isStrings(record.names))
92
+
93
+ // Each package name OSV has in `ecosystem`: from its list of records, each
94
+ // record read again only once it is modified.
95
+ async function osvNames(ecosystem, cache) {
96
+ const kept = await readJSON('osv/names', ecosystem, cache)
97
+ const records = isKept(kept) ? kept.records : {}
98
+ const age = isKept(kept) ? Date.now() - kept.at : Number.NaN
99
+ if (!(age >= 0 && age <= NAMES_TTL_MS)) {
100
+ const list = (await request(buildUrl(OSV_EXPORTS, [ecosystem, 'modified_id.csv']), { as: 'text' })).split('\n').filter(Boolean).map((line) => LISTED.exec(line)?.groups)
101
+ assert.ok(list.every((entry) => entry && isOsvId(entry.id)), `advisories: malformed list of OSV's ${ecosystem} records`)
102
+ const changed = list.filter(({ id, modified }) => records[id]?.modified !== modified)
103
+ const read = new Map((await pool(changed.map(({ id }) => id), RECORDS_AT_ONCE, getVuln)).map((record) => [record.id, namesIn(record, ecosystem)]))
104
+ const fresh = Object.fromEntries(list.map(({ id, modified }) => [id, { modified, names: read.get(id) ?? records[id].names }]))
105
+ await writeJSON('osv/names', ecosystem, { at: Date.now(), records: fresh }, cache)
106
+ return Object.values(fresh).flatMap(({ names }) => names)
107
+ }
108
+ return Object.values(records).flatMap(({ names }) => names)
109
+ }
110
+
111
+ export const SWIFT = {
112
+ osv: 'SwiftURL',
113
+ github: 'swift',
114
+ lookUp: (names) => new Map(names.map((name) => [name, swiftRepo(name)])),
115
+ assertName: assertion("a Swift package's repository, `github.com/owner/name`", matches(SWIFT_NAME)),
116
+ assertVersion: assertion('a version as SwiftPM writes one', matches(SWIFT_VERSION)),
117
+ // GitHub's URLs are case-insensitive.
118
+ nameKey: (name) => name.toLowerCase(),
119
+ advisories: async (asked, options) => {
120
+ // OSV matches a Swift package only as it spells it, case and all.
121
+ const spelling = new Map((await osvNames('SwiftURL', options.cache)).map((name) => [name.toLowerCase(), name]))
122
+ const osvName = (name) => spelling.get(name.toLowerCase()) ?? name
123
+ const askedAs = new Map([...asked.keys()].map((name) => [osvName(name), name]))
124
+ const rows = await osvRows(SWIFT, new Map([...asked].map(([name, versions]) => [osvName(name), versions])), options)
125
+ return await withRepositories(rows.map((row) => ({ ...row, name: askedAs.get(row.name) })), asked, options, SWIFT)
126
+ },
127
+ }
128
+
129
+ // What `pip-audit` reads. OSV takes a name in any spelling PEP 503
130
+ // normalizes alike.
131
+ export const PYPI = {
132
+ osv: 'PyPI',
133
+ github: 'pip',
134
+ lookUp: pypiRepos,
135
+ assertName: assertPypiName,
136
+ assertVersion: assertPypiVersion,
137
+ nameKey: normalName,
138
+ // `1.0` and `1.0.0` are equal, so are ordered by their text.
139
+ compare: (a, b) => comparePypiVersions(a, b) || order(a, b),
140
+ bound: boundPypiRange,
141
+ versionsIn: (asked, range) => {
142
+ const test = readPypiRange(range)
143
+ return test === undefined ? [...asked] : asked.filter(test)
144
+ },
145
+ advisories: (asked, options) => osvAdvisories(PYPI, asked, options),
146
+ }
147
+
148
+ // The ids OSV answers each query with, a thousand queries a request.
149
+ async function idsOf(queries, what) {
150
+ const ids = []
151
+ for (const chunk of chunks(queries, QUERIES_PER_REQUEST)) {
152
+ const answer = await request(QUERY_URL, { method: 'POST', body: { queries: chunk }, as: 'json' })
153
+ assert.ok(Array.isArray(answer?.results) && answer.results.length === chunk.length, 'advisories: expected one OSV result per query')
154
+ for (const result of answer.results) {
155
+ const vulns = result?.vulns ?? []
156
+ assert.ok(result && result.next_page_token === undefined && Array.isArray(vulns) && vulns.every((vuln) => isOsvId(vuln?.id)), `advisories: malformed OSV result for ${what(ids.length)}`)
157
+ ids.push(vulns.map(({ id }) => id))
158
+ }
159
+ }
160
+ return ids
161
+ }
162
+
163
+ // Every record OSV has of each name, for an ecosystem whose versions it
164
+ // can't match: [{ record, names }], withdrawn ones left out.
165
+ export async function packageRecords(osv, names) {
166
+ const byId = new Map()
167
+ for (const [j, ids] of (await idsOf(names.map((name) => ({ package: { name, ecosystem: osv } })), (at) => names[at])).entries()) {
168
+ for (const id of ids) (byId.get(id) ?? byId.set(id, new Set()).get(id)).add(names[j])
169
+ }
170
+ const records = await pool([...byId.keys()], RECORDS_AT_ONCE, getVuln)
171
+ return records.filter((record) => !record.withdrawn).map((record) => ({ record, names: byId.get(record.id) }))
50
172
  }
51
173
 
52
174
  export async function getVuln(id) {
@@ -57,7 +179,7 @@ export async function getVuln(id) {
57
179
  return { ...record, aliases: (record.aliases ?? []).filter(isOsvId) }
58
180
  }
59
181
 
60
- function toAdvisory(ecosystem, name, versions, record, details) {
182
+ export function toAdvisory(ecosystem, name, versions, record, details) {
61
183
  const { aliases } = record
62
184
  const ghsas = aliases.filter(isGhsa)
63
185
  const ghsa = isGhsa(record.id) ? record.id : (ghsas.length === 1 ? ghsas[0] : undefined)
@@ -79,28 +201,18 @@ function toAdvisory(ecosystem, name, versions, record, details) {
79
201
  }
80
202
  }
81
203
 
82
- // OSV's batch query matches versions on its side, but answers ids only:
83
- // each record is fetched once after. An advisory more than one database
84
- // publishes comes back under each one's id, the records naming each other
85
- // as aliases, either way round, directly or through others: one group, in
86
- // which each version is reported under the first answered for it, and
87
- // each record has the others' ids as aliases. `osv` is OSV's name for the
88
- // ecosystem.
204
+ // OSV's batch query answers ids only, each record fetched after. Records
205
+ // of one advisory, naming each other as aliases, are one group: each
206
+ // version is reported under its first, the rest its aliases.
89
207
  export async function osvRows({ osv }, asked, { details }) {
90
208
  const list = [...asked].flatMap(([name, versions]) => versions.map((version) => ({ name, version })))
91
209
  const hits = new Map() // id -> name -> versions, in `list` order
92
- for (const chunk of chunks(list, QUERIES_PER_REQUEST)) {
93
- const body = { queries: chunk.map(({ name, version }) => ({ package: { name, ecosystem: osv }, version })) }
94
- const answer = await request(QUERY_URL, { method: 'POST', body, as: 'json' })
95
- assert.ok(Array.isArray(answer?.results) && answer.results.length === chunk.length, 'advisories: expected one OSV result per query')
96
- for (const [j, result] of answer.results.entries()) {
97
- const { name, version } = chunk[j]
98
- const vulns = result?.vulns ?? []
99
- assert.ok(result && result.next_page_token === undefined && Array.isArray(vulns) && vulns.every((vuln) => isOsvId(vuln?.id)), `advisories: malformed OSV result for ${name}@${version}`)
100
- for (const { id } of vulns) {
101
- const byName = hits.get(id) ?? hits.set(id, new Map()).get(id)
102
- byName.set(name, (byName.get(name) ?? new Set()).add(version))
103
- }
210
+ const found = await idsOf(list.map(({ name, version }) => ({ package: { name, ecosystem: osv }, version })), (j) => `${list[j].name}@${list[j].version}`)
211
+ for (const [j, ids] of found.entries()) {
212
+ const { name, version } = list[j]
213
+ for (const id of ids) {
214
+ const byName = hits.get(id) ?? hits.set(id, new Map()).get(id)
215
+ byName.set(name, (byName.get(name) ?? new Set()).add(version))
104
216
  }
105
217
  }
106
218
  const records = (await pool([...hits.keys()], RECORDS_AT_ONCE, getVuln)).filter((record) => !record.withdrawn)
@@ -126,6 +238,5 @@ export async function osvRows({ osv }, asked, { details }) {
126
238
  }
127
239
 
128
240
  async function osvAdvisories(ecosystem, asked, options) {
129
- const { github, lookUp, covers } = ecosystem
130
- return await withRepositories(await osvRows(ecosystem, asked, options), asked, options, { ecosystem: github, lookUp, covers })
241
+ return await withRepositories(await osvRows(ecosystem, asked, options), asked, options, ecosystem)
131
242
  }
@@ -0,0 +1,74 @@
1
+ import assert from 'node:assert/strict'
2
+
3
+ import { allows, normalize, parseConstraints } from '@preventive/lockfile/composer-semver.js'
4
+
5
+ import { isGhsa, isStrings, matches, show } from '../args.js'
6
+ import { PACKAGIST, request } from '../http.js'
7
+ import { chunks } from '../pool.js'
8
+ import { advisoryUrl, isText, metrics } from './common.js'
9
+
10
+ // What `composer audit` reads. Its `/` is needed: without it, a 404.
11
+ const ADVISORIES_URL = `${PACKAGIST}/api/security-advisories/`
12
+ // POSTed, as a name can be 256 characters.
13
+ const NAMES_PER_REQUEST = 100
14
+ const isPksa = matches(/^PKSA(?:-[\da-z]{4}){3}$/u)
15
+ const isCve = matches(/^CVE-\d{4}-\d{4,}$/u)
16
+ const isUrl = (text) => /^https?:$/u.test(URL.parse(text)?.protocol)
17
+
18
+ const isAdvisory = (advisory, name) => advisory && typeof advisory === 'object' && isPksa(advisory.advisoryId) && advisory.packageName === name
19
+ && isText(advisory.title) && typeof advisory.affectedVersions === 'string'
20
+ && [advisory.cve, advisory.link, advisory.severity].every((value) => value == null || typeof value === 'string')
21
+ && Array.isArray(advisory.sources) && isStrings(advisory.sources.map((source) => source?.remoteId))
22
+
23
+ // Its one GHSA, from its sources or its link, where it has one.
24
+ function ghsaOf({ sources, link }) {
25
+ const ghsas = new Set([...sources.map((source) => source.remoteId), /\/(GHSA[\w-]+)$/u.exec(link ?? '')?.[1]].filter(isGhsa))
26
+ return ghsas.size === 1 ? [...ghsas][0] : undefined
27
+ }
28
+
29
+ // As `composer audit` matches. A constraint or version Composer can't read
30
+ // is covered: a missed advisory is worse than a spare one.
31
+ function versionsIn(asked, constraints) {
32
+ const parsed = parseConstraints(constraints)
33
+ if (parsed === undefined) return [...asked]
34
+ return asked.filter((version) => {
35
+ const normal = normalize(version)
36
+ return normal === undefined || allows(parsed, normal)
37
+ })
38
+ }
39
+
40
+ function toRow(name, advisory, asked) {
41
+ const ghsa = ghsaOf(advisory)
42
+ const id = ghsa ?? advisory.advisoryId
43
+ const url = isUrl(advisory.link) ? advisory.link : (ghsa && advisoryUrl(ghsa))
44
+ return {
45
+ name,
46
+ source: 'packagist',
47
+ id,
48
+ ...(ghsa && { ghsa }),
49
+ ...(url && { url }),
50
+ aliases: [advisory.advisoryId, advisory.cve].filter((other) => (isPksa(other) || isCve(other)) && other !== id),
51
+ title: advisory.title,
52
+ ...metrics({ severity: advisory.severity }),
53
+ range: advisory.affectedVersions,
54
+ versions: versionsIn(asked, advisory.affectedVersions),
55
+ }
56
+ }
57
+
58
+ // An answer of none is PHP's empty array, `[]`.
59
+ export async function packagistRows(asked) {
60
+ const rows = []
61
+ for (const chunk of chunks([...asked.keys()], NAMES_PER_REQUEST)) {
62
+ const body = new TextEncoder().encode(new URLSearchParams(chunk.map((name) => ['packages[]', name])).toString())
63
+ const answer = await request(ADVISORIES_URL, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, as: 'json' })
64
+ const found = Array.isArray(answer?.advisories) && answer.advisories.length === 0 ? {} : answer?.advisories
65
+ assert.ok(found && typeof found === 'object' && !Array.isArray(found), 'advisories: expected an object of advisories from Packagist')
66
+ for (const name of Object.keys(found)) assert.ok(chunk.includes(name), `advisories: Packagist answered for ${show(name)}, which was not asked`)
67
+ for (const name of chunk) {
68
+ const list = Object.hasOwn(found, name) ? found[name] : []
69
+ assert.ok(Array.isArray(list) && list.every((advisory) => isAdvisory(advisory, name)), `advisories: malformed advisories from Packagist for ${name}`)
70
+ rows.push(...list.map((advisory) => toRow(name, advisory, asked.get(name))))
71
+ }
72
+ }
73
+ return rows
74
+ }
@@ -1,19 +1,21 @@
1
1
  import assert from 'node:assert/strict'
2
+ import { setTimeout as sleep } from 'node:timers/promises'
2
3
 
3
4
  import { show } from '../args.js'
4
5
  import { addRepos, readRepos } from '../cache.js'
5
6
  import { lookUpCrateRepos } from '../cargo/repos.js'
6
- import { PACKAGIST_REPO, SOLDEER_API, buildUrl, isNotFound, recover, request } from '../http.js'
7
+ import { specPath } from '../cocoapods.js'
8
+ import { COCOAPODS_CDN, PACKAGIST_REPO, PYPI, RUBYGEMS, SOLDEER_API, buildUrl, encodeSegment, isNotFound, recover, request } from '../http.js'
7
9
  import { getVersionDocument } from '../npm/versions.js'
8
10
  import { getRepo } from '../package.js'
9
11
  import { pool } from '../pool.js'
12
+ import { normalName } from '../pypi/version.js'
10
13
  import { githubRepoOfUrl } from '../remote.js'
11
14
 
12
15
  const PACKAGES_AT_ONCE = 8
13
16
 
14
- // Name -> its GitHub repo, or null where the registry has no such package
15
- // or it names no GitHub repo; any other failure throws. Only a repo found
16
- // is cached, for a month, in the cache set or `cache` (readRecord).
17
+ // Name -> its GitHub repo, or null for none; only one found is cached, a
18
+ // month.
17
19
  async function cachedRepos(dir, names, fetchMissing, cache) {
18
20
  const repos = await readRepos(dir, names, cache)
19
21
  await addRepos(dir, repos, await fetchMissing(names.filter((name) => !repos.has(name))), cache)
@@ -43,17 +45,67 @@ async function fetchSoldeerRepo(name) {
43
45
  return githubRepoOfUrl(answer.data[0]?.github_url) ?? null
44
46
  }
45
47
 
46
- // The repo the newest version asked of each package names, from that
47
- // version's document, kept for good (getVersionDocument): null where the
48
- // registry does not have that version, or it names no GitHub repo.
48
+ // The podspec's `source` by :git, else :http, else its `homepage`. Trunk's
49
+ // CDN redirects to jsDelivr.
50
+ async function fetchPodRepo(name, version) {
51
+ const url = buildUrl(COCOAPODS_CDN, specPath(name, version).map(encodeSegment))
52
+ const podspec = await request(url, { as: 'json', redirect: 'follow' }).catch(recover(isNotFound, null))
53
+ if (podspec === null) return null
54
+ assert.ok(podspec?.name === name && podspec.version === version, `advisories: trunk answered for ${show(podspec?.name)} ${show(podspec?.version)}, not ${name} ${version}`)
55
+ const { git, http } = podspec.source ?? {}
56
+ return [git, http, podspec.homepage].map(repoOfLink).find((repo) => repo !== undefined) ?? null
57
+ }
58
+
59
+ // rubygems.org takes 10 requests a second from one address.
60
+ const GEM_PACE_MS = 100
61
+ let nextGemAt = 0
62
+ async function pacedForGems() {
63
+ const now = Date.now()
64
+ const at = Math.max(now, nextGemAt)
65
+ nextGemAt = at + GEM_PACE_MS
66
+ if (at > now) await sleep(at - now)
67
+ }
68
+
69
+ // Rails' gems link a page in the repo's tree, and a pod's :http source a
70
+ // tag's archive or a release's asset.
71
+ const TREE_PAGE = /^(?<repo>(?i:https?:\/\/github\.com)\/[\w-]+\/[\w.-]+)\/(?:tree|blob|archive|releases\/download)\//u
72
+ const repoOfLink = (url) => githubRepoOfUrl(url) ?? githubRepoOfUrl(TREE_PAGE.exec(typeof url === 'string' ? url : '')?.groups.repo)
73
+
74
+ async function fetchGemRepo(name) {
75
+ await pacedForGems()
76
+ const answer = await request(buildUrl(RUBYGEMS, ['api', 'v1', 'gems', `${name}.json`]), { as: 'json' }).catch(recover(isNotFound, null))
77
+ if (answer === null) return null
78
+ assert.ok(answer?.name === name, `advisories: rubygems.org answered for ${show(answer?.name)}, not ${name}`)
79
+ return [answer.source_code_uri, answer.homepage_uri].map(repoOfLink).find((repo) => repo !== undefined) ?? null
80
+ }
81
+
82
+ // One version's JSON, not the project's, which lists every release's files
83
+ // (3 MB for boto3). Links by label as PyPI normalizes them, source first.
84
+ const LABELS = ['source', 'sourcecode', 'repository', 'code', 'github', 'homepage']
85
+ const rank = ([label]) => {
86
+ const at = LABELS.indexOf(label.toLowerCase().replaceAll(/[^\da-z]/gu, ''))
87
+ return at === -1 ? LABELS.length : at
88
+ }
89
+ async function fetchPypiRepo(name, version) {
90
+ const answer = await request(buildUrl(PYPI, ['pypi', name, version, 'json'].map(encodeSegment)), { as: 'json' }).catch(recover(isNotFound, null))
91
+ if (answer === null) return null
92
+ const info = answer?.info
93
+ assert.ok(typeof info?.name === 'string' && normalName(info.name) === normalName(name), `advisories: PyPI answered for ${show(info?.name)}, not ${name}`)
94
+ const links = [...Object.entries(info.project_urls ?? {}), ['home_page', info.home_page]].toSorted((a, b) => rank(a) - rank(b))
95
+ return links.map(([, url]) => repoOfLink(url)).find((repo) => repo !== undefined) ?? null
96
+ }
97
+
98
+ // From the newest version asked's document, kept for good; null where the
99
+ // registry hasn't that version.
49
100
  async function npmRepo(name, version, cache) {
50
101
  const json = await getVersionDocument('advisories', name, version, cache)
51
102
  return (json && getRepo(json).github) ?? null
52
103
  }
53
104
 
54
- // Each takes the names to look up, the versions `asked` of each, and the
55
- // call's `cache`.
56
105
  export const crateRepos = (names, { cache }) => lookUpCrateRepos('advisories', names, { cache })
57
106
  export const composerRepos = (names, { cache }) => cachedRepos('composer/repos', names, (missing) => fetchEach(missing, fetchComposerRepo), cache)
107
+ export const gemRepos = (names, { cache }) => cachedRepos('rubygems/repos', names, (missing) => fetchEach(missing, fetchGemRepo), cache)
108
+ export const pypiRepos = (names, { asked, cache }) => cachedRepos('pypi/repos', names, (missing) => fetchEach(missing, (name) => fetchPypiRepo(name, asked.get(name).at(-1))), cache)
109
+ export const podRepos = (names, { asked, cache }) => cachedRepos('cocoapods/repos', names, (missing) => fetchEach(missing, (name) => fetchPodRepo(name, asked.get(name).at(-1))), cache)
58
110
  export const npmRepos = (names, { asked, cache }) => fetchEach(names, (name) => npmRepo(name, asked.get(name).at(-1), cache))
59
111
  export const soldeerRepos = (names, { cache }) => cachedRepos('soldeer/repos', names, (missing) => fetchEach(missing, fetchSoldeerRepo), cache)
@@ -0,0 +1,157 @@
1
+ import assert from 'node:assert/strict'
2
+ import { Buffer } from 'node:buffer'
3
+
4
+ import { parseYaml } from '@preventive/lockfile/yaml.js'
5
+
6
+ import { assertion, isGhsa, isSha, isStrings, matches } from '../args.js'
7
+ import { readJSON, readRecord, writeJSON, writeRecord } from '../cache.js'
8
+ import { pool } from '../pool.js'
9
+ import { compareVersions, readRange } from '../rubygems/version.js'
10
+ import { objectId } from '../tree.js'
11
+ import { advisoryUrl, detailsOf, isText, metrics, order } from './common.js'
12
+
13
+ // ruby-advisory-db: `gems/<gem>/<id>.yml`, what `bundler-audit` reads, and
14
+ // `rubies/<engine>/<id>.yml`, what `ruby-audit` does.
15
+ const DB = 'rubysec/ruby-advisory-db'
16
+ // How late an advisory added to it can be seen.
17
+ const LISTING_TTL_MS = 90 * 60 * 1000
18
+ // Raised when what is kept changes.
19
+ const VERSION = 2
20
+ const FILES_AT_ONCE = 8
21
+ const FILE = /^(?<dir>gems|rubies)\/(?<name>[^/]+)\/(?<id>[\w.-]+)\.yml$/u
22
+ const isId = matches(/^(?=.{1,128}$)[A-Z][\dA-Z]*(?:-[\dA-Za-z]+)+$/u)
23
+ const isFile = (entry) => Array.isArray(entry) && entry.length === 4 && ['gems', 'rubies'].includes(entry[0]) && typeof entry[1] === 'string' && typeof entry[2] === 'string' && isSha(entry[3])
24
+ const isDigest = (value) => value?.v === VERSION && isId(value.id) && isStrings(value.aliases) && isText(value.title) && isStrings(value.unaffected) && isStrings(value.patched)
25
+
26
+ // Each advisory file's directory, gem or engine, id and blob, from one listing
27
+ // of the repository.
28
+ async function listRepository(github, cache) {
29
+ const kept = await readRecord('rubysec/index', 'gems', cache, LISTING_TTL_MS)
30
+ if (kept?.v === VERSION && isSha(kept.oid) && Array.isArray(kept.files) && kept.files.every(isFile)) return kept
31
+ const { oid } = await github.getRepoHead({ repo: DB, branch: 'master' })
32
+ const { entries, cut } = await github.listRepoTree({ repo: DB, sha: oid })
33
+ assert.ok(!cut, `advisories: GitHub's listing of ${DB} is cut short`)
34
+ const files = entries.flatMap(({ path, type, sha }) => {
35
+ const found = type === 'blob' && FILE.exec(path)
36
+ return found ? [[found.groups.dir, found.groups.name, found.groups.id, sha]] : []
37
+ })
38
+ await writeRecord('rubysec/index', 'gems', { v: VERSION, oid, files }, cache)
39
+ return { oid, files }
40
+ }
41
+
42
+ // Gems and Rubies asked at once share the one listing in flight.
43
+ const inFlight = new WeakMap()
44
+ function listing(github, cache) {
45
+ const calls = inFlight.get(github) ?? inFlight.set(github, new Map()).get(github)
46
+ if (!calls.has(cache)) calls.set(cache, listRepository(github, cache).finally(() => calls.delete(cache)))
47
+ return calls.get(cache)
48
+ }
49
+
50
+ // One value or a list of them, as Array() reads it.
51
+ const list = (value) => (value == null ? [] : [value].flat())
52
+ // `CVE-2024-1` of `2024-1` and of `CVE-2024-1` alike.
53
+ const ids = (prefix, values) => values.filter((value) => value !== '').map((value) => (String(value).startsWith(prefix) ? String(value) : `${prefix}${value}`))
54
+ const score = (value) => (typeof value === 'number' ? value : (/^(?:\d+\.?\d*|\.\d+)$/u.test(value ?? '') ? Number(value) : undefined))
55
+ // bundler-audit's criticality, from a v3 score (or a v4's), else a v2's.
56
+ const V3 = [[9, 'critical'], [7, 'high'], [4, 'moderate'], [0.1, 'low']]
57
+ const V2 = [[7, 'high'], [4, 'moderate'], [0, 'low']]
58
+ const rate = (value, scale) => scale.find(([from]) => value >= from)?.[1]
59
+
60
+ // Its ids as bundler-audit has them, `related`'s too, going by the GHSA where
61
+ // there is one. Lockfile's reader refuses a date and `.17`, so `date` is
62
+ // dropped and CVSS scores quoted.
63
+ function digest(dir, name, file, yaml) {
64
+ const what = `advisories: ${DB} ${dir}/${name}/${file}.yml`
65
+ let doc
66
+ try {
67
+ doc = parseYaml(yaml.replace(/^date: .*$/mu, '').replaceAll(/^(cvss_v[234]): ([\d.]+)$/gmu, '$1: "$2"'), { workflow: true })
68
+ } catch (cause) {
69
+ throw new Error(`${what}: ${cause.message}`, { cause })
70
+ }
71
+ const { title, description, url } = doc
72
+ const related = doc.related ?? {}
73
+ const [unaffected, patched] = [doc.unaffected_versions, doc.patched_versions].map(list)
74
+ const of = doc[dir === 'gems' ? 'gem' : 'engine']
75
+ assert.ok(of === name, `${what} is of ${JSON.stringify(of)}, not ${name}`)
76
+ assert.ok([title, description, url].every((value) => value == null || isText(value)) && related && typeof related === 'object' && isStrings(unaffected) && isStrings(patched), `${what} is malformed`)
77
+ const id = ids('GHSA-', list(doc.ghsa)).find(isGhsa) ?? file
78
+ assert.ok(isId(id), `${what} has no id`)
79
+ const all = [...ids('GHSA-', [...list(doc.ghsa), ...list(related.ghsa)]), ...ids('CVE-', [...list(doc.cve), ...list(related.cve)]), ...ids('OSVDB-', [...list(doc.osvdb), ...list(related.osvdb)]), file]
80
+ const [v2, v3] = [score(doc.cvss_v2), score(doc.cvss_v3) ?? score(doc.cvss_v4)]
81
+ const severity = v3 === undefined ? v2 !== undefined && rate(v2, V2) : rate(v3, V3)
82
+ return {
83
+ v: VERSION,
84
+ id,
85
+ aliases: [...new Set(all.filter(isId))].filter((other) => other !== id),
86
+ title: title ?? id,
87
+ ...(description && { description }),
88
+ ...(/^https?:$/u.test(URL.parse(url)?.protocol) && { url }),
89
+ ...((v3 ?? v2) !== undefined && { cvss: v3 ?? v2 }),
90
+ ...(severity && { severity }),
91
+ unaffected,
92
+ patched,
93
+ }
94
+ }
95
+
96
+ // Kept for good by its blob, which names its content.
97
+ async function advisoryOf(github, oid, [dir, name, file, sha], cache) {
98
+ const kept = await readJSON('rubysec/advisories', sha, cache)
99
+ if (isDigest(kept)) return kept
100
+ const path = `${dir}/${name}/${file}.yml`
101
+ const yaml = await github.getRepoFile({ repo: DB, path, ref: oid })
102
+ assert.ok(objectId('blob', Buffer.from(yaml)).toString('hex') === sha, `advisories: ${DB} ${path} at ${oid} is not blob ${sha}`)
103
+ const found = digest(dir, name, file, yaml)
104
+ await writeJSON('rubysec/advisories', sha, found, cache)
105
+ return found
106
+ }
107
+
108
+ // As bundler-audit: vulnerable unless a patched or unaffected entry takes
109
+ // the version; one the port can't read takes none.
110
+ function toRow(name, advisory, asked, details, versionOf) {
111
+ const takes = [...advisory.patched, ...advisory.unaffected].map(readRange).filter(Boolean)
112
+ const ghsa = isGhsa(advisory.id) ? advisory.id : undefined
113
+ const url = ghsa ? advisoryUrl(ghsa) : advisory.url
114
+ return {
115
+ name,
116
+ source: 'rubysec',
117
+ id: advisory.id,
118
+ ...(ghsa && { ghsa }),
119
+ ...(url && { url }),
120
+ aliases: advisory.aliases,
121
+ title: advisory.title,
122
+ ...(details && detailsOf(advisory.description, advisory.id)),
123
+ ...metrics({ severity: advisory.severity, score: advisory.cvss }),
124
+ versions: asked.filter((version) => !takes.some((test) => test(versionOf(version)))),
125
+ }
126
+ }
127
+
128
+ // The listing first, then the files of the asked names under `dir` alone.
129
+ export async function rubysecRows(github, asked, { details, cache }, dir = 'gems', versionOf = (version) => version) {
130
+ const { oid, files } = await listing(github, cache)
131
+ const wanted = files.filter(([under, name]) => under === dir && asked.has(name))
132
+ const advisories = await pool(wanted, FILES_AT_ONCE, (entry) => advisoryOf(github, oid, entry, cache))
133
+ return wanted.map(([, name], i) => toRow(name, advisories[i], asked.get(name), details, versionOf))
134
+ }
135
+
136
+ // Bundler's `3.3.6p108` as ruby-audit matches it, `3.3.6.108`; a preview's
137
+ // `p-1` is no patchlevel.
138
+ const release = (version) => version.replace(/(?<=\d)p(?:-1|(\d+))$/u, (_, level) => (level === undefined ? '' : `.${level}`))
139
+
140
+ export const RUBY = {
141
+ repositoryOnly: true,
142
+ assertName: assertion('a Ruby engine, `ruby` or `jruby` say', matches(/^[a-z][\da-z]{0,31}$/u)),
143
+ assertVersion: assertion('a Ruby version as Bundler writes one, `3.3.6p108`', matches(/^(?=.{5,64}$)\d+\.\d+\.\d+(?:\.[\dA-Za-z]+)*(?:p(?:-1|0|[1-9]\d*))?$/u)),
144
+ compare: (a, b) => compareVersions(release(a), release(b)) || order(a, b),
145
+ advisories: (asked, { github, details, cache }) => rubysecRows(github, asked, { details, cache }, 'rubies', release),
146
+ }
147
+
148
+ // One without a GHSA that OSV has under another id (its CVE an alias of
149
+ // OSV's GHSA record) takes that id, to be one row with OSV's.
150
+ export function sameIds(rows, osv) {
151
+ const idOf = new Map()
152
+ for (const row of osv) for (const id of [row.id, ...row.aliases]) if (!idOf.has(`${row.name} ${id}`)) idOf.set(`${row.name} ${id}`, row.id)
153
+ return rows.map((row) => {
154
+ const id = isGhsa(row.id) ? undefined : [row.id, ...row.aliases].map((each) => idOf.get(`${row.name} ${each}`)).find(Boolean)
155
+ return id === undefined ? row : { ...row, id, aliases: [row.id, ...row.aliases].filter((each) => each !== id) }
156
+ })
157
+ }
package/src/args.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
+ import { isVersion as isGemVersion } from './rubygems/version.js'
3
4
  import { isExactVersion } from './semver.js'
4
5
 
5
6
  const isControl = (char) => char < ' ' || (char >= '\u007F' && char <= '\u009F')
@@ -102,9 +103,14 @@ export const assertSoldeerVersion = assertion('letters, digits, `.`, `_`, `+` an
102
103
  // A root's name as Podfile.lock has it, and @preventive/lockfile reads it:
103
104
  // printable ASCII but for spaces, parentheses, slashes and backslashes, no
104
105
  // `.` first, which the spec linter refuses, and 1024 characters at most.
105
- const assertPodName = assertion('a pod\'s root name', matches(/^(?=.{1,1024}$)(?!\.)[!-'*-.0-[\]-~]+$/u))
106
+ export const assertPodName = assertion('a pod\'s root name', matches(/^(?=.{1,1024}$)(?!\.)[!-'*-.0-[\]-~]+$/u))
106
107
  // Pod::Version's pattern, as Podfile.lock writes a version.
107
- const assertPodVersion = assertion('a CocoaPods version', matches(/^(?=.{1,256}$)\d+(?:\.[\dA-Za-z-]+)*(?:\+[\dA-Za-z.-]+)?$/u))
108
+ export const assertPodVersion = assertion('a CocoaPods version', matches(/^(?=.{1,256}$)\d+(?:\.[\dA-Za-z-]+)*(?:\+[\dA-Za-z.-]+)?$/u))
109
+ // Gem::SpecificationPolicy#validate_name's rule; the 256 cap is ours.
110
+ export const assertGemName = assertion('a gem name', matches(/^(?=.{1,256}$)(?=[\w.-]*[A-Za-z])[A-Za-z\d][\w.-]*$/u))
111
+ // As Gemfile.lock writes one: no `-`, which Bundler reads as the start of a
112
+ // platform.
113
+ export const assertGemVersion = assertion('a RubyGems version', (value) => isGemVersion(value) && !value.includes('-'))
108
114
  // A package's name and version, as a registry's getters take them.
109
115
  const assertNameVersion = (assertName, assertVersion) => (method, name, version) => {
110
116
  assertName(method, 'name', name)
@@ -114,7 +120,9 @@ export const assertCrate = assertNameVersion(assertCrateName, assertCrateVersion
114
120
  export const assertPackage = assertNameVersion(assertPackageName, assertPackageVersion)
115
121
  export const assertSoldeerPackage = assertNameVersion(assertSoldeerName, assertSoldeerVersion)
116
122
  export const assertPod = assertNameVersion(assertPodName, assertPodVersion)
123
+ export const assertGem = assertNameVersion(assertGemName, assertGemVersion)
117
124
  // As Cargo.lock and soldeer.lock write a checksum.
118
- export const assertSha256 = assertion('a sha256 in lowercase hex', matches(/^[\da-f]{64}$/u))
125
+ export const isSha256 = matches(/^[\da-f]{64}$/u)
126
+ export const assertSha256 = assertion('a sha256 in lowercase hex', isSha256)
119
127
  // As Podfile.lock writes a podspec's checksum.
120
128
  export const assertSha1 = assertion('a sha1 in lowercase hex', isSha1)
package/src/cache.js CHANGED
@@ -10,23 +10,23 @@ import { assertCacheName, assertDirectoryPath, assertion, isRepo } from './args.
10
10
  import { MAX_BYTES, decode } from './http.js'
11
11
  import { pool } from './pool.js'
12
12
 
13
- const DIRS = new Set(['npm/repos', 'npm/public', 'npm/tarballs', 'npm/versions', 'cargo/repos', 'cargo/crates', 'composer/repos', 'soldeer/repos', 'soldeer/zips', 'cocoapods/podspecs', 'github/trees', 'github/advisories'])
13
+ const DIRS = new Set(['npm/repos', 'npm/public', 'npm/tarballs', 'npm/versions', 'cargo/repos', 'cargo/crates', 'cargo/index', 'composer/repos', 'soldeer/repos', 'soldeer/zips', 'rubygems/repos', 'rubygems/gems', 'pypi/repos', 'cocoapods/podspecs', 'cocoapods/archives', 'cocoapods/repos', 'github/trees', 'github/advisories', 'osv/names', 'rubysec/index', 'rubysec/advisories'])
14
14
  const RECORD_TTL_MS = 30 * 24 * 60 * 60 * 1000 // A link only moves on a transfer or rename, and GitHub redirects those.
15
15
  const RECORDS_AT_ONCE = 8
16
16
  // JSON filed gzipped, as `<name>.json.gz`: a listing carries each
17
17
  // advisory's full text, Markdown that compresses well, and a version
18
18
  // document all npm has of that version.
19
- const GZIP_DIRS = new Set(['github/advisories', 'npm/versions'])
19
+ const GZIP_DIRS = new Set(['github/advisories', 'npm/versions', 'rubysec/index', 'rubysec/advisories'])
20
20
  const compress = promisify(gzip)
21
21
  const decompress = promisify(gunzip)
22
22
 
23
23
  // An environment variable may hold anything: only an absolute path is one.
24
- const absolute = (path) => (typeof path === 'string' && isAbsolute(path) ? path : undefined)
24
+ export const absolute = (path) => (typeof path === 'string' && isAbsolute(path) ? path : undefined)
25
25
  const within = (base, ...names) => (base === undefined ? undefined : join(base, ...names))
26
26
 
27
27
  // os.homedir() takes $HOME as it is, relative or empty, and throws where
28
28
  // neither it nor the user's passwd entry has one.
29
- function home() {
29
+ export function home() {
30
30
  try {
31
31
  return absolute(homedir())
32
32
  } catch {