@preventive/upstream 1.3.0 → 1.5.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.
package/advisories.d.ts CHANGED
@@ -58,8 +58,11 @@ export interface AdvisoryOptions {
58
58
  // its id among an OSV record's id and aliases, is left to that row,
59
59
  // which takes the record's ids among its aliases; the versions a record
60
60
  // of the row's own id covers beyond the registry's range join it too.
61
- // Sends each npm package's name and versions to OSV, so not for a
62
- // private package.
61
+ // Only packages whose name npm's registry serves without a token (a
62
+ // HEAD, unscoped names too) go to OSV; the rest, private ones above all,
63
+ // go to the registry alone. The name decides, not the version: npm takes
64
+ // down malicious versions but keeps their name. Public names are cached
65
+ // for a month.
63
66
  osv?: boolean
64
67
  }
65
68
 
@@ -130,6 +133,11 @@ export interface Advisory {
130
133
  // `unmaintained`, `unsound`, `notice`. For an id answered more than once,
131
134
  // only where each answer gives it.
132
135
  informational?: string
136
+ // Where the advisory is of malware, not a vulnerability: an OSV MAL-
137
+ // record (its `id` or an alias), CWE-506 (how GitHub files malware), or
138
+ // a `title` with the word "malware". `severity` is left as rated: MAL-
139
+ // records have none, and GitHub rates some malware high.
140
+ malware?: true
133
141
  versions: string[]
134
142
  }
135
143
 
