@preventive/upstream 1.9.0 → 1.9.1

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.
package/advisories.d.ts CHANGED
@@ -21,7 +21,12 @@ export interface Package {
21
21
  versions: string[]
22
22
  // A `github` package: true to ask its repository alone, its name sent to
23
23
  // no other source (OSV), as for one not everyone may read. Any spelling
24
- // saying so holds for all. Not for other ecosystems.
24
+ // saying so holds for all. Not for other ecosystems. Without it, a
25
+ // `github` package is asked of OSV only where github.com serves it to
26
+ // anyone, its git ref advertisement asked with no credentials answering
27
+ // 200; a private or internal repository, or one gone or moved, is asked
28
+ // of its repository alone too, and any other answer (a rate limit, an
29
+ // error) throws, before OSV is asked. A public one is cached a month.
25
30
  internal?: boolean
26
31
  }
27
32
 
@@ -63,9 +68,12 @@ export interface Advisory {
63
68
  cvss?: number
64
69
  cvssVector?: string
65
70
  cwe: string[]
66
- // The affected range as its source wrote it, where it has one. OSV's as
67
- // GitHub writes one, `>= 9.5.0, < 15.5.13 || >= 16.0.0-beta.0, < 16.1.7`:
68
- // the ranges holding the versions it reports, else all of them.
71
+ // The affected range as its source wrote it, where it has one: those
72
+ // covering the asked versions. One a repository gives with no end of its
73
+ // own ends below each version it names as patched, a range per release
74
+ // line: `>=9.5.0` patched in `15.5.13, 16.1.7` is `>=9.5.0, < 15.5.13`
75
+ // and `>= 16.0.0-0, < 16.1.7`. OSV's are as GitHub writes one, those
76
+ // holding the versions it reports, else all of them.
69
77
  range?: string
70
78
  // RustSec's `unmaintained`, `unsound` or `notice`: not a vulnerability as
71
79
  // such. A yanked crate isn't an advisory: see cargo.js's yankedVersions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/upstream",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "Minimal npm, crates.io, RubyGems, Soldeer, CocoaPods trunk, GitHub and git checkout clients",
5
5
  "type": "module",
6
6
  "exports": {
@@ -87,6 +87,7 @@
87
87
  "src/advisories/npm.js",
88
88
  "src/advisories/osv.js",
89
89
  "src/advisories/packagist.js",
90
+ "src/advisories/patched.js",
90
91
  "src/advisories/repos.js",
91
92
  "src/advisories/rubysec.js",
92
93
  "src/args.js",
@@ -1,8 +1,11 @@
1
1
  import { assertRepo, assertion, isRefName, isSha } from '../args.js'
2
+ import { readRecord, writeRecord } from '../cache.js'
3
+ import { GITHUB_WEB, HttpError, buildUrl, send } from '../http.js'
4
+ import { pool } from '../pool.js'
2
5
  import { valid, validRange } from '../semver.js'
3
6
  import { inRange, overlap } from './common.js'
4
7
  import { bySemver, coversPlaceholder, repositoryAdvisories } from './github.js'
5
- import { packageRecords, toAdvisory } from './osv.js'
8
+ import { RECORDS_AT_ONCE, packageRecords, toAdvisory } from './osv.js'
6
9
 
7
10
  const ACTIONS = 'GitHub Actions'
8
11
 
@@ -61,8 +64,47 @@ async function actionRows(asked, details) {
61
64
  return rows
62
65
  }
63
66
 
64
- // GitHub repositories as dependencies: OSV's records of them as Actions,
65
- // but of those `internal`, and every range their own advisories list,
67
+ // What github.com answers for a repository it serves to no one without
68
+ // credentials: a private or internal one, or one gone (401), and a moved
69
+ // one's redirect, which is not followed. 404 too.
70
+ const NOT_SERVED = new Set([301, 302, 307, 308, 401, 404])
71
+
72
+ // Whether github.com serves `repo` to anyone: its ref advertisement, asked
73
+ // with no credentials, as `git ls-remote` asks it, over git's protocol v2,
74
+ // which answers with its capabilities alone, a few hundred bytes, not every
75
+ // ref. Any other answer (a 403 or 429 of a rate limit, a 5xx) or a failure
76
+ // throws, before OSV is asked anything. A HEAD is refused (403): a GET, its
77
+ // body left unread.
78
+ async function servesAnyone(repo) {
79
+ const [owner, name] = repo.split('/')
80
+ const url = buildUrl(GITHUB_WEB, [owner, `${name}.git`, 'info', 'refs'], { service: 'git-upload-pack' })
81
+ const res = await send(url, { as: 'text', headers: { 'Git-Protocol': 'version=2' } })
82
+ await res.body?.cancel()
83
+ if (res.status === 200) return true
84
+ if (NOT_SERVED.has(res.status)) return false
85
+ throw new HttpError(res.status, `GET ${url} ${res.status}`, res.headers)
86
+ }
87
+
88
+ // Those of `asked` github.com serves to anyone (servesAnyone), which alone
89
+ // OSV is asked of: a name not known public is sent to it never. Only public
90
+ // ones are kept, a month, by the name in lowercase, as GitHub takes it in
91
+ // any case; one not public is asked again each time, so one made public is
92
+ // asked of OSV as soon as it is.
93
+ async function publicOnly(asked, cache) {
94
+ const names = [...asked.keys()]
95
+ const kept = await pool(names, RECORDS_AT_ONCE, (name) => readRecord('github/public', name.toLowerCase(), cache))
96
+ const serving = new Set(names.filter((name, i) => kept[i]?.public === true))
97
+ const missing = names.filter((name) => !serving.has(name))
98
+ const found = await pool(missing, RECORDS_AT_ONCE, servesAnyone)
99
+ const added = missing.filter((name, i) => found[i])
100
+ await pool(added, RECORDS_AT_ONCE, (name) => writeRecord('github/public', name.toLowerCase(), { public: true }, cache))
101
+ for (const name of added) serving.add(name)
102
+ return new Map([...asked].filter(([name]) => serving.has(name)))
103
+ }
104
+
105
+ // GitHub repositories as dependencies: OSV's records of them as Actions, of
106
+ // those github.com serves to anyone (publicOnly) but those `internal`, which
107
+ // are not asked of it either; and every range their own advisories list,
66
108
  // whichever package it names.
67
109
  export const GITHUB = {
68
110
  repositoryOnly: true,
@@ -73,7 +115,7 @@ export const GITHUB = {
73
115
  const external = new Map(asked)
74
116
  for (const name of internal) external.delete(name)
75
117
  return (await Promise.all([
76
- actionRows(external, details),
118
+ publicOnly(external, cache).then((open) => actionRows(open, details)),
77
119
  repositoryAdvisories(github, asked, { repoOf: (repo) => repo, versionsIn: bySemver(coversPlaceholder), details, cache }),
78
120
  ])).flat()
79
121
  },
@@ -5,9 +5,9 @@ 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'
9
- import { isExactVersion } from '../semver.js'
10
- import { advisoryUrl, covered, detailsOf, isOpenAbove, isText, mayBeInRange, metrics, order, overlap } from './common.js'
8
+ import { compareVersions, readRange } from '../rubygems/version.js'
9
+ import { advisoryUrl, covered, detailsOf, isText, mayBeInRange, metrics, order } from './common.js'
10
+ import { boundGemRange, boundSemverRange } from './patched.js'
11
11
  import { podRepos, soldeerRepos } from './repos.js'
12
12
 
13
13
  const REPOS_AT_ONCE = 4
@@ -23,15 +23,6 @@ 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 range with no upper bound ends below its one patched version, where
27
- // that leaves some of it; any other is as given.
28
- function boundedRange(range, patched) {
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
33
- }
34
-
35
26
  // What is kept of a listing. One whose only fault is a description is
36
27
  // answered but not kept.
37
28
  function digest(repo, list) {
@@ -108,16 +99,18 @@ function fromRepository(repo, name, advisory, range, versions, details) {
108
99
  }
109
100
  }
110
101
 
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 }) {
102
+ // A row per advisory, range and asked name `takes` it for, a range with no
103
+ // end of its own one per line its patched versions end (see patched.js).
104
+ export async function repositoryAdvisories(github, asked, { repoOf, takes = () => true, versionsIn = bySemver(), bound = boundSemverRange, details, cache }) {
113
105
  const namesOf = Map.groupBy([...asked.keys()].filter(repoOf), (name) => repoOf(name).toLowerCase())
114
106
  const listed = await pool([...namesOf.values()], REPOS_AT_ONCE, async (names) => ({ names, ...(await listAdvisories(github, repoOf(names[0]), cache)) }))
115
107
  const rows = new Map()
116
108
  for (const { repo, names, advisories } of listed) {
117
109
  for (const advisory of advisories) {
118
110
  for (const { range: given, patched, ...pkg } of advisory.ranges) {
119
- const range = bound(given, patched)
120
- for (const name of names.filter((candidate) => takes(candidate, pkg))) {
111
+ const taken = names.filter((candidate) => takes(candidate, pkg))
112
+ const ranges = taken.length > 0 ? bound(given, patched) : []
113
+ for (const [name, range] of taken.flatMap((each) => ranges.map((one) => [each, one]))) {
121
114
  rows.set(`${name} ${advisory.ghsa} ${range}`, fromRepository(repo, name, advisory, range, versionsIn(asked.get(name), range), details))
122
115
  }
123
116
  }
@@ -171,5 +164,5 @@ export const COCOAPODS = {
171
164
  assertName: assertPodName,
172
165
  assertVersion: assertPodVersion,
173
166
  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 }),
167
+ advisories: async (asked, { github, known, details, cache }) => await repositoryAdvisories(github, asked, { repoOf: await reposOf(asked, known, podRepos, cache), versionsIn: podsIn, bound: boundGemRange, details, cache }),
175
168
  }
@@ -6,11 +6,12 @@ import { assertCrateName, assertCrateVersion, assertGemName, assertGemVersion, a
6
6
  import { readJSON, writeJSON } from '../cache.js'
7
7
  import { OSV_API, OSV_EXPORTS, buildUrl, request } from '../http.js'
8
8
  import { chunks, pool } from '../pool.js'
9
- import { assertPypiName, assertPypiVersion, boundRange as boundPypiRange, compareVersions as comparePypiVersions, isVersion as isPypiVersion, normalName, readRange as readPypiRange } from '../pypi/version.js'
10
- import { boundRange as boundGemRange, compareVersions as compareGemVersions, isVersion as isGemVersion, readRange as readGemRange } from '../rubygems/version.js'
9
+ import { assertPypiName, assertPypiVersion, compareVersions as comparePypiVersions, isVersion as isPypiVersion, normalName, readRange as readPypiRange } from '../pypi/version.js'
10
+ import { compareVersions as compareGemVersions, isVersion as isGemVersion, readRange as readGemRange } from '../rubygems/version.js'
11
11
  import { compareVersions as compareSemver, isExactVersion } from '../semver.js'
12
12
  import { advisoryUrl, detailsOf, inRange, isText, metrics, order } from './common.js'
13
13
  import { bySemver, withRepositories } from './github.js'
14
+ import { boundGemRange, boundPypiRange } from './patched.js'
14
15
  import { packagistRows } from './packagist.js'
15
16
  import { composerRepos, crateRepos, gemRepos, pypiRepos } from './repos.js'
16
17
  import { rubysecRows, sameIds } from './rubysec.js'
@@ -0,0 +1,79 @@
1
+ import { compareVersions as comparePypiVersions, isVersion as isPypiVersion, lowerBoundsBelow as pypiBoundsBelow, releaseOf as pypiRelease, readRange as readPypiRange } from '../pypi/version.js'
2
+ import { compareVersions as compareGemVersions, exclusionsOf, lowerBoundsBelow as gemBoundsBelow, releaseOf as gemRelease, isVersion as isGemVersion, meetsLowerBounds } from '../rubygems/version.js'
3
+ import { compareVersions as compareSemver, isExactVersion } from '../semver.js'
4
+ import { inRange, isOpenAbove, overlap } from './common.js'
5
+
6
+ // Of two releases, the number they first differ in, the major's or the
7
+ // minor's; -1 where neither does, as one line.
8
+ function lineAt(a, b) {
9
+ for (const at of [0, 1]) if ((a[at] ?? 0n) !== (b[at] ?? 0n)) return at
10
+ return -1
11
+ }
12
+
13
+ // A range with no end of its own, ended below the versions an advisory
14
+ // names as patched, a range per release line: below the lowest, then from
15
+ // where each one's line ends to below the next. A line is a major, or a
16
+ // minor where the next patched version is of the same major; the highest
17
+ // of a line's patched versions ends it, and a line none ends stays in. A
18
+ // line the range begins below keeps what the range leaves out (a gem's
19
+ // `!=`). Any other range, or a list it can't read all of, is as given.
20
+ //
21
+ // So Next.js's GHSA-ggv3-7p47-pfv8, `>=9.5.0` patched in `16.1.7, 15.5.13`,
22
+ // is `>=9.5.0, < 15.5.13` and `>= 16.0.0-0, < 16.1.7`, as GitHub reviewed it.
23
+ function endBelow({ isVersion, compare, release, lowest, opensBelow, above, kept = () => [] }) {
24
+ return (range, patched) => {
25
+ const versions = typeof patched === 'string' && patched.length <= 1024 ? patched.split(',').map((part) => part.trim()) : []
26
+ if (versions.length === 0 || !versions.every(isVersion)) return [range]
27
+ const given = range.trim()
28
+ const sorted = versions.toSorted(compare)
29
+ const releases = sorted.length > 1 ? sorted.map(release) : []
30
+ if ((given !== '' && !opensBelow(given, sorted.at(-1))) || releases.includes(undefined)) return [range]
31
+ const ranges = []
32
+ let from
33
+ for (const [i, version] of sorted.entries()) {
34
+ const at = i + 1 < sorted.length ? lineAt(releases[i], releases[i + 1]) : 0
35
+ if (at === -1) continue
36
+ const below = `< ${version}`
37
+ if (from !== undefined && given === '') ranges.push(`>= ${from}, ${below}`)
38
+ else if (given === '') ranges.push(below)
39
+ else if (from !== undefined && above(given, from)) ranges.push([`>= ${from}`, ...kept(given), below].join(', '))
40
+ else if (opensBelow(given, version)) ranges.push(`${given}, ${below}`)
41
+ if (i + 1 < sorted.length) from = lowest([...releases[i].slice(0, at), (releases[i][at] ?? 0n) + 1n])
42
+ }
43
+ return ranges
44
+ }
45
+ }
46
+
47
+ // GitHub's `>= 1.0.0, < 1.2.6` is npm's without the commas.
48
+ const npm = (range) => range.replaceAll(',', ' ')
49
+
50
+ // A line from its lowest prerelease, `-0`.
51
+ export const boundSemverRange = endBelow({
52
+ isVersion: isExactVersion,
53
+ compare: compareSemver,
54
+ release: (version) => /^\d+\.\d+\.\d+/u.exec(version)[0].split('.').map(BigInt),
55
+ lowest: (release) => `${[...release, 0n, 0n].slice(0, 3).join('.')}-0`,
56
+ opensBelow: (range, version) => isOpenAbove(npm(range)) && overlap(npm(range), `< ${version}`),
57
+ above: (range, version) => inRange(version, npm(range)),
58
+ })
59
+
60
+ // From `.A`, below any letters a prerelease has: Ruby orders them by byte.
61
+ export const boundGemRange = endBelow({
62
+ isVersion: isGemVersion,
63
+ compare: compareGemVersions,
64
+ release: gemRelease,
65
+ lowest: (release) => `${release.join('.')}.A`,
66
+ opensBelow: gemBoundsBelow,
67
+ above: meetsLowerBounds,
68
+ kept: exclusionsOf,
69
+ })
70
+
71
+ // From `.dev0`, below its pre-releases.
72
+ export const boundPypiRange = endBelow({
73
+ isVersion: isPypiVersion,
74
+ compare: comparePypiVersions,
75
+ release: pypiRelease,
76
+ lowest: (release) => `${release.join('.')}.dev0`,
77
+ opensBelow: pypiBoundsBelow,
78
+ above: (range, version) => readPypiRange(range)(version),
79
+ })
package/src/cache.js CHANGED
@@ -10,7 +10,7 @@ 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', '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'])
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', 'github/public', '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
@@ -39,11 +39,11 @@ export function readRange(text) {
39
39
  return parts && ((version) => parts.every(([operator, against]) => OPERATORS[operator](compareVersions(version, against))))
40
40
  }
41
41
 
42
- // Lower bounds alone end below the one patched version above them; any
43
- // other range is as given.
44
- export function boundRange(range, patched) {
45
- if (!isVersion(patched)) return range
46
- if (range.trim() === '') return `< ${patched}`
47
- const open = requirementsOf(range)?.every(([operator, against]) => (operator === '>=' || operator === '>') && compareVersions(against, patched) < 0)
48
- return open ? `${range.trim()}, < ${patched}` : range
42
+ // Whether a range is lower bounds alone, each below `version`.
43
+ export const lowerBoundsBelow = (range, version) => requirementsOf(range)?.every(([operator, against]) => (operator === '>=' || operator === '>') && compareVersions(against, version) < 0) === true
44
+
45
+ // Its release numbers; none where it has an epoch, which no line spans.
46
+ export function releaseOf(version) {
47
+ const { epoch, release } = parseVersion(version)
48
+ return epoch === '0' ? release.map(BigInt) : undefined
49
49
  }
@@ -114,11 +114,14 @@ export function readRange(text) {
114
114
  }
115
115
  }
116
116
 
117
- // Lower bounds alone end below the one patched version above them; any
118
- // other range is as given.
119
- export function boundRange(range, patched) {
120
- if (!isVersion(patched)) return range
121
- if (range.trim() === '') return `< ${patched}`
122
- const open = requirementsOf(range)?.every(([operator, against]) => operator === '!=' || ((operator === '>=' || operator === '>') && compareVersions(against, patched) < 0))
123
- return open ? `${range.trim()}, < ${patched}` : range
124
- }
117
+ // Whether a range is lower bounds alone, `!=` among them, each below
118
+ // `version`.
119
+ export const lowerBoundsBelow = (range, version) => requirementsOf(range)?.every(([operator, against]) => operator === '!=' || ((operator === '>=' || operator === '>') && compareVersions(against, version) < 0)) === true
120
+
121
+ // Of a range lowerBoundsBelow takes, whether a version meets each lower
122
+ // bound, and the `!=` it keeps.
123
+ export const meetsLowerBounds = (range, version) => requirementsOf(range).every(([operator, against]) => operator === '!=' || OPERATORS[operator](compareVersions(version, against)))
124
+ export const exclusionsOf = (range) => requirementsOf(range).filter(([operator]) => operator === '!=').map((part) => part.join(' '))
125
+
126
+ // Its numbers before any letters, as Gem::Version reads it.
127
+ export const releaseOf = (version) => numeric(read(version))