@preventive/upstream 1.4.0 → 1.5.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
@@ -58,8 +58,12 @@ 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 (its
62
+ // latest version's document, else, where it has no `latest` tag, a HEAD
63
+ // of the package's; unscoped names too, 32 names at a time) go to OSV;
64
+ // the rest, private ones above all, go to the registry alone.
65
+ // The name decides, not the version: npm takes down malicious versions
66
+ // but keeps their name. Public names are cached for a month.
63
67
  osv?: boolean
64
68
  }
65
69
 
@@ -130,6 +134,11 @@ export interface Advisory {
130
134
  // `unmaintained`, `unsound`, `notice`. For an id answered more than once,
131
135
  // only where each answer gives it.
132
136
  informational?: string
137
+ // Where the advisory is of malware, not a vulnerability: an OSV MAL-
138
+ // record (its `id` or an alias), CWE-506 (how GitHub files malware), or
139
+ // a `title` with the word "malware". `severity` is left as rated: MAL-
140
+ // records have none, and GitHub rates some malware high.
141
+ malware?: true
133
142
  versions: string[]
134
143
  }
135
144
 
@@ -140,7 +149,8 @@ export interface Advisory {
140
149
  // one GHSA among npm's rows; a project Soldeer does not have or that names
141
150
  // no GitHub repository, a repository gone or blocked, and one GitHub
142
151
  // 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
152
+ // GHSA OSV does not have adds no `details`. With `osv`, a name npm's
153
+ // registry doesn't serve without a token is taken as private (see `osv`). A repository renamed or
144
154
  // transferred, which GitHub redirects to it by its id, is listed by the
145
155
  // name it has now, as getRepo's `followRedirect` (github.js) finds it, its
146
156
  // rows' `url` on it. Any other failure, a malformed answer, or one about
package/github.d.ts CHANGED
@@ -180,6 +180,16 @@ export interface Client {
180
180
  // found as getRepoTreeId finds it: GitHub's listing, hashed back to the
181
181
  // tree's id, so none is left out or changed.
182
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 }>
183
193
  // Every page of the repo's branches, as GitHub lists them, each with the
184
194
  // commit at its head; more than `maxPages` (100 by default) pages of 100
185
195
  // is an error, as is a branch with no commit.
package/npm.d.ts CHANGED
@@ -51,8 +51,9 @@ export function setCacheDir(dir?: string | false): void
51
51
  // what is kept and a `key` which one: `npm/versions` and `npm/tarballs`
52
52
  // with `<name>@<version>` for a version's document and tarball; and for
53
53
  // advisories.js, `github/advisories` with the repository's `owner/name` in
54
- // lowercase for its listing, and `cargo/repos`, `composer/repos` and
55
- // `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`.
56
57
  // Values are plain JSON data, which `read` may answer as written or as a
57
58
  // copy, but a tarball's are its bytes, a Uint8Array. Whatever it answers
58
59
  // is checked as a cached file is: one malformed, stale or kept differently
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/upstream",
3
- "version": "1.4.0",
3
+ "version": "1.5.1",
4
4
  "description": "Minimal npm, crates.io, Soldeer, CocoaPods trunk, GitHub and git checkout clients",
5
5
  "type": "module",
6
6
  "exports": {
@@ -38,6 +38,12 @@ export function detailsOf(text, id) {
38
38
  return { details: text }
39
39
  }
40
40
 
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
+
41
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)
@@ -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 { SEVERITIES, 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'
@@ -95,7 +95,7 @@ export async function advisories(packages, options = {}) {
95
95
  const asked = new Map(names.map((name) => [name, [...named.get(name).versions].toSorted(compare)]))
96
96
  const known = new Map(names.filter((name) => named.get(name).github).map((name) => [name, named.get(name).github]))
97
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 })
98
- 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 }) }))
99
99
  }))
100
100
  return found.flat().toSorted((a, b) => order(a.ecosystem, b.ecosystem) || order(a.name, b.name))
101
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,9 @@ 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
+ // Names checked at once for whether they are public: each a small document,
17
+ // answered in about a tenth of a second.
18
+ const NAMES_AT_ONCE = 32
15
19
 
16
20
  const isRow = (row) => row && typeof row === 'object' && Number.isSafeInteger(row.id)
17
21
  && ['url', 'severity', 'vulnerable_versions'].every((key) => typeof row[key] === 'string') && isText(row.title)
@@ -85,14 +89,58 @@ function withOsv(registry, osv) {
85
89
  return [...rows, ...added]
86
90
  }
87
91
 
