@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.
@@ -3,16 +3,22 @@ import { readdir } from 'node:fs/promises'
3
3
  import { homedir } from 'node:os'
4
4
  import { join, resolve } from 'node:path'
5
5
 
6
- import { assertCrate, assertSha256, printable, show } from '../args.js'
6
+ import { assertArgs, assertCrate, assertCrateName, assertCrateVersion, assertSha256, assertion, isIterable, isStrings, optional, printable, show } from '../args.js'
7
+ import { assertCache, readRecord, writeRecord } from '../cache.js'
7
8
  import { verifiedDownload } from '../download.js'
8
- import { CRATES_INDEX, CRATES_STATIC, buildUrl, encodeSegment, request } from '../http.js'
9
+ import { CRATES_INDEX, CRATES_STATIC, buildUrl, encodeSegment, isNotFound, recover, request } from '../http.js'
10
+ import { pool } from '../pool.js'
9
11
 
10
12
  const DIR = 'cargo/crates' // No expiry: crates.io never takes a version twice.
13
+ const INDEX_DIR = 'cargo/index'
14
+ // A yank is news: kept as long as a repository's advisories.
15
+ const INDEX_TTL_MS = 90 * 60 * 1000
16
+ const CRATES_AT_ONCE = 8
11
17
 
12
18
  // The sparse index, what cargo reads: a file per crate, by its lowercased
13
19
  // name under 1/, 2/, 3/<first letter>/ or <1st-2nd>/<3rd-4th>/, with a