@@ -140,7 +148,8 @@ export interface Advisory {
140
148
  // one GHSA among npm's rows; a project Soldeer does not have or that names
141
149
  // no GitHub repository, a repository gone or blocked, and one GitHub
142
150
  // redirects anywhere but to a repository by its id, add nothing, and a
143
- // GHSA OSV does not have adds no `details`. A repository renamed or
151
+ // GHSA OSV does not have adds no `details`. With `osv`, a name npm's
152
+ // registry doesn't answer a HEAD for is taken as private (see `osv`). A repository renamed or
144
153
  // transferred, which GitHub redirects to it by its id, is listed by the
145
154
  // name it has now, as getRepo's `followRedirect` (github.js) finds it, its
146
155
  // rows' `url` on it. Any other failure, a malformed answer, or one about
package/cocoapods.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ // The name is asserted to be a root's as Podfile.lock writes it, printable
2
+ // ASCII but for spaces, parentheses, slashes and backslashes, with no `.`
3
+ // first; the version one of Pod::Version's; and the checksum 40 lowercase
4
+ // hex digits, before any request or cache path. The cache is setCacheDir's
5
+ // (npm.js).
6
+
7
+ export { HttpError } from './npm.js'
8
+
9
+ // A version's podspec from trunk, the JSON CocoaPods reads, whole, in
10
+ // memory, as the CDN serves it under Specs/<a>/<b>/<c>/<name>/<version>/,
11
+ // the first three hex digits of the md5 of the name: the files of
12
+ // CocoaPods/Specs, so a pod from https://github.com/CocoaPods/Specs.git
13
+ // too. Trunk says nothing of what a podspec hashes to, so `checksum` is
14
+ // required: its sha1, as Podfile.lock records it in SPEC CHECKSUMS. The
15
+ // bytes are checked against it, whether they were downloaded (before they
16
+ // are cached) or read from a cache. The CDN's redirect to jsDelivr is
17
+ // followed, as the bytes are checked whoever answers.
18
+ //
19
+ // A podspec is not fixed once trunk has it: `pod trunk deprecate` adds a
20
+ // field to the latest version's. So one is cached by its checksum as well
21
+ // as its version, and a lockfile written before such a change has a
22
+ // checksum no download matches any longer, which throws.
23
+ //
24
+ // CocoaPods' own spec repos are read first, and never written: that path
25
+ // in each directory under $CP_REPOS_DIR, else $CP_HOME_DIR/repos, else
26
+ // `~/.cocoapods/repos`. A file there that does not match is passed over.
27
+ // One in setCacheDir's cache that does not match throws. A cached podspec
28
+ // that matches is answered with no request at all.
29
+ //
30
+ // What the pod is built from is not trunk's, and is not fetched here: a
31
+ // commit of a GitHub repo, as a podspec's `source` or CHECKOUT OPTIONS
32
+ // may name, is github.js's getRepoTarball's.
33
+ export function getPodspec(name: string, version: string, checksum: string): Promise<Uint8Array>
package/cocoapods.js ADDED
@@ -0,0 +1,2 @@
1
+ export { getPodspec } from './src/cocoapods.js'
2
+ export { HttpError } from './src/http.js'
package/github.d.ts CHANGED
@@ -89,6 +89,17 @@ export interface Client {
89
89
  // `node_modules`, of packages installed. A symlink is no file. Refused
90
90
  // where a path found is one getRepoFile does not take, such as one with a
91
91
  // control character in it.
92
+ // How `head` stands to `base` in the repo (each a full commit sha, or a
93
+ // branch or tag name), as GitHub's compare tells it: `ahead` where `base`
94
+ // is in `head`'s history, `behind` the other way round, `identical`, or
95
+ // `diverged`; with the commits each has that the other hasn't, and their
96
+ // merge base. Refused unless the status agrees with those counts, the
97
+ // merge base is `base` where `head` is ahead of it or the same, and the
98
+ // base GitHub compared is `base` where that is a commit. GitHub answers
99
+ // for a commit of any fork of the repo too, through the repo's own name:
100
+ // whether one is the repo's own is whether a ref of the repo (its default
101
+ // branch, say) is ahead of it or the same.
102
+ compareCommits(options: { repo: RepoName; base: string; head: string }): Promise<{ status: 'ahead' | 'behind' | 'identical' | 'diverged'; aheadBy: number; behindBy: number; mergeBase: string }>
92
103
  findRepoLockfiles(options: { repo: RepoName; sha: string; directory?: string }): Promise<{ lockfiles: RepoLockfile[]; projects: RepoProjectFile[] }>
93
104
  // An advisory by its GHSA id. With `repo`, that repository's published
94
105
  // copy: the maintainer's latest text, there before GitHub reviews it,
@@ -169,6 +180,20 @@ export interface Client {
169
180
  // found as getRepoTreeId finds it: GitHub's listing, hashed back to the
170
181
  // tree's id, so none is left out or changed.
171
182
  listRepoDir(options: { repo: RepoName; sha: string; directory?: string }): Promise<RepoDirEntry[]>
183
+ // Every entry of the full commit `sha`'s tree, `path` the one from its
184
+ // root: GitHub's listing of the tree with every tree under it, each of
185
+ // those hashed back to its id, so none is left out, changed or added.
186
+ // Where GitHub cuts that short, past 100,000 entries or 7 MB, its own
187
+ // listing instead, then each tree's in it the same way, as GitHub
188
+ // advises; with `paths`, only the trees those paths are in, so another
189
+ // tree's entries may be left out. No more than `maxTrees` trees (500 by
190
+ // default) are listed, six at once: past them, the rest are left out
191
+ // too, and `cut` is true.
192
+ listRepoTree(options: { repo: RepoName; sha: string; paths?: string[]; maxTrees?: number }): Promise<{ entries: RepoDirEntry[]; cut: boolean }>
193
+ // Every page of the repo's branches, as GitHub lists them, each with the
194
+ // commit at its head; more than `maxPages` (100 by default) pages of 100
195
+ // is an error, as is a branch with no commit.
196
+ listRepoBranches(options: { repo: RepoName; maxPages?: number }): Promise<{ branch: string; oid: string }[]>
172
197
  // Every page of the repo's tags, as GitHub lists them, each with the
173
198
  // commit GitHub names for it, an annotated tag's included, which
174
199
  // getRepoTag checks is one; more than `maxPages` (100 by default) pages
package/npm.d.ts CHANGED
@@ -37,11 +37,12 @@ export const defaultCacheDir: string | undefined
37
37
  // with no request. Point it only at storage that
38
38
  // nothing less trusted than the caller can write, never a cache shared
39
39
  // with or restored from lower-trust jobs. Tarballs, crates (cargo.js), zips
40
- // (soldeer.js) and tree tarballs (github.js) don't rely on this, since
41
- // they are checked against their integrity on every call; and the version
42
- // documents kept here (getMeta) never supply an integrity, only confirm
43
- // one a caller gives (verifyDist, and getMeta with a `dist`). A call's `cache` option, where it has
44
- // one, keeps what it caches elsewhere, or writes none of it here.
40
+ // (soldeer.js), podspecs (cocoapods.js) and tree tarballs (github.js) don't
41
+ // rely on this, since they are checked against their integrity on every
42
+ // call; and the version documents kept here (getMeta) never supply an
43
+ // integrity, only confirm one a caller gives (verifyDist, and getMeta with
44
+ // a `dist`). A call's `cache` option, where it has one, keeps what it
45
+ // caches elsewhere, or writes none of it here.
45
46
  export function setCacheDir(dir?: string | false): void
46
47
 
47
48
  // A store of the caller's, a database's say, for what would otherwise be
@@ -50,8 +51,9 @@ export function setCacheDir(dir?: string | false): void
50
51
  // what is kept and a `key` which one: `npm/versions` and `npm/tarballs`
51
52
  // with `<name>@<version>` for a version's document and tarball; and for
52
53
  // advisories.js, `github/advisories` with the repository's `owner/name` in
53
- // lowercase for its listing, and `cargo/repos`, `composer/repos` and
54
- // `soldeer/repos` with a package's name for the repository it names.
54
+ // lowercase for its listing, `cargo/repos`, `composer/repos` and
55
+ // `soldeer/repos` with a package's name for the repository it names, and
56
+ // `npm/public` with an npm package's name that is public, for `osv`.
55
57
  // Values are plain JSON data, which `read` may answer as written or as a
56
58
  // copy, but a tarball's are its bytes, a Uint8Array. Whatever it answers
57
59
  // is checked as a cached file is: one malformed, stale or kept differently
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@preventive/upstream",
3
- "version": "1.3.0",
4
- "description": "Minimal npm, crates.io, Soldeer, GitHub and git checkout clients",
3
+ "version": "1.5.0",
4
+ "description": "Minimal npm, crates.io, Soldeer, CocoaPods trunk, GitHub and git checkout clients",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  "./advisories.js": {
@@ -12,6 +12,10 @@
12
12
  "types": "./cargo.d.ts",
13
13
  "default": "./cargo.js"
14
14
  },
15
+ "./cocoapods.js": {
16
+ "types": "./cocoapods.d.ts",
17
+ "default": "./cocoapods.js"
18
+ },
15
19
  "./github.js": {
16
20
  "types": "./github.d.ts",
17
21
  "default": "./github.js"
@@ -52,6 +56,8 @@
52
56
  "advisories.js",
53
57
  "cargo.d.ts",
54
58
  "cargo.js",
59
+ "cocoapods.d.ts",
60
+ "cocoapods.js",
55
61
  "github.d.ts",
56
62
  "github.js",
57
63
  "git.d.ts",
@@ -79,6 +85,7 @@
79
85
  "src/cache.js",
80
86
  "src/cargo/crate.js",
81
87
  "src/cargo/repos.js",
88
+ "src/cocoapods.js",
82
89
  "src/download.js",
83
90
  "src/git.js",
84
91
  "src/github/client.js",
@@ -38,7 +38,13 @@ export function detailsOf(text, id) {
38
38
  return { details: text }
39
39
  }
40
40
 
41
- const SEVERITIES = new Set(['critical', 'high', 'moderate', 'low', 'info'])
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.
45
+ export const isMalware = ({ id, aliases, cwe, title }) => [id, ...aliases].some((each) => each.startsWith('MAL-')) || cwe.includes('CWE-506') || /\bmalware\b/iu.test(title ?? '')
46
+
47
+ export const SEVERITIES = ['critical', 'high', 'moderate', 'low', 'info']
42
48
  const isCvssVector = matches(/^CVSS:[34]\.\d(?:\/[A-Z]{1,4}:[A-Z]{1,2})+$/u)
43
49
  const isCwe = matches(/^CWE-\d{1,6}$/u)
44
50
 
@@ -48,7 +54,7 @@ const isCwe = matches(/^CWE-\d{1,6}$/u)
48
54
  export function metrics({ severity, score, vector, cwe }) {
49
55
  const word = typeof severity === 'string' ? severity.toLowerCase().replace(/^medium$/u, 'moderate') : undefined
50
56
  return {
51
- ...(SEVERITIES.has(word) && { severity: word }),
57
+ ...(SEVERITIES.includes(word) && { severity: word }),
52
58
  ...(typeof score === 'number' && score > 0 && score <= 10 && { cvss: score }),
53
59
  ...(isCvssVector(vector) && { cvssVector: vector }),
54
60
  cwe: isStrings(cwe) ? cwe.filter(isCwe) : [],
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
2
2
 
3
3
  import { assertArgs, assertBoolean, assertRepo, assertion, isIterable, optional, sameName } from '../args.js'
4
4
  import { assertCache } from '../cache.js'
5
- import { order } from './common.js'
5
+ import { SEVERITIES, isMalware, order } from './common.js'
6
6
  import { GITHUB, SOLDEER, assertClient } from './github.js'
7
7
  import { NPM } from './npm.js'
8
8
  import { CARGO, COMPOSER } from './osv.js'
@@ -37,7 +37,6 @@ function collect(packages) {
37
37
  // Which of an advisory's rows stands for it: npm's registry's, then OSV's,
38
38
  // then its repository's.
39
39
  const SOURCES = ['registry', 'osv', 'repository']
40
- const SEVERITIES = ['critical', 'high', 'moderate', 'low', 'info']
41
40
  const worse = (a, b) => (b === undefined || (a !== undefined && SEVERITIES.indexOf(a) < SEVERITIES.indexOf(b)) ? a : b)
42
41
 
43
42
  // An advisory's rows as one: the first's by source, what it lacks from the
@@ -96,7 +95,7 @@ export async function advisories(packages, options = {}) {
96
95
  const asked = new Map(names.map((name) => [name, [...named.get(name).versions].toSorted(compare)]))
97
96
  const known = new Map(names.filter((name) => named.get(name).github).map((name) => [name, named.get(name).github]))
98
97
  const rows = await find(asked, { github: options.github, repoAdvisories: options.repoAdvisories === true, details: options.details === true, osv: options.osv === true, known, cache: options.cache })
99
- return oneRowPerAdvisory(rows.filter((row) => row.versions.length > 0), asked).map((row) => ({ ecosystem, ...row }))
98
+ return oneRowPerAdvisory(rows.filter((row) => row.versions.length > 0), asked).map((row) => ({ ecosystem, ...row, ...(isMalware(row) && { malware: true }) }))
100
99
  }))
101
100
  return found.flat().toSorted((a, b) => order(a.ecosystem, b.ecosystem) || order(a.name, b.name))
102
101
  }
@@ -1,7 +1,8 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
3
  import { assertPackageName, assertPackageVersion, isGhsa, isStrings, show } from '../args.js'
4
- import { NPM_REGISTRY, buildUrl, isNotFound, recover, request } from '../http.js'
4
+ import { readRecord, writeRecord } from '../cache.js'
5
+ import { NPM_REGISTRY, answersHead, buildUrl, isNotFound, recover, request } from '../http.js'
5
6
  import { chunks, pool } from '../pool.js'
6
7
  import { compareVersions } from '../semver.js'
7
8
  import { advisoryUrl, covered, detailsOf, isText, metrics } from './common.js'
@@ -12,6 +13,7 @@ import { npmRepos } from './repos.js'
12
13
  const BULK_URL = buildUrl(NPM_REGISTRY, ['-', 'npm', 'v1', 'security', 'advisories', 'bulk'])
13
14
  const NAMES_PER_REQUEST = 250
14
15
  const GHSA_PAGE = 'https://github.com/advisories/'
16
+ const NAMES_AT_ONCE = 8
15
17
 
16
18
  const isRow = (row) => row && typeof row === 'object' && Number.isSafeInteger(row.id)
17
19
  && ['url', 'severity', 'vulnerable_versions'].every((key) => typeof row[key] === 'string') && isText(row.title)
@@ -85,14 +87,47 @@ function withOsv(registry, osv) {
85
87
  return [...rows, ...added]
86
88
  }
87
89
 
90
+ // Whether npm's registry serves `name` to anyone: a HEAD with no token,
91
+ // answered 2xx. Private packages and other registries' answer 404; any
92
+ // other answer, or none, counts as private too, as in triage.
93
+ async function servesAnyone(name) {
94
+ try {
95
+ return await answersHead(buildUrl(NPM_REGISTRY, name.split('/')))
96
+ } catch {
97
+ return false
98
+ }
99
+ }
100
+
101
+ // The packages of `asked` whose name is public (servesAnyone). The name
102
+ // decides, not the version: npm takes down malicious versions but keeps
103
+ // their name. Public names are kept a month, as a scoped package can be
104
+ // made private; the rest are asked again each time.
105
+ async function publicOnly(asked, cache) {
106
+ const names = [...asked.keys()]
107
+ const kept = await pool(names, NAMES_AT_ONCE, (name) => readRecord('npm/public', name, cache))
108
+ const missing = names.filter((name, i) => kept[i]?.public !== true)
109
+ const found = await pool(missing, NAMES_AT_ONCE, servesAnyone)
110
+ const added = missing.filter((name, i) => found[i])
111
+ await pool(added, NAMES_AT_ONCE, (name) => writeRecord('npm/public', name, { public: true }, cache))
112
+ const serving = new Set([...names.filter((name, i) => kept[i]?.public === true), ...added])
113
+ return new Map([...asked].filter(([name]) => serving.has(name)))
114
+ }
115
+
116
+ // OSV's records of the public packages only: no request to OSV names a
117
+ // private one.
118
+ async function osvOfPublic(asked, options) {
119
+ const told = await publicOnly(asked, options.cache)
120
+ return told.size > 0 ? await osvRows({ osv: 'npm' }, told, options) : []
121
+ }
122
+
88
123
  // What `npm audit` asks the registry, one row per vulnerable range, and
89
- // with `osv`, what OSV has besides.
124
+ // with `osv`, OSV's records of the public packages.
90
125
  export const NPM = {
91
126
  assertName: assertPackageName,
92
127
  assertVersion: assertPackageVersion,
93
128
  compare: compareVersions,
94
129
  advisories: async (asked, options) => {
95
- const [registry, osv] = await Promise.all([registryAdvisories(asked), options.osv ? osvRows({ osv: 'npm' }, asked, options) : []])
130
+ const [registry, osv] = await Promise.all([registryAdvisories(asked), options.osv ? osvOfPublic(asked, options) : []])
96
131
  const rows = withOsv(registry, osv)
97
132
  return await withRepositories(options.details ? await withDetails(rows) : rows, asked, options, { ecosystem: 'npm', lookUp: npmRepos })
98
133
  },
package/src/args.js CHANGED
@@ -99,6 +99,12 @@ export const assertSoldeerName = assertion('a Soldeer package name', matches(/^(
99
99
  // Soldeer takes any version but an empty one. Its registry has semver
100
100
  // (`5.7.0-rc.0`, `1.0.2-solc-0.8-simulate`), bare numbers and commit hashes.
101
101
  export const assertSoldeerVersion = assertion('letters, digits, `.`, `_`, `+` and `-`', matches(/^(?=.{1,128}$)[\dA-Za-z][\w.+-]*$/u))
102
+ // A root's name as Podfile.lock has it, and @preventive/lockfile reads it:
103
+ // printable ASCII but for spaces, parentheses, slashes and backslashes, no
104
+ // `.` 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
+ // 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))
102
108
  // A package's name and version, as a registry's getters take them.
103
109
  const assertNameVersion = (assertName, assertVersion) => (method, name, version) => {
104
110
  assertName(method, 'name', name)
@@ -107,5 +113,8 @@ const assertNameVersion = (assertName, assertVersion) => (method, name, version)
107
113
  export const assertCrate = assertNameVersion(assertCrateName, assertCrateVersion)
108
114
  export const assertPackage = assertNameVersion(assertPackageName, assertPackageVersion)
109
115
  export const assertSoldeerPackage = assertNameVersion(assertSoldeerName, assertSoldeerVersion)
116
+ export const assertPod = assertNameVersion(assertPodName, assertPodVersion)
110
117
  // As Cargo.lock and soldeer.lock write a checksum.
111
118
  export const assertSha256 = assertion('a sha256 in lowercase hex', matches(/^[\da-f]{64}$/u))
119
+ // As Podfile.lock writes a podspec's checksum.
120
+ export const assertSha1 = assertion('a sha1 in lowercase hex', isSha1)
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/tarballs', 'npm/versions', 'cargo/repos', 'cargo/crates', 'composer/repos', 'soldeer/repos', 'soldeer/zips', 'github/trees', 'github/advisories'])
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'])
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
@@ -0,0 +1,51 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { readdir } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import { join, resolve } from 'node:path'
5
+
6
+ import { assertPod, assertSha1 } from './args.js'
7
+ import { verifiedDownload } from './download.js'
8
+ import { COCOAPODS_CDN, buildUrl, encodeSegment } from './http.js'
9
+
10
+ // No expiry, but kept by checksum as well: trunk refuses a version it
11
+ // already has, yet rewrites a podspec it has, as `pod trunk deprecate`
12
+ // adds a field to the latest version's.
13
+ const DIR = 'cocoapods/podspecs'
14
+
15
+ // Where a spec repo keeps a version's podspec: under a directory each for
16
+ // the first three hex digits of the md5 of the name, as
17
+ // Pod::Source::Metadata shards trunk, and CocoaPods/Specs with it.
18
+ function specPath(name, version) {
19
+ const shard = createHash('md5').update(name).digest('hex').slice(0, 3)
20
+ return ['Specs', ...shard, name, version, `${name}.podspec.json`]
21
+ }
22
+
23
+ // CocoaPods' spec repos, a directory each under $CP_REPOS_DIR, else
24
+ // $CP_HOME_DIR/repos, else ~/.cocoapods/repos: `trunk` with the podspecs
25
+ // it read off the CDN as they were served, `master` a clone of
26
+ // CocoaPods/Specs, others a team's own. os.homedir() throws where there is
27
+ // no home directory to be found.
28
+ async function localPaths(name, version) {
29
+ const { CP_REPOS_DIR, CP_HOME_DIR } = process.env
30
+ let root
31
+ try {
32
+ root = resolve(CP_REPOS_DIR || join(CP_HOME_DIR || join(homedir(), '.cocoapods'), 'repos'))
33
+ } catch {
34
+ return []
35
+ }
36
+ return (await readdir(root).catch(() => [])).map((repo) => join(root, repo, ...specPath(name, version)))
37
+ }
38
+
39
+ // Trunk has no hash to check a podspec against, so the caller brings one,
40
+ // as Podfile.lock records it. The CDN redirects to jsDelivr, which is
41
+ // followed: whoever answers, the bytes are held to the checksum.
42
+ export async function getPodspec(name, version, checksum) {
43
+ assertPod('getPodspec', name, version)
44
+ assertSha1('getPodspec', 'checksum', checksum)
45
+ const what = `${name}@${version}`
46
+ const locate = () => buildUrl(COCOAPODS_CDN, specPath(name, version).map(encodeSegment))
47
+ return await verifiedDownload({
48
+ method: 'getPodspec', dir: DIR, what, entry: `${what}-${checksum}`, ext: 'podspec.json', algorithm: 'sha1', expected: checksum,
49
+ local: await localPaths(name, version), locate, options: { redirect: 'follow' },
50
+ })
51
+ }
package/src/download.js CHANGED
@@ -6,11 +6,13 @@ import { request } from './http.js'
6
6
  import { gitTreeOfTarball } from './tree.js'
7
7
 
8
8
  // A hash as each registry writes it: npm's integrity, one sha512 in base64
9
- // after `sha512-`; crates.io's and Soldeer's checksum, a sha256 in hex; a
10
- // git tree id for a tarball of that tree.
9
+ // after `sha512-`; crates.io's and Soldeer's checksum, a sha256 in hex;
10
+ // Podfile.lock's checksum of a podspec, a sha1 in hex; a git tree id for a
11
+ // tarball of that tree.
11
12
  const DIGESTS = {
12
13
  sha512: (bytes) => `sha512-${createHash('sha512').update(bytes).digest('base64')}`,
13
14
  sha256: (bytes) => createHash('sha256').update(bytes).digest('hex'),
15
+ sha1: (bytes) => createHash('sha1').update(bytes).digest('hex'),
14
16
  tree: gitTreeOfTarball,
15
17
  }
16
18
 
@@ -20,12 +22,12 @@ const DIGESTS = {
20
22
  // whether set or not (read, never written; a mismatch is passed over),
21
23
  // else the cache set, or a `cache` store in its place (readBytes; a
22
24
  // mismatch throws), else what `locate` answers, checked and then kept as
23
- // writeBytes keeps it. A tree's `list` and `symlinksAbove` are
24
- // gitTreeOfTarball's.
25
- export async function verifiedDownload({ method, dir, what, ext, algorithm, expected, local = [], ours = false, cache, locate, options = {}, list, symlinksAbove }) {
25
+ // writeBytes keeps it, as `entry`, `what` unless given. A tree's `list`
26
+ // and `symlinksAbove` are gitTreeOfTarball's.
27
+ export async function verifiedDownload({ method, dir, what, entry = what, ext, algorithm, expected, local = [], ours = false, cache, locate, options = {}, list, symlinksAbove }) {
26
28
  assert.ok(Object.hasOwn(DIGESTS, algorithm) && typeof expected === 'string' && expected !== '', `${method}: nothing to check ${what} against`)
27
29
  const digest = (bytes) => DIGESTS[algorithm](bytes, { expected, list, symlinksAbove })
28
- const key = `${what}.${ext}`
30
+ const key = `${entry}.${ext}`
29
31
  for (const path of ours ? [...local, ...ourCachePaths(dir, key)] : local) {
30
32
  const bytes = await readRegularFile(path)
31
33
  if (bytes && await digest(bytes) === expected) return bytes
@@ -35,10 +37,10 @@ export async function verifiedDownload({ method, dir, what, ext, algorithm, expe
35
37
  assert.ok(actual === expected, `${method}: integrity mismatch for ${what} from ${from}: expected ${expected}, got ${actual}`)
36
38
  return bytes
37
39
  }
38
- const cached = await readBytes(dir, what, key, cache)
40
+ const cached = await readBytes(dir, entry, key, cache)
39
41
  if (cached) return await check(cached, cache ? 'the store' : 'the cache')
40
42
  const url = await locate()
41
43
  const bytes = await check(await request(url, { ...options, as: 'bytes' }), url)
42
- await writeBytes(dir, what, key, bytes, cache)
44
+ await writeBytes(dir, entry, key, bytes, cache)
43
45
  return bytes
44
46
  }
package/src/git.js CHANGED
@@ -52,7 +52,6 @@ export async function findGitCheckout(dir) {
52
52
  const dirs = start && await isDirectory(start) ? await findGitDirs(start) : null
53
53
  if (dirs === null) return {}
54
54
  const directory = relative(dirs.root, start).split(sep).join('/')
55
- const github = await originGitHub(dirs.commonDir)
56
- const commit = await headCommit(dirs.gitDir, dirs.commonDir)
55
+ const [github, commit] = await Promise.all([originGitHub(dirs.commonDir), headCommit(dirs.gitDir, dirs.commonDir)])
57
56
  return { ...(github && { github }), directory, ...(github && { url: `https://github.com/${github}` }), ...(commit && { commit }) }
58
57
  }
@@ -1,15 +1,18 @@
1
1
  import assert from 'node:assert/strict'
2
2
  import { Buffer } from 'node:buffer'
3
3
 
4
- import { assertArgs, assertBoolean, assertGhsa, assertLevels, assertLogin, assertNumber, assertPath, assertRef, assertRepo, assertSha, assertTagName, assertTreeId, isRepo, isSha, isSha1, isTagName, optional, sameName, show } from '../args.js'
4
+ import { assertArgs, assertBoolean, assertGhsa, assertLevels, assertLogin, assertNumber, assertPath, assertRef, assertRepo, assertSha, assertTagName, assertTreeId, assertion, isRefName, isRepo, isRepoPath, isSha, isSha1, isTagName, optional, sameName, show } from '../args.js'
5
5
  import { verifiedDownload } from '../download.js'
6
6
  import { HttpError, decode, encodeSegment, requestWithHeaders } from '../http.js'
7
7
  import { FORMATS, lockfileOf, projectFormats } from '../lockfiles.js'
8
+ import { pool } from '../pool.js'
8
9
  import { gitTreeOfListing, objectId } from '../tree.js'
9
10
  import { api, bindMethods, call, clientHeaders, isGone, repoApi } from './client.js'
10
11
 
11
12
  const PER_PAGE = 100
12
13
  const MAX_PAGES = 100
14
+ const MAX_TREES = 500
15
+ const TREES_AT_ONCE = 6
13
16
 
14
17
  // A list of exactly `maxPages` full pages is whole only if the next is empty.
15
18
  async function* pages(method, headers, pageUrl, maxPages = MAX_PAGES) {
@@ -111,6 +114,49 @@ async function listRepoTags(headers, options) {
111
114
  })
112
115
  }
113
116
 
117
+ // GitHub lists each branch with the commit at its head.
118
+ async function listRepoBranches(headers, options) {
119
+ assertArgs('listRepoBranches', options, { repo: assertRepo, maxPages: optional(assertNumber) })
120
+ const { repo, maxPages } = options
121
+ const branches = await paginate('listRepoBranches', headers, (paging) => repoApi(repo, ['branches'], paging), maxPages)
122
+ return branches.map((entry) => {
123
+ assert.ok(isRefName(entry?.name) && isSha(entry.commit?.sha), `listRepoBranches: GitHub listed ${show(entry?.name)} in ${repo}, which is no branch name with a commit`)
124
+ return { branch: entry.name, oid: entry.commit.sha }
125
+ })
126
+ }
127
+
128
+ const assertRevision = assertion('a full commit sha, or a branch or tag name', (value) => isSha(value) || isRefName(value))
129
+ // What GitHub's compare says of the counts it gives with it.
130
+ const COMPARED = {
131
+ ahead: (ahead, behind) => ahead > 0 && behind === 0,
132
+ behind: (ahead, behind) => ahead === 0 && behind > 0,
133
+ identical: (ahead, behind) => ahead === 0 && behind === 0,
134
+ diverged: (ahead, behind) => ahead > 0 && behind > 0,
135
+ }
136
+ const isCount = (value) => Number.isSafeInteger(value) && value >= 0
137
+
138
+ // How `head` stands to `base` in the repo, as GitHub's compare tells it:
139
+ // `ahead` where `base` is in `head`'s history, `behind` the other way round,
140
+ // `identical`, or `diverged`; with the commits each has that the other
141
+ // hasn't, and their merge base. Refused unless the status agrees with those
142
+ // counts, the merge base is `base` where `head` is ahead of it or the same,
143
+ // and the base GitHub compared is `base` where that is a commit. GitHub
144
+ // answers for a commit of any fork of the repo too: whether one is the
145
+ // repo's own is whether a ref of the repo has it in its history.
146
+ async function compareCommits(headers, options) {
147
+ assertArgs('compareCommits', options, { repo: assertRepo, base: assertRevision, head: assertRevision })
148
+ const { repo, base, head } = options
149
+ const body = await call(headers, repoApi(repo, ['compare', `${encodeSegment(base)}...${encodeSegment(head)}`], { per_page: 1 }))
150
+ const { status, ahead_by: aheadBy, behind_by: behindBy } = body ?? {}
151
+ const baseCommit = body?.base_commit?.sha
152
+ const mergeBase = body?.merge_base_commit?.sha
153
+ assert.ok(Object.hasOwn(COMPARED, status) && isCount(aheadBy) && isCount(behindBy) && COMPARED[status](aheadBy, behindBy),
154
+ `compareCommits: GitHub compared ${repo} ${base}...${head} as ${show(status)}, ${show(aheadBy)} ahead and ${show(behindBy)} behind`)
155
+ assert.ok(isSha(baseCommit) && isSha(mergeBase) && (!isSha(base) || baseCommit === base) && (!['ahead', 'identical'].includes(status) || mergeBase === baseCommit),
156
+ `compareCommits: GitHub compared ${repo} ${base}...${head} from ${show(baseCommit)}, merge base ${show(mergeBase)}`)
157
+ return { status, aheadBy, behindBy, mergeBase }
158
+ }
159
+
114
160
  // GitHub's object for the path first: a directory, symlink or submodule is
115
161
  // refused rather than read as a file's text. Up to 1 MB the object holds
116
162
  // the content; past it, `encoding: none`, and the blob it names is read,
@@ -232,6 +278,40 @@ async function* filesIn(method, headers, repo, tree, base) {
232
278
  }
233
279
  }
234
280
 
281
+ const assertPaths = assertion('an array of paths inside a repository', (value) => Array.isArray(value) && value.every(isRepoPath))
282
+
283
+ // Every entry of a commit's tree, by its path from the root, as
284
+ // listTreeDeep lists it; where GitHub cuts that short, the tree's own
285
+ // listing, then each tree in it the same way, only those `paths` are in
286
+ // if given, `maxTrees` trees listed at most. Whether some were left
287
+ // unlisted is `cut`.
288
+ async function listRepoTree(headers, options) {
289
+ assertArgs('listRepoTree', options, { repo: assertRepo, sha: assertSha, paths: optional(assertPaths), maxTrees: optional(assertNumber) })
290
+ const { repo, sha, paths, maxTrees = MAX_TREES } = options
291
+ const dirs = paths && new Set(paths.flatMap((path) => path.split('/').slice(0, -1).map((_, at, names) => names.slice(0, at + 1).join('/'))))
292
+ const at = (base, entries) => entries.map(({ path, mode, type, sha: id }) => ({ path: `${base}${path}`, mode, type, sha: id }))
293
+ const entries = []
294
+ let cut = false
295
+ let listed = 0
296
+ let round = [{ tree: await commitTree('listRepoTree', headers, repo, sha), base: '' }]
297
+ while (round.length > 0) {
298
+ const asked = round.slice(0, maxTrees - listed)
299
+ cut ||= asked.length < round.length
300
+ listed += asked.length
301
+ const answers = await pool(asked, TREES_AT_ONCE, async ({ tree, base }) => {
302
+ const deep = await listTreeDeep('listRepoTree', headers, repo, tree)
303
+ return { base, deep, own: deep ?? await listTree('listRepoTree', headers, repo, tree) }
304
+ })
305
+ round = []
306
+ for (const { base, deep, own } of answers) {
307
+ const found = at(base, own)
308
+ entries.push(...found)
309
+ if (deep === null) round.push(...found.filter(({ path, type }) => type === 'tree' && (dirs?.has(path) ?? true)).map(({ path, sha: tree }) => ({ tree, base: `${path}/` })))
310
+ }
311
+ }
312
+ return { entries, cut }
313
+ }
314
+
235
315
  const byPath = (a, b) => (a.path < b.path ? -1 : 1)
236
316
 
237
317
  async function findRepoLockfiles(headers, options) {
@@ -305,5 +385,5 @@ async function listRepoAdvisories(headers, options) {
305
385
  return (await Array.fromAsync(cursorPages('listRepoAdvisories', headers, pageUrl))).flat()
306
386
  }
307
387
 
308
- export const readMethods = { getCurrentUser, listUserRepos, getRepo, getRepoHead, getRepoTag, listRepoTags, getRepoFile, getRepoTarball, getRepoTreeTarball, getRepoTreeId, listRepoDir, findRepoLockfiles, getPullRequest, getCollaboratorPermission, getAdvisory, listRepoAdvisories }
388
+ export const readMethods = { getCurrentUser, listUserRepos, getRepo, getRepoHead, getRepoTag, listRepoTags, listRepoBranches, compareCommits, getRepoFile, getRepoTarball, getRepoTreeTarball, getRepoTreeId, listRepoDir, listRepoTree, findRepoLockfiles, getPullRequest, getCollaboratorPermission, getAdvisory, listRepoAdvisories }
309
389
  export const createClient = (options) => bindMethods(clientHeaders('createClient', options, true), readMethods)
package/src/http.js CHANGED
@@ -15,9 +15,10 @@ export const CRATES_INDEX = 'https://index.crates.io'
15
15
  export const CRATES_STATIC = 'https://static.crates.io'
16
16
  export const SOLDEER_API = 'https://api.soldeer.xyz'
17
17
  export const SOLDEER_REVISIONS = 'https://soldeer-revisions.s3.amazonaws.com'
18
+ export const COCOAPODS_CDN = 'https://cdn.cocoapods.org'
18
19
  export const MAX_BYTES = 512 * 1024 * 1024
19
20
 
20
- const ORIGINS = new Set([NPM_REGISTRY, GITHUB_API, OSV_API, CRATES_API, PACKAGIST_REPO, CRATES_INDEX, CRATES_STATIC, SOLDEER_API, SOLDEER_REVISIONS])
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])
21
22
  const isSegment = matches(/^(?!\.\.?$)(?:[\w.~@-]|%[\dA-F]{2})+$/u)
22
23
  const isQueryKey = matches(/^[a-z_]+(?:\[\])?$/u)
23
24
  const isQueryValue = (value) => (typeof value === 'string' && value !== '') || (Number.isSafeInteger(value) && value >= 0)
@@ -77,7 +78,8 @@ export function buildUrl(origin, segments, query = {}) {
77
78
  export async function send(url, { method = 'GET', headers = {}, body, redirect = 'manual', as } = {}) {
78
79
  const parsed = typeof url === 'string' ? URL.parse(url) : null
79
80
  assert.ok(parsed?.href === url && ORIGINS.has(parsed.origin) && !parsed.username && !parsed.password && !parsed.hash, `Unexpected URL: ${printable(url)}`)
80
- assert.ok(['GET', 'POST'].includes(method), `Unexpected method: ${method}`)
81
+ assert.ok(['GET', 'HEAD', 'POST'].includes(method), `Unexpected method: ${method}`)
82
+ assert.ok(method !== 'HEAD' || body === undefined, 'Unexpected body with HEAD')
81
83
  assert.ok(['manual', 'follow'].includes(redirect), `Unexpected redirect mode: ${redirect}`)
82
84
  assert.ok(Object.hasOwn(LIMITS, as), `Unexpected response type: ${as}`)
83
85
  assert.ok(Object.entries(headers).every(isHeader), 'Unexpected header')
@@ -127,3 +129,11 @@ export async function requestWithHeaders(url, options) {
127
129
  }
128
130
 
129
131
  export const request = async (url, options) => (await requestWithHeaders(url, options)).body
132
+
133
+ // Whether `url` answers a HEAD with a 2xx. No body is read; a redirect is
134
+ // not followed, and counts as no.
135
+ export async function answersHead(url) {
136
+ const res = await send(url, { method: 'HEAD', as: 'json' })
137
+ await res.body?.cancel()
138
+ return res.ok
139
+ }
@@ -13,6 +13,7 @@ import { readRegularFile } from '../cache.js'
13
13
  const KEY = 'make-fetch-happen:request-cache:'
14
14
  const digest = (algorithm, data, encoding) => createHash(algorithm).update(data).digest(encoding)
15
15
  const shard = (hex) => [hex.slice(0, 2), hex.slice(2, 4), hex.slice(4)]
16
+ export const contentPath = (cache, sha512) => join(cache, 'content-v2', 'sha512', ...shard(Buffer.from(sha512, 'base64').toString('hex')))
16
17
  const decoder = new TextDecoder('utf-8')
17
18
 
18
19
  async function lastEntry(root, key) {
@@ -39,6 +40,6 @@ export async function readNpmCached(root, url) {
39
40
  const integrity = typeof entry?.integrity === 'string' ? entry.integrity : ''
40
41
  const sha512 = /(?:^|\s)sha512-([\d+/A-Za-z]+={0,2})(?=[\s?]|$)/u.exec(integrity)?.[1]
41
42
  if (sha512 === undefined) return null
42
- const body = await readRegularFile(join(root, 'content-v2', 'sha512', ...shard(Buffer.from(sha512, 'base64').toString('hex'))))
43
+ const body = await readRegularFile(contentPath(root, sha512))
43
44
  return body && digest('sha512', body, 'base64') === sha512 ? { body, metadata: entry.metadata } : null
44
45
  }
@@ -1,4 +1,3 @@
1
- import { Buffer } from 'node:buffer'
2
1
  import { homedir } from 'node:os'
3
2
  import { join, resolve } from 'node:path'
4
3
 
@@ -6,7 +5,7 @@ import { assertArgs, assertPackage, assertPackageName, isPlainObject, isSha, opt
6
5
  import { assertCache } from '../cache.js'
7
6
  import { verifiedDownload } from '../download.js'
8
7
  import { NPM_REGISTRY, decode } from '../http.js'
9
- import { readNpmCached } from './cacache.js'
8
+ import { contentPath, readNpmCached } from './cacache.js'
10
9
  import { getDocument, withNpmToken } from './registry.js'
11
10
  import { checkedDist, getVersion, matchingDist } from './versions.js'
12
11
 
@@ -25,8 +24,7 @@ function npmCacheDirs() {
25
24
  // npm 5+ (cacache) files a tarball by its sha512, npm 4 and before as
26
25
  // <name>/<version>/package.tgz; ~/.audit as <org>:<name>-<version>.tgz.
27
26
  function localPaths(name, version, integrity) {
28
- const hex = Buffer.from(integrity.slice('sha512-'.length), 'base64').toString('hex')
29
- const npm = npmCacheDirs().flatMap((root) => [join(root, '_cacache/content-v2/sha512', hex.slice(0, 2), hex.slice(2, 4), hex.slice(4)), join(root, name, version, 'package.tgz')])
27
+ const npm = npmCacheDirs().flatMap((root) => [contentPath(join(root, '_cacache'), integrity.slice('sha512-'.length)), join(root, name, version, 'package.tgz')])
30
28
  return [...npm, join(homedir(), '.audit/cache/tgz', `${name.replace(/^@/u, '').replace('/', ':')}-${version}.tgz`)]
31
29
  }
32
30
 
@@ -117,7 +115,7 @@ export async function getPublishTimes(name) {
117
115
  const time = record(json.time)
118
116
  const times = new Map()
119
117
  for (const version of Object.keys(record(json.versions))) {
120
- const at = readTime(Object.hasOwn(time, version) ? time[version] : undefined)
118
+ const at = readTime(own(time, version))
121
119
  if (at !== undefined) times.set(version, at)
122
120
  }
123
121
  return times