92
+ // Whether npm's registry serves `name` to anyone: its latest version's
93
+ // document, for that name, read with no token. Private packages and other
94
+ // registries' answer 404; any other answer, or none, counts as private too,
95
+ // as in triage. That document first, as npm answers a HEAD of the package's
96
+ // in two seconds or more about one time in ten; but a 404 for it may only
97
+ // mean no `latest` tag (a package published with `--tag` alone, or one
98
+ // unpublished whole, its name kept), so then the package's document, a HEAD
99
+ // with no token, decides.
100
+ async function servesAnyone(name) {
101
+ try {
102
+ const json = await request(buildUrl(NPM_REGISTRY, [...name.split('/'), 'latest']), { as: 'json' })
103
+ return json?.name === name
104
+ } catch (err) {
105
+ if (!isNotFound(err)) return false
106
+ }
107
+ try {
108
+ return await answersHead(buildUrl(NPM_REGISTRY, name.split('/')))
109
+ } catch {
110
+ return false
111
+ }
112
+ }
113
+
114
+ // The packages of `asked` whose name is public (servesAnyone). The name
115
+ // decides, not the version: npm takes down malicious versions but keeps
116
+ // their name. Public names are kept a month, as a scoped package can be
117
+ // made private; the rest are asked again each time.
118
+ async function publicOnly(asked, cache) {
119
+ const names = [...asked.keys()]
120
+ const kept = await pool(names, NAMES_AT_ONCE, (name) => readRecord('npm/public', name, cache))
121
+ const missing = names.filter((name, i) => kept[i]?.public !== true)
122
+ const found = await pool(missing, NAMES_AT_ONCE, servesAnyone)
123
+ const added = missing.filter((name, i) => found[i])
124
+ await pool(added, NAMES_AT_ONCE, (name) => writeRecord('npm/public', name, { public: true }, cache))
125
+ const serving = new Set([...names.filter((name, i) => kept[i]?.public === true), ...added])
126
+ return new Map([...asked].filter(([name]) => serving.has(name)))
127
+ }
128
+
129
+ // OSV's records of the public packages only: no request to OSV names a
130
+ // private one.
131
+ async function osvOfPublic(asked, options) {
132
+ const told = await publicOnly(asked, options.cache)
133
+ return told.size > 0 ? await osvRows({ osv: 'npm' }, told, options) : []
134
+ }
135
+
88
136
  // What `npm audit` asks the registry, one row per vulnerable range, and
89
- // with `osv`, what OSV has besides.
137
+ // with `osv`, OSV's records of the public packages.
90
138
  export const NPM = {
91
139
  assertName: assertPackageName,
92
140
  assertVersion: assertPackageVersion,
93
141
  compare: compareVersions,
94
142
  advisories: async (asked, options) => {
95
- const [registry, osv] = await Promise.all([registryAdvisories(asked), options.osv ? osvRows({ osv: 'npm' }, asked, options) : []])
143
+ const [registry, osv] = await Promise.all([registryAdvisories(asked), options.osv ? osvOfPublic(asked, options) : []])
96
144
  const rows = withOsv(registry, osv)
97
145
  return await withRepositories(options.details ? await withDetails(rows) : rows, asked, options, { ecosystem: 'npm', lookUp: npmRepos })
98
146
  },
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', 'cocoapods/podspecs', '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
@@ -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, assertion, isRefName, 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) {
@@ -275,6 +278,40 @@ async function* filesIn(method, headers, repo, tree, base) {
275
278
  }
276
279
  }
277
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
+
278
315
  const byPath = (a, b) => (a.path < b.path ? -1 : 1)
279
316
 
280
317
  async function findRepoLockfiles(headers, options) {
@@ -348,5 +385,5 @@ async function listRepoAdvisories(headers, options) {
348
385
  return (await Array.fromAsync(cursorPages('listRepoAdvisories', headers, pageUrl))).flat()
349
386
  }
350
387
 
351
- export const readMethods = { getCurrentUser, listUserRepos, getRepo, getRepoHead, getRepoTag, listRepoTags, listRepoBranches, compareCommits, 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 }
352
389
  export const createClient = (options) => bindMethods(clientHeaders('createClient', options, true), readMethods)
package/src/http.js CHANGED
@@ -78,7 +78,8 @@ export function buildUrl(origin, segments, query = {}) {
78
78
  export async function send(url, { method = 'GET', headers = {}, body, redirect = 'manual', as } = {}) {
79
79
  const parsed = typeof url === 'string' ? URL.parse(url) : null
80
80
  assert.ok(parsed?.href === url && ORIGINS.has(parsed.origin) && !parsed.username && !parsed.password && !parsed.hash, `Unexpected URL: ${printable(url)}`)
81
- 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')
82
83
  assert.ok(['manual', 'follow'].includes(redirect), `Unexpected redirect mode: ${redirect}`)
83
84
  assert.ok(Object.hasOwn(LIMITS, as), `Unexpected response type: ${as}`)
84
85
  assert.ok(Object.entries(headers).every(isHeader), 'Unexpected header')
@@ -128,3 +129,11 @@ export async function requestWithHeaders(url, options) {
128
129
  }
129
130
 
130
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
+ }