14
- // JSON line per version, `cksum` the .crate's sha256.
15
- async function getChecksum(method, name, version) {
20
+ // JSON line per version.
21
+ async function readIndex(method, name) {
16
22
  const lower = name.toLowerCase()
17
23
  const prefix = lower.length < 3 ? [String(lower.length)] : lower.length === 3 ? ['3', lower[0]] : [lower.slice(0, 2), lower.slice(2, 4)]
18
24
  const text = await request(buildUrl(CRATES_INDEX, [...prefix, lower]), { as: 'text' })
@@ -23,7 +29,11 @@ async function getChecksum(method, name, version) {
23
29
  assert.fail(`${method}: the index for ${name} has a line that is not JSON: ${printable(line.slice(0, 200))}`)
24
30
  }
25
31
  }
26
- const entry = text.split('\n').filter(Boolean).map(parse).find((candidate) => candidate?.vers === version)
32
+ return text.split('\n').filter(Boolean).map(parse)
33
+ }
34
+
35
+ async function getChecksum(method, name, version) {
36
+ const entry = (await readIndex(method, name)).find((candidate) => candidate?.vers === version)
27
37
  assert.ok(entry, `${method}: the index has no ${name}@${version}`)
28
38
  assert.ok(entry.name === name, `${method}: the index answered for ${show(entry.name)}, not ${name}`)
29
39
  assertSha256(method, 'the index cksum', entry.cksum)
@@ -51,3 +61,39 @@ export async function getCrate(name, version, checksum) {
51
61
  const locate = () => buildUrl(CRATES_STATIC, ['crates', name, `${name}-${encodeSegment(version)}.crate`])
52
62
  return await verifiedDownload({ method: 'getCrate', dir: DIR, what: `${name}@${version}`, ext: 'crate', algorithm: 'sha256', expected, local: await localPaths(name, version), locate })
53
63
  }
64
+
65
+ // A crate's versions on crates.io, yanked or not; null where it has none.
66
+ async function indexVersions(name, cache) {
67
+ const kept = await readRecord(INDEX_DIR, name, cache, INDEX_TTL_MS)
68
+ if (isStrings(kept?.published) && isStrings(kept.yanked)) return kept
69
+ const entries = await readIndex('yankedVersions', name).catch(recover(isNotFound, null))
70
+ if (entries === null) return null
71
+ for (const entry of entries) {
72
+ assert.ok(entry?.name === name, `yankedVersions: the index answered for ${show(entry?.name)}, not ${name}`)
73
+ assert.ok(typeof entry.vers === 'string' && typeof entry.yanked === 'boolean', `yankedVersions: malformed index line for ${name}`)
74
+ }
75
+ const versions = { published: entries.filter((entry) => !entry.yanked).map((entry) => entry.vers), yanked: entries.filter((entry) => entry.yanked).map((entry) => entry.vers) }
76
+ await writeRecord(INDEX_DIR, name, versions, cache)
77
+ return versions
78
+ }
79
+
80
+ const assertVersions = assertion('a non-empty array', (value) => Array.isArray(value) && value.length > 0)
81
+
82
+ export async function yankedVersions(crates, options = {}) {
83
+ assertArgs('yankedVersions', options, { cache: optional(assertCache) })
84
+ assert.ok(isIterable(crates), 'yankedVersions: crates must be an iterable of { name, versions }')
85
+ const asked = new Map()
86
+ for (const crate of crates) {
87
+ assertArgs('yankedVersions', crate, { name: assertCrateName, versions: assertVersions }, 'crate')
88
+ for (const version of crate.versions) assertCrateVersion('yankedVersions', 'crate.versions', version)
89
+ const versions = asked.get(crate.name) ?? asked.set(crate.name, new Set()).get(crate.name)
90
+ for (const version of crate.versions) versions.add(version)
91
+ }
92
+ const names = [...asked.keys()]
93
+ const found = await pool(names, CRATES_AT_ONCE, (name) => indexVersions(name, options.cache))
94
+ return new Map(names.map((name, i) => {
95
+ const [yanked, published] = [new Set(found[i]?.yanked), new Set(found[i]?.published)]
96
+ const versions = [...asked.get(name)]
97
+ return [name, { yanked: versions.filter((version) => yanked.has(version)), unknown: versions.filter((version) => !yanked.has(version) && !published.has(version)) }]
98
+ }))
99
+ }
@@ -3,7 +3,7 @@ import { setTimeout as sleep } from 'node:timers/promises'
3
3
 
4
4
  import { assertCrateName, assertNames, show } from '../args.js'
5
5
  import { addRepos, readRepos } from '../cache.js'
6
- import { CRATES_API, buildUrl, request } from '../http.js'
6
+ import { CRATES_API, buildUrl, recover, request } from '../http.js'
7
7
  import { chunks } from '../pool.js'
8
8
  import { githubRepoOfUrl } from '../remote.js'
9
9
 
@@ -36,11 +36,7 @@ export async function lookUpCrateRepos(method, names, { soft = false, cachedOnly
36
36
  if (cachedOnly) return repos
37
37
  for (const [i, chunk] of chunks(names.filter((name) => !repos.has(name)), PER_REQUEST).entries()) {
38
38
  if (i > 0) await sleep(PACE_MS)
39
- const answer = await askCrates(method, chunk).catch((error) => {
40
- if (soft) return new Map()
41
- throw error
42
- })
43
- await addRepos(DIR, repos, answer, cache)
39
+ await addRepos(DIR, repos, await askCrates(method, chunk).catch(recover(() => soft, new Map())), cache)
44
40
  }
45
41
  return repos
46
42
  }
package/src/cocoapods.js CHANGED
@@ -3,9 +3,9 @@ import { readdir } from 'node:fs/promises'
3
3
  import { homedir } from 'node:os'
4
4
  import { join, resolve } from 'node:path'
5
5
 
6
- import { assertPod, assertSha1 } from './args.js'
6
+ import { assertPod, assertSha1, assertSha256, assertion, isRepo } from './args.js'
7
7
  import { verifiedDownload } from './download.js'
8
- import { COCOAPODS_CDN, buildUrl, encodeSegment } from './http.js'
8
+ import { COCOAPODS_CDN, GITHUB_WEB, buildUrl, encodeSegment } from './http.js'
9
9
 
10
10
  // No expiry, but kept by checksum as well: trunk refuses a version it
11
11
  // already has, yet rewrites a podspec it has, as `pod trunk deprecate`
@@ -15,7 +15,7 @@ const DIR = 'cocoapods/podspecs'
15
15
  // Where a spec repo keeps a version's podspec: under a directory each for
16
16
  // the first three hex digits of the md5 of the name, as
17
17
  // Pod::Source::Metadata shards trunk, and CocoaPods/Specs with it.
18
- function specPath(name, version) {
18
+ export function specPath(name, version) {
19
19
  const shard = createHash('md5').update(name).digest('hex').slice(0, 3)
20
20
  return ['Specs', ...shard, name, version, `${name}.podspec.json`]
21
21
  }
@@ -36,6 +36,39 @@ async function localPaths(name, version) {
36
36
  return (await readdir(root).catch(() => [])).map((repo) => join(root, repo, ...specPath(name, version)))
37
37
  }
38
38
 
39
+ // Where pod archives are kept: by their hash alone, which names them.
40
+ const ARCHIVES = 'cocoapods/archives'
41
+
42
+ // https://github.com/<owner>/<repo>/ and a path under it, as buildUrl
43
+ // would write it: no query, fragment, credentials or port, and nothing in
44
+ // a segment but what it lets through.
45
+ function isGitHubUrl(value) {
46
+ const parsed = typeof value === 'string' ? URL.parse(value) : null
47
+ if (parsed?.origin !== GITHUB_WEB) return false
48
+ const segments = parsed.pathname.slice(1).split('/')
49
+ if (segments.length < 3 || !isRepo(`${segments[0]}/${segments[1]}`)) return false
50
+ try {
51
+ return buildUrl(GITHUB_WEB, segments) === value
52
+ } catch {
53
+ return false
54
+ }
55
+ }
56
+ const assertGitHubUrl = assertion('an https URL of a GitHub repository\'s, with a path under it', isGitHubUrl)
57
+
58
+ // An archive a podspec's source names by :http, held to the sha256 the
59
+ // podspec gives of it: a sha1 alone, which two archives made to collide
60
+ // share, is not taken. GitHub's answer for a tag's archive or a release's
61
+ // asset is a redirect, to codeload.github.com or to where it keeps the
62
+ // files, which is followed: the bytes are held to the hash whoever answers.
63
+ export async function getPodArchive(url, sha256) {
64
+ assertGitHubUrl('getPodArchive', 'url', url)
65
+ assertSha256('getPodArchive', 'sha256', sha256)
66
+ return await verifiedDownload({
67
+ method: 'getPodArchive', dir: ARCHIVES, what: url, entry: `sha256-${sha256}`, ext: 'archive', algorithm: 'sha256', expected: sha256,
68
+ locate: () => url, options: { redirect: 'follow' },
69
+ })
70
+ }
71
+
39
72
  // Trunk has no hash to check a podspec against, so the caller brings one,
40
73
  // as Podfile.lock records it. The CDN redirects to jsDelivr, which is
41
74
  // followed: whoever answers, the bytes are held to the checksum.
@@ -0,0 +1,137 @@
1
+ // A commit's tree, held to the commit's id: the commit object itself, as
2
+ // git fetches it from github.com over its protocol v2, and hashed, where
3
+ // the API's answer for a commit is GitHub's word for what is in it.
4
+
5
+ import assert from 'node:assert/strict'
6
+ import { Buffer } from 'node:buffer'
7
+ import { createHash } from 'node:crypto'
8
+ import { inflateSync } from 'node:zlib'
9
+
10
+ import { assertArgs, assertRepo, assertion, isSha1, printable, show } from '../args.js'
11
+ import { GITHUB_WEB, buildUrl, request } from '../http.js'
12
+
13
+ // A commit object is a few KiB; one past this is refused rather than read.
14
+ const MAX_OBJECT = 1024 * 1024
15
+
16
+ const ascii = (text) => Buffer.from(text, 'latin1')
17
+ const pkt = (text) => {
18
+ const data = ascii(text)
19
+ return Buffer.concat([ascii((data.length + 4).toString(16).padStart(4, '0')), data])
20
+ }
21
+ const DELIM = ascii('0001')
22
+ const FLUSH = ascii('0000')
23
+
24
+ // `git fetch --depth 1 --filter=tree:0 origin <sha>`, as protocol v2 asks
25
+ // it: the commit alone, none of its trees, blobs or parents.
26
+ const fetchRequest = (sha) => Buffer.concat([
27
+ pkt('command=fetch\n'), pkt('object-format=sha1\n'), DELIM,
28
+ pkt(`want ${sha}\n`), pkt('deepen 1\n'), pkt('filter tree:0\n'), pkt('no-progress\n'), pkt('done\n'), FLUSH,
29
+ ])
30
+
31
+ // The response's packet lines, each its data or, for a flush, a delimiter
32
+ // or a response end, null.
33
+ function* packets(bytes, method) {
34
+ let at = 0
35
+ while (at < bytes.length) {
36
+ const head = bytes.subarray(at, at + 4).toString('latin1')
37
+ assert.ok(/^[\da-f]{4}$/u.test(head), `${method}: GitHub's answer is not git's packet lines`)
38
+ const length = Number.parseInt(head, 16)
39
+ if (length < 4) {
40
+ at += 4
41
+ yield null
42
+ continue
43
+ }
44
+ assert.ok(at + length <= bytes.length, `${method}: GitHub's answer ends inside a packet`)
45
+ yield bytes.subarray(at + 4, at + length)
46
+ at += length
47
+ }
48
+ }
49
+
50
+ // The packfile section's bytes, side-band 1 of each of its packets, to the
51
+ // flush that ends it. Before it, shallow-info and the like are passed over;
52
+ // git's ERR, or side-band 3, refuses.
53
+ function packOf(bytes, method) {
54
+ const chunks = []
55
+ let inPack = false
56
+ for (const data of packets(bytes, method)) {
57
+ if (!inPack) {
58
+ const text = data === null ? '' : data.toString('latin1').replace(/\n$/u, '')
59
+ assert.ok(!text.startsWith('ERR '), `${method}: GitHub refused the fetch: ${printable(text.slice(4))}`)
60
+ inPack = text === 'packfile'
61
+ continue
62
+ }
63
+ if (data === null) return Buffer.concat(chunks)
64
+ assert.ok(data[0] !== 3, `${method}: GitHub refused the fetch: ${printable(data.subarray(1).toString('latin1'))}`)
65
+ if (data[0] === 1) chunks.push(data.subarray(1))
66
+ }
67
+ assert.fail(`${method}: GitHub answered with no packfile`)
68
+ }
69
+
70
+ // The bytes of the commit `sha` in the pack, an object of the commit type
71
+ // whose `commit <size>\0` and bytes hash to it. The pack is held to its
72
+ // trailer, the sha1 of the rest; an object is read a zlib stream at a time.
73
+ function commitIn(pack, sha, method) {
74
+ assert.ok(pack.length >= 32 && pack.toString('latin1', 0, 4) === 'PACK' && [2, 3].includes(pack.readUInt32BE(4)), `${method}: GitHub's packfile is no packfile`)
75
+ const end = pack.length - 20
76
+ assert.ok(createHash('sha1').update(pack.subarray(0, end)).digest().equals(pack.subarray(end)), `${method}: GitHub's packfile does not match its trailer`)
77
+ let at = 12
78
+ for (let count = pack.readUInt32BE(8); count > 0; count--) {
79
+ let byte = pack[at++]
80
+ const type = (byte >> 4) & 7
81
+ let size = byte & 15
82
+ for (let shift = 4; byte & 0x80; shift += 7) {
83
+ byte = pack[at++]
84
+ size += (byte & 0x7f) * 2 ** shift
85
+ }
86
+ assert.ok(at <= end && size <= MAX_OBJECT, `${method}: an object in GitHub's packfile is cut short, or larger than ${MAX_OBJECT} bytes`)
87
+ // A delta names its base by an offset, or by its id.
88
+ if (type === 6) {
89
+ while (pack[at] & 0x80) at++
90
+ at++
91
+ }
92
+ if (type === 7) at += 20
93
+ let object
94
+ try {
95
+ object = inflateSync(pack.subarray(at, end), { info: true, maxOutputLength: Math.max(size, 1) })
96
+ } catch (cause) {
97
+ throw new Error(`${method}: an object in GitHub's packfile does not inflate`, { cause })
98
+ }
99
+ at += object.engine.bytesWritten
100
+ if (type !== 1 || object.buffer.length !== size) continue
101
+ const id = createHash('sha1').update(`commit ${size}\0`).update(object.buffer).digest('hex')
102
+ if (id === sha) return object.buffer
103
+ }
104
+ assert.fail(`${method}: GitHub's packfile holds no commit ${sha}`)
105
+ }
106
+
107
+ // A sha1 alone: GitHub keeps no repository in sha256.
108
+ const assertCommit = assertion('a full commit sha1', isSha1)
109
+
110
+ // The id of the tree of the full commit `sha`, from the commit's own
111
+ // object: fetched from github.com's git-upload-pack, as git fetches it, and
112
+ // held to `sha`, so the tree is the commit's whatever GitHub's API says.
113
+ // The API's token, where the client has one, is sent as git sends one, by
114
+ // Basic. A redirect is not followed: one for a repository renamed or
115
+ // transferred throws, as getRepo is the call that follows it.
116
+ export async function getCommitTree(headers, options) {
117
+ assertArgs('getCommitTree', options, { repo: assertRepo, sha: assertCommit })
118
+ const { repo, sha } = options
119
+ const [owner, name] = repo.split('/')
120
+ const token = /^Bearer (.+)$/u.exec(headers.Authorization ?? '')?.[1]
121
+ const answer = await request(buildUrl(GITHUB_WEB, [owner, `${name}.git`, 'git-upload-pack']), {
122
+ method: 'POST',
123
+ as: 'bytes',
124
+ headers: {
125
+ ...(token !== undefined && { Authorization: `Basic ${Buffer.from(`x-access-token:${token}`).toString('base64')}` }),
126
+ 'User-Agent': headers['User-Agent'],
127
+ 'Git-Protocol': 'version=2',
128
+ 'Content-Type': 'application/x-git-upload-pack-request',
129
+ Accept: 'application/x-git-upload-pack-result',
130
+ },
131
+ body: fetchRequest(sha),
132
+ })
133
+ const commit = commitIn(packOf(Buffer.from(answer), 'getCommitTree'), sha, 'getCommitTree')
134
+ const tree = /^tree ([\da-f]{40})\n/u.exec(commit.toString('latin1'))?.[1]
135
+ assert.ok(tree !== undefined, `getCommitTree: the commit ${sha} in ${repo} names no tree first, as git writes one: ${show(commit.toString('latin1', 0, 60))}`)
136
+ return tree
137
+ }
@@ -8,6 +8,7 @@ import { FORMATS, lockfileOf, projectFormats } from '../lockfiles.js'
8
8
  import { pool } from '../pool.js'
9
9
  import { gitTreeOfListing, objectId } from '../tree.js'
10
10
  import { api, bindMethods, call, clientHeaders, isGone, repoApi } from './client.js'
11
+ import { getCommitTree } from './commit.js'
11
12
 
12
13
  const PER_PAGE = 100
13
14
  const MAX_PAGES = 100
@@ -385,5 +386,5 @@ async function listRepoAdvisories(headers, options) {
385
386
  return (await Array.fromAsync(cursorPages('listRepoAdvisories', headers, pageUrl))).flat()
386
387
  }
387
388
 
388
- export const readMethods = { getCurrentUser, listUserRepos, getRepo, getRepoHead, getRepoTag, listRepoTags, listRepoBranches, compareCommits, getRepoFile, getRepoTarball, getRepoTreeTarball, getRepoTreeId, listRepoDir, listRepoTree, findRepoLockfiles, getPullRequest, getCollaboratorPermission, getAdvisory, listRepoAdvisories }
389
+ export const readMethods = { getCurrentUser, listUserRepos, getRepo, getRepoHead, getRepoTag, listRepoTags, listRepoBranches, compareCommits, getRepoFile, getCommitTree, getRepoTarball, getRepoTreeTarball, getRepoTreeId, listRepoDir, listRepoTree, findRepoLockfiles, getPullRequest, getCollaboratorPermission, getAdvisory, listRepoAdvisories }
389
390
  export const createClient = (options) => bindMethods(clientHeaders('createClient', options, true), readMethods)
package/src/http.js CHANGED
@@ -9,16 +9,22 @@ import { matches, printable } from './args.js'
9
9
  export const NPM_REGISTRY = 'https://registry.npmjs.org'
10
10
  export const GITHUB_API = 'https://api.github.com'
11
11
  export const OSV_API = 'https://api.osv.dev'
12
+ export const OSV_EXPORTS = 'https://osv-vulnerabilities.storage.googleapis.com'
12
13
  export const CRATES_API = 'https://crates.io'
13
14
  export const PACKAGIST_REPO = 'https://repo.packagist.org'
15
+ export const PACKAGIST = 'https://packagist.org'
14
16
  export const CRATES_INDEX = 'https://index.crates.io'
15
17
  export const CRATES_STATIC = 'https://static.crates.io'
16
18
  export const SOLDEER_API = 'https://api.soldeer.xyz'
17
19
  export const SOLDEER_REVISIONS = 'https://soldeer-revisions.s3.amazonaws.com'
18
20
  export const COCOAPODS_CDN = 'https://cdn.cocoapods.org'
21
+ export const RUBYGEMS = 'https://rubygems.org'
22
+ export const RUBYGEMS_INDEX = 'https://index.rubygems.org'
23
+ export const PYPI = 'https://pypi.org'
24
+ export const GITHUB_WEB = 'https://github.com'
19
25
  export const MAX_BYTES = 512 * 1024 * 1024
20
26
 
21
- const ORIGINS = new Set([NPM_REGISTRY, GITHUB_API, OSV_API, CRATES_API, PACKAGIST_REPO, CRATES_INDEX, CRATES_STATIC, SOLDEER_API, SOLDEER_REVISIONS, COCOAPODS_CDN])
27
+ const ORIGINS = new Set([NPM_REGISTRY, GITHUB_API, OSV_API, OSV_EXPORTS, CRATES_API, PACKAGIST_REPO, PACKAGIST, CRATES_INDEX, CRATES_STATIC, SOLDEER_API, SOLDEER_REVISIONS, COCOAPODS_CDN, RUBYGEMS, RUBYGEMS_INDEX, PYPI, GITHUB_WEB])
22
28
  const isSegment = matches(/^(?!\.\.?$)(?:[\w.~@-]|%[\dA-F]{2})+$/u)
23
29
  const isQueryKey = matches(/^[a-z_]+(?:\[\])?$/u)
24
30
  const isQueryValue = (value) => (typeof value === 'string' && value !== '') || (Number.isSafeInteger(value) && value >= 0)
@@ -83,7 +89,8 @@ export async function send(url, { method = 'GET', headers = {}, body, redirect =
83
89
  assert.ok(['manual', 'follow'].includes(redirect), `Unexpected redirect mode: ${redirect}`)
84
90
  assert.ok(Object.hasOwn(LIMITS, as), `Unexpected response type: ${as}`)
85
91
  assert.ok(Object.entries(headers).every(isHeader), 'Unexpected header')
86
- const json = body === undefined ? {} : { headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }
92
+ // Bytes as they are, under the type `headers` give; anything else as JSON.
93
+ const json = body === undefined ? {} : body instanceof Uint8Array ? { body } : { headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) }
87
94
  return await fetch(url, { method, headers, redirect, signal: AbortSignal.timeout(LIMITS[as].ms), ...json })
88
95
  }
89
96
 
@@ -40,12 +40,6 @@ function isKeepable(method, name, version, json) {
40
40
  }
41
41
  }
42
42
 
43
- // A version's document as `cache` keeps it (readJSON), or none.
44
- async function keptDocument(method, name, version, cache) {
45
- const json = await readJSON(DIR, `${name}@${version}`, cache)
46
- return isKeepable(method, name, version, json) ? json : undefined
47
- }
48
-
49
43
  // The registry's document, kept whole in `cache` once it is keepable; one
50
44
  // whose dist is refused is answered all the same.
51
45
  async function keepDocument(method, name, version, json, cache) {
@@ -54,15 +48,13 @@ async function keepDocument(method, name, version, json, cache) {
54
48
  return json
55
49
  }
56
50
 
57
- const fetchDocument = async (method, name, version, cache) => await keepDocument(method, name, version, await getDocument(method, name, version), cache)
58
-
59
- // A version's document, kept or else fetched, for what is not an
60
- // integrity: a package's repo (advisories.js), as trusted as setCacheDir's
61
- // repo records are. Null where the registry does not have that version:
62
- // its 404 alone, never a failure of the cache's.
51
+ // A version's document, kept (readJSON) or else fetched, for what is not
52
+ // an integrity: a package's repo (advisories.js), as trusted as
53
+ // setCacheDir's repo records are. Null where the registry does not have
54
+ // that version: its 404 alone, never a failure of the cache's.
63
55
  export async function getVersionDocument(method, name, version, cache) {
64
- const kept = await keptDocument(method, name, version, cache)
65
- if (kept) return kept
56
+ const kept = await readJSON(DIR, `${name}@${version}`, cache)
57
+ if (isKeepable(method, name, version, kept)) return kept
66
58
  const json = await getDocument(method, name, version).catch(recover(isNotFound, null))
67
59
  return json && await keepDocument(method, name, version, json, cache)
68
60
  }
@@ -87,7 +79,7 @@ export async function getVersion(method, name, version, given, cache) {
87
79
  const dist = matchingDist(method, name, version, kept, given)
88
80
  if (dist) return { dist, json: kept }
89
81
  }
90
- const json = await fetchDocument(method, name, version, cache)
82
+ const json = await keepDocument(method, name, version, await getDocument(method, name, version), cache)
91
83
  const dist = distOf(method, name, version, json)
92
84
  if (given !== undefined) {
93
85
  assert.ok(dist.integrity === given.integrity, `${method}: ${name}@${version} is ${dist.integrity} on the registry, not ${given.integrity}`)
@@ -0,0 +1,49 @@
1
+ import { compareVersions, parseVersion } from '@preventive/lockfile/pep440.js'
2
+
3
+ import { assertion, matches } from '../args.js'
4
+
5
+ // PEP 440 versions, by @preventive/lockfile, and GitHub's ranges of them.
6
+ export { compareVersions }
7
+
8
+ // 256 at most, before any regex runs.
9
+ export const isVersion = (text) => typeof text === 'string' && text.length <= 256 && parseVersion(text) !== undefined
10
+ export const assertPypiVersion = assertion('a PEP 440 version', isVersion)
11
+ // PEP 508's: letters, digits and `-_.` inside.
12
+ export const assertPypiName = assertion('a Python package name', matches(/^(?=.{1,255}$)[\dA-Za-z](?:[\w.-]*[\dA-Za-z])?$/u))
13
+
14
+ // PEP 503's: any case, and a run of `-`, `_` and `.` one `-`.
15
+ export const normalName = (name) => name.toLowerCase().replaceAll(/[-_.]+/gu, '-')
16
+
17
+ const PART = /^\s*(<=|>=|<|>|=)?\s*(\S+)\s*$/u
18
+ const OPERATORS = {
19
+ __proto__: null,
20
+ '=': (cmp) => cmp === 0,
21
+ '<': (cmp) => cmp < 0,
22
+ '<=': (cmp) => cmp <= 0,
23
+ '>': (cmp) => cmp > 0,
24
+ '>=': (cmp) => cmp >= 0,
25
+ }
26
+
27
+ // Undefined where a part isn't an operator and a version, or the range is
28
+ // over 1,024 characters.
29
+ function requirementsOf(text) {
30
+ if (text.length > 1024) return undefined
31
+ const parts = text.split(',').map((part) => PART.exec(part))
32
+ if (parts.some((match) => match === null || !isVersion(match[2]))) return undefined
33
+ return parts.map(([, operator = '=', against]) => [operator, against])
34
+ }
35
+
36
+ // A pre-release is in a range around it, as for every ecosystem here.
37
+ export function readRange(text) {
38
+ const parts = requirementsOf(text)
39
+ return parts && ((version) => parts.every(([operator, against]) => OPERATORS[operator](compareVersions(version, against))))
40
+ }
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
49
+ }
@@ -0,0 +1,96 @@
1
+ import assert from 'node:assert/strict'
2
+ import { readdir } from 'node:fs/promises'
3
+ import { delimiter, join, resolve } from 'node:path'
4
+
5
+ import { assertGem, assertSha256, assertion, isSha256, matches, printable } from '../args.js'
6
+ import { absolute, home } from '../cache.js'
7
+ import { verifiedDownload } from '../download.js'
8
+ import { RUBYGEMS, RUBYGEMS_INDEX, buildUrl, encodeSegment, request } from '../http.js'
9
+ import { isGemPlatform, platformOf } from './platform.js'
10
+ import { isVersion } from './version.js'
11
+
12
+ // No expiry: a yanked version keeps its number, so is never pushed again,
13
+ // and an unyank restores the same file.
14
+ const DIR = 'rubygems/gems'
15
+
16
+ const assertPlatform = assertion('`ruby` or a platform as RubyGems writes one', (value) => value === 'ruby' || isGemPlatform(value))
17
+ const hexOf = (checksum) => checksum.replace(/^sha256=/u, '')
18
+ const assertChecksum = assertion('a sha256 in lowercase hex, bare or after `sha256=`', (value) => typeof value === 'string' && isSha256(hexOf(value)))
19
+
20
+ // The cache entry, `<name>@<version>[-<platform>]`, can't collide: a name
21
+ // has no `@`, a version no `-`.
22
+ function gemOf(method, name, version, platform) {
23
+ assertGem(method, name, version)
24
+ assertPlatform(method, 'platform', platform)
25
+ const suffix = platform === 'ruby' ? '' : `-${platform}`
26
+ return { name, version, platform, what: `${name}@${version}${suffix}`, file: `${name}-${version}${suffix}.gem` }
27
+ }
28
+
29
+ // `<version>[-<platform>] <deps>|<key:value,...>`, split at the first `-`
30
+ // as Bundler does.
31
+ const LINE = /^(?<version>[^\s|-]+)(?:-(?<platform>[^\s|]+))? [^|]*\|(?<metadata>.*)$/u
32
+
33
+ // The compact index, as Bundler reads it: every line after the first `---`,
34
+ // each of a version Gem::Version reads, and of a platform as RubyGems 3 or 4
35
+ // reads it, so `i686-linux` is `x86-linux` too. grpc's, of 1,500, is 340 KB.
36
+ const MAX_INDEX = 16 * 1024 * 1024
37
+ const readsAs = (written, platform) => written === platform || (written !== 'ruby' && platform !== 'ruby' && (platformOf(written, 3) === platform || platformOf(written, 4) === platform))
38
+ async function getChecksum(method, { name, version, platform, what }) {
39
+ const text = await request(buildUrl(RUBYGEMS_INDEX, ['info', name]), { as: 'text' })
40
+ assert.ok(text.length <= MAX_INDEX, `${method}: the index for ${name} is over ${MAX_INDEX} characters`)
41
+ const lines = text.split('\n')
42
+ while (lines.at(-1) === '') lines.pop()
43
+ const found = []
44
+ for (const line of lines.slice(lines.indexOf('---') + 1)) {
45
+ const match = LINE.exec(line)
46
+ if (match === null || !isVersion(match.groups.version) || match.groups.platform === 'current') {
47
+ assert.fail(`${method}: the index for ${name} has a line that is not a version's: ${printable(line.slice(0, 200))}`)
48
+ }
49
+ if (match.groups.version === version && readsAs(match.groups.platform ?? 'ruby', platform)) found.push(match.groups.metadata)
50
+ }
51
+ assert.ok(found.length > 0, `${method}: the index has no ${what}`)
52
+ assert.ok(found.length === 1, `${method}: the index has ${what} on ${found.length} lines`)
53
+ const checksums = found[0].split(',').filter((pair) => pair.startsWith('checksum:'))
54
+ assert.ok(checksums.length === 1, `${method}: the index has ${checksums.length} checksums for ${what}`)
55
+ const checksum = checksums[0].slice('checksum:'.length)
56
+ assertSha256(method, 'the index checksum', checksum)
57
+ return checksum
58
+ }
59
+
60
+ // Gem.user_dir: <engine>/<ruby version> under ~/.gem and the XDG data dir, as
61
+ // RUBY_ENGINE and RbConfig's ruby_version name them, so not a GEM_HOME's gems/.
62
+ const isEngine = matches(/^[a-z]{1,32}$/u)
63
+ const isRubyVersion = matches(/^\d+(?:\.\d+){0,2}(?:\+\d+)?$/u)
64
+ async function userDirs() {
65
+ const base = home()
66
+ if (base === undefined) return []
67
+ const data = absolute(process.env.XDG_DATA_HOME) ?? join(base, '.local', 'share')
68
+ const below = (keep) => async (dir) => (await readdir(dir).catch(() => [])).filter(keep).map((name) => join(dir, name))
69
+ const engines = (await Promise.all([join(base, '.gem'), join(data, 'gem')].map(below(isEngine)))).flat()
70
+ return (await Promise.all(engines.map(below(isRubyVersion)))).flat()
71
+ }
72
+
73
+ // RubyGems' own downloads, in the cache/ of each absolute gem dir: the cwd is
74
+ // not ours to read. Gem.default_dir depends on how Ruby was built, so is read
75
+ // only as GEM_PATH or GEM_HOME names it.
76
+ async function localPaths(file) {
77
+ const { GEM_HOME, GEM_PATH } = process.env
78
+ const named = [...(GEM_PATH ?? '').split(delimiter), GEM_HOME].map(absolute).filter(Boolean).map((dir) => resolve(dir))
79
+ return [...new Set([...named, ...await userDirs()])].map((dir) => join(dir, 'cache', file))
80
+ }
81
+
82
+ export async function verifyChecksum(name, version, platform, checksum) {
83
+ const gem = gemOf('verifyChecksum', name, version, platform)
84
+ assertChecksum('verifyChecksum', 'checksum', checksum)
85
+ const hex = hexOf(checksum)
86
+ const indexed = await getChecksum('verifyChecksum', gem)
87
+ assert.ok(indexed === hex, `verifyChecksum: ${gem.what} is ${indexed} on rubygems.org, not ${hex}`)
88
+ }
89
+
90
+ export async function getGem(name, version, platform, checksum) {
91
+ const gem = gemOf('getGem', name, version, platform)
92
+ if (checksum !== undefined) assertChecksum('getGem', 'checksum', checksum)
93
+ const expected = checksum === undefined ? await getChecksum('getGem', gem) : hexOf(checksum)
94
+ const locate = () => buildUrl(RUBYGEMS, ['gems', encodeSegment(gem.file)])
95
+ return await verifiedDownload({ method: 'getGem', dir: DIR, what: gem.what, ext: 'gem', algorithm: 'sha256', expected, local: await localPaths(gem.file), locate })
96
+